@codingfactory/mediables-vue 2.16.0 → 2.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{PixiFrameExporter-cu2jpN20.js → PixiFrameExporter-B1jinD_-.js} +2 -2
- package/dist/{PixiFrameExporter-cu2jpN20.js.map → PixiFrameExporter-B1jinD_-.js.map} +1 -1
- package/dist/{PixiFrameExporter-BOijjcAa.cjs → PixiFrameExporter-vNJtMooF.cjs} +2 -2
- package/dist/{PixiFrameExporter-BOijjcAa.cjs.map → PixiFrameExporter-vNJtMooF.cjs.map} +1 -1
- package/dist/components/AlbumNavRail.vue.d.ts +27 -0
- package/dist/components/AlbumTree.vue.d.ts +2 -0
- package/dist/components/MediaAlbumPickerModal.vue.d.ts +14 -0
- package/dist/components/MediaBulkActionBar.vue.d.ts +33 -0
- package/dist/components/MediaEmptyState.vue.d.ts +20 -0
- package/dist/components/MediaFilterChips.vue.d.ts +26 -0
- package/dist/components/MediaInspectorPanel.vue.d.ts +36 -0
- package/dist/components/MediaLibraryShell.vue.d.ts +36 -0
- package/dist/components/MediaLibraryToolbar.vue.d.ts +11 -0
- package/dist/components/MediaLibraryWorkspace.vue.d.ts +70 -0
- package/dist/components/MediaManagementView.vue.d.ts +30 -0
- package/dist/components/MediaShortcutHelp.vue.d.ts +13 -0
- package/dist/components/MediaTrashWorkspace.vue.d.ts +15 -0
- package/dist/components/MediaUsageList.vue.d.ts +17 -0
- package/dist/components/MediaVariantStrip.vue.d.ts +10 -0
- package/dist/composables/useMediaDeletion.d.ts +36 -0
- package/dist/composables/useMediaDisplayName.d.ts +19 -0
- package/dist/composables/useMediaLibraryQuery.d.ts +25 -2
- package/dist/composables/useMediaLibraryUploads.d.ts +41 -0
- package/dist/composables/useMediaSelection.d.ts +34 -4
- package/dist/index-DCTHBp0p.cjs +357 -0
- package/dist/index-DCTHBp0p.cjs.map +1 -0
- package/dist/{index-Bff5fDnU.js → index-IIKslTrU.js} +19487 -17202
- package/dist/index-IIKslTrU.js.map +1 -0
- package/dist/index.d.ts +32 -2
- package/dist/mediables-vue.cjs +1 -1
- package/dist/mediables-vue.mjs +109 -93
- package/dist/style.css +1 -1
- package/dist/types/media.d.ts +5 -0
- package/dist/types/mediaLibraryPicker.d.ts +43 -1
- package/package.json +1 -1
- package/dist/index-Bff5fDnU.js.map +0 -1
- package/dist/index-zFuo-sDY.cjs +0 -357
- package/dist/index-zFuo-sDY.cjs.map +0 -1
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
"use strict";var ch=Object.defineProperty;var uh=(o,a,t)=>a in o?ch(o,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[a]=t;var ee=(o,a,t)=>uh(o,typeof a!="symbol"?a+"":a,t);const Yr=require("pinia"),e=require("vue"),Mt=require("pixi.js"),oe=require("./editor-DLvndiXG.cjs"),H=require("@ionic/vue"),mh=require("pixi-filters");function ph(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 Gt=ph(Mt),dl=1,fh=new Set(["free","square","circle"]);function hh(o){if(typeof o!="number"||!Number.isFinite(o))return 0;const a=o%360;return a<0?a+360:a}function vh(o){const a=typeof o;return a==="string"||a==="number"||a==="boolean"}function gh(o){if(!o||typeof o!="object")return!1;const a=o;return typeof a.x=="number"&&typeof a.y=="number"&&typeof a.width=="number"&&typeof a.height=="number"}function ql(o){if(!o||typeof o!="object")return null;const a=o;if(a.version!==dl)return null;const t=a.crop,n=t&&gh(t.rect)?{...t.rect}:null,i=t&&typeof t.shape=="string"&&fh.has(t.shape)?t.shape:"free",r=t&&typeof t.aspectRatio=="string"?t.aspectRatio:"free",s=a.transform,l=hh(s==null?void 0:s.rotation),d=a.filters,c=[];if(Array.isArray(d))for(const u of d){if(!u||typeof u!="object")continue;const m=u;if(typeof m.id!="string")continue;const f={},p=m.values;if(p&&typeof p=="object"&&!Array.isArray(p))for(const[h,v]of Object.entries(p))vh(v)&&(f[h]=v);c.push({id:m.id,enabled:m.enabled!==!1,values:f})}return{version:dl,crop:{rect:n,aspectRatio:r,shape:i},transform:{rotation:l},filters:c}}function Hu(o){const a=ql(o);return a?JSON.stringify(a):null}function bh(o){try{const a=JSON.parse(o);return ql(a)}catch{return null}}function yh(){return{version:dl,crop:{rect:null,aspectRatio:"free",shape:"free"},transform:{rotation:0},filters:[]}}let ba={apiBaseUrl:"/api/v1",isAdmin:!1};function oc(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 Io(o){ba={...ba,...o}}function Zu(){return{...ba}}function Gu(o){ba={...o}}function Xu(o){const a=Zu();return Io(o),()=>{Gu(a)}}function wh(o){const a=o.trim().replace(/\/+$/,"");return a===""?"/api/v1":a.startsWith("/")?a:`/${a}`}function kh(o,a){const t=wh(a),n=(i,r="")=>{const s=`/api${t}`;return!t.startsWith("/api/")&&i.startsWith(`${s}/`)?`${i.slice(4)}${r}`:!t.startsWith("/api/")&&i===s?`${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 _h=async(o,a={})=>{var l;const t=(l=document.querySelector('meta[name="csrf-token"]'))==null?void 0:l.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 s=await fetch(o,r);if(!s.ok){const d=await s.json().catch(()=>({message:"Request failed"}));throw new Error(d.message||`HTTP ${s.status}`)}if(s.status!==204)return await s.json()},xa=Yr.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),s=e.ref(24),l=e.ref({type:null,uuid:null}),d=e.ref([]),c=e.ref(!1),u=e.ref(null),m=e.ref(new Map),f=e.ref(new Map),p=e.ref(new Set),h=e.ref(new Map),v=e.ref({}),E=5*60*1e3,y=e.computed(()=>{if(ba.apiScope)return ba.apiScope;if(ba.isAdmin)return"admin"}),k=e.computed(()=>y.value==="admin");function g(){return ba.httpClient||_h}function b(be){const _e=ba.apiBaseUrl||"/api/v1",ve=y.value?`/${y.value}`:"";return`${_e}${ve}${be}`}function R(be){return`${ba.apiBaseUrl||"/api/v1"}${be}`}function N(be,_e){return`${y.value??"default"}-${be}-${JSON.stringify(_e)}`}function T(be){return Date.now()-be<E}function S(){h.value.clear(),v.value={}}function B(be){if(!be||!be.data)return;const _e={};be.data.forEach(ve=>{const xe=`${ve.file_name}-${ve.collection_name||"default"}`,Se=_e[xe];(!Se||Object.keys(ve.generated_conversions||{}).length>Object.keys(Se.generated_conversions||{}).length)&&(_e[xe]=ve)}),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 A(be=1,_e={}){const ve=N(be,_e),xe=h.value.get(ve);if(xe&&T(xe.timestamp)){const Se=xe.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",s.value.toString()),k.value&&Se.append("linked","1");for(const ge in _e)if(Object.prototype.hasOwnProperty.call(_e,ge)){const Ge=_e[ge];Ge!=null&&Ge!==""&&Se.append(ge,String(Ge))}const re=await g()(b(`/media?${Se}`));return h.value.set(ve,{data:re,timestamp:Date.now()}),B(re),re}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 ve=`${be.name}-${Date.now()}`,xe={file:be,progress:0,status:"uploading"};m.value.set(ve,xe);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 re=await g()(b("/media"),{method:"POST",body:Se});return xe.status="completed",xe.progress=100,xe.media=re==null?void 0:re.data,i.value===1&&(re!=null&&re.data)&&(o.value=[re.data,...o.value]),S(),(re==null?void 0:re.data)||null}catch(Se){throw xe.status="error",xe.error=Se instanceof Error?Se.message:"Upload failed",n.value=xe.error,new Error(n.value)}finally{t.value=!1,setTimeout(()=>{m.value.delete(ve)},5e3)}}async function M(be){t.value=!0,n.value=null;const _e=o.value.findIndex(xe=>xe.uuid===be);let ve;_e!==-1&&(ve=o.value.splice(_e,1)[0]);try{return await g()(b(`/media/${be}`),{method:"DELETE"}),p.value.delete(be),S(),!0}catch(xe){throw ve&&_e!==-1&&o.value.splice(_e,0,ve),n.value=xe instanceof Error?xe.message:"Failed to delete media",new Error(n.value)}finally{t.value=!1}}async function w(be,_e){t.value=!0,n.value=null;try{const xe=await g()(b(`/media/${be}`),{method:"PATCH",body:_e,data:_e});if(xe!=null&&xe.data){const Se=o.value.findIndex(Ae=>Ae.uuid===be);return Se!==-1&&(o.value[Se]={...o.value[Se],...xe.data}),S(),xe.data}return null}catch(ve){throw n.value=ve instanceof Error?ve.message:"Failed to update media",new Error(n.value)}finally{t.value=!1}}async function F(){t.value=!0,n.value=null;try{const _e=await g()(b("/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 P(be,_e,ve="images",xe){c.value=!0,u.value=null;try{const Se=new URLSearchParams;Se.append("collection",ve),xe&&Se.append("search",xe);const re=await g()(b(`/media/model/${be}/${_e}?${Se}`));return re!=null&&re.data?(d.value=re.data,re.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 D(be,_e,ve,xe="images"){c.value=!0,u.value=null;const Se=[...d.value];try{const re=await g()(b(`/media/model/${be}/${_e}/attach`),{method:"POST",body:{media_uuids:ve,collection:xe}});return await P(be,_e,xe),(re==null?void 0:re.data)||[]}catch(Ae){throw d.value=Se,u.value=Ae instanceof Error?Ae.message:"Failed to attach media",new Error(u.value)}finally{c.value=!1}}async function O(be,_e,ve,xe="images"){c.value=!0,u.value=null;const Se=[...d.value];d.value=d.value.filter(Ae=>Ae.uuid!==ve);try{return await g()(b(`/media/model/${be}/${_e}/detach`),{method:"POST",body:{media_uuid:ve,collection:xe}}),!0}catch(Ae){throw d.value=Se,u.value=Ae instanceof Error?Ae.message:"Failed to detach media",new Error(u.value)}finally{c.value=!1}}async function I(be,_e,ve,xe="images"){c.value=!0,u.value=null;const Se=[...d.value],Ae=new Map(d.value.map(re=>[re.uuid,re]));d.value=ve.map(re=>Ae.get(re)).filter(re=>re!==void 0);try{return await g()(b(`/media/model/${be}/${_e}/reorder`),{method:"POST",body:{media_uuids:ve,collection:xe}}),!0}catch(re){throw d.value=Se,u.value=re instanceof Error?re.message:"Failed to reorder media",new Error(u.value)}finally{c.value=!1}}async function Z(be,_e,ve={}){var lt,Et;const xe=g(),Se=ba.apiBaseUrl||"/api/v1";let Ae=oc(_e.documentId)?_e.documentId:oc((lt=_e.document)==null?void 0:lt.id)?_e.document.id:null,re=_e.documentRevisionId??null,ge=typeof _e.documentRevisionNumber=="number"?_e.documentRevisionNumber:typeof((Et=_e.document)==null?void 0:Et.revision)=="number"?_e.document.revision:null;if(_e.document){const Ee=await xe(`${Se}/media/${be}/editor-documents/materialize`,{method:"POST",body:{document_id:Ae,base_document_revision:ge,document:_e.document}});Ae=Ee.document_id,re=Ee.document_revision_id,ge=Ee.document_revision_number}if(_e.document&&Ae&&re&&typeof ge=="number"){const Ee=new FormData,Re=(_e.mimeType||_e.blob.type||"image/png")==="image/jpeg"?"jpg":"png";Ee.append("flattened_file",_e.blob,`edited.${Re}`),Ee.append("document_id",Ae),Ee.append("document_revision_id",re),Ee.append("expected_document_revision",String(ge)),Ee.append("output_mode",ve.asVariant?"save-as-variant":"save-as-new");const et=await xe(`${Se}/media/${be}/editor-documents/save`,{method:"POST",body:Ee});if(et.media)return et.media;throw new Error("Unexpected response from layered editor save endpoint")}const Ge=new FormData,at=(_e.mimeType||_e.blob.type||"image/png")==="image/jpeg"?"jpg":"png";Ge.append("image_file",_e.blob,`edited.${at}`);const rt=Hu(_e.state);rt&&Ge.append("editor_state",rt),Ge.append("save_as_new","true"),ve.asVariant&&Ge.append("as_variant","true"),ve.name!==void 0&&Ge.append("name",ve.name);const gt=await xe(`${Se}/editor/${be}/save`,{method:"POST",body:Ge});if("media"in gt&>.media)return gt.media;if("status_url"in gt&>.status_url)return z(xe,kh(gt.status_url,Se),ve.pollTimeout??6e4);throw new Error("Unexpected response from editor save endpoint")}async function z(be,_e,ve){const xe=Date.now(),Se=2e3;for(;Date.now()-xe<ve;){await new Promise(re=>setTimeout(re,Se));const Ae=await be(_e);if(Ae.status==="completed"&&Ae.media)return Ae.media;if(Ae.status==="failed")throw new Error(Ae.error??"Image processing failed")}throw new Error("Image processing timed out")}function K(be,_e,ve){l.value=ve!==void 0?{type:be,uuid:_e,collection:ve}:{type:be,uuid:_e},v.value[`${be}-${_e}`]={timestamp:Date.now()}}function se(){l.value={type:null,uuid:null},d.value=[],u.value=null}async function Be(){if(!l.value.type||!l.value.uuid)return;const be=await P(l.value.type,l.value.uuid,l.value.collection||"images");d.value=be||[]}function ce(){o.value.forEach(be=>p.value.add(be.uuid))}function ie(){p.value.clear()}function W(be){p.value.has(be)?p.value.delete(be):p.value.add(be)}function C(be){return p.value.has(be)}function U(){return Array.from(m.value.values()).some(be=>be.status==="uploading")}function j(be){return m.value.get(be)||f.value.get(be)}function ne(){return[...Array.from(m.value.values()),...Array.from(f.value.values())]}async function de(){const be=Array.from(p.value);let _e=0;for(const ve of be)try{await M(ve),_e++}catch{}return ie(),_e}function Ke(be,_e){var ve;return _e&&((ve=be.conversion_urls)!=null&&ve[_e])?be.conversion_urls[_e]||"":be.original_url||be.url||""}return{items:o,collections:a,loading:t,error:n,currentPage:i,totalPages:r,itemsPerPage:s,isAdmin:k,modelContext:l,modelMedia:d,isLoadingModelMedia:c,modelMediaError:u,selectedItems:p,uploadProgress:m,uploadQueue:f,cachedResponses:v,fetchMedia:A,uploadFile:x,deleteMedia:M,updateMedia:w,clearCache:S,fetchCollections:F,fetchModelMedia:P,attachMedia:D,detachMedia:O,reorderMedia:I,saveEditedImage:Z,setModelContext:K,clearModelContext:se,refreshModelMedia:Be,selectAllItems:ce,clearSelection:ie,toggleSelection:W,isSelected:C,deleteSelectedItems:de,getHttpClient:g,getApiUrl:b,getEditorApiUrl:R,hasActiveUploads:U,getUploadProgress:j,getAllUploadProgress:ne,getMediaUrl:Ke}}),Ku=()=>((ba.apiScope!=="admin"||ba.isAdmin!==!0)&&Io({...ba,apiScope:"admin",isAdmin:!0}),xa());class Ju{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=oe.el("div",{className:"panel-tabs",role:"tablist","aria-label":"Filter categories","data-testid":"v2-category-tabs"}),oe.EDITOR_CATEGORIES.forEach(t=>{const n=oe.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=oe.el("span",{className:"panel-tab-icon","aria-hidden":"true"});i.innerHTML=t.icon,n.appendChild(i)}n.appendChild(oe.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 qu{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=oe.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(s=>{var c;const l=((c=n==null?void 0:n.has)==null?void 0:c.call(n,s.id))??!1,d=i===s.id;this.element.appendChild(this._renderRow(s,l,d,r))})}_renderRow(a,t,n,i=null){const r=oe.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)}}),s=oe.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 f,p,h,v;u.stopPropagation();const m=!((p=(f=this.state.get("activeFilters"))==null?void 0:f.has)!=null&&p.call(f,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&&(s.innerHTML=oe.checkmark),r.appendChild(s);const l=oe.el("div",{className:"filter-row-body"});l.appendChild(oe.el("span",{className:"filter-row-name"},a.name));const d=this._buildSummary(a,t);d&&l.appendChild(oe.el("span",{className:"filter-row-summary"},d)),r.appendChild(l);const c=oe.el("span",{className:"filter-row-chevron","aria-hidden":"true"});return c.innerHTML=oe.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 s=n[r.id];if(!(s===void 0||s===r.default)&&(i.push(this._formatControlValue(r,s)),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 s=this.element.querySelector(`[data-filter="${r.id}"]`);if(!s)continue;const l=((i=n==null?void 0:n.has)==null?void 0:i.call(n,r.id))??!1,d=this._buildSummary(r,l),c=s.querySelector(".filter-row-summary");if(d&&c)c.textContent=d;else if(d&&!c){const u=s.querySelector(".filter-row-body");u==null||u.appendChild(oe.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 Yu{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=oe.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(oe.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(oe.el("div",{className:"no-filter-selected"},"Filter not found"));return}const i=oe.el("div",{className:"controls-header"});i.appendChild(oe.el("span",{className:"controls-title"},n.name)),i.appendChild(oe.createButton({label:"Reset",className:"btn-text",onClick:()=>this._handleReset(a,t)})),this.element.appendChild(i);const r=oe.el("div",{className:"controls-grid"}),s=this.state.getFilterValues(a);(n.controls||[]).forEach(d=>{if(d.hidden)return;const c=this._createControl(a,d,s[d.id]??d.default,t);c&&r.appendChild(c)});const l=this.filterManager.getInstance(a);if(l&&typeof l.getDynamicControls=="function"){let d=[];try{d=l.getDynamicControls()||[]}catch{}d.forEach(c=>{const u=c.property||c.id,m=s[u]??c.default,f=this._createControl(a,c,m,t);f&&r.appendChild(f)})}this.element.appendChild(r)}_createControl(a,t,n,i=null){if(t.hidden)return null;const r=t.label||t.id,s=this._normalizeControlType(t.type),l=t.property||t.id;switch(s){case"slider":return oe.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,l,d,i)}});case"toggle":return oe.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,l,d,i)}});case"color":return oe.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,l,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 oe.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,l,c,i)}})}case"text":return oe.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,l,d,i)}});case"button":{const d=oe.el("div",{className:"button-control"});return d.appendChild(oe.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 Eh{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=oe.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=oe.el("div",{className:"panel-section-title"});if(i.appendChild(oe.el("span",{},`Active (${t})`)),t>0&&this._onClearAll&&i.appendChild(oe.el("button",{type:"button",className:"btn btn-text",style:{padding:"2px 8px",fontSize:"11px"},"data-testid":"v2-clear-all",onClick:()=>{var l;return(l=this._onClearAll)==null?void 0:l.call(this,n)}},"Clear all")),this.element.appendChild(i),t===0){this.element.appendChild(oe.el("div",{className:"active-empty"},"No filters applied"));return}const r=oe.el("div",{className:"active-stack"}),s=this.state.get("selectedFilter");for(const l of a){const d=this.filterManager.getFilterDef(l);d&&r.appendChild(this._renderChip(d,l===s,n))}this.element.appendChild(r)}_renderChip(a,t,n=null){const i=oe.el("div",{className:`active-chip ${t?"selected":""}`,"data-filter":a.id,"data-testid":`v2-active-${a.id}`});i.appendChild(oe.el("button",{type:"button",className:"active-chip-name","aria-label":`Select ${a.name}`,onClick:()=>{var s;return(s=this._onSelect)==null?void 0:s.call(this,a.id,n)}},a.name));const r=oe.el("button",{type:"button",className:"active-chip-remove","aria-label":`Remove ${a.name}`,"data-testid":`v2-active-remove-${a.id}`,onClick:()=>{var s;return(s=this._onRemove)==null?void 0:s.call(this,a.id,n)}});return r.innerHTML=oe.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 So=["collapsed","half","full"];class Sh{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=oe.el("div",{className:"editor-v2-drawer",role:"dialog","aria-label":this._ariaLabel,"data-testid":"v2-bottom-drawer","data-snap":this._snap}),this._handle=oe.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=oe.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=oe.el("div",{className:"drawer-header"}),a&&this._headerSlot.appendChild(a),this.element.appendChild(this._headerSlot),this._body=oe.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={}){So.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"),s=Math.max(i,Math.min(r,n));this.element&&(this.element.style.height=`${s}px`),Math.abs(t)>4&&(this._wasDragging=!0),a.preventDefault()}_onPointerEnd(a){var i,r,s;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=((s=this.element)==null?void 0:s.offsetHeight)||0,n=this._nearestSnap(t);this._applySnap(n,{animate:!0})}_cycleSnap(){const a=So.indexOf(this._snap),t=So[(a+1)%So.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=So[0],n=1/0;for(const i of So){const r=this._heightForSnap(i),s=Math.abs(r-a);s<n&&(n=s,t=i)}return t}_applySnap(a,{animate:t}){var r,s;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&&((s=this._onSnapChange)==null||s.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 Ch=[{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 Qu{constructor(a,t){this.state=a,this.editor=t,this.element=null,this._errorMessage=null,this._unsubscribers=[]}render(){return this.element=oe.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 p,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,s=t.kind==="color"&&typeof t.value=="string"?t.value:"#ffffff";this.element.appendChild(oe.el("div",{className:"panel-section-title"},oe.el("span",{},"Background"))),this._errorMessage&&this.element.appendChild(oe.el("p",{className:"background-panel-error",role:"alert","data-testid":"v2-background-error"},this._errorMessage));const l=oe.el("input",{type:"color",className:"color-input",value:s,disabled:r?"disabled":void 0,"aria-label":"Background color","data-testid":"v2-background-color",onInput:E=>{this._runAction(this.editor.setBackgroundColor(E.target.value))}});this.element.appendChild(this._field("Color",l));const d=oe.el("div",{className:"background-gradient-grid"});for(const E of Ch){const y=oe.el("button",{type:"button",className:"background-gradient-swatch",style:{background:E.style},"aria-label":E.ariaLabel,disabled:r?"disabled":void 0,"data-testid":`v2-background-gradient-${E.id}`,onClick:()=>{this._runAction(this.editor.setBackgroundGradient(E.fill))}},oe.el("span",{className:"background-gradient-label"},E.label));d.appendChild(y)}this.element.appendChild(this._field("Gradient",d));const c=oe.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:E=>{var k;const y=(k=E.target.files)==null?void 0:k[0];y&&this._runAction(this.editor.setBackgroundImageFromFile(y,{fit:n})),E.target.value=""}});this.element.appendChild(this._field("Upload",c));const u=(v=(h=(p=this.editor)==null?void 0:p._options)==null?void 0:h.backgroundReplacement)==null?void 0:v.mediaChoices;if(Array.isArray(u)&&u.length>0){const E=oe.el("div",{className:"background-media-grid"});for(const y of u)y!=null&&y.source&&E.appendChild(oe.el("button",{type:"button",className:"background-media-choice","aria-label":`Use ${y.label||"media"} as background`,disabled:r?"disabled":void 0,"data-testid":`v2-background-media-${y.id||y.source.mediaUuid||"choice"}`,onClick:()=>{this._runAction(this.editor.setBackgroundMediaSource(y.source,{fit:y.fit||n}))}},y.label||"Media"));this.element.appendChild(this._field("Media",E))}const m=oe.el("select",{className:"select-input",disabled:r?"disabled":void 0,"aria-label":"Background image fit","data-testid":"v2-background-fit",onChange:E=>{this._runAction(this.editor.setBackgroundFit(E.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 f=oe.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:E=>{this._runAction(this.editor.setBackgroundBlur(Number(E.target.value)))}});this.element.appendChild(this._field("Blur",f)),this.element.appendChild(oe.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 oe.el("label",{className:"background-field"},oe.el("span",{className:"background-field-label"},a),t)}_option(a,t,n){return oe.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(s=>(s==null?void 0:s.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 em{constructor(a,t){this.state=a,this.editor=t,this.element=null,this._listEl=null,this._unsubscribers=[]}render(){return this.element=oe.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(oe.el("div",{className:"layer-stack-header"},oe.el("span",{className:"layer-stack-title"},"Layers"),oe.el("span",{className:"layer-stack-order"},"Bottom to top"))),this._listEl=oe.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(oe.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),s=(a==null?void 0:a.visible)!==!1,l=(a==null?void 0:a.locked)===!0,d=this.state.get("activeLayerId")===i,c=[d?"active":null,s?"visible":"hidden",l?"locked":"unlocked"].filter(Boolean).join(", "),u=oe.el("div",{className:`layer-row${d?" active":""}${s?"":" hidden"}${l?" 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 f,p;return(p=(f=this.editor).selectLayer)==null?void 0:p.call(f,i)})},this._thumbnail(a))),u.appendChild(oe.el("div",{className:"layer-row-main"},oe.el("span",{className:"layer-row-name"},r),oe.el("span",{className:"layer-row-meta"},this._layerTypeLabel(a))));const m=oe.el("div",{className:"layer-row-actions"});return m.appendChild(this._iconButton({testId:`v2-layer-${s?"hide":"show"}-${i}`,label:`${s?"Hide":"Show"} ${r}`,icon:s?oe.eye:oe.eyeOff,disabled:l,onClick:()=>this._runAction(()=>{var f,p;return(p=(f=this.editor).setLayerVisibility)==null?void 0:p.call(f,i,!s)})})),m.appendChild(this._iconButton({testId:`v2-layer-${l?"unlock":"lock"}-${i}`,label:`${l?"Unlock":"Lock"} ${r}`,icon:l?oe.lockClosed:oe.lockOpen,onClick:()=>this._runAction(()=>{var f,p;return(p=(f=this.editor).setLayerLocked)==null?void 0:p.call(f,i,!l)})})),m.appendChild(this._iconButton({testId:`v2-layer-move-up-${i}`,label:`Move ${r} up`,icon:oe.chevronRight,disabled:l,onClick:()=>this._runAction(()=>{var f,p;return(p=(f=this.editor).moveLayer)==null?void 0:p.call(f,i,"up")})})),m.appendChild(this._iconButton({testId:`v2-layer-move-down-${i}`,label:`Move ${r} down`,icon:oe.chevronLeft,disabled:l,onClick:()=>this._runAction(()=>{var f,p;return(p=(f=this.editor).moveLayer)==null?void 0:p.call(f,i,"down")})})),m.appendChild(this._iconButton({testId:`v2-layer-bring-front-${i}`,label:`Bring ${r} to front`,icon:oe.chevronRight,disabled:l,onClick:()=>this._runAction(()=>{var f,p;return(p=(f=this.editor).moveLayer)==null?void 0:p.call(f,i,"front")})})),m.appendChild(this._iconButton({testId:`v2-layer-send-back-${i}`,label:`Send ${r} to back`,icon:oe.chevronLeft,disabled:l,onClick:()=>this._runAction(()=>{var f,p;return(p=(f=this.editor).moveLayer)==null?void 0:p.call(f,i,"back")})})),m.appendChild(this._iconButton({testId:`v2-layer-rename-${i}`,label:`Rename ${r}`,icon:oe.pencil,disabled:l,onClick:()=>this._renameLayer(i,r)})),m.appendChild(this._iconButton({testId:`v2-layer-duplicate-${i}`,label:`Duplicate ${r}`,icon:oe.duplicate,disabled:l,onClick:()=>this._runAction(()=>{var f,p;return(p=(f=this.editor).duplicateLayer)==null?void 0:p.call(f,i)})})),m.appendChild(this._iconButton({testId:`v2-layer-delete-${i}`,label:`Delete ${r}`,icon:oe.trash,disabled:l||n<=1,onClick:()=>this._runAction(()=>{var f,p;return(p=(f=this.editor).deleteLayer)==null?void 0:p.call(f,i)})})),u.appendChild(m),u}_thumbnail(a){const t=oe.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"?oe.layers:oe.move;return t}_button({testId:a,label:t,...n},i){const r=oe.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 s=oe.el("button",{type:"button",className:"layer-action-btn","aria-label":t,title:t,disabled:i?"disabled":void 0,"data-testid":a,onClick:r});return s.innerHTML=n,s}_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,s;return(s=(r=this.editor).renameLayer)==null?void 0:s.call(r,a,n)})}_runAction(a){var t,n;try{Promise.resolve(a()).catch(i=>{var r,s;return(s=(r=this.editor).emit)==null?void 0:s.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 xh=[{value:"400",label:"Regular"},{value:"500",label:"Medium"},{value:"600",label:"Semibold"},{value:"700",label:"Bold"},{value:"800",label:"Heavy"}],Vh=[{value:"left",label:"Left"},{value:"center",label:"Center"},{value:"right",label:"Right"}],Nh=[{value:"normal",label:"Normal"},{value:"multiply",label:"Multiply"},{value:"screen",label:"Screen"},{value:"overlay",label:"Overlay"}],or={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 tm{constructor(a,t){this.state=a,this.editor=t,this.element=null,this._errorMessage=null,this._unsubscribers=[]}render(){return this.element=oe.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(oe.el("div",{className:"text-panel-header"},oe.el("div",{className:"panel-section-title"},oe.el("span",{},"Text")),oe.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(oe.el("p",{className:"text-panel-error",role:"alert","data-testid":"v2-text-error"},this._errorMessage)),!a){this.element.appendChild(oe.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:{},s=a.transform&&typeof a.transform=="object"?a.transform:{},l=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:Nh,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:oe.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:xh,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:Vh,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:s.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:l.stroke.enabled,disabled:t,onChange:d=>this._updateEffects(a.id,{stroke:{enabled:d}})}),this._colorField({label:"Stroke Color",testId:"v2-text-stroke-color",value:l.stroke.color,disabled:t,onInput:d=>this._updateEffects(a.id,{stroke:{color:d}})}),this._numberField({label:"Stroke Width",testId:"v2-text-stroke-width",value:l.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:l.shadow.enabled,disabled:t,onChange:d=>this._updateEffects(a.id,{shadow:{enabled:d}})}),this._colorField({label:"Shadow Color",testId:"v2-text-shadow-color",value:l.shadow.color,disabled:t,onInput:d=>this._updateEffects(a.id,{shadow:{color:d}})}),this._numberField({label:"Shadow Alpha",testId:"v2-text-shadow-alpha",value:l.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:l.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:l.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:l.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:l.glow.enabled,disabled:t,onChange:d=>this._updateEffects(a.id,{glow:{enabled:d}})}),this._colorField({label:"Glow Color",testId:"v2-text-glow-color",value:l.glow.color,disabled:t,onInput:d=>this._updateEffects(a.id,{glow:{color:d}})}),this._numberField({label:"Glow Alpha",testId:"v2-text-glow-alpha",value:l.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:l.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:l.backdrop.enabled,disabled:t,onChange:d=>this._updateEffects(a.id,{backdrop:{enabled:d}})}),this._colorField({label:"Backdrop Color",testId:"v2-text-backdrop-color",value:l.backdrop.color,disabled:t,onInput:d=>this._updateEffects(a.id,{backdrop:{color:d}})}),this._numberField({label:"Backdrop Opacity",testId:"v2-text-backdrop-opacity",value:l.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:l.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:l.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:l.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=oe.el("div",{className:"text-field text-content-field"});i.appendChild(oe.el("label",{className:"text-field-label",for:"v2-text-content"},"Content"));let r=t==null?"":String(t);const s=oe.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),s.value=r,s.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})),s.blur())}});s.value=r,i.appendChild(s);const l=oe.el("div",{className:"text-content-actions"});return l.appendChild(oe.el("button",{type:"button",className:"btn btn-text",disabled:n?"disabled":void 0,"data-testid":"v2-text-cancel",onClick:()=>{r=t==null?"":String(t),s.value=r}},"Cancel")),l.appendChild(oe.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(l),i}_controlGrid(a){const t=oe.el("div",{className:"text-control-grid"});for(const n of a)t.appendChild(n);return t}_effectSection(a,t){return oe.el("div",{className:"text-effect-section"},oe.el("div",{className:"text-effect-title"},a),this._controlGrid(t))}_selectField({label:a,testId:t,value:n,options:i,disabled:r,onChange:s}){const l=oe.el("select",{className:"select-input",disabled:r?"disabled":void 0,"data-testid":t,onChange:d=>s(d.target.value)});for(const d of i)l.appendChild(oe.el("option",{value:d.value,selected:String(n)===String(d.value)?"selected":void 0},d.label));return this._field(a,l)}_numberField({label:a,testId:t,value:n,min:i,max:r,step:s,disabled:l,onInput:d}){const c=oe.el("input",{type:"number",className:"text-number-input",min:String(i),max:String(r),step:String(s),value:String(n),disabled:l?"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 s=oe.el("input",{type:"color",className:"color-input",value:n,disabled:i?"disabled":void 0,"data-testid":t,onInput:l=>r(l.target.value)});return this._field(a,s)}_checkboxField({label:a,testId:t,checked:n,disabled:i,onChange:r}){const s=oe.el("input",{type:"checkbox",className:"text-checkbox-input",checked:n?"checked":void 0,disabled:i?"disabled":void 0,"data-testid":t,onChange:l=>r(l.target.checked===!0)});return oe.el("label",{className:"text-field text-checkbox-field"},oe.el("span",{className:"text-field-label"},a),s)}_field(a,t){return oe.el("label",{className:"text-field"},oe.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:{...or.stroke,...t.stroke&&typeof t.stroke=="object"?t.stroke:{}},shadow:{...or.shadow,...t.shadow&&typeof t.shadow=="object"?t.shadow:{}},glow:{...or.glow,...t.glow&&typeof t.glow=="object"?t.glow:{}},backdrop:{...or.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 Th{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=oe.el("div",{className:"drawer-nav","data-testid":"v2-mobile-nav"}),this._headerEl=oe.el("div",{className:"drawer-nav-header"}),this.element.appendChild(this._headerEl),this._bodyEl=oe.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 Ju(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 qu(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 Yu(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 Qu(this.state,this.editor),this._backgroundPanelEl=this._backgroundPanel.render(),this._layerStackPanel=new em(this.state,this.editor),this._layerStackPanelEl=this._layerStackPanel.render(),this._textPanel=new tm(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=oe.el("button",{type:"button",className:"drawer-back-btn","aria-label":"Go back","data-testid":"v2-drawer-back",onClick:()=>this._goBack()});n.innerHTML=oe.chevronLeft,this._headerEl.appendChild(n)}const t=this._titleForView(this._view);if(this._headerEl.appendChild(oe.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(oe.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=oe.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,s,l;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(),(s=this._textPanel)==null||s.destroy(),(l=this.element)==null||l.remove(),this.element=null}}class Bh{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=oe.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=oe.el("div",{className:"mobile-active-track"}),i=this.state.get("selectedFilter"),r=this._activeFilterLayerId();for(const s of a){const l=this.filterManager.getFilterDef(s);l&&n.appendChild(this._renderChip(l,s===i,r))}this.element.appendChild(n)}_renderChip(a,t,n=null){const i=oe.el("div",{className:`mobile-active-chip ${t?"selected":""}`,"data-filter":a.id,"data-testid":`v2-mobile-chip-${a.id}`});i.appendChild(oe.el("button",{type:"button",className:"mobile-active-chip-name","aria-label":`Edit ${a.name}`,onClick:()=>{var s;return(s=this._onSelect)==null?void 0:s.call(this,a.id,n)}},a.name));const r=oe.el("button",{type:"button",className:"mobile-active-chip-remove","aria-label":`Remove ${a.name}`,"data-testid":`v2-mobile-chip-remove-${a.id}`,onClick:s=>{var l;s.stopPropagation(),(l=this._onRemove)==null||l.call(this,a.id,n)}});return r.innerHTML=oe.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 ic="(max-width: 900px)";let Mh=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=oe.el("div",{className:"editor-v2-body"}),this.canvasSection=oe.el("div",{className:"editor-v2-canvas"}),this.canvasContainer=oe.el("div",{className:"canvas-container"}),this.cropOverlay=oe.el("canvas",{className:"crop-overlay","aria-hidden":"true"}),this.canvasSection.appendChild(this.canvasContainer),this.canvasSection.appendChild(this.cropOverlay),this.root.appendChild(this.canvasSection),this._isMobile=typeof window<"u"&&((t=window.matchMedia)==null?void 0:t.call(window,ic).matches)===!0,this._isMobile?this._buildMobileShell():this._buildDesktopShell(),typeof window<"u"&&window.matchMedia&&(this._mql=window.matchMedia(ic),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=oe.el("div",{className:"editor-v2-panel","data-testid":"v2-inspector-panel"}),this._categoryTabs=new Ju(this.state,this.editor),this._panel.appendChild(this._categoryTabs.render({onSelect:()=>this._handleDesktopCategoryChange()}));const a=oe.el("div",{className:"panel-body"});this._desktopFilterListSection=oe.el("div",{className:"panel-section"}),this._desktopFilterListSection.appendChild(oe.el("div",{className:"panel-section-title"},oe.el("span",{},"Filters"))),this._filterListView=new qu(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 Yu(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=oe.el("div",{className:"crop-controls-wrapper",style:{display:"none"}}),a.appendChild(this._desktopCropWrapper),this._activeStack=new Eh(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=oe.el("div",{className:"panel-section",style:{display:"none"}}),this._backgroundPanel=new Qu(this.state,this.editor),this._desktopBackgroundSection.appendChild(this._backgroundPanel.render()),a.appendChild(this._desktopBackgroundSection),this._desktopLayerSection=oe.el("div",{className:"panel-section",style:{display:"none"}}),this._layerStackPanel=new em(this.state,this.editor),this._desktopLayerSection.appendChild(this._layerStackPanel.render()),a.appendChild(this._desktopLayerSection),this._desktopTextSection=oe.el("div",{className:"panel-section",style:{display:"none"}}),this._textPanel=new tm(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 Bh(this.state,this.filterManager);const a=this._mobileChips.render({onSelect:(r,s)=>{var l,d;this._callbacks.onFilterSelect(r,s),(l=this._mobileDrawer)==null||l.snapTo("full"),(d=this._mobileNav)==null||d.navigateTo("controls")},onRemove:(r,s)=>this._callbacks.onFilterToggle(r,!1,s)});this.root.appendChild(a),this._mobileDrawer=new Sh({onSnapChange:r=>{this.canvasContainer&&window.dispatchEvent(new Event("resize"))}}),this._mobileNav=new Th(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 s;r==="controls"&&((s=this._mobileDrawer)==null?void 0:s.snap)==="collapsed"&&this._mobileDrawer.snapTo("half")}});this._mobileCropWrapper=oe.el("div",{className:"crop-controls-wrapper",style:{display:"none"}});const n=oe.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,s,l,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,(s=this._layerStackPanel)==null||s.destroy(),this._layerStackPanel=null,(l=this._textPanel)==null||l.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 l,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",s=n||i||r;this._desktopFilterListSection&&(this._desktopFilterListSection.style.display=t||s?"none":""),(l=this._filterControlsView)!=null&&l.element&&(this._filterControlsView.element.style.display=t||s?"none":""),(d=this._activeStack)!=null&&d.element&&(this._activeStack.element.style.display=t||s?"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")}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 Vo(o){if(!Number.isFinite(Number(o)))return 0;const a=Number(o)%360;return a<0?a+360:a}function Ih(o,a){const t=Vo(o);return(Vo(a)-t+540)%360-180}function $h(){return new Date().toISOString()}function ir(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 Fh extends oe.EventEmitter{constructor(a,t={}){var r,s,l,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?oe.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=oe.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 oe.PixiRenderer,this._filterManager=new oe.FilterManager(this._state,this._renderer),this._cropManager=new oe.CropManager(this._state,this._renderer),this._removeBgManager=null,this._backgroundRemovalAvailable=!1,((r=this._options.backgroundRemoval)==null?void 0:r.enabled)!==!1&&(this._removeBgManager=new oe.RemoveBgManager({endpoint:(s=this._options.backgroundRemoval)==null?void 0:s.endpoint,optionsEndpoint:(l=this._options.backgroundRemoval)==null?void 0:l.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._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=oe.el("div",{className:`vanilla-image-editor-v2 ${this._state.get("isDarkMode")?"dark":"light"}`}),this._toolbarContainer=oe.el("div",{className:"editor-v2-toolbar"}),this._editorEl.appendChild(this._toolbarContainer),this._layout=new Mh(this._state,this._filterManager,this);const{root:a,canvasContainer:t,cropOverlay:n}=this._layout.build({onFilterToggle:(i,r,s)=>this._handleFilterToggle(i,r,s),onFilterSelect:(i,r)=>this._handleFilterSelect(i,r),onFilterChange:(i,r,s,l)=>this._handleFilterChange(i,r,s,l),onFilterReset:(i,r)=>this._handleFilterReset(i,r),onFilterAction:(i,r,s)=>this._handleFilterAction(i,r,s),onClearAll:i=>this.resetAll(i)});this._canvasContainer=t,this._cropOverlay=n,this._editorEl.appendChild(a),this._fileInput=oe.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 oe.Toolbar(this._state,this),this._toolbarContainer.appendChild(this._toolbar.render()),this._cropControls=new oe.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 s=oe.REGISTRY_TO_UI[i.category]||i.category;this._state.get("selectedCategory")!==s&&this._state.set("selectedCategory",s)}}_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 s=this._captureEditorDocumentContext(),l=await this._probeImageDimensions(n);if(!this._isCurrentEditorDocumentContext(s))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:l.width,originalHeight:l.height,sourceHash:null,previewUrl:n}),this._isCurrentEditorDocumentContext(u)?this.setBackgroundMediaSource(c,{fit:t.fit||"cover"}):(URL.revokeObjectURL(n),this._objectUrls.delete(n),null)}catch(s){throw URL.revokeObjectURL(n),this._objectUrls.delete(n),s}}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,s;const a=(s=(r=this._options)==null?void 0:r.backgroundReplacement)==null?void 0:s.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 s=this._resolveBackgroundEndpoint(n,r);if(!s)return!1;const l=this._captureDocumentMaterializationContext(r,i,t),d=ir(i.documentId)?i.documentId:null,c=await fetch(s,{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(l)?(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 p,h,v;const i=(h=(p=this._options)==null?void 0:p.backgroundReplacement)==null?void 0:h.assetEndpoint,r=this._state.getEditorDocumentBinding(),s=this._state.getSerializableDocument();if(!i||!(r!=null&&r.documentId)||!s)return null;const l=this._resolveBackgroundEndpoint(i,s);if(!l)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(l,{method:"POST",credentials:"include",headers:{Accept:"application/json"},body:c});if(!u.ok)throw new Error("Background upload failed");const m=await u.json(),f=(v=m==null?void 0:m.asset)==null?void 0:v.source;if(!f||typeof f!="object")throw new Error("Background upload did not return a usable layer source");return{...f,previewUrl:n}}_backgroundMaterializeEndpoint(){var i,r,s,l,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=(l=(s=this._options)==null?void 0:s.backgroundReplacement)==null?void 0:l.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,s;const t=await a.arrayBuffer(),n=await((s=(r=(i=globalThis.crypto)==null?void 0:i.subtle)==null?void 0:r.digest)==null?void 0:s.call(r,"SHA-256",t));if(!n)throw new Error("Background upload hashing is unavailable");return Array.from(new Uint8Array(n)).map(l=>l.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 l,d,c,u;if(this._destroyed)return;(d=(l=this._removeBgManager)==null?void 0:l.cancelActiveRequests)==null||d.call(l,"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 s=await this._renderer.loadTexture(i,{isCurrent:()=>!this._destroyed&&this._loadVersion===n});if(this._destroyed||this._loadVersion!==n){this._revokeObjectUrl(r);return}if(!s){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??(ir((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,f;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=$h(),s=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,l=s?{kind:"media",mediaUuid:s,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:s,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:l,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}),(f=(m=this._renderer).renderLayerDocument)==null||f.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??(ir(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=Vo(((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[s,l]of Object.entries(r.values))this._state.setFilterValue(r.id,s,l);if(i!==null){this._state.set("selectedFilter",i);const r=this._filterManager.getFilterDef(i);if(typeof(r==null?void 0:r.category)=="string"){const s=oe.REGISTRY_TO_UI[r.category]??r.category;this._state.set("selectedCategory",s)}}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)??(ir(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 s of a){const l=this._state.getFilterValues(s);t.push({id:s,enabled:!0,values:{...l}})}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:Vo(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=Vo(this._state.get("transform.rotation")??0),n=Vo(a),i=Ih(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,s,l,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 f=this._activeBackgroundRemovalLayer();if(this._hasSavedEditorDocumentBinding()&&f!==null&&this._backgroundMaterializeEndpoint()&&!await this._materializeCurrentDocument("Background removal materialization failed"))return this.emit("background-removal-stale",{operationId:a.operationId??null,targetLayerId:f.id}),{stale:!0};const p=this._buildSavedBackgroundRemovalContext(a);if(p){const b=await this._removeBgManager.removeSavedMediaBackground(p.request);if(!this._isCurrentBackgroundRemovalContext(p,b))return this.emit("background-removal-stale",{operationId:p.request.operationId,targetLayerId:p.request.targetLayerId}),{stale:!0};const R=(t=b==null?void 0:b.result)==null?void 0:t.source;if(!R||R.kind!=="edit-asset")throw new Error("Background removal did not return a persisted layer source");const N=(n=b==null?void 0:b.result)==null?void 0:n.previewDataUrl;return typeof N=="string"&&N.startsWith("data:image/")&&(!await this._renderer.loadTexture(N,{isCurrent:()=>!this._destroyed&&this._isCurrentBackgroundRemovalContext(p,b)})||!this._isCurrentBackgroundRemovalContext(p,b))?(this.emit("background-removal-stale",{operationId:p.request.operationId,targetLayerId:p.request.targetLayerId}),{stale:!0}):this._isCurrentBackgroundRemovalContext(p,b)?(this._state.replaceLayerSource(p.request.targetLayerId,R),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:(s=b==null?void 0:b.result)==null?void 0:s.model,processMs:(l=b==null?void 0:b.result)==null?void 0:l.process_ms,source:R,operationId:p.request.operationId,targetLayerId:p.request.targetLayerId}),{model:(d=b==null?void 0:b.result)==null?void 0:d.model,processMs:(c=b==null?void 0:b.result)==null?void 0:c.process_ms,source:R}):(this.emit("background-removal-stale",{operationId:p.request.operationId,targetLayerId:p.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),E=await this._removeBgManager.preparePreviewRequest(h.imageData,h.options),y=this._resolvePreviewBackgroundRemovalContext(v,E);if(!await this._isCurrentPreviewBackgroundRemovalContext(y))return this.emit("background-removal-stale",{operationId:y.operationId,sourceHash:y.sourceHash,targetLayerId:y.activeLayerId??null}),{stale:!0};const k=await this._removeBgManager.removeBackground(E.blob,E);if(!await this._isCurrentPreviewBackgroundRemovalContext(y,k))return this.emit("background-removal-stale",{operationId:y.operationId,sourceHash:y.sourceHash}),{stale:!0};const g=await this._applyPreviewBackgroundRemovalResult(y,k);return g?(this.emit("background-removed",{model:k.model,processMs:k.processMs,operationId:y.operationId,targetLayerId:y.activeLayerId??null,source:g.source}),{model:k.model,processMs:k.processMs,...g.source?{source:g.source}:{}}):(this.emit("background-removal-stale",{operationId:y.operationId,sourceHash:y.sourceHash,targetLayerId:y.activeLayerId??null}),{stale:!0})}catch(f){throw this.emit("error",{error:f,context:"background-removal"}),f}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 s;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=(s=i==null?void 0:i.source)==null?void 0:s.sourceHash;return t&&(typeof r!="string"||!/^[a-f0-9]{64}$/i.test(r))?null:i}_buildSavedBackgroundRemovalContext(a={}){var u,m,f,p,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}),s=r==null?void 0:r.id,l=(u=r==null?void 0:r.source)==null?void 0:u.sourceHash;if(!s||typeof l!="string"||!/^[a-f0-9]{64}$/i.test(l))return null;const d=a.operationId||((f=(m=globalThis.crypto)==null?void 0:m.randomUUID)==null?void 0:f.call(m))||`op-${Date.now()}-${Math.random().toString(16).slice(2)}`,c={loadVersion:this._loadVersion,activeLayerId:s,documentRevisionId:n.documentRevisionId,documentSignature:this._documentMaterializationSignature(t),sourceHash:l,request:{targetMediaUuid:i,operationId:d,documentId:n.documentId,documentRevisionId:n.documentRevisionId,targetLayerId:s,expectedSourceHash:l,tier:a.tier||((h=(p=this._options)==null?void 0:p.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,s;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((s=(r=this._renderer).renderLayerDocument)==null?void 0:s.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 s;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||((s=r==null?void 0:r.source)==null?void 0:s.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=oe.el("div",{className:"editor-loading-overlay"},oe.el("div",{className:"editor-loading-spinner"}),oe.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()}destroy(){var a,t,n,i,r,s,l;this._destroyed=!0,(t=(a=this._removeBgManager)==null?void 0:a.cancelActiveRequests)==null||t.call(a,"editor-destroy");for(const d of this._objectUrls)try{URL.revokeObjectURL(d)}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(),(s=this._layout)==null||s.destroy(),(l=this._editorEl)==null||l.remove(),this._container=null,this._state=null,this.emit("destroyed"),this.removeAllListeners()}}function Dh(o,a){try{let t=oe.getFilter(o);if(t||(oe.registerCorePixiFilters(),t=oe.getFilter(o)),!t){try{const r=oe.getAllFilters()}catch{}return null}const n={...t.defaultParams,...a};return t.createFilter(n)}catch{return null}}const Rh=78e5,Ah=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,s=null;function l(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,E,y;try{if(!r){n("error",new Error("Editor not initialized"));return}const k=await((v=r.exportBlob)==null?void 0:v.call(r,"png",.92,{maxPixels:Rh}));if(!k){n("error",new Error("Failed to export image — the image could not be processed"));return}const g=r.getSerializableState(),b={blob:k.blob,mimeType:k.blob.type||"image/png",dimensions:{width:k.width,height:k.height},state:g},R=((E=r.getSerializableDocument)==null?void 0:E.call(r))??null;if(R){const N=((y=r.getEditorDocumentBinding)==null?void 0:y.call(r))??null;b.document=R,b.documentId=(N==null?void 0:N.documentId)??(l(R.id)?R.id:null),b.documentRevisionId=(N==null?void 0:N.documentRevisionId)??null,b.documentRevisionNumber=(N==null?void 0:N.documentRevisionNumber)??R.revision??null}n("save",b)}catch(k){n("error",k instanceof Error?k: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 E=v.error;if(E instanceof Error)return E;if(typeof E=="string"&&E.trim()!=="")return new Error(E)}return typeof v=="string"&&v.trim()!==""?new Error(v):new Error("Failed to load image")}function f(v){n("error",m(v))}function p(){if(!i.value||r)return;window.PIXI=Gt,oe.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 E=t.editorVersion==="v2"?Fh:oe.VanillaImageEditor,y=new E(i.value,v);r=y,y.setFilterRegistry({getAllFilters:oe.getAllFilters,getFilter:oe.getFilter,getFiltersByCategory:oe.getFiltersByCategory}),y.save=function(){c()},y.on("cancel",u),y.on("error",f),t.initialImage&&y.loadImage(t.initialImage,d())}e.onMounted(()=>{i.value&&(i.value.clientWidth>0?p():(s=new ResizeObserver(v=>{const E=v[0];E&&E.contentRect.width>0&&!r&&(p(),s==null||s.disconnect(),s=null)}),s.observe(i.value)))});const h=()=>{!r||!t.initialImage||r.loadImage(t.initialImage,d())};return e.watch(()=>t.initialImage,(v,E)=>{!r||!v||v===E||h()}),e.watch(()=>t.sessionKey,(v,E)=>{v!==E&&h()}),e.watch(()=>t.initialState,(v,E)=>{v!==E&&h()}),e.watch(()=>[t.initialDocument,t.initialDocumentId,t.initialDocumentRevisionId,t.initialDocumentRevisionNumber],(v,E)=>{v!==E&&h()}),e.onUnmounted(()=>{s==null||s.disconnect(),s=null,r&&(r.destroy(),r=null)}),(v,E)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"containerRef",ref:i,class:"vanilla-editor-wrapper","data-testid":"vanilla-image-editor"},null,512))}}),Fe=(o,a)=>{const t=o.__vccOpts||o;for(const[n,i]of a)t[n]=i;return t},am=Fe(Ah,[["__scopeId","data-v-8ab74f83"]]),Lh={class:"editor-modal-panel"},Ph={class:"editor-fill"},Uh=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),s=e.ref(!1),l=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&&(l.value=document.activeElement,c())},{immediate:!0});const u=async v=>{try{if(s.value=!0,t.saveHandler){await t.saveHandler(v);return}n("save",v)}catch(E){d(E instanceof Error?E:new Error("Failed to save image"))}finally{s.value=!1}},m=()=>{n("cancel"),p()},f=()=>{s.value||p()},p=()=>{r.value=!1,n("update:modelValue",!1),l.value&&l.value instanceof HTMLElement&&(l.value.focus(),l.value=null)},h=v=>{if(v.key==="Escape"&&r.value&&!s.value){p();return}if(v.key==="Tab"&&r.value&&i.value){const E=i.value.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])');if(E.length===0)return;const y=E[0],k=E[E.length-1];v.shiftKey&&document.activeElement===y?(v.preventDefault(),k.focus()):!v.shiftKey&&document.activeElement===k&&(v.preventDefault(),y.focus())}};return e.onMounted(()=>{document.addEventListener("keydown",h)}),e.onBeforeUnmount(()=>{document.removeEventListener("keydown",h)}),(v,E)=>(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(f,["escape"])},[e.createElementVNode("div",{class:"editor-modal-backdrop",onClick:f}),e.createElementVNode("div",Lh,[e.createElementVNode("div",Ph,[e.createVNode(am,{"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)]))}}),nm=Fe(Uh,[["__scopeId","data-v-bd4e671f"]]),Oh={class:"media-workspace"},zh={class:"media-workspace-toolbar"},jh={class:"media-workspace-label"},Wh=["value"],Hh={class:"media-workspace-grid"},Zh=["onClick"],Gh=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=xa(),r=e.ref(t.initialScopeId??((m=t.subScopes[0])==null?void 0:m.id)??""),s=e.computed(()=>t.subScopes),l=e.computed(()=>s.value.find(f=>f.id===r.value));let d=null;function c(){d&&(d(),d=null),t.apiScope&&(d=Xu({apiScope:t.apiScope,isAdmin:t.apiScope==="admin"}))}async function u(){var p;const f={};(p=l.value)!=null&&p.collection&&(f.collection=l.value.collection),await i.fetchMedia(1,f),n("update:media",[...i.items])}return e.watch(()=>t.initialScopeId,f=>{f&&f!==r.value&&(r.value=f)}),e.watch(()=>t.subScopes,f=>{if(f.length===0){r.value="";return}f.some(p=>p.id===r.value)||(r.value=f[0].id)},{deep:!0}),e.watch(()=>t.apiScope,()=>{c(),u()}),e.watch(r,f=>{f&&(n("scope-change",f),u())}),e.onMounted(()=>{c(),u()}),e.onUnmounted(()=>{d&&(d(),d=null)}),(f,p)=>(e.openBlock(),e.createElementBlock("div",Oh,[e.createElementVNode("div",zh,[e.createElementVNode("label",jh,[p[2]||(p[2]=e.createElementVNode("span",{class:"media-workspace-label-text"},"Scope",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":p[0]||(p[0]=h=>r.value=h),"data-testid":"scope-select",class:"media-workspace-select"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(s.value,h=>(e.openBlock(),e.createElementBlock("option",{key:h.id,value:h.id},e.toDisplayString(h.label),9,Wh))),128))],512),[[e.vModelSelect,r.value]])]),e.createElementVNode("button",{type:"button",class:"media-workspace-upload","data-testid":"upload-button",onClick:p[1]||(p[1]=h=>n("upload"))}," Upload ")]),e.createElementVNode("div",Hh,[(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,Zh))),128))])]))}}),Xh=Fe(Gh,[["__scopeId","data-v-895f26fe"]]),Kh={class:"managed-media-gallery"},Jh={class:"gallery-grid"},qh=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",Kh,[e.createElementVNode("div",Jh,[e.renderSlot(a.$slots,"default",{},void 0,!0)])]))}}),Yh=Fe(qh,[["__scopeId","data-v-10a9b8c5"]]),wr="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>",Yl="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>",Qh="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>",Ql="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>",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' stroke-width='48' d='M244 400L100 256l144-144M120 256h292' class='ionicon-fill-none'/></svg>",tv="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>",rc="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>",sc="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>",ci="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>",av="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>",om="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>",im="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>",lc="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>",nv="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>",ov="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>",dc="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>",Yn="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>",cc="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>",iv="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>",Cn="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>",rv="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>",ti="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>",cl="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>",sv="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>",uc="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>",$r="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>",$o="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>",lv="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>",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='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>",cv="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>",uv="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>",ui="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>",mc="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>",Us="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>",mv="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>",pv="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>",Os="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>",fv="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>",hv="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>",vv="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>",gv="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>",rm="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>",ed="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>",bv="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>",yv="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>",wv="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>",kv="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>",sm="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>",_v="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>",Ev="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>",td="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>",Sv="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>",Cv="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>",io="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>",xv="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>",Vv="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>",pc="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>",Qr="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>",Nv="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>",zs="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>",Sn="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>",ai="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>",fc="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>",Tv="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>",lm="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>",Fr="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>",dm="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>",Bv="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>",Mv="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>",Iv="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>",$v="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>",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-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>",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-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>",Rv="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>",rr="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 hc=()=>{};function Av(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 Lv(o,a={}){let t,n,i=hc;const r=d=>{clearTimeout(d),i(),i=hc};let s;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,f)=>{i=a.rejectOnCancel?f:m,s=d,u&&!n&&(n=setTimeout(()=>{t&&r(t),n=null,m(s())},u)),t=setTimeout(()=>{n&&r(n),n=null,m(d())},c)})}}function Pv(o,a=200,t={}){return Av(Lv(a,t),o)}const ni=new Map;function Uv(o){const a=e.getCurrentScope();function t(l){var d;const c=ni.get(o)||new Set;c.add(l),ni.set(o,c);const u=()=>i(l);return(d=a==null?void 0:a.cleanups)==null||d.push(u),u}function n(l){function d(...c){i(d),l(...c)}return t(d)}function i(l){const d=ni.get(o);d&&(d.delete(l),d.size||r())}function r(){ni.delete(o)}function s(l,d){var c;(c=ni.get(o))==null||c.forEach(u=>u(l,d))}return{on:t,once:n,off:i,emit:s,reset:r}}function cm(){var r,s;const o=typeof window<"u"&&"Capacitor"in window&&((s=(r=window.Capacitor)==null?void 0:r.isNativePlatform)==null?void 0:s.call(r));return{selection:()=>{var l,d;if(o)try{const c=(d=(l=window.Capacitor)==null?void 0:l.Plugins)==null?void 0:d.Haptics;c&&c.impact({style:"LIGHT"})}catch{}else"vibrate"in navigator&&navigator.vibrate(10)},success:()=>{var l,d;if(o)try{const c=(d=(l=window.Capacitor)==null?void 0:l.Plugins)==null?void 0:d.Haptics;c&&c.impact({style:"MEDIUM"})}catch{}else"vibrate"in navigator&&navigator.vibrate(30)},error:()=>{var l,d;if(o)try{const c=(d=(l=window.Capacitor)==null?void 0:l.Plugins)==null?void 0:d.Haptics;c&&c.impact({style:"HEAVY"})}catch{}else"vibrate"in navigator&&navigator.vibrate([50,50,50])},notification:()=>{var l,d;if(o)try{const c=(d=(l=window.Capacitor)==null?void 0:l.Plugins)==null?void 0:d.Haptics;c&&c.notification({type:"SUCCESS"})}catch{}else"vibrate"in navigator&&navigator.vibrate([20,100,20])}}}function es(o,a={}){const t=e.ref(new Set),n=e.ref(new Map),i=e.ref(null),r=e.ref(-1),s=e.ref(a.scopeKey!==void 0?e.toValue(a.scopeKey):"default"),l=e.ref(!1),d=e.ref(null),c=Uv("media-selection"),u=cm(),m=()=>{if(a.currentPage===void 0)return null;const z=e.toValue(a.currentPage);return typeof z=="number"&&Number.isFinite(z)?z:null};function f(z){t.value=z,n.value=new Map(Array.from(n.value.entries()).filter(([K])=>z.has(K)))}function p(z){if(n.value.has(z))return;const K=new Map(n.value);K.set(z,{uuid:z,selectedAt:Date.now(),page:m()}),n.value=K}const h=e.computed(()=>o.value.filter(z=>t.value.has(z.uuid))),v=e.computed(()=>t.value.size),E=e.computed(()=>Array.from(n.value.values()).sort((z,K)=>z.selectedAt-K.selectedAt).map(z=>z.uuid)),y=e.computed(()=>Math.max(0,v.value-h.value.length)),k=e.computed(()=>{const z=new Map;for(const K of n.value.values())K.page!==null&&z.set(K.page,(z.get(K.page)??0)+1);return z});e.watch(t,z=>{c.emit({type:"selection:changed",count:z.size,selectedIds:Array.from(z)})}),a.scopeKey!==void 0&&e.watch(()=>e.toValue(a.scopeKey),(z,K)=>{z!==void 0&&z!==K&&O(z)});const g=e.computed(()=>o.value.length>0&&o.value.every(z=>t.value.has(z.uuid))),b=e.computed(()=>o.value.some(z=>t.value.has(z.uuid)));function R(z){return t.value.has(z)}function N(z){const K=new Set(t.value),se=K.size===0;K.add(z),p(z),t.value=K,i.value=z,r.value=o.value.findIndex(Be=>Be.uuid===z),se&&u.selection()}function T(z){const K=new Set(t.value);K.delete(z);const se=new Map(n.value);se.delete(z),n.value=se,t.value=K,i.value===z&&(i.value=null,r.value=-1)}function S(z){if(t.value.has(z)){T(z);return}N(z)}function B(){const z=new Set(t.value);for(const K of o.value)z.add(K.uuid),p(K.uuid);t.value=z}function A(){t.value=new Set,n.value=new Map,i.value=null,r.value=-1,l.value=!1,d.value=null}function x(){if(g.value){A();return}B()}function M(z,K){const se=o.value.findIndex(Be=>Be.uuid===z);if(se!==-1){if(K!=null&&K.shiftKey&&r.value!==-1){const Be=Math.min(r.value,se),ce=Math.max(r.value,se),ie=new Set(t.value);for(let W=Be;W<=ce;W++){const C=o.value[W];C!==void 0&&(ie.add(C.uuid),p(C.uuid))}t.value=ie;return}S(z)}}function w(){if(o.value.length===0)return;let z=r.value+1;z>=o.value.length&&(z=0),A();const K=o.value[z];K!==void 0&&N(K.uuid)}function F(){if(o.value.length===0)return;let z=r.value-1;z<0&&(z=o.value.length-1),A();const K=o.value[z];K!==void 0&&N(K.uuid)}function P(z){switch(z.key){case"ArrowDown":z.preventDefault(),w();break;case"ArrowUp":z.preventDefault(),F();break;case"a":(z.ctrlKey||z.metaKey)&&(z.preventDefault(),B());break;case"Escape":z.preventDefault(),A();break;case" ":i.value&&(z.preventDefault(),S(i.value));break}}async function D(z){var se;if(v.value===0||s.value===z)return!0;const K=(se=a.confirmScopeChange)==null?void 0:se.call(a,{from:s.value,to:z,selectedCount:v.value});return K===void 0?!0:await K}async function O(z){return s.value===z?!0:await D(z)?(s.value=z,A(),!0):!1}async function I(){if(!a.fetchMatchingUuids){const K={uuids:o.value.map(se=>se.uuid),overCap:!1,totalMatching:o.value.length};return Z(K),K}const z=await a.fetchMatchingUuids();return Z(z),z}function Z(z){const K=new Set(z.uuids),se=new Map,Be=Date.now();z.uuids.forEach((ce,ie)=>{se.set(ce,{uuid:ce,selectedAt:Be+ie,page:m()})}),f(K),n.value=se,l.value=z.overCap,d.value=z.totalMatching}return{selectedIds:e.computed(()=>t.value),selectedRecords:e.computed(()=>n.value),selectedItems:h,selectedCount:v,orderedIds:E,crossPageCount:y,selectedPages:k,overCap:e.computed(()=>l.value),totalMatching:e.computed(()=>d.value),activeScopeKey:e.computed(()=>s.value),isAllSelected:g,isSomeSelected:b,lastSelectedId:e.computed(()=>i.value),isSelected:R,toggle:S,select:N,deselect:T,selectAll:B,clear:A,toggleAll:x,rangeSelect:M,selectAcrossAllPages:I,setScopeKey:O,canChangeScope:D,selectNext:w,selectPrevious:F,handleKeydown:P,selectionBus:c}}const Ov={class:"flex items-center justify-between w-full px-4"},zv={class:"p-4"},jv={key:0,class:"mb-4 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg"},Wv={class:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"},Hv=["value"],Zv={class:"flex gap-2 mt-4"},Gv={class:"flex justify-end mb-4"},Xv={key:1,class:"flex justify-center items-center h-64"},Kv={key:2,class:"flex flex-col items-center justify-center h-64 text-center"},Jv={class:"text-sm text-theme-secondary"},qv={key:0},Yv={class:"mb-4"},Qv={class:"mb-4"},eg={class:"flex gap-2"},tg={class:"flex items-center justify-between px-4 py-2"},ag={class:"text-sm text-theme-secondary"},ng={key:0},og={key:0},ig={key:1},rg={class:"flex gap-2"},sg=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"),s=e.ref(""),l=e.ref(!1),d=e.ref([]),{selectedItems:c}=e.toRefs(t),u=e.ref(new Set(c.value)),m=e.ref(!1),f=e.ref({}),p=e.ref(["images","documents","videos"]),h=e.ref(1),v=e.ref(!0),E=e.ref(!1),y=Ku(),k=es(d);function g(W){var be;const C=W.conversion_urls||{},U=W.proxy_url||W.original_url||W.url||"",j=C.thumb||C.preview||W.preview_url||W.thumbnail_url||U,ne=W.custom_properties||{},de=ne.width,Ke=ne.height;return{...W,uuid:W.uuid,name:W.name||W.file_name,file_name:W.file_name,filename:W.file_name,mime_type:W.mime_type,size:W.size,collection_name:W.collection_name||"images",disk:W.disk,original_url:U,url:U,thumbnail_url:j,conversions:W.conversions||{},conversion_urls:C,generated_conversions:W.generated_conversions||{},custom_properties:ne,caption:W.caption||null,alt_text:W.alt_text||null,created_at:W.created_at,updated_at:W.updated_at,is_image:((be=W.mime_type)==null?void 0:be.startsWith("image/"))||!1,...typeof de=="number"?{width:de}:{},...typeof Ke=="number"?{height:Ke}:{},...W.formatted_size!==void 0?{formatted_size:W.formatted_size}:{}}}e.watch(()=>t.selectedItems,W=>{u.value=new Set(W),k.clear(),W.forEach(C=>k.select(C))});const b=e.computed(()=>{var C;let W=d.value;return(C=f.value.types)!=null&&C.length&&(W=W.filter(U=>{var ne,de;const j=(ne=U.mime_type)==null?void 0:ne.split("/")[0];return(de=f.value.types)==null?void 0:de.includes(j)})),(f.value.sizeMin!==void 0||f.value.sizeMax!==void 0)&&(W=W.filter(U=>{const j=U.size/1048576;return!(f.value.sizeMin!==void 0&&j<f.value.sizeMin||f.value.sizeMax!==void 0&&j>f.value.sizeMax)})),W}),R=e.computed(()=>{var C;let W=0;return f.value.search&&W++,f.value.collection&&W++,(f.value.dateFrom||f.value.dateTo)&&W++,(C=f.value.types)!=null&&C.length&&(W+=f.value.types.length),(f.value.sizeMin!==void 0||f.value.sizeMax!==void 0)&&W++,W}),N=e.computed(()=>{const W=k.selectedCount.value;return W===0?"Select Media":`Select ${t.selectionMode==="multiple"?`${W} ${W===1?"Item":"Items"}`:"Item"}`}),T=e.computed(()=>{const W=k.selectedCount.value;return!!(W===0||t.selectionMode==="single"&&W>1||t.maxSelection&&W>t.maxSelection)}),S=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(W=!0){W?(l.value=!0,d.value=[],h.value=1,v.value=!0):E.value=!0;try{const C={collection:f.value.collection||t.collection,per_page:24};switch((s.value||f.value.search)&&(C.search=s.value||f.value.search||""),f.value.dateFrom&&(C.from_date=f.value.dateFrom),f.value.dateTo&&(C.to_date=f.value.dateTo),i.value){case"recent":await y.fetchMedia(h.value,C),W?d.value=y.items.map(U=>g(U)):d.value=[...d.value,...y.items.map(U=>g(U))],v.value=y.currentPage<y.totalPages;break;case"model":if(t.modelType&&t.modelId){const U=await y.fetchModelMedia(t.modelType,t.modelId,C.collection,C.search);d.value=U?U.map(j=>g(j)):[],v.value=!1}break;case"library":await y.fetchMedia(h.value,C),W?d.value=y.items.map(U=>g(U)):d.value=[...d.value,...y.items.map(U=>g(U))],v.value=y.currentPage<y.totalPages;break}}catch{}finally{l.value=!1,E.value=!1}}async function A(W){if(!v.value||E.value){W!=null&&W.target&&W.target.complete();return}h.value++,await B(!1),W!=null&&W.target&&(W.target.complete(),v.value||(W.target.disabled=!0))}function x(W){return W==="recent"||W==="model"||W==="library"}function M(W){i.value=W,B()}function w(W){typeof W=="string"&&x(W)&&M(W)}async function F(W){t.selectionMode==="single"?(k.clear(),k.select(W.uuid)):(k.toggle(W.uuid),t.maxSelection&&k.selectedCount.value>t.maxSelection&&(k.deselect(W.uuid),await(await H.toastController.create({message:`Maximum ${t.maxSelection} items can be selected`,duration:2e3,color:"warning"})).present()))}function P(){n("confirm",k.selectedItems.value)}function D(){n("close")}function O(W){}const I=e.ref(null),Z=e.ref(!1);function z(W){I.value=W,Z.value=!0}function K(W){const C=d.value.findIndex(j=>j.uuid===W.uuid);C!==-1&&(d.value[C]=W);const U={};W.alt_text!==void 0&&(U.alt_text=W.alt_text),W.caption!==void 0&&(U.caption=W.caption),W.custom_properties!==void 0&&(U.custom_properties=W.custom_properties),y.updateMedia(W.uuid,U)}function se(){B()}function Be(){f.value={},s.value="",B()}const ce=Pv(()=>{B(!0)},300);e.watch(s,()=>{t.isOpen&&ce()});async function ie(W){try{await(await H.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 y.deleteMedia(W),await B()}}]})).present()}catch{}}return e.watch(()=>t.isOpen,W=>{W&&B()}),e.onMounted(()=>{t.selectedItems.length>0&&t.selectedItems.forEach(W=>k.select(W))}),(W,C)=>{const U=e.resolveComponent("AdminMediaGrid"),j=e.resolveComponent("AdminMediaListItem");return e.openBlock(),e.createBlock(e.unref(H.IonModal),{"is-open":W.isOpen,onDidDismiss:D,"backdrop-dismiss":!1,class:"media-browser-modal"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonHeader),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonToolbar),null,{end:e.withCtx(()=>[e.createVNode(e.unref(H.IonButtons),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButton),{onClick:D},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{name:"close-outline"})]),_:1})]),_:1})]),default:e.withCtx(()=>[e.createVNode(e.unref(H.IonTitle),null,{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(S.value),1)]),_:1})]),_:1}),e.createVNode(e.unref(H.IonToolbar),null,{default:e.withCtx(()=>[e.createElementVNode("div",Ov,[e.createVNode(e.unref(H.IonSegment),{value:i.value,onIonChange:C[0]||(C[0]=ne=>w(ne.detail.value)),class:"max-w-xs"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonSegmentButton),{value:"recent"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...C[15]||(C[15]=[e.createTextVNode("Recent",-1)])]),_:1})]),_:1}),t.modelType&&t.modelId?(e.openBlock(),e.createBlock(e.unref(H.IonSegmentButton),{key:0,value:"model"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...C[16]||(C[16]=[e.createTextVNode("Model",-1)])]),_:1})]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(H.IonSegmentButton),{value:"library"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...C[17]||(C[17]=[e.createTextVNode("Library",-1)])]),_:1})]),_:1})]),_:1},8,["value"]),e.createVNode(e.unref(H.IonButton),{fill:"clear",size:"small",onClick:C[1]||(C[1]=ne=>m.value=!m.value),class:"relative"},{"icon-only":e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{name:"filter-outline"})]),default:e.withCtx(()=>[R.value>0?(e.openBlock(),e.createBlock(e.unref(H.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(R.value),1)]),_:1})):e.createCommentVNode("",!0)]),_:1})])]),_:1})]),_:1}),e.createVNode(e.unref(H.IonContent),null,{default:e.withCtx(()=>[e.createElementVNode("div",zv,[m.value?(e.openBlock(),e.createElementBlock("div",jv,[e.createElementVNode("div",Wv,[e.createElementVNode("div",null,[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...C[18]||(C[18]=[e.createTextVNode("Collection",-1)])]),_:1}),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":C[2]||(C[2]=ne=>f.value.collection=ne),class:"w-full p-2 border rounded"},[C[19]||(C[19]=e.createElementVNode("option",{value:""},"All Collections",-1)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(p.value,ne=>(e.openBlock(),e.createElementBlock("option",{key:ne,value:ne},e.toDisplayString(ne),9,Hv))),128))],512),[[e.vModelSelect,f.value.collection]])]),e.createElementVNode("div",null,[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...C[20]||(C[20]=[e.createTextVNode("From Date",-1)])]),_:1}),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":C[3]||(C[3]=ne=>f.value.dateFrom=ne),type:"date",class:"w-full p-2 border rounded"},null,512),[[e.vModelText,f.value.dateFrom]])]),e.createElementVNode("div",null,[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...C[21]||(C[21]=[e.createTextVNode("To Date",-1)])]),_:1}),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":C[4]||(C[4]=ne=>f.value.dateTo=ne),type:"date",class:"w-full p-2 border rounded"},null,512),[[e.vModelText,f.value.dateTo]])])]),e.createElementVNode("div",Zv,[e.createVNode(e.unref(H.IonButton),{size:"small",onClick:se},{default:e.withCtx(()=>[...C[22]||(C[22]=[e.createTextVNode("Apply",-1)])]),_:1}),e.createVNode(e.unref(H.IonButton),{size:"small",fill:"clear",onClick:Be},{default:e.withCtx(()=>[...C[23]||(C[23]=[e.createTextVNode("Clear",-1)])]),_:1})])])):e.createCommentVNode("",!0),e.createVNode(e.unref(H.IonSearchbar),{modelValue:s.value,"onUpdate:modelValue":C[5]||(C[5]=ne=>s.value=ne),placeholder:"Search media...",debounce:300,class:"mb-4"},null,8,["modelValue"]),e.createElementVNode("div",Gv,[e.createVNode(e.unref(H.IonButtons),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButton),{fill:r.value==="grid"?"solid":"clear",size:"small",onClick:C[6]||(C[6]=ne=>r.value="grid")},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{name:"grid-outline"})]),_:1},8,["fill"]),e.createVNode(e.unref(H.IonButton),{fill:r.value==="list"?"solid":"clear",size:"small",onClick:C[7]||(C[7]=ne=>r.value="list")},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{name:"list-outline"})]),_:1},8,["fill"])]),_:1})]),l.value?(e.openBlock(),e.createElementBlock("div",Xv,[e.createVNode(e.unref(H.IonSpinner),{name:"crescent"})])):b.value.length===0?(e.openBlock(),e.createElementBlock("div",Kv,[e.createVNode(e.unref(H.IonIcon),{name:"images-outline",class:"text-6xl text-theme-secondary mb-4"}),C[24]||(C[24]=e.createElementVNode("h3",{class:"text-lg font-medium text-theme mb-2"}," No Media Found ",-1)),e.createElementVNode("p",Jv,e.toDisplayString(s.value?"Try adjusting your search":"No media items available"),1)])):r.value==="grid"?(e.openBlock(),e.createBlock(U,{key:3,"media-items":b.value,"selected-items":e.unref(k).selectedItems.value,"is-loading":!1,"selection-mode":!0,columns:{mobile:2,sm:3,md:4,lg:5,xl:6},onToggleSelect:F,onPreview:O,onEdit:z,onDelete:ie},null,8,["media-items","selected-items"])):(e.openBlock(),e.createBlock(e.unref(H.IonList),{key:4,lines:"none",class:"rounded-lg overflow-hidden"},{default:e.withCtx(()=>[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(b.value,(ne,de)=>(e.openBlock(),e.createBlock(j,{key:ne.uuid,media:ne,selected:e.unref(k).isSelected(ne.uuid),"selection-mode":!0,index:de,onToggleSelect:F,onPreview:O,onEdit:z,onDelete:ie},null,8,["media","selected","index"]))),128))]),_:1})),!l.value&&b.value.length>0&&i.value!=="model"?(e.openBlock(),e.createBlock(e.unref(H.IonInfiniteScroll),{key:5,threshold:"100px",onIonInfinite:C[8]||(C[8]=ne=>A(ne))},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonInfiniteScrollContent),{"loading-spinner":"crescent","loading-text":"Loading more media..."})]),_:1})):e.createCommentVNode("",!0)])]),_:1}),e.createVNode(e.unref(H.IonModal),{"is-open":Z.value,onDidDismiss:C[14]||(C[14]=ne=>Z.value=!1)},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonHeader),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonToolbar),null,{end:e.withCtx(()=>[e.createVNode(e.unref(H.IonButtons),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButton),{onClick:C[9]||(C[9]=ne=>Z.value=!1)},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{name:"close-outline"})]),_:1})]),_:1})]),default:e.withCtx(()=>[e.createVNode(e.unref(H.IonTitle),null,{default:e.withCtx(()=>[...C[25]||(C[25]=[e.createTextVNode("Edit Media Info",-1)])]),_:1})]),_:1})]),_:1}),e.createVNode(e.unref(H.IonContent),{class:"p-4"},{default:e.withCtx(()=>[I.value?(e.openBlock(),e.createElementBlock("div",qv,[e.createElementVNode("div",Yv,[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...C[26]||(C[26]=[e.createTextVNode("Caption",-1)])]),_:1}),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":C[10]||(C[10]=ne=>I.value.caption=ne),type:"text",class:"w-full p-2 border rounded mt-1",placeholder:"Enter caption..."},null,512),[[e.vModelText,I.value.caption]])]),e.createElementVNode("div",Qv,[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...C[27]||(C[27]=[e.createTextVNode("Alt Text",-1)])]),_:1}),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":C[11]||(C[11]=ne=>I.value.alt_text=ne),type:"text",class:"w-full p-2 border rounded mt-1",placeholder:"Enter alt text..."},null,512),[[e.vModelText,I.value.alt_text]])]),e.createElementVNode("div",eg,[e.createVNode(e.unref(H.IonButton),{onClick:C[12]||(C[12]=ne=>K(I.value))},{default:e.withCtx(()=>[...C[28]||(C[28]=[e.createTextVNode("Save",-1)])]),_:1}),e.createVNode(e.unref(H.IonButton),{fill:"clear",onClick:C[13]||(C[13]=ne=>Z.value=!1)},{default:e.withCtx(()=>[...C[29]||(C[29]=[e.createTextVNode("Cancel",-1)])]),_:1})])])):e.createCommentVNode("",!0)]),_:1})]),_:1},8,["is-open"]),e.createVNode(e.unref(H.IonFooter),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonToolbar),null,{default:e.withCtx(()=>[e.createElementVNode("div",tg,[e.createElementVNode("div",ag,[e.unref(k).selectedCount.value>0?(e.openBlock(),e.createElementBlock("span",ng,[e.createTextVNode(e.toDisplayString(e.unref(k).selectedCount.value)+" selected ",1),t.maxSelection?(e.openBlock(),e.createElementBlock("span",og," / "+e.toDisplayString(t.maxSelection)+" max ",1)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("span",ig," Select "+e.toDisplayString(t.selectionMode==="multiple"?"items":"an item"),1))]),e.createElementVNode("div",rg,[e.createVNode(e.unref(H.IonButton),{fill:"clear",onClick:D},{default:e.withCtx(()=>[...C[30]||(C[30]=[e.createTextVNode(" Cancel ",-1)])]),_:1}),e.createVNode(e.unref(H.IonButton),{disabled:T.value,onClick:P},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(N.value),1)]),_:1},8,["disabled"])])])]),_:1})]),_:1})]),_:1},8,["is-open"])}}}),lg=Fe(sg,[["__scopeId","data-v-9a8c0954"]]),dg={key:1,class:"flex flex-col items-center justify-center py-16"},cg=["draggable","onDragstart","onDragover","onDrop"],ug={key:0,class:"absolute top-2 left-2 z-20"},mg=["checked","onChange"],pg={key:2,class:"absolute top-2 right-2 z-20 opacity-0 group-hover:opacity-100 transition-opacity cursor-move"},fg=["data-media-id"],hg={key:0,class:"w-full h-full flex items-center justify-center"},vg=["src","alt","onError","onLoad"],gg={key:2,class:"w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-700"},bg={class:"text-center"},yg={class:"text-4xl text-gray-400 mb-2"},wg={class:"text-sm font-medium text-gray-500"},kg={class:"absolute inset-0 bg-black/70 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2"},_g=["onClick"],Eg=["onClick"],Sg=["onClick"],Cg={class:"p-3"},xg={class:"text-sm font-medium truncate mb-1"},Vg={class:"text-xs text-gray-600 dark:text-gray-400"},Ng={key:0},Tg={key:0,class:"text-xs text-gray-500 dark:text-gray-500 mt-1 truncate"},Bg=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),s=e.ref(new Set),l=e.ref(null),d=T=>t.selectedItems.some(S=>S.uuid===T.uuid),c=e.computed(()=>{const T=t.columns,S=["grid","gap-4"];switch(T.mobile){case 1:S.push("grid-cols-1");break;case 2:S.push("grid-cols-2");break;case 3:S.push("grid-cols-3");break;case 4:S.push("grid-cols-4");break;default:S.push("grid-cols-2");break}switch(T.sm){case 1:S.push("sm:grid-cols-1");break;case 2:S.push("sm:grid-cols-2");break;case 3:S.push("sm:grid-cols-3");break;case 4:S.push("sm:grid-cols-4");break;case 5:S.push("sm:grid-cols-5");break;default:S.push("sm:grid-cols-3");break}switch(T.md){case 2:S.push("md:grid-cols-2");break;case 3:S.push("md:grid-cols-3");break;case 4:S.push("md:grid-cols-4");break;case 5:S.push("md:grid-cols-5");break;case 6:S.push("md:grid-cols-6");break;default:S.push("md:grid-cols-4");break}switch(T.lg){case 3:S.push("lg:grid-cols-3");break;case 4:S.push("lg:grid-cols-4");break;case 5:S.push("lg:grid-cols-5");break;case 6:S.push("lg:grid-cols-6");break;case 7:S.push("lg:grid-cols-7");break;default:S.push("lg:grid-cols-5");break}switch(T.xl){case 4:S.push("xl:grid-cols-4");break;case 5:S.push("xl:grid-cols-5");break;case 6:S.push("xl:grid-cols-6");break;case 7:S.push("xl:grid-cols-7");break;case 8:S.push("xl:grid-cols-8");break;default:S.push("xl:grid-cols-6");break}return S.join(" ")});function u(T,S,B){t.reorderable&&(i.value=S,T.dataTransfer&&(T.dataTransfer.effectAllowed="move",T.dataTransfer.setData("text/html","")))}function m(T,S){t.reorderable&&(T.preventDefault(),r.value=S)}function f(){r.value=null}function p(T,S){if(!t.reorderable||!i.value)return;T.preventDefault();const B=[...t.mediaItems],A=B.findIndex(x=>{var M;return x.uuid===((M=i.value)==null?void 0:M.uuid)});if(A!==-1&&A!==S&&i.value){const[x]=B.splice(A,1);B.splice(S,0,x),n("reorder",B)}i.value=null,r.value=null}function h(T){return T<1024?T+" B":T<1024*1024?(T/1024).toFixed(1)+" KB":(T/(1024*1024)).toFixed(1)+" MB"}function v(T){var B;return T.thumbnail_url||((B=T.conversion_urls)==null?void 0:B.thumb)||T.original_url||T.url||""}function E(T){var A,x,M;const S=((A=T.mime_type)==null?void 0:A.startsWith("image/"))||!1,B=!!(T.thumbnail_url||(x=T.conversion_urls)!=null&&x.thumb||(M=T.conversion_urls)!=null&&M.preview||T.original_url||T.url);return S&&B}function y(T){var S;return((S=T.split(".").pop())==null?void 0:S.toUpperCase())||""}function k(T){var B;const S=((B=T.mime_type)==null?void 0:B.toLowerCase())||"";return S.startsWith("image/")?"image":S.startsWith("video/")?"videocam":S.startsWith("audio/")?"musical-notes":S.includes("pdf")?"document-text":S.includes("zip")||S.includes("rar")?"archive":S.includes("sheet")||S.includes("excel")?"grid":S.includes("document")||S.includes("word")?"document-text":"document"}e.onMounted(()=>{typeof window<"u"&&"IntersectionObserver"in window&&(l.value=new IntersectionObserver(T=>{T.forEach(S=>{var B;if(S.isIntersecting){const A=S.target.getAttribute("data-media-id");A&&(s.value.add(A),(B=l.value)==null||B.unobserve(S.target))}})},{rootMargin:"50px"}))}),e.onUnmounted(()=>{l.value&&l.value.disconnect()});function g(T){return!0}function b(){l.value&&e.nextTick(()=>{document.querySelectorAll("[data-media-id]").forEach(S=>{var A;const B=S.getAttribute("data-media-id");B&&!s.value.has(B)&&((A=l.value)==null||A.observe(S))})})}e.watch(()=>t.mediaItems,()=>{s.value.clear(),b()},{immediate:!0,deep:!0});function R(T,S){const B=T.target;delete B.dataset.fallbackIndex}function N(T,S){const B=T.target,A=B.closest("[data-media-id]"),x=[S.original_url,S.url,S.thumbnail_url,"preview_url"in S?S.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",A&&!A.querySelector(".media-fallback-icon")){const w=document.createElement("div");w.className="media-fallback-icon w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-800",w.innerHTML=`
|
|
2
|
+
<div class="text-center">
|
|
3
|
+
<div class="text-4xl text-gray-400 mb-2">${k(S)}</div>
|
|
4
|
+
<p class="text-sm font-medium text-gray-500">${y(S.file_name)}</p>
|
|
5
|
+
</div>
|
|
6
|
+
`,A.appendChild(w)}}return(T,S)=>T.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"},[...S[1]||(S[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)):!T.mediaItems||!T.mediaItems.length?(e.openBlock(),e.createElementBlock("div",dg,[S[2]||(S[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)),S[3]||(S[3]=e.createElementVNode("h3",{class:"text-lg font-medium mb-2"}," No Media Items ",-1)),S[4]||(S[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:S[0]||(S[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(T.mediaItems,(B,A)=>(e.openBlock(),e.createElementBlock("div",{key:B.uuid,class:e.normalizeClass(["relative group",{"ring-2 ring-blue-500 ring-offset-2":r.value===A}]),draggable:T.reorderable,onDragstart:x=>u(x,B),onDragover:x=>m(x,A),onDragleave:f,onDrop:x=>p(x,A)},[T.selectionMode?(e.openBlock(),e.createElementBlock("div",ug,[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,mg)])):e.createCommentVNode("",!0),T.$slots.badge?(e.openBlock(),e.createElementBlock("div",{key:1,class:e.normalizeClass(["absolute top-2 z-20",T.selectionMode?"left-10":"left-2"])},[e.renderSlot(T.$slots,"badge",{media:B,index:A},void 0,!0)],2)):e.createCommentVNode("",!0),T.reorderable?(e.openBlock(),e.createElementBlock("div",pg,[...S[5]||(S[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},[E(B)&&!g(B.uuid)?(e.openBlock(),e.createElementBlock("div",hg,[...S[6]||(S[6]=[e.createElementVNode("div",{class:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"},null,-1)])])):e.createCommentVNode("",!0),E(B)&&g(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=>N(x,B),onLoad:x=>R(x)},null,40,vg)):(e.openBlock(),e.createElementBlock("div",gg,[e.createElementVNode("div",bg,[e.createElementVNode("div",yg,e.toDisplayString(k(B)),1),e.createElementVNode("p",wg,e.toDisplayString(y(B.file_name)),1)])])),e.createElementVNode("div",kg,[e.createElementVNode("button",{onClick:x=>n("preview",B),class:"p-2 bg-white/20 text-white rounded hover:bg-white/30",title:"Preview"},[...S[7]||(S[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,_g),T.showEditButton&&E(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"},[...S[8]||(S[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,Eg)):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"},[...S[9]||(S[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,Sg)])],8,fg),e.createElementVNode("div",Cg,[e.createElementVNode("h4",xg,e.toDisplayString(B.file_name),1),e.createElementVNode("p",Vg,[e.createTextVNode(e.toDisplayString(h(B.size))+" ",1),B.width&&B.height?(e.openBlock(),e.createElementBlock("span",Ng," • "+e.toDisplayString(B.width)+"x"+e.toDisplayString(B.height),1)):e.createCommentVNode("",!0)]),B.caption?(e.openBlock(),e.createElementBlock("p",Tg,e.toDisplayString(B.caption),1)):e.createCommentVNode("",!0)])],2)],42,cg))),128))],2))}}),Mg=Fe(Bg,[["__scopeId","data-v-f0c343b7"]]),Ig={class:"model-media-manager"},$g=["accept","multiple"],Fg={class:"flex items-center justify-between mb-4"},Dg={key:0,class:"text-lg font-medium"},Rg={class:"flex gap-2"},Ag={key:0,class:"flex items-center justify-center py-8"},Lg={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"},Pg={class:"text-gray-600 dark:text-gray-400"},Ug={class:"flex gap-2 mt-4"},Og={key:0,class:"px-2 py-1 bg-blue-500 text-white text-xs font-medium rounded"},zg=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=xa(),r=e.ref(!1),s=e.ref(!1),l=e.ref(!1),d=e.ref(!1),c=e.ref(null),u=e.ref(0),m=e.ref(null),f=e.ref(null),p=e.ref(null),h=e.ref(null),v=e.ref(null),E=e.ref(void 0),y=e.ref(null),k=e.ref(null),g=e.computed(()=>{if(t.maxFiles!==void 0)return Math.max(0,t.maxFiles-i.modelMedia.length)}),b=e.computed(()=>i.modelMedia.map(ce=>ce.uuid)),R=e.computed(()=>{if(!(!t.acceptedMimeTypes||t.acceptedMimeTypes.length===0))return t.acceptedMimeTypes.join(",")});function N(){Io({isAdmin:t.mode==="admin"})}async function T(ce){await(await H.toastController.create({message:ce,duration:3e3,color:"danger",position:"bottom"})).present()}async function S(){if(!s.value)if(s.value=!0,N(),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(ce){const ie=ce instanceof Error?ce.message:"Failed to fetch media";n("error",{operation:"fetch",message:ie,details:ce})}finally{r.value=!1,n("loading",!1)}}}e.watch(()=>i.modelMedia,ce=>{s.value&&n("update:media",ce)},{deep:!0}),e.watch(()=>[t.mediableType,t.mediableId,t.collection],()=>{s.value=!1,S()}),e.watch(()=>t.mode,()=>{N()}),e.onMounted(()=>{S()}),e.onUnmounted(()=>{i.clearModelContext()});function B(){return i.modelMedia.length>0}function A(){return t.maxFiles===void 0?!1:i.modelMedia.length>=t.maxFiles}function x(ce){var W,C,U;if(!((W=ce.mime_type)!=null&&W.startsWith("image/")))return null;const ie=ce.original_url||ce.url||((C=ce.conversion_urls)==null?void 0:C.preview)||((U=ce.conversion_urls)==null?void 0:U.thumb)||ce.thumbnail_url;return ie&&ie.trim()!==""?ie:null}function M(){c.value=null,E.value=void 0,m.value=null,f.value=null,p.value=null,h.value=null,v.value=null}function w(){l.value=!0}function F(){var ce;(ce=k.value)==null||ce.click()}function P(){l.value=!1}async function D(ce){if(t.allowEdit&&x(ce)){M(),c.value=ce,u.value++;try{const ie=i.getHttpClient(),W=i.getEditorApiUrl(""),C=await ie(`${W.replace(/\/$/,"")}/editor/${ce.uuid}/edit`);if(!C.editable_source_url)throw new Error("Editor source URL missing from edit context");E.value=C.editable_source_url,m.value=C.editor_state??null,f.value=C.editor_document??null,p.value=C.editor_document_id??null,h.value=C.editor_document_revision_id??null,v.value=C.editor_document_revision_number??null}catch(ie){M();const W=ie instanceof Error?`Unable to load image editor: ${ie.message}`:"Unable to load image editor";await T(W);return}d.value=!0}}function O(){d.value=!1,M()}async function I(ce){if(!c.value)throw new Error("No media selected for editing");const ie=c.value,W=t.editMode==="variant";try{y.value=null;const C=await i.saveEditedImage(ie.uuid,ce,{asVariant:W});W||await i.detachMedia(t.mediableType,t.mediableId,ie.uuid,t.collection),await i.attachMedia(t.mediableType,t.mediableId,[C.uuid],t.collection),n("edit-complete",{originalMedia:ie,editedMedia:C,mode:t.editMode}),d.value=!1,M()}catch(C){const U=C instanceof Error?C.message:"Failed to save edited image";throw y.value=U,await T(U),C}}function Z(ce){if(y.value===ce.message){y.value=null;return}T(ce.message)}async function z(ce){const ie=ce.target,W=ie.files;if(!(!W||W.length===0)){for(let C=0;C<W.length;C++){const U=W[C];if(g.value!==void 0&&g.value<=0)break;if(t.acceptedMimeTypes&&t.acceptedMimeTypes.length>0&&!t.acceptedMimeTypes.includes(U.type)){n("error",{operation:"upload",message:`File type ${U.type} is not accepted`,details:{file:U.name}});continue}if(t.maxFileSize!==void 0&&U.size>t.maxFileSize){n("error",{operation:"upload",message:`File size exceeds limit of ${t.maxFileSize} bytes`,details:{file:U.name,size:U.size}});continue}n("upload-progress",{status:"uploading",progress:0,file:U});try{const j=await i.uploadFile(U,{collection:t.collection});j!=null&&j.uuid&&(await i.attachMedia(t.mediableType,t.mediableId,[j.uuid],t.collection),n("upload-progress",{status:"complete",progress:100,file:U}),n("attach",[j]))}catch(j){const ne=j instanceof Error?j.message:"Upload failed";n("error",{operation:"upload",message:ne,details:j}),n("upload-progress",{status:"error",progress:0,file:U,error:ne})}}ie.value=""}}async function K(ce){const ie=ce.map(W=>W.uuid);try{await i.reorderMedia(t.mediableType,t.mediableId,ie,t.collection),n("reorder",i.modelMedia)}catch(W){const C=W instanceof Error?W.message:"Failed to reorder media";n("error",{operation:"reorder",message:C,details:W}),await T(C)}}async function se(ce){const ie=i.modelMedia.find(W=>W.uuid===ce);try{await i.detachMedia(t.mediableType,t.mediableId,ce,t.collection),ie&&n("detach",ie)}catch(W){const C=W instanceof Error?W.message:"Failed to detach media";n("error",{operation:"detach",message:C,details:W}),await T(C)}}async function Be(ce){l.value=!1;const ie=ce.map(U=>U.uuid),W=new Set(b.value);let C=Array.from(new Set(ie)).filter(U=>!W.has(U));if(g.value!==void 0&&C.length>g.value&&(C=C.slice(0,g.value)),C.length!==0)try{await i.attachMedia(t.mediableType,t.mediableId,C,t.collection);const U=i.modelMedia.filter(j=>C.includes(j.uuid));n("attach",U)}catch(U){const j=U instanceof Error?U.message:"Failed to attach media";n("error",{operation:"attach",message:j,details:U})}}return(ce,ie)=>(e.openBlock(),e.createElementBlock("div",Ig,[e.createElementVNode("input",{ref_key:"fileInputRef",ref:k,type:"file",accept:R.value,multiple:g.value===void 0||g.value>1,class:"hidden","data-testid":"upload-input",onChange:z},null,40,$g),e.createElementVNode("div",Fg,[ce.title?(e.openBlock(),e.createElementBlock("h3",Dg,e.toDisplayString(ce.title),1)):e.createCommentVNode("",!0),e.createElementVNode("div",Rg,[ce.allowBrowse?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:0,fill:"outline",size:"small",disabled:A(),"data-testid":"browse-button",onClick:w},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{slot:"start",icon:e.unref(Os)},null,8,["icon"]),ie[1]||(ie[1]=e.createTextVNode(" Browse ",-1))]),_:1},8,["disabled"])):e.createCommentVNode("",!0),ce.allowUpload?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:1,fill:"solid",size:"small",disabled:A(),"data-testid":"upload-button",onClick:F},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{slot:"start",icon:e.unref(cc)},null,8,["icon"]),ie[2]||(ie[2]=e.createTextVNode(" Upload ",-1))]),_:1},8,["disabled"])):e.createCommentVNode("",!0)])]),r.value||e.unref(i).isLoadingModelMedia?(e.openBlock(),e.createElementBlock("div",Ag,[e.createVNode(e.unref(H.IonSpinner),{"data-testid":"spinner"})])):B()?(e.openBlock(),e.createBlock(Mg,{key:2,"media-items":e.unref(i).modelMedia,reorderable:!!ce.allowReorder,"is-loading":r.value||e.unref(i).isLoadingModelMedia,"show-edit-button":!!ce.allowEdit,"selection-mode":!1,onReorder:K,onDelete:se,onEdit:D},e.createSlots({_:2},[ce.showPrimaryBadge?{name:"badge",fn:e.withCtx(({index:W})=>[W===0?(e.openBlock(),e.createElementBlock("div",Og," Primary ")):e.createCommentVNode("",!0)]),key:"0"}:void 0]),1032,["media-items","reorderable","is-loading","show-edit-button"])):(e.openBlock(),e.createElementBlock("div",Lg,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Os),class:"w-12 h-12 text-gray-400 mb-4"},null,8,["icon"]),e.createElementVNode("p",Pg,e.toDisplayString(ce.emptyText),1),e.createElementVNode("div",Ug,[ce.allowBrowse?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:0,fill:"outline",size:"small","data-testid":"browse-button-empty",onClick:w},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{slot:"start",icon:e.unref(Os)},null,8,["icon"]),ie[3]||(ie[3]=e.createTextVNode(" Browse Library ",-1))]),_:1})):e.createCommentVNode("",!0),ce.allowUpload?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:1,fill:"solid",size:"small","data-testid":"upload-button-empty",onClick:F},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{slot:"start",icon:e.unref(cc)},null,8,["icon"]),ie[4]||(ie[4]=e.createTextVNode(" Upload Files ",-1))]),_:1})):e.createCommentVNode("",!0)])])),e.createVNode(lg,e.mergeProps({"is-open":l.value,"selected-items":b.value,collection:ce.collection},g.value!==null&&g.value!==void 0?{maxSelection:g.value}:{},{onConfirm:Be,onClose:P}),null,16,["is-open","selected-items","collection"]),e.createVNode(nm,{modelValue:d.value,"onUpdate:modelValue":ie[0]||(ie[0]=W=>d.value=W),"initial-image":E.value,"initial-state":m.value,"initial-document":f.value,"initial-document-id":p.value,"initial-document-revision-id":h.value,"initial-document-revision-number":v.value,"session-key":u.value,"save-handler":I,onCancel:O,onError:Z},null,8,["modelValue","initial-image","initial-state","initial-document","initial-document-id","initial-document-revision-id","initial-document-revision-number","session-key"])]))}}),jg=Fe(zg,[["__scopeId","data-v-c58d85c8"]]),Wg={class:"existing-media-selector","data-testid":"existing-media-selector"},Hg={key:0,class:"existing-media-selector__status","data-testid":"existing-media-loading"},Zg=["data-testid"],Gg={class:"existing-media-selector__section-header"},Xg={class:"existing-media-selector__section-title"},Kg=["data-testid","aria-label","onClick"],Jg={class:"existing-media-selector__grid"},qg=["data-testid","aria-label","aria-pressed","onClick"],Yg=["src","alt"],Qg={key:0,class:"existing-media-selector__selected-badge"},eb={key:1,class:"existing-media-selector__caption"},tb={key:0,class:"existing-media-selector__section existing-media-selector__section--albums","data-testid":"existing-media-albums"},ab={class:"existing-media-selector__section-header"},nb={class:"existing-media-selector__section-title"},ob={class:"existing-media-selector__albums"},ib=["data-testid","aria-label","aria-pressed","onClick"],rb={class:"existing-media-selector__album-name"},sb={key:0,class:"existing-media-selector__album-count"},lb={class:"existing-media-selector__album-panel","data-testid":"existing-media-active-album"},db={class:"existing-media-selector__section-header"},cb={class:"existing-media-selector__section-subtitle"},ub={key:0,class:"existing-media-selector__section-description"},mb={key:0,class:"existing-media-selector__status","data-testid":"existing-media-active-album-loading"},pb={key:1,class:"existing-media-selector__grid"},fb=["data-testid","aria-label","aria-pressed","onClick"],hb=["src","alt"],vb={key:0,class:"existing-media-selector__selected-badge"},gb={key:1,class:"existing-media-selector__caption"},bb={key:2,class:"existing-media-selector__empty","data-testid":"existing-media-active-album-empty"},yb={key:1,class:"existing-media-selector__empty","data-testid":"existing-media-empty"},wb=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(b=>b.items.length>0)),s=e.computed(()=>t.albums.length>0),l=e.computed(()=>r.value.length>0||s.value),d=e.computed(()=>{if(typeof t.activeAlbumTitle=="string"&&t.activeAlbumTitle.trim().length>0)return t.activeAlbumTitle.trim();const b=t.albums.find(R=>R.id===t.activeAlbumId);return b!=null&&b.name.trim().length?b.name.trim():t.albumSectionTitle}),c=e.computed(()=>{if(typeof t.activeAlbumDescription=="string"&&t.activeAlbumDescription.trim().length>0)return t.activeAlbumDescription.trim();const b=t.albums.find(R=>R.id===t.activeAlbumId);return typeof(b==null?void 0:b.description)=="string"&&b.description.trim().length>0?b.description.trim():""});function u(b){const R=b.initialVisibleCount??6;return R>0?R:6}function m(b){return i[b]===!0}function f(b){i[b]=!m(b)}function p(b){return m(b.id)?b.items:b.items.slice(0,u(b))}function h(b){return b.items.length>u(b)}function v(b){n("select",b)}function E(b){n("update:activeAlbumId",b)}function y(b){var N;const R=(N=b.description)==null?void 0:N.trim();return R&&R.length>0?`Select ${R}`:"Select existing media"}function k(b,R){var T;const N=(T=R.description)==null?void 0:T.trim();return typeof R.alt=="string"&&R.alt.trim().length>0?R.alt.trim():N&&N.length>0?N:b.title}function g(b){const R=typeof b.mediaCount=="number"?` with ${b.mediaCount} item${b.mediaCount===1?"":"s"}`:"";return`Browse album ${b.name}${R}`}return(b,R)=>(e.openBlock(),e.createElementBlock("div",Wg,[b.isLoading?(e.openBlock(),e.createElementBlock("div",Hg," Loading your media... ")):(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.value,N=>(e.openBlock(),e.createElementBlock("section",{key:N.id,class:"existing-media-selector__section","data-testid":`existing-media-section-${N.id}`},[e.createElementVNode("div",Gg,[e.createElementVNode("h3",Xg,e.toDisplayString(N.title),1),h(N)?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"existing-media-selector__toggle","data-testid":`existing-media-toggle-${N.id}`,"aria-label":m(N.id)?`Show fewer items from ${N.title}`:`Show more items from ${N.title}`,onClick:T=>f(N.id)},e.toDisplayString(m(N.id)?"See less":"See more"),9,Kg)):e.createCommentVNode("",!0)]),e.createElementVNode("div",Jg,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(p(N),T=>(e.openBlock(),e.createElementBlock("button",{key:T.id,type:"button",class:e.normalizeClass(["existing-media-selector__item",{"is-selected":b.selectedId===T.id}]),"data-testid":`existing-media-item-${N.id}-${T.id}`,"aria-label":y(T),"aria-pressed":b.selectedId===T.id?"true":"false",onClick:S=>v(T)},[e.createElementVNode("img",{class:"existing-media-selector__image",src:T.previewUrl,alt:k(N,T)},null,8,Yg),b.selectedId===T.id?(e.openBlock(),e.createElementBlock("div",Qg," Selected ")):e.createCommentVNode("",!0),T.description?(e.openBlock(),e.createElementBlock("div",eb,e.toDisplayString(T.description),1)):e.createCommentVNode("",!0)],10,qg))),128))])],8,Zg))),128)),s.value?(e.openBlock(),e.createElementBlock("section",tb,[e.createElementVNode("div",ab,[e.createElementVNode("h3",nb,e.toDisplayString(b.albumBrowseTitle),1)]),e.createElementVNode("div",ob,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(b.albums,N=>(e.openBlock(),e.createElementBlock("button",{key:N.id,type:"button",class:e.normalizeClass(["existing-media-selector__album",{"is-active":b.activeAlbumId===N.id}]),"data-testid":`existing-media-album-${N.id}`,"aria-label":g(N),"aria-pressed":b.activeAlbumId===N.id?"true":"false",onClick:T=>E(N.id)},[e.createElementVNode("span",rb,e.toDisplayString(N.name),1),typeof N.mediaCount=="number"?(e.openBlock(),e.createElementBlock("span",sb,e.toDisplayString(N.mediaCount),1)):e.createCommentVNode("",!0)],10,ib))),128))]),e.createElementVNode("div",lb,[e.createElementVNode("div",db,[e.createElementVNode("div",null,[e.createElementVNode("h4",cb,e.toDisplayString(d.value),1),c.value?(e.openBlock(),e.createElementBlock("p",ub,e.toDisplayString(c.value),1)):e.createCommentVNode("",!0)])]),b.isAlbumLoading?(e.openBlock(),e.createElementBlock("div",mb," Loading album... ")):b.activeAlbumItems.length>0?(e.openBlock(),e.createElementBlock("div",pb,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(b.activeAlbumItems,N=>(e.openBlock(),e.createElementBlock("button",{key:N.id,type:"button",class:e.normalizeClass(["existing-media-selector__item",{"is-selected":b.selectedId===N.id}]),"data-testid":`existing-media-item-album-${N.id}`,"aria-label":y(N),"aria-pressed":b.selectedId===N.id?"true":"false",onClick:T=>v(N)},[e.createElementVNode("img",{class:"existing-media-selector__image",src:N.previewUrl,alt:N.alt||N.description||d.value},null,8,hb),b.selectedId===N.id?(e.openBlock(),e.createElementBlock("div",vb," Selected ")):e.createCommentVNode("",!0),N.description?(e.openBlock(),e.createElementBlock("div",gb,e.toDisplayString(N.description),1)):e.createCommentVNode("",!0)],10,fb))),128))])):(e.openBlock(),e.createElementBlock("div",bb,[e.renderSlot(b.$slots,"active-album-empty",{},()=>[e.createTextVNode(e.toDisplayString(b.activeAlbumEmptyMessage),1)],!0)]))])])):e.createCommentVNode("",!0),l.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",yb,[e.renderSlot(b.$slots,"empty",{},()=>[e.createTextVNode(e.toDisplayString(b.emptyMessage),1)],!0)]))],64))]))}}),kb=Fe(wb,[["__scopeId","data-v-904abb6b"]]);function sr(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 _b(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 Eb=["src","crossorigin"],Sb={class:"preview-controls"},Cb=["aria-label"],xb={class:"time-display"},Vb={class:"current-time"},Nb={class:"total-time"},Tb={key:0,class:"fps-display"},Bb={key:0,class:"loading-overlay"},Mb={key:1,class:"error-overlay"},Ib=.1,$b=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}=Gt,r=o,s=t,l=e.ref(),d=e.ref(),c=e.ref(),u=e.ref(!0),m=e.ref(),f=e.ref(0),p=e.ref(0),h=e.ref(!1);let v,E,y=null,k=null,g=null,b=[],R="",N=null,T=0,S=0,B=0,A=0,x=!1,M=0,w=0,F,P=null,D=!1,O=!1,I=0;const Z=e.computed(()=>r.source&&typeof r.source=="string"?r.source:""),z=e.computed(()=>{const Ee=Z.value;if(!(!Ee||Ee.startsWith("blob:")))return"anonymous"}),K=e.computed(()=>_b(h.value,r.fitMode));function se(Ee){return typeof Ee=="number"&&Number.isFinite(Ee)&&Ee>=0?Ee:Number.isFinite(r.fallbackDuration)&&r.fallbackDuration>0?r.fallbackDuration:0}function Be(Ee){const Ce=se(Ee.duration);return Ce<=0?!1:Ee.currentTime>=Math.max(0,Ce-Ib)}async function ce(){var Ee,Ce;if(!O&&d.value&&!v&&!(!c.value||c.value.readyState<3)){O=!0;try{m.value=void 0;let Re=((Ee=l.value)==null?void 0:Ee.clientWidth)||800,et=((Ce=l.value)==null?void 0:Ce.clientHeight)||450;if((Re<=0||et<=0)&&(Re=c.value.videoWidth||800,et=c.value.videoHeight||450),v=new Gt.Application,await v.init({width:Re,height:et,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&&ce()},100),v&&(v.destroy(!0),v=null);return}if(T=c.value.videoWidth,S=c.value.videoHeight,k=document.createElement("canvas"),k.width=T,k.height=S,g=k.getContext("2d"),!g)throw new Error("Unable to create 2D canvas context for video preview");const qe=sr(c.value,g,T,S),Ze=Gt.Texture.from(k);y=Ze.source,E=new Gt.Sprite(Ze),E.visible=!0,E.alpha=1,rt(),v.stage.addChild(E),v.renderer&&!v.renderer.destroyed&&v.render()}U(),r.targetFps<60?ie():v.ticker.add(W),h.value=!0,"ResizeObserver"in window&&(N=new ResizeObserver(qe=>{x||(x=!0,requestAnimationFrame(()=>{x=!1;const Ze=qe[qe.length-1],{width:bt,height:ct}=Ze.contentRect;if(bt<=0||ct<=0)return;const At=Math.round(bt),$t=Math.round(ct);At===B&&$t===A||(B=At,A=$t,rt())}))}),N.observe(l.value)),r.filters&&r.filters.length>0&&U(),r.showFps&&re(),I=0}catch{if(Ve(),!D&&!!c.value&&c.value.readyState>=2&&c.value.videoWidth>0&&c.value.videoHeight>0&&I<2){I+=1,window.setTimeout(()=>{D||ce()},I*150);return}m.value="Failed to initialize video preview",s("error",m.value)}finally{O=!1}}}function ie(){const Ee=1e3/r.targetFps;let Ce=performance.now();function Re(){if(D||!v)return;const et=performance.now(),qe=et-Ce;qe>=Ee&&(W(),Ce=et-qe%Ee),P=requestAnimationFrame(Re)}P=requestAnimationFrame(Re)}function W(){if(!(!v||!E||D)&&r.active)try{g&&k&&y&&c.value&&(c.value.readyState>=2&&sr(c.value,g,k.width,k.height)&&y.update(),c.value.paused||s("frame-update",de())),r.showFps&&w++,v.renderer&&!v.renderer.destroyed&&v.render()}catch{D=!0}}function C(){for(const Ee of b)try{Ee.destroy()}catch{}b=[]}function U(){if(E){if(!r.filters||r.filters.length===0){E.filters=null,C();return}C(),r.filters.forEach(Ee=>{const Ce=j(Ee);Ce&&b.push(Ce)}),E.filters=b.length>0?b:null,R=JSON.stringify(r.filters),v&&v.render()}}function j(Ee){const Ce=Ee.filterId,Re=Ee.params||{},et=oe.getFilter(Ce);if(et&&!oe.isFilterCompatibleWithMedia(Ce,"video"))return null;if(et&&et.createFilter)try{return et.createFilter(Re)}catch{}const qe=(Ze,bt,ct)=>Math.min(ct,Math.max(bt,Ze));switch(Ce){case"brightness":{const Ze=new n,bt=qe(typeof Re.brightness=="number"?Re.brightness:typeof Re.value=="number"?Re.value:1,0,5);return Ze.brightness(bt,!0),Ze}case"contrast":{const Ze=new n,bt=qe(typeof Re.contrast=="number"?Re.contrast:typeof Re.value=="number"?Re.value:1,0,5);return Ze.contrast(bt,!0),Ze}case"saturation":{const Ze=new n,bt=qe(typeof Re.saturation=="number"?Re.saturation:typeof Re.value=="number"?Re.value:1,0,5);return Ze.saturate(bt,!0),Ze}case"hue":{const Ze=new n,bt=qe(typeof Re.value=="number"?Re.value:0,-180,180);return Ze.hue(bt,!0),Ze}case"gaussian-blur":case"blur":{const Ze=qe(typeof Re.blur=="number"?Re.blur:typeof Re.value=="number"?Re.value:2,0,10);return new i(Ze)}case"grayscale":{const Ze=new n;return Ze.desaturate(),Ze}case"sepia":case"color-matrix":{const Ze=new n;return Ze.sepia(!0),Ze}case"vignette":{const Ze=typeof Re.value=="number"?Re.value:.3;return ne(qe(Ze,0,1))}default:return null}}function ne(Ee){const Ce=`
|
|
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 Gt.Filter(void 0,Ce,{strength:Ee})}function de(){var Ce;return!v||!E?null:{dataUrl:v.canvas.toDataURL("image/jpeg",.8),timestamp:((Ce=c.value)==null?void 0:Ce.currentTime)||0,width:T||0,height:S||0}}function Ke(){var Ee;f.value=se((Ee=c.value)==null?void 0:Ee.duration),s("duration-change",f.value)}function be(){u.value=!1,m.value=void 0}function _e(){u.value&&(u.value=!1),!h.value&&r.active?ce():h.value}function ve(){var Ce,Re,et;const Ee=((Ce=c.value)==null?void 0:Ce.currentTime)||0;s("frame-update",{dataUrl:null,timestamp:Ee,width:((Re=c.value)==null?void 0:Re.videoWidth)||0,height:((et=c.value)==null?void 0:et.videoHeight)||0})}function xe(){c.value&&(c.value.currentTime=0),s("play-pause")}function Se(Ee){var Re;const Ce=Ee.target;if(Ce!=null&&Ce.error)switch(Ce.error.code){case Ce.error.MEDIA_ERR_ABORTED:m.value="Video playback aborted";break;case Ce.error.MEDIA_ERR_NETWORK:m.value="Network error loading video";break;case Ce.error.MEDIA_ERR_DECODE:m.value="Video format not supported";break;case Ce.error.MEDIA_ERR_SRC_NOT_SUPPORTED:m.value=`Video source not supported: ${(Re=Ce.src)==null?void 0:Re.substring(0,100)}`;break;default:m.value="Failed to load video"}else m.value="Failed to load video";s("error",m.value),u.value=!1}function Ae(Ee){c.value&&(c.value.currentTime=Math.max(0,Math.min(Ee,f.value)))}function re(){F=window.setInterval(()=>{const Ee=performance.now(),Ce=Ee-M;p.value=Math.round(w*1e3/Ce),w=0,M=Ee},1e3)}function ge(Ee){if(!Number.isFinite(Ee)||Ee<0)return"00:00";const Ce=Math.floor(Ee/60),Re=Math.floor(Ee%60);return`${Ce.toString().padStart(2,"0")}:${Re.toString().padStart(2,"0")}`}function Ge(){m.value=void 0,u.value=!0,I=0,Ve(),c.value&&c.value.load()}function Ve(){if(N&&(N.disconnect(),N=null),P&&(cancelAnimationFrame(P),P=null),v!=null&&v.ticker&&(v.ticker.stop(),v.ticker.remove(W)),v)try{v.destroy(!0,{children:!0,texture:!0})}catch{}d.value&&(d.value.innerHTML=""),C(),v=null,E=null,y=null,k=null,g=null,h.value=!1,x=!1,R=""}function at(){v&&(x||(x=!0,requestAnimationFrame(()=>{x=!1,rt()})))}function rt(){if(!v||!E||!T||!S||!l.value)return;const Ee=Math.round(l.value.clientWidth),Ce=Math.round(l.value.clientHeight);if(Ee<=0||Ce<=0)return;v.renderer.resize(Ee,Ce);const Re=v.screen.width/T,et=v.screen.height/S;let qe=1;switch(r.fitMode){case"cover":qe=Math.max(Re,et);break;case"none":qe=1;break;case"contain":default:qe=Math.min(Re,et);break}E.scale.set(qe),E.anchor.set(.5),E.position.set(v.screen.width/2,v.screen.height/2),E.visible=!0,E.alpha=1,v.renderer&&!v.renderer.destroyed&&v.render()}e.watch(()=>r.filters,()=>{h.value&&U()},{deep:!0}),e.watch(()=>r.active,async Ee=>{if(Ee&&!v&&c.value&&c.value.readyState>=2){await ce();return}v&&(Ee&&(await e.nextTick(),l.value&&l.value.getBoundingClientRect(),E&&g&&k&&y&&(c.value&&c.value.readyState>=2&&sr(c.value,g,k.width,k.height)&&y.update(),rt(),v.renderer&&!v.renderer.destroyed&&v.render())),r.targetFps>=60&&v.ticker&&(Ee?v.ticker.start():v.ticker.stop()))}),e.watch(Z,Ee=>{Ee?(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 gt(){if(c.value){m.value=void 0,Be(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",s("error",m.value)}}e.watch(()=>r.isPlaying,Ee=>{c.value&&(Ee?gt():c.value.pause())}),e.watch(()=>r.playhead,Ee=>{c.value&&Math.abs(c.value.currentTime-Ee)>.5&&Ae(Ee)}),e.watch(()=>r.fitMode,()=>{rt()}),e.onMounted(()=>{D=!1,e.nextTick(()=>{l.value&&l.value.getBoundingClientRect(),c.value}),window.addEventListener("resize",at),M=performance.now(),e.nextTick(()=>{c.value&&c.value.readyState>=2&&!h.value?ce():c.value&&c.value.src&&c.value.readyState===0&&c.value.load()})}),e.onUnmounted(()=>{if(D=!0,P&&(cancelAnimationFrame(P),P=null),window.removeEventListener("resize",at),N&&(N.disconnect(),N=null),F&&clearInterval(F),v&&v.ticker&&(v.ticker.stop(),v.ticker.remove(W)),v){try{v.destroy(!0,{children:!0,texture:!0})}catch{}v=null}b.forEach(Ee=>{try{Ee.destroy()}catch{}}),b=[],E=null,y=null,k=null,g=null,c.value&&(c.value.pause(),c.value.removeAttribute("src"),c.value.load())});async function lt(Ee){if(!await Et()||!c.value||!g||!k||!y)return null;const Re=c.value,et=Number.isFinite(f.value)&&f.value>0?f.value:Number.isFinite(Re.duration)&&Re.duration>0?Re.duration:0,qe=Math.max(0,Math.min(Ee,et));return await new Promise(bt=>{let ct=!1,At=0;const $t=()=>{ct||(ct=!0,Re.removeEventListener("seeked",Pt),window.clearTimeout(At),bt())},Pt=()=>{$t()},Ut=Number.isFinite(Re.currentTime)?Re.currentTime:0;if(Math.abs(Ut-qe)<.016){requestAnimationFrame(()=>$t());return}Re.addEventListener("seeked",Pt),At=window.setTimeout(()=>$t(),700),Re.currentTime=qe}),sr(Re,g,k.width,k.height)?(y.update(),v.render(),v.canvas):null}async function Et(){if(!c.value)return!1;if(!v){if(!(c.value.readyState>=2))return!1;await ce()}if(!v||!E||!g||!k||!y)return!1;if(r.filters&&r.filters.length>0){const Ee=E.filters,Ce=Array.isArray(Ee)?Ee.length:0,et=JSON.stringify(r.filters)!==R;(Ce===0||Ce!==r.filters.length||et)&&U()}return await e.nextTick(),await new Promise(Ee=>{requestAnimationFrame(()=>Ee())}),!0}return a({captureFrameAt:lt,ensureReadyForCapture:Et,duration:f,pixiCanvas:e.computed(()=>v?v.canvas:null),videoElement:e.computed(()=>c.value??null)}),(Ee,Ce)=>(e.openBlock(),e.createElementBlock("div",{class:"video-preview",ref_key:"containerRef",ref:l},[e.createElementVNode("div",{class:"canvas-container",ref_key:"canvasContainerRef",ref:d},null,512),e.createElementVNode("video",{ref_key:"videoRef",ref:c,src:Z.value,onLoadedmetadata:Ke,onLoadeddata:be,onCanplay:_e,onTimeupdate:ve,onEnded:xe,onError:Se,style:e.normalizeStyle(K.value),crossorigin:z.value,preload:"auto",playsinline:"",controls:""},null,44,Eb),e.createElementVNode("div",Sb,[e.createElementVNode("button",{class:"play-button",onClick:Ce[0]||(Ce[0]=Re=>Ee.$emit("play-pause")),"aria-label":Ee.isPlaying?"Pause":"Play"},[e.createVNode(e.unref(H.IonIcon),{icon:Ee.isPlaying?e.unref(rm):e.unref(sm)},null,8,["icon"])],8,Cb),e.createElementVNode("div",xb,[e.createElementVNode("span",Vb,e.toDisplayString(ge(Ee.playhead)),1),Ce[1]||(Ce[1]=e.createElementVNode("span",{class:"separator"},"/",-1)),e.createElementVNode("span",Nb,e.toDisplayString(ge(f.value)),1)]),Ee.showFps?(e.openBlock(),e.createElementBlock("div",Tb,e.toDisplayString(p.value)+" FPS ",1)):e.createCommentVNode("",!0)]),u.value?(e.openBlock(),e.createElementBlock("div",Bb,[e.createVNode(e.unref(H.IonSpinner),{name:"crescent"}),Ce[2]||(Ce[2]=e.createElementVNode("p",null,"Loading video...",-1))])):e.createCommentVNode("",!0),m.value?(e.openBlock(),e.createElementBlock("div",Mb,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Ql)},null,8,["icon"]),e.createElementVNode("p",null,e.toDisplayString(m.value),1),e.createElementVNode("button",{onClick:Ge},"Retry")])):e.createCommentVNode("",!0)],512))}}),ul=Fe($b,[["__scopeId","data-v-dd1744f4"]]);var ad=(o,a,t)=>{if(!a.has(o))throw TypeError("Cannot "+t)},q=(o,a,t)=>(ad(o,a,"read from private field"),t?t.call(o):a.get(o)),it=(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)},na=(o,a,t,n)=>(ad(o,a,"write to private field"),a.set(o,t),t),Fb=(o,a,t,n)=>({set _(i){na(o,a,i)},get _(){return q(o,a,n)}}),mt=(o,a,t)=>(ad(o,a,"access private method"),t),vt=new Uint8Array(8),an=new DataView(vt.buffer),Qt=o=>[(o%256+256)%256],_t=o=>(an.setUint16(0,o,!1),[vt[0],vt[1]]),Db=o=>(an.setInt16(0,o,!1),[vt[0],vt[1]]),um=o=>(an.setUint32(0,o,!1),[vt[1],vt[2],vt[3]]),je=o=>(an.setUint32(0,o,!1),[vt[0],vt[1],vt[2],vt[3]]),Rb=o=>(an.setInt32(0,o,!1),[vt[0],vt[1],vt[2],vt[3]]),Qn=o=>(an.setUint32(0,Math.floor(o/2**32),!1),an.setUint32(4,o,!1),[vt[0],vt[1],vt[2],vt[3],vt[4],vt[5],vt[6],vt[7]]),nd=o=>(an.setInt16(0,2**8*o,!1),[vt[0],vt[1]]),Qa=o=>(an.setInt32(0,2**16*o,!1),[vt[0],vt[1],vt[2],vt[3]]),js=o=>(an.setInt32(0,2**30*o,!1),[vt[0],vt[1],vt[2],vt[3]]),Ma=(o,a=!1)=>{let t=Array(o.length).fill(null).map((n,i)=>o.charCodeAt(i));return a&&t.push(0),t},Dr=o=>o&&o[o.length-1],od=o=>{let a;for(let t of o)(!a||t.presentationTimestamp>a.presentationTimestamp)&&(a=t);return a},tn=(o,a,t=!0)=>{let n=o*a;return t?Math.round(n):n},mm=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]},pm=mm(0),fm=o=>[Qa(o[0]),Qa(o[1]),js(o[2]),Qa(o[3]),Qa(o[4]),js(o[5]),Qa(o[6]),Qa(o[7]),js(o[8])],vi=o=>!o||typeof o!="object"?o:Array.isArray(o)?o.map(vi):Object.fromEntries(Object.entries(o).map(([a,t])=>[a,vi(t)])),Fo=o=>o>=0&&o<2**32,Kt=(o,a,t)=>({type:o,contents:a&&new Uint8Array(a.flat(10)),children:t}),Rt=(o,a,t,n,i)=>Kt(o,[Qt(a),um(t),n??[]],i),Ab=o=>{let a=512;return o.fragmented?Kt("ftyp",[Ma("iso5"),je(a),Ma("iso5"),Ma("iso6"),Ma("mp41")]):Kt("ftyp",[Ma("isom"),je(a),Ma("isom"),o.holdsAvc?Ma("avc1"):[],Ma("mp41")])},ml=o=>({type:"mdat",largeSize:o}),Lb=o=>({type:"free",size:o}),kr=(o,a,t=!1)=>Kt("moov",null,[Pb(a,o),...o.map(n=>Ub(n,a)),t?g0(o):null]),Pb=(o,a)=>{let t=tn(Math.max(0,...a.filter(s=>s.samples.length>0).map(s=>{const l=od(s.samples);return l.presentationTimestamp+l.duration})),hl),n=Math.max(...a.map(s=>s.id))+1,i=!Fo(o)||!Fo(t),r=i?Qn:je;return Rt("mvhd",+i,0,[r(o),r(o),je(hl),r(t),Qa(1),nd(1),Array(10).fill(0),fm(pm),Array(24).fill(0),je(n)])},Ub=(o,a)=>Kt("trak",null,[Ob(o,a),zb(o,a)]),Ob=(o,a)=>{let t=od(o.samples),n=tn(t?t.presentationTimestamp+t.duration:0,hl),i=!Fo(a)||!Fo(n),r=i?Qn:je,s;return o.info.type==="video"?s=typeof o.info.rotation=="number"?mm(o.info.rotation):o.info.rotation:s=pm,Rt("tkhd",+i,3,[r(a),r(a),je(o.id),je(0),r(n),Array(8).fill(0),_t(0),_t(0),nd(o.info.type==="audio"?1:0),_t(0),fm(s),Qa(o.info.type==="video"?o.info.width:0),Qa(o.info.type==="video"?o.info.height:0)])},zb=(o,a)=>Kt("mdia",null,[jb(o,a),Wb(o.info.type==="video"?"vide":"soun"),Hb(o)]),jb=(o,a)=>{let t=od(o.samples),n=tn(t?t.presentationTimestamp+t.duration:0,o.timescale),i=!Fo(a)||!Fo(n),r=i?Qn:je;return Rt("mdhd",+i,0,[r(a),r(a),je(o.timescale),r(n),_t(21956),_t(0)])},Wb=o=>Rt("hdlr",0,0,[Ma("mhlr"),Ma(o),je(0),je(0),je(0),Ma("mp4-muxer-hdlr",!0)]),Hb=o=>Kt("minf",null,[o.info.type==="video"?Zb():Gb(),Xb(),qb(o)]),Zb=()=>Rt("vmhd",0,1,[_t(0),_t(0),_t(0),_t(0)]),Gb=()=>Rt("smhd",0,0,[_t(0),_t(0)]),Xb=()=>Kt("dinf",null,[Kb()]),Kb=()=>Rt("dref",0,0,[je(1)],[Jb()]),Jb=()=>Rt("url ",0,1),qb=o=>{const a=o.compositionTimeOffsetTable.length>1||o.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return Kt("stbl",null,[Yb(o),u0(o),m0(o),p0(o),f0(o),h0(o),a?v0(o):null])},Yb=o=>Rt("stsd",0,0,[je(1)],[o.info.type==="video"?Qb(V0[o.info.codec],o):l0(T0[o.info.codec],o)]),Qb=(o,a)=>Kt(o,[Array(6).fill(0),_t(1),_t(0),_t(0),Array(12).fill(0),_t(a.info.width),_t(a.info.height),je(4718592),je(4718592),je(0),_t(1),Array(32).fill(0),_t(24),Db(65535)],[N0[a.info.codec](a),a.info.decoderConfig.colorSpace?n0(a):null]),e0={bt709:1,bt470bg:5,smpte170m:6},t0={bt709:1,smpte170m:6,"iec61966-2-1":13},a0={rgb:0,bt709:1,bt470bg:5,smpte170m:6},n0=o=>Kt("colr",[Ma("nclx"),_t(e0[o.info.decoderConfig.colorSpace.primaries]),_t(t0[o.info.decoderConfig.colorSpace.transfer]),_t(a0[o.info.decoderConfig.colorSpace.matrix]),Qt((o.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),o0=o=>o.info.decoderConfig&&Kt("avcC",[...new Uint8Array(o.info.decoderConfig.description)]),i0=o=>o.info.decoderConfig&&Kt("hvcC",[...new Uint8Array(o.info.decoderConfig.description)]),r0=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]),l=(Number(t[3])<<4)+(0<<1)+Number(a.colorSpace.fullRange);return Rt("vpcC",1,0,[Qt(n),Qt(i),Qt(l),Qt(2),Qt(2),Qt(2),_t(0)])},s0=()=>{let t=(1<<7)+1;return Kt("av1C",[t,0,0,0])},l0=(o,a)=>Kt(o,[Array(6).fill(0),_t(1),_t(0),_t(0),je(0),_t(a.info.numberOfChannels),_t(16),_t(0),_t(0),Qa(a.info.sampleRate)],[B0[a.info.codec](a)]),d0=o=>{let a=new Uint8Array(o.info.decoderConfig.description);return Rt("esds",0,0,[je(58753152),Qt(32+a.byteLength),_t(1),Qt(0),je(75530368),Qt(18+a.byteLength),Qt(64),Qt(21),um(0),je(130071),je(130071),je(92307584),Qt(a.byteLength),...a,je(109084800),Qt(1),Qt(2)])},c0=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 Kt("dOps",[Qt(0),Qt(o.info.numberOfChannels),_t(a),je(o.info.sampleRate),nd(t),Qt(0)])},u0=o=>Rt("stts",0,0,[je(o.timeToSampleTable.length),o.timeToSampleTable.map(a=>[je(a.sampleCount),je(a.sampleDelta)])]),m0=o=>{if(o.samples.every(t=>t.type==="key"))return null;let a=[...o.samples.entries()].filter(([,t])=>t.type==="key");return Rt("stss",0,0,[je(a.length),a.map(([t])=>je(t+1))])},p0=o=>Rt("stsc",0,0,[je(o.compactlyCodedChunkTable.length),o.compactlyCodedChunkTable.map(a=>[je(a.firstChunk),je(a.samplesPerChunk),je(1)])]),f0=o=>Rt("stsz",0,0,[je(0),je(o.samples.length),o.samples.map(a=>je(a.size))]),h0=o=>o.finalizedChunks.length>0&&Dr(o.finalizedChunks).offset>=2**32?Rt("co64",0,0,[je(o.finalizedChunks.length),o.finalizedChunks.map(a=>Qn(a.offset))]):Rt("stco",0,0,[je(o.finalizedChunks.length),o.finalizedChunks.map(a=>je(a.offset))]),v0=o=>Rt("ctts",0,0,[je(o.compositionTimeOffsetTable.length),o.compositionTimeOffsetTable.map(a=>[je(a.sampleCount),je(a.sampleCompositionTimeOffset)])]),g0=o=>Kt("mvex",null,o.map(b0)),b0=o=>Rt("trex",0,0,[je(o.id),je(1),je(0),je(0),je(0)]),vc=(o,a)=>Kt("moof",null,[y0(o),...a.map(w0)]),y0=o=>Rt("mfhd",0,0,[je(o)]),hm=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},w0=o=>Kt("traf",null,[k0(o),_0(o),E0(o)]),k0=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:hm(t)};return Rt("tfhd",0,a,[je(o.id),je(n.duration),je(n.size),je(n.flags)])},_0=o=>Rt("tfdt",1,0,[Qn(tn(o.currentChunk.startTimestamp,o.timescale))]),E0=o=>{let a=o.currentChunk.samples.map(v=>v.timescaleUnitsToNextSample),t=o.currentChunk.samples.map(v=>v.size),n=o.currentChunk.samples.map(hm),i=o.currentChunk.samples.map(v=>tn(v.presentationTimestamp-v.decodeTimestamp,o.timescale)),r=new Set(a),s=new Set(t),l=new Set(n),d=new Set(i),c=l.size===2&&n[0]!==n[1],u=r.size>1,m=s.size>1,f=!c&&l.size>1,p=d.size>1||[...d].some(v=>v!==0),h=0;return h|=1,h|=4*+c,h|=256*+u,h|=512*+m,h|=1024*+f,h|=2048*+p,Rt("trun",1,h,[je(o.currentChunk.samples.length),je(o.currentChunk.offset-o.currentChunk.moofOffset||0),c?je(n[0]):[],o.currentChunk.samples.map((v,E)=>[u?je(a[E]):[],m?je(t[E]):[],f?je(n[E]):[],p?Rb(i[E]):[]])])},S0=o=>Kt("mfra",null,[...o.map(C0),x0()]),C0=(o,a)=>Rt("tfra",1,0,[je(o.id),je(63),je(o.finalizedChunks.length),o.finalizedChunks.map(n=>[Qn(tn(n.startTimestamp,o.timescale)),Qn(n.moofOffset),je(a+1),je(1),je(1)])]),x0=()=>Rt("mfro",0,0,[je(0)]),V0={avc:"avc1",hevc:"hvc1",vp9:"vp09",av1:"av01"},N0={avc:o0,hevc:i0,vp9:r0,av1:s0},T0={aac:"mp4a",opus:"Opus"},B0={aac:d0,opus:c0},ts=class{},id=class extends ts{constructor(){super(...arguments),this.buffer=null}},vm=class extends ts{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.")}},M0=class extends ts{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")}},On,xo,gm=class{constructor(){this.pos=0,it(this,On,new Uint8Array(8)),it(this,xo,new DataView(q(this,On).buffer)),this.offsets=new WeakMap}seek(o){this.pos=o}writeU32(o){q(this,xo).setUint32(0,o,!1),this.write(q(this,On).subarray(0,4))}writeU64(o){q(this,xo).setUint32(0,Math.floor(o/2**32),!1),q(this,xo).setUint32(4,o,!1),this.write(q(this,On).subarray(0,8))}writeAscii(o){for(let a=0;a<o.length;a++)q(this,xo).setUint8(a%8,o.charCodeAt(a)),a%8===7&&this.write(q(this,On));o.length%8!==0&&this.write(q(this,On).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}}};On=new WeakMap;xo=new WeakMap;var _r,Jn,Ni,mi,Er,pl,I0=class extends gm{constructor(o){super(),it(this,Er),it(this,_r,void 0),it(this,Jn,new ArrayBuffer(2**16)),it(this,Ni,new Uint8Array(q(this,Jn))),it(this,mi,0),na(this,_r,o)}write(o){mt(this,Er,pl).call(this,this.pos+o.byteLength),q(this,Ni).set(o,this.pos),this.pos+=o.byteLength,na(this,mi,Math.max(q(this,mi),this.pos))}finalize(){mt(this,Er,pl).call(this,this.pos),q(this,_r).buffer=q(this,Jn).slice(0,Math.max(q(this,mi),this.pos))}};_r=new WeakMap;Jn=new WeakMap;Ni=new WeakMap;mi=new WeakMap;Er=new WeakSet;pl=function(o){let a=q(this,Jn).byteLength;for(;a<o;)a*=2;if(a===q(this,Jn).byteLength)return;let t=new ArrayBuffer(a),n=new Uint8Array(t);n.set(q(this,Ni),0),na(this,Jn,t),na(this,Ni,n)};var $0=2**24,F0=2,gi,zn,pi,un,Na,Rr,fl,rd,bm,sd,ym,bi,Ar,ld=class extends gm{constructor(o){var a,t;super(),it(this,Rr),it(this,rd),it(this,sd),it(this,bi),it(this,gi,void 0),it(this,zn,[]),it(this,pi,void 0),it(this,un,void 0),it(this,Na,[]),na(this,gi,o),na(this,pi,((a=o.options)==null?void 0:a.chunked)??!1),na(this,un,((t=o.options)==null?void 0:t.chunkSize)??$0)}write(o){q(this,zn).push({data:o.slice(),start:this.pos}),this.pos+=o.byteLength}flush(){var t,n;if(q(this,zn).length===0)return;let o=[],a=[...q(this,zn)].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],s=a[i];s.start<=r.start+r.size?r.size=Math.max(r.size,s.start+s.data.byteLength-r.start):o.push({start:s.start,size:s.data.byteLength})}for(let i of o){i.data=new Uint8Array(i.size);for(let r of q(this,zn))i.start<=r.start&&r.start<i.start+i.size&&i.data.set(r.data,r.start-i.start);q(this,pi)?(mt(this,Rr,fl).call(this,i.data,i.start),mt(this,bi,Ar).call(this)):(n=(t=q(this,gi).options).onData)==null||n.call(t,i.data,i.start)}q(this,zn).length=0}finalize(){q(this,pi)&&mt(this,bi,Ar).call(this,!0)}};gi=new WeakMap;zn=new WeakMap;pi=new WeakMap;un=new WeakMap;Na=new WeakMap;Rr=new WeakSet;fl=function(o,a){let t=q(this,Na).findIndex(l=>l.start<=a&&a<l.start+q(this,un));t===-1&&(t=mt(this,sd,ym).call(this,a));let n=q(this,Na)[t],i=a-n.start,r=o.subarray(0,Math.min(q(this,un)-i,o.byteLength));n.data.set(r,i);let s={start:i,end:i+r.byteLength};if(mt(this,rd,bm).call(this,n,s),n.written[0].start===0&&n.written[0].end===q(this,un)&&(n.shouldFlush=!0),q(this,Na).length>F0){for(let l=0;l<q(this,Na).length-1;l++)q(this,Na)[l].shouldFlush=!0;mt(this,bi,Ar).call(this)}r.byteLength<o.byteLength&&mt(this,Rr,fl).call(this,o.subarray(r.byteLength),a+r.byteLength)};rd=new WeakSet;bm=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)};sd=new WeakSet;ym=function(o){let t={start:Math.floor(o/q(this,un))*q(this,un),data:new Uint8Array(q(this,un)),written:[],shouldFlush:!1};return q(this,Na).push(t),q(this,Na).sort((n,i)=>n.start-i.start),q(this,Na).indexOf(t)};bi=new WeakSet;Ar=function(o=!1){var a,t;for(let n=0;n<q(this,Na).length;n++){let i=q(this,Na)[n];if(!(!i.shouldFlush&&!o)){for(let r of i.written)(t=(a=q(this,gi).options).onData)==null||t.call(a,i.data.subarray(r.start,r.end),i.start+r.start);q(this,Na).splice(n--,1)}}};var D0=class extends ld{constructor(o){var a;super(new vm({onData:(t,n)=>o.stream.write({type:"write",data:t,position:n}),chunked:!0,chunkSize:(a=o.options)==null?void 0:a.chunkSize}))}},hl=1e3,R0=["avc","hevc","vp9","av1"],A0=["aac","opus"],L0=2082844800,P0=["strict","offset","cross-track-offset"],Je,Qe,Lr,Va,ia,aa,No,To,dd,jn,Wn,yi,vl,wm,gl,km,cd,_m,bl,Em,ud,Sm,Sr,yl,Ya,cn,md,Cm,wi,Pr,Ur,pd,Do,Di,Cr,wl,xm=class{constructor(o){if(it(this,vl),it(this,gl),it(this,cd),it(this,bl),it(this,ud),it(this,Sr),it(this,Ya),it(this,md),it(this,wi),it(this,Ur),it(this,Do),it(this,Cr),it(this,Je,void 0),it(this,Qe,void 0),it(this,Lr,void 0),it(this,Va,void 0),it(this,ia,null),it(this,aa,null),it(this,No,Math.floor(Date.now()/1e3)+L0),it(this,To,[]),it(this,dd,1),it(this,jn,[]),it(this,Wn,[]),it(this,yi,!1),mt(this,vl,wm).call(this,o),o.video=vi(o.video),o.audio=vi(o.audio),o.fastStart=vi(o.fastStart),this.target=o.target,na(this,Je,{firstTimestampBehavior:"strict",...o}),o.target instanceof id)na(this,Qe,new I0(o.target));else if(o.target instanceof vm)na(this,Qe,new ld(o.target));else if(o.target instanceof M0)na(this,Qe,new D0(o.target));else throw new Error(`Invalid target: ${o.target}`);mt(this,bl,Em).call(this),mt(this,gl,km).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(mt(this,Cr,wl).call(this),!q(this,Je).video)throw new Error("No video track declared.");if(typeof q(this,Je).fastStart=="object"&&q(this,ia).samples.length===q(this,Je).fastStart.expectedVideoChunks)throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${q(this,Je).fastStart.expectedVideoChunks}).`);let s=mt(this,Sr,yl).call(this,q(this,ia),o,a,t,n,i,r);if(q(this,Je).fastStart==="fragmented"&&q(this,aa)){for(;q(this,Wn).length>0&&q(this,Wn)[0].decodeTimestamp<=s.decodeTimestamp;){let l=q(this,Wn).shift();mt(this,Ya,cn).call(this,q(this,aa),l)}s.decodeTimestamp<=q(this,aa).lastDecodeTimestamp?mt(this,Ya,cn).call(this,q(this,ia),s):q(this,jn).push(s)}else mt(this,Ya,cn).call(this,q(this,ia),s)}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(mt(this,Cr,wl).call(this),!q(this,Je).audio)throw new Error("No audio track declared.");if(typeof q(this,Je).fastStart=="object"&&q(this,aa).samples.length===q(this,Je).fastStart.expectedAudioChunks)throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${q(this,Je).fastStart.expectedAudioChunks}).`);let r=mt(this,Sr,yl).call(this,q(this,aa),o,a,t,n,i);if(q(this,Je).fastStart==="fragmented"&&q(this,ia)){for(;q(this,jn).length>0&&q(this,jn)[0].decodeTimestamp<=r.decodeTimestamp;){let s=q(this,jn).shift();mt(this,Ya,cn).call(this,q(this,ia),s)}r.decodeTimestamp<=q(this,ia).lastDecodeTimestamp?mt(this,Ya,cn).call(this,q(this,aa),r):q(this,Wn).push(r)}else mt(this,Ya,cn).call(this,q(this,aa),r)}finalize(){if(q(this,yi))throw new Error("Cannot finalize a muxer more than once.");if(q(this,Je).fastStart==="fragmented"){for(let a of q(this,jn))mt(this,Ya,cn).call(this,q(this,ia),a);for(let a of q(this,Wn))mt(this,Ya,cn).call(this,q(this,aa),a);mt(this,Ur,pd).call(this,!1)}else q(this,ia)&&mt(this,wi,Pr).call(this,q(this,ia)),q(this,aa)&&mt(this,wi,Pr).call(this,q(this,aa));let o=[q(this,ia),q(this,aa)].filter(Boolean);if(q(this,Je).fastStart==="in-memory"){let a;for(let n=0;n<2;n++){let i=kr(o,q(this,No)),r=q(this,Qe).measureBox(i);a=q(this,Qe).measureBox(q(this,Va));let s=q(this,Qe).pos+r+a;for(let l of q(this,To)){l.offset=s;for(let{data:d}of l.samples)s+=d.byteLength,a+=d.byteLength}if(s<2**32)break;a>=2**32&&(q(this,Va).largeSize=!0)}let t=kr(o,q(this,No));q(this,Qe).writeBox(t),q(this,Va).size=a,q(this,Qe).writeBox(q(this,Va));for(let n of q(this,To))for(let i of n.samples)q(this,Qe).write(i.data),i.data=null}else if(q(this,Je).fastStart==="fragmented"){let a=q(this,Qe).pos,t=S0(o);q(this,Qe).writeBox(t);let n=q(this,Qe).pos-a;q(this,Qe).seek(q(this,Qe).pos-4),q(this,Qe).writeU32(n)}else{let a=q(this,Qe).offsets.get(q(this,Va)),t=q(this,Qe).pos-a;q(this,Va).size=t,q(this,Va).largeSize=t>=2**32,q(this,Qe).patchBox(q(this,Va));let n=kr(o,q(this,No));if(typeof q(this,Je).fastStart=="object"){q(this,Qe).seek(q(this,Lr)),q(this,Qe).writeBox(n);let i=a-q(this,Qe).pos;q(this,Qe).writeBox(Lb(i))}else q(this,Qe).writeBox(n)}mt(this,Do,Di).call(this),q(this,Qe).finalize(),na(this,yi,!0)}};Je=new WeakMap;Qe=new WeakMap;Lr=new WeakMap;Va=new WeakMap;ia=new WeakMap;aa=new WeakMap;No=new WeakMap;To=new WeakMap;dd=new WeakMap;jn=new WeakMap;Wn=new WeakMap;yi=new WeakMap;vl=new WeakSet;wm=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 ts))throw new TypeError("The target must be provided and an instance of Target.");if(o.video){if(!R0.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(!A0.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&&!P0.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.")};gl=new WeakSet;km=function(){var o;if(q(this,Qe).writeBox(Ab({holdsAvc:((o=q(this,Je).video)==null?void 0:o.codec)==="avc",fragmented:q(this,Je).fastStart==="fragmented"})),na(this,Lr,q(this,Qe).pos),q(this,Je).fastStart==="in-memory")na(this,Va,ml(!1));else if(q(this,Je).fastStart!=="fragmented"){if(typeof q(this,Je).fastStart=="object"){let a=mt(this,cd,_m).call(this);q(this,Qe).seek(q(this,Qe).pos+a)}na(this,Va,ml(!0)),q(this,Qe).writeBox(q(this,Va))}mt(this,Do,Di).call(this)};cd=new WeakSet;_m=function(){if(typeof q(this,Je).fastStart!="object")return;let o=0,a=[q(this,Je).fastStart.expectedVideoChunks,q(this,Je).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};bl=new WeakSet;Em=function(){if(q(this,Je).video&&na(this,ia,{id:1,info:{type:"video",codec:q(this,Je).video.codec,width:q(this,Je).video.width,height:q(this,Je).video.height,rotation:q(this,Je).video.rotation??0,decoderConfig:null},timescale:q(this,Je).video.frameRate??57600,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),q(this,Je).audio&&(na(this,aa,{id:q(this,Je).video?2:1,info:{type:"audio",codec:q(this,Je).audio.codec,numberOfChannels:q(this,Je).audio.numberOfChannels,sampleRate:q(this,Je).audio.sampleRate,decoderConfig:null},timescale:q(this,Je).audio.sampleRate,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),q(this,Je).audio.codec==="aac")){let o=mt(this,ud,Sm).call(this,2,q(this,Je).audio.sampleRate,q(this,Je).audio.numberOfChannels);q(this,aa).info.decoderConfig={codec:q(this,Je).audio.codec,description:o,numberOfChannels:q(this,Je).audio.numberOfChannels,sampleRate:q(this,Je).audio.sampleRate}}};ud=new WeakSet;Sm=function(o,a,t){let i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350].indexOf(a),r=t,s="";s+=o.toString(2).padStart(5,"0"),s+=i.toString(2).padStart(4,"0"),i===15&&(s+=a.toString(2).padStart(24,"0")),s+=r.toString(2).padStart(4,"0");let l=Math.ceil(s.length/8)*8;s=s.padEnd(l,"0");let d=new Uint8Array(s.length/8);for(let c=0;c<s.length;c+=8)d[c/8]=parseInt(s.slice(c,c+8),2);return d};Sr=new WeakSet;yl=function(o,a,t,n,i,r,s){let l=n/1e6,d=(n-(s??0))/1e6,c=i/1e6,u=mt(this,md,Cm).call(this,l,d,o);return l=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:l,decodeTimestamp:d,duration:c,data:a,size:a.byteLength,type:t,timescaleUnitsToNextSample:tn(c,o.timescale)}};Ya=new WeakSet;cn=function(o,a){q(this,Je).fastStart!=="fragmented"&&o.samples.push(a);const t=tn(a.presentationTimestamp-a.decodeTimestamp,o.timescale);if(o.lastTimescaleUnits!==null){let i=tn(a.decodeTimestamp,o.timescale,!1),r=Math.round(i-o.lastTimescaleUnits);if(o.lastTimescaleUnits+=r,o.lastSample.timescaleUnitsToNextSample=r,q(this,Je).fastStart!=="fragmented"){let s=Dr(o.timeToSampleTable);s.sampleCount===1?(s.sampleDelta=r,s.sampleCount++):s.sampleDelta===r?s.sampleCount++:(s.sampleCount--,o.timeToSampleTable.push({sampleCount:2,sampleDelta:r}));const l=Dr(o.compositionTimeOffsetTable);l.sampleCompositionTimeOffset===t?l.sampleCount++:o.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:t})}}else o.lastTimescaleUnits=0,q(this,Je).fastStart!=="fragmented"&&(o.timeToSampleTable.push({sampleCount:1,sampleDelta:tn(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(q(this,Je).fastStart==="fragmented"){let r=q(this,ia)??q(this,aa);const s=q(this,Je).minFragmentDuration??1;o===r&&a.type==="key"&&i>=s&&(n=!0,mt(this,Ur,pd).call(this))}else n=i>=.5}n&&(o.currentChunk&&mt(this,wi,Pr).call(this,o),o.currentChunk={startTimestamp:a.presentationTimestamp,samples:[]}),o.currentChunk.samples.push(a)};md=new WeakSet;Cm=function(o,a,t){var s,l;const n=q(this,Je).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(q(this,Je).firstTimestampBehavior==="offset"||q(this,Je).firstTimestampBehavior==="cross-track-offset"){t.firstDecodeTimestamp===void 0&&(t.firstDecodeTimestamp=a);let d;q(this,Je).firstTimestampBehavior==="offset"?d=t.firstDecodeTimestamp:d=Math.min(((s=q(this,ia))==null?void 0:s.firstDecodeTimestamp)??1/0,((l=q(this,aa))==null?void 0:l.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}};wi=new WeakSet;Pr=function(o){if(q(this,Je).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),q(this,To).push(o.currentChunk),(o.compactlyCodedChunkTable.length===0||Dr(o.compactlyCodedChunkTable).samplesPerChunk!==o.currentChunk.samples.length)&&o.compactlyCodedChunkTable.push({firstChunk:o.finalizedChunks.length,samplesPerChunk:o.currentChunk.samples.length}),q(this,Je).fastStart==="in-memory"){o.currentChunk.offset=0;return}o.currentChunk.offset=q(this,Qe).pos;for(let a of o.currentChunk.samples)q(this,Qe).write(a.data),a.data=null;mt(this,Do,Di).call(this)}};Ur=new WeakSet;pd=function(o=!0){if(q(this,Je).fastStart!=="fragmented")throw new Error("Can't finalize a fragment unless 'fastStart' is set to 'fragmented'.");let a=[q(this,ia),q(this,aa)].filter(l=>l&&l.currentChunk);if(a.length===0)return;let t=Fb(this,dd)._++;if(t===1){let l=kr(a,q(this,No),!0);q(this,Qe).writeBox(l)}let n=q(this,Qe).pos,i=vc(t,a);q(this,Qe).writeBox(i);{let l=ml(!1),d=0;for(let u of a)for(let m of u.currentChunk.samples)d+=m.size;let c=q(this,Qe).measureBox(l)+d;c>=2**32&&(l.largeSize=!0,c=q(this,Qe).measureBox(l)+d),l.size=c,q(this,Qe).writeBox(l)}for(let l of a){l.currentChunk.offset=q(this,Qe).pos,l.currentChunk.moofOffset=n;for(let d of l.currentChunk.samples)q(this,Qe).write(d.data),d.data=null}let r=q(this,Qe).pos;q(this,Qe).seek(q(this,Qe).offsets.get(i));let s=vc(t,a);q(this,Qe).writeBox(s),q(this,Qe).seek(r);for(let l of a)l.finalizedChunks.push(l.currentChunk),q(this,To).push(l.currentChunk),l.currentChunk=null;o&&mt(this,Do,Di).call(this)};Do=new WeakSet;Di=function(){q(this,Qe)instanceof ld&&q(this,Qe).flush()};Cr=new WeakSet;wl=function(){if(q(this,yi))throw new Error("Cannot add new video or audio chunks after the file has been finalized.")};const Ti=30;class Ro extends Error{constructor({message:t="",code:n=""},...i){super(t,...i);ee(this,"message");ee(this,"code");this.code=n,this.message=t}}class mn extends Ro{}class Xt extends Ro{}class Or extends Ro{}class gc extends Ro{}function U0(o,a=Ti){if(a<1)throw new Xt({code:"invalidArgument",message:"FPS must be greater or equal to 1"});return Math.round(o*a)}function Bo(o,a=Ti){if(a<1)throw new Xt({code:"invalidArgument",message:"FPS must be greater or equal to 1"});return Math.round(o/a*1e3)}class Oe{constructor(a=0){ee(this,"time");this.time=Math.round(a)}get millis(){return this.time}set millis(a){this.time=Math.round(a)}get frames(){return U0(this.millis/1e3)}set frames(a){this.millis=Bo(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=Bo(a);return this.millis=this.millis+t,this}add(a){return new Oe(a.millis+this.millis)}subtract(a){return new Oe(this.millis-a.millis)}static fromSeconds(a){const t=new Oe;return t.millis=a*1e3,t}static fromFrames(a,t){const n=new Oe;return n.millis=Bo(a,t),n}copy(){return new Oe(this.millis)}toJSON(){return this.millis}static fromJSON(a){return new Oe(a)}}function bc(o,a){return[o.slice(0,a),o.slice(a)].filter(t=>t.length>0)}function xr(o,a){return a?Math.floor(Math.random()*(a-o+1)+o):o}function O0(o,a,t){t<0&&(t=0);const n=o[a];o.splice(a,1),o.splice(t,0,n)}function yc(o){return typeof o!="function"?!1:/^class\s/.test(Function.prototype.toString.call(o))}function z0(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 s=o.getChannelData(r)[i]*32767;s>32767&&(s=32767),s<-32767&&(s=-32767),n[i*a+r]=s}return n}function j0(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 s=o.getChannelData(r),l=i.getChannelData(r),d=o.sampleRate/a;for(let c=0;c<l.length;c++){const u=c*d,m=Math.floor(u),f=Math.ceil(u);if(f>=s.length)l[c]=s[m];else{const p=u-m;l[c]=s[m]*(1-p)+s[f]*p}}}return i}async function W0(o){const{fps:a,height:t,width:n,bitrate:i}=o,r=["avc1.640034","avc1.4d0034","avc1.640028","avc1.640C32","avc1.64001f","avc1.42001E"],s=["prefer-hardware","prefer-software"],l=[];for(const c of r)for(const u of s)l.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 l){const u=await VideoEncoder.isConfigSupported(c);u.supported&&d.push(u.config??c)}return d.sort(H0)}function H0(o,a){const t=o.hardwareAcceleration??"",n=a.hardwareAcceleration??"";return t<n?-1:t>n?1:0}async function Z0(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 s=new Uint8Array(r),l=new Blob([s],{type:"image/svg+xml"});t.href=URL.createObjectURL(l),t.download=a.split(".")[0]+".svg"}else typeof o=="string"?t.href=o:t.href=URL.createObjectURL(o);t.click(),t.remove()}function wc(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 kc(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 lr{constructor(a){ee(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 Oe}get stop(){var a;return((a=this.words.at(-1))==null?void 0:a.stop)??new Oe}}var kl=(o=>(o.en="en",o.de="de",o))(kl||{});class _c{constructor(a,t,n,i){ee(this,"id",crypto.randomUUID());ee(this,"text");ee(this,"start");ee(this,"stop");ee(this,"confidence");this.text=a,this.start=new Oe(t),this.stop=new Oe(n),this.confidence=i}get duration(){return this.stop.subtract(this.start)}}class Zn{constructor(a=[],t=kl.en){ee(this,"id",crypto.randomUUID());ee(this,"language",kl.en);ee(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[s,l]of i.words.entries())r&&(a&&r.words.length>=xr(...a)?(yield r,r=void 0):t&&(r==null?void 0:r.duration.seconds)>=xr(...t)?(yield r,r=void 0):n&&r.text.length>=xr(...n)&&(yield r,r=void 0)),r?r.words.push(l):r=new lr([l]),s==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=kc(i.start.seconds),s=kc(i.stop.seconds);n+=`${t}
|
|
22
|
+
`+wc(r)+" --> "+wc(s)+`
|
|
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 s of r.words)if(i.length==0&&t&&(n=s.start.millis),i.push(new _c(s.text,s.start.millis-n,s.stop.millis-n)),i.length==a)return new Zn([new lr(i)]);return new Zn([new lr(i)])}copy(){return Zn.fromJSON(this.toJSON())}static fromJSON(a){const t=new Zn;for(const n of a){const i=new lr;for(const r of n)i.words.push(new _c(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 mn({code:"unexpectedIOError",message:"An unexpected error occurred while fetching the file"});return Zn.fromJSON(await n.json())}}function Vr(o,a,t){return o+(a-o)*t}function G0(o,a,t){const n=Number.parseInt(o.slice(1),16),i=Number.parseInt(a.slice(1),16),r=n>>16&255,s=n>>8&255,l=n&255,d=i>>16&255,c=i>>8&255,u=i&255,m=Math.round(Vr(r,d,t)),f=Math.round(Vr(s,c,t)),p=Math.round(Vr(l,u,t));return`#${((1<<24)+(m<<16)+(f<<8)+p).toString(16).slice(1)}`}const X0={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 Xe{constructor(a,t,n={}){ee(this,"input");ee(this,"output");ee(this,"options");if(a.length!==t.length)throw new Xt({code:"invalidKeyframes",message:"inputRange and outputRange must have the same length"});this.input=a.map(i=>Bo(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=X0[this.options.easing](a);if(typeof n=="number"&&typeof i=="number")return Vr(n,i,r);if(typeof n=="string"&&typeof i=="string")return G0(n,i,r);if(this.output.length==1)return this.output[0];throw new Xt({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(Bo(a)),this.output.push(t),this}toJSON(){return this}static fromJSON(a){const t=new Xe([],[]);return Object.assign(t,a),t}}class $a{constructor(){ee(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 Le(o){return function(a,t){a.constructor.__serializableProperties||(a.constructor.__serializableProperties=[]),a.constructor.__serializableProperties.push({propertyKey:t,serializer:o})}}function Ri(o){return class extends o{constructor(){super(...arguments);ee(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,s;const i=new CustomEvent(t,{detail:n});Object.defineProperty(i,"currentTarget",{writable:!1,value:this});for(const l in this._handlers[t]??{})(r=this._handlers[t])==null||r[l](i);for(const l in this._handlers["*"]??{})(s=this._handlers["*"])==null||s[l](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 fd(o,a,t=0){if(!(o instanceof Mt.Container||o instanceof Mt.Filter||t==3))for(const n in o){const i=o[n];n&&(i instanceof Xe&&(o[n]=i.value(a)),i!=null&&typeof i=="object"&&Object.keys(i).length&&fd(i,a,t+1))}}var K0=Object.defineProperty,as=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&K0(a,t,i),i};const Ai=class Vm extends Ri($a){constructor(t={}){super();ee(this,"_name");ee(this,"_start",new Oe);ee(this,"_stop",Oe.fromSeconds(16));ee(this,"type","base");ee(this,"source");ee(this,"view",new Mt.Container);ee(this,"createdAt",new Date);ee(this,"disabled",!1);ee(this,"state","IDLE");ee(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",Oe.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,s;if(t||(t=(s=(r=this.track)==null?void 0:r.composition)==null?void 0:s.frame),typeof t=="number"&&(t=Oe.fromFrames(t)),!t||t.millis<=this.start.millis||t.millis>=this.stop.millis)throw new Xt({code:"splitOutOfRange",message:"Cannot split clip at the specified time"});if(!this.track)throw new Xt({code:"trackNotAttached",message:"Track must be attached to a track"});const n=this.copy();this.stop=t.copy(),n.start=t.copy().addMillis(1),fd(n,n.start.subtract(this.start));const i=this.track.clips.findIndex(l=>l.id==this.id);return await this.track.add(n,i+1),n}copy(){return Vm.fromJSON(JSON.parse(JSON.stringify(this)))}set(t){return t&&Object.assign(this,t),this.trigger("update",void 0),this}};as([Le()],Ai.prototype,"_name");as([Le(Oe)],Ai.prototype,"_start");as([Le(Oe)],Ai.prototype,"_stop");as([Le()],Ai.prototype,"disabled");let Li=Ai;var J0=Object.defineProperty,ro=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&J0(a,t,i),i};class nn extends Ri($a){constructor(){super(...arguments);ee(this,"state","IDLE");ee(this,"metadata");ee(this,"objectURL");ee(this,"duration",Oe.fromSeconds(16));ee(this,"added",!1);ee(this,"type","base");ee(this,"name","");ee(this,"mimeType");ee(this,"externalURL");ee(this,"external",!1);ee(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 Xt({code:"fileNotAccessible",message:"The desired file cannot be accessed"});return this.file}async loadFile(t){this.name=t.name,this.mimeType=Cl(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 mn({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=Cl(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();Z0(t,this.name)}async thumbnail(){return document.createElement("div")}static async from(t,n,i=new this){return i.from(t,n)}}ro([Le()],nn.prototype,"objectURL");ro([Le()],nn.prototype,"duration");ro([Le()],nn.prototype,"type");ro([Le()],nn.prototype,"name");ro([Le()],nn.prototype,"mimeType");ro([Le()],nn.prototype,"externalURL");ro([Le()],nn.prototype,"external");const Ec="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3C/svg%3E";function q0(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 Sc(o){if(!o||!o.body)return Ec;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 Ec;const s=new XMLSerializer,l=i?s.serializeToString(i):"",d=s.serializeToString(r),c=`
|
|
26
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="${a}" height="${t}">
|
|
27
|
+
body { padding: 0; }
|
|
28
|
+
${l}
|
|
29
|
+
<foreignObject width="100%" height="100%">
|
|
30
|
+
${d}
|
|
31
|
+
</foreignObject>
|
|
32
|
+
</svg>`;return"data:image/svg+xml;base64,"+q0(c)}class Cc extends nn{constructor(){super();ee(this,"type","html");ee(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=Sc(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=s=>r(s)})}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=Sc(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 Y0(o,a={}){const{threshold:t=.02,hopSize:n=1024,minDuration:i=500}=a,r=[],s=o.getChannelData(0),l=o.sampleRate,d=Math.floor(i/1e3*l);let c=null,u=0;for(let m=0;m<s.length;m+=n){let f=0;const p=Math.min(m+n,s.length);for(let h=m;h<p;h++)f+=s[h]*s[h];f=Math.sqrt(f/(p-m)),f<t?(u+=n,c===null&&(c=m)):(c!==null&&u>=d&&r.push({start:Oe.fromSeconds(c/l),stop:Oe.fromSeconds(m/l)}),c=null,u=0)}return c!==null&&u>=d&&r.push({start:Oe.fromSeconds(c/l),stop:Oe.fromSeconds(s.length/l)}),r}const Ws=3e3;class xn extends nn{constructor(){super(...arguments);ee(this,"type","audio");ee(this,"decoding",!1);ee(this,"_silences");ee(this,"transcript");ee(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(),s=await new OfflineAudioContext(t,1,n).decodeAudioData(r);return this.duration.seconds=s.duration,i&&(this.audioBuffer=s),this.decoding=!1,this.trigger("update",void 0),s}async samples(t=60,n=50,i=0){const r=this.audioBuffer??await this.decode(1,3e3,!0),s=Math.round(r.sampleRate/n),l=r.sampleRate*r.duration-s,d=Math.ceil(l/t),c=r.getChannelData(0),u=[];for(let m=0;m<l;m+=d){let f=0;for(let p=m;p<m+s;p++)f+=Math.abs(c[m]);u.push(Math.log1p(f/s*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 s=this.audioBuffer??await this.decode(1,Ws,!0),l=s.getChannelData(0),d=Math.floor(Math.max(n*Ws/1e3,0)),c=i?Math.floor(Math.min(i*Ws/1e3,s.length)):s.length,u=Math.floor((c-d)/t),m=new Float32Array(t);for(let f=0;f<t;f++){const p=d+f*u,h=p+u;let v=-1/0;for(let E=p;E<h;E++){const y=l[E];y>v&&(v=y)}m[f]=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 s=document.createElement("div");s.className="audio-sample-item",s.style.height=`${r}%`,i.appendChild(s)}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=Y0(r,t),i.close(),this._silences}}class _l extends nn{constructor(){super(...arguments);ee(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 Xn extends xn{constructor(){super(...arguments);ee(this,"type","video");ee(this,"downloadInProgress",!0)}async loadUrl(t,n){const i=await fetch(t,n);if(!(i!=null&&i.ok))throw new mn({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=Cl(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 Xt({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(),s=n.clientX-((r==null?void 0:r.left)??0),l=i==null?void 0:i.duration;l&&r&&r.width>0&&(i.currentTime=Math.round(l*(s/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 Q0{static fromJSON(a){return[new Oe(a[0]),new Oe(a[1])]}}var ey=Object.defineProperty,ty=Object.getOwnPropertyDescriptor,Lo=(o,a,t,n)=>{for(var i=n>1?void 0:n?ty(a,t):a,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(a,t,i):s(i))||i);return n&&i&&ey(a,t,i),i};const so=class Nm extends Li{constructor(t={}){super();ee(this,"source",new xn);ee(this,"_offset",new Oe);ee(this,"playing",!1);ee(this,"duration",new Oe);ee(this,"range",[new Oe,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=Oe.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=Oe.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",Oe.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 gc({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=Oe.fromFrames(t)),typeof n=="number"&&(n=Oe.fromFrames(n)),t.millis>=n.millis)throw new Xt({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=Nm.fromJSON(JSON.parse(JSON.stringify(this)));return t.source=this.source,t}async split(t){var r,s;if(t||(t=(s=(r=this.track)==null?void 0:r.composition)==null?void 0:s.frame),typeof t=="number"&&(t=Oe.fromFrames(t)),!t||t.millis<=this.start.millis||t.millis>=this.stop.millis)throw new Xt({code:"invalidKeyframe",message:"Cannot split clip at the specified time"});if(!this.track)throw new gc({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),fd(n,n.start.subtract(this.start));const i=this.track.clips.findIndex(l=>l.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 Xt({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(s=>xc(s,this.range)).sort((s,l)=>s.start.millis-l.start.millis);if(n.length==0)return[this];const i=t.padding??500,r=[this];for(const s of n){const l=r.at(-1);if(!l)break;if(!xc(s,l.range))continue;const d=new Oe(Math.min(s.start.millis+i,s.stop.millis));if(s.start.millis>l.range[0].millis&&s.stop.millis<l.range[1].millis){const c=l.copy();l.range[1]=d,c.range[0]=s.stop,r.push(c)}else s.start.millis<=l.range[0].millis?l.range[0]=s.stop:s.stop.millis>=l.range[1].millis&&(l.range[1]=d)}return r}};Lo([Le(Oe)],so.prototype,"_offset",2);Lo([Le(Oe)],so.prototype,"duration",2);Lo([Le(Q0)],so.prototype,"range",2);Lo([Le(Zn)],so.prototype,"transcript",1);Lo([Le()],so.prototype,"muted",1);Lo([Le()],so.prototype,"volume",1);let ns=so;function xc(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 dr{static fromJSON(a){return typeof a=="object"?Xe.fromJSON(a):a}}class Hs{static fromJSON(a){return typeof a.x=="object"&&(a.x=Xe.fromJSON(a.x)),typeof a.y=="object"&&(a.y=Xe.fromJSON(a.y)),a}}let ay=class{constructor(o){ee(this,"target");ee(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 Xe(i,r,{easing:n})}};function ny(o){const a=new Proxy(o,{get(t,n){return n=="to"?(i,r)=>{if(!t.animation)throw new Xt({code:"undefinedKeyframe",message:"Cannot use 'to() before selecting a property"});const s=new Oe(t.animation.input.at(-1)).frames+r;return t.animation.push(s,i),a}:(i,r,s)=>(t.init(n,i,r,s),a)}});return a}class oy extends ay{}var iy=Object.defineProperty,ry=Object.getOwnPropertyDescriptor,En=(o,a,t,n)=>{for(var i=n>1?void 0:n?ry(a,t):a,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(a,t,i):s(i))||i);return n&&i&&iy(a,t,i),i};function os(o){class a extends o{constructor(){super(...arguments);ee(this,"filters");ee(this,"_height");ee(this,"_width");ee(this,"_position",{x:this.view.position.x,y:this.view.position.y});ee(this,"_scale");ee(this,"rotation",this.view.angle);ee(this,"alpha",1);ee(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 Xe||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 Mt.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 s of this.view.children)s instanceof Mt.Sprite&&s.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 ny(new oy(this))}}return En([Le(dr)],a.prototype,"_height",2),En([Le(dr)],a.prototype,"_width",2),En([Le(Hs)],a.prototype,"_position",2),En([Le(Hs)],a.prototype,"_scale",2),En([Le(dr)],a.prototype,"rotation",2),En([Le(dr)],a.prototype,"alpha",2),En([Le(Hs)],a.prototype,"translate",2),En([Le()],a.prototype,"anchor",1),a}function is(o,a,t){const n=t.value;return t.value=function(...i){var m,f,p,h;const r=i[0].subtract(this.start),s={width:((f=(m=this.track)==null?void 0:m.composition)==null?void 0:f.width)??1920,height:((h=(p=this.track)==null?void 0:p.composition)==null?void 0:h.height)??1080};let l;typeof this.translate.x=="number"?l=this.translate.x:typeof this.translate.x=="function"?l=this.translate.x.bind(this)(r):l=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)*s.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)*s.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+l,u+d),typeof this._height=="string"?this.view.height=Math.round(Number.parseFloat(this._height)*s.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)*s.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 E;typeof this._scale.y=="number"?E=this._scale.y:typeof this._scale.y=="function"?E=this._scale.y.bind(this)(r):E=this._scale.y.value(r),(this._width||this._height)&&(v*=this.view.scale._x,E*=this.view.scale._y),this.view.scale.set(v,E)}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 sy=Object.defineProperty,ly=Object.getOwnPropertyDescriptor,dy=(o,a,t,n)=>{for(var i=ly(a,t),r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&sy(a,t,i),i};const Tm=class Bm extends os(Li){constructor(t,n={}){super();ee(this,"type","image");ee(this,"element",new Image);ee(this,"source",new _l);ee(this,"sprite",new Mt.Sprite);this.view.addChild(this.sprite),t instanceof _l&&(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=Mt.Texture.from(this.element),this.state="READY",t()},this.element.onerror=i=>{this.state="ERROR",n(new mn({code:"sourceNotProcessable",message:"An error occurred while processing the input medium."}))}})}update(t){}copy(){const t=Bm.fromJSON(JSON.parse(JSON.stringify(this)));return t.filters=this.filters,t.source=this.source,t}};dy([is],Tm.prototype,"update");let cy=Tm;const cr={"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 uy=Object.defineProperty,rs=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&uy(a,t,i),i};const Pi=class El extends Ri($a){constructor(t){super();ee(this,"loaded",!1);ee(this,"family");ee(this,"weight");ee(this,"source");ee(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=El.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(cr).map(t=>({family:t,variants:cr[t].weights.map(n=>({family:t,source:`url(${cr[t].url})`,weight:n}))}))}static fromFamily({family:t,weight:n}){return new El({family:t,source:`url(${cr[t].url})`,weight:n})}};rs([Le()],Pi.prototype,"family");rs([Le()],Pi.prototype,"weight");rs([Le()],Pi.prototype,"source");rs([Le()],Pi.prototype,"style");let ca=Pi;const en=4,Mm={center:.5,justify:.5,left:0,right:1},Im={alphabetic:0,top:0,middle:.5,hanging:1,bottom:1,ideographic:1};var my=Object.defineProperty,py=Object.getOwnPropertyDescriptor,ka=(o,a,t,n)=>{for(var i=py(a,t),r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&my(a,t,i),i};const pa=class $m extends os(Li){constructor(t){super();ee(this,"type","text");ee(this,"_text","");ee(this,"_textCase");ee(this,"_anchor",{x:0,y:0});ee(this,"_font",new ca);ee(this,"style",new Mt.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 Mt.Text({text:this.transformedText,style:this.style,resolution:en,scale:en});this.view.addChild(n)}this.view.children[0]instanceof Mt.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*en}set maxWidth(t){t?(this.style.wordWrap=!0,this.style.wordWrapWidth=t/en):this.style.wordWrap=!1}get textAlign(){return this.style.align}set textAlign(t){this.style.align=t,this.anchor.x=Mm[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=Im[t]}get fillStyle(){const{fill:t}=this.style;return new Mt.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:s}=this.style.stroke;return t=new Mt.Color(t).toHex().toUpperCase(),{color:t,alpha:n,width:i,join:r,miterLimit:s}}set stroke(t){if(!t){this.style.stroke=void 0;return}const{color:n="#000000",alpha:i=1,width:r=3,join:s="round",miterLimit:l}=t;this.style.stroke={color:n,alpha:i,width:r,join:s,miterLimit:l}}get textCase(){return this._textCase}set textCase(t){this._textCase=t,this.view.children[0]instanceof Mt.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:s}=this.style.dropShadow,l=new Mt.Color(r).toHex().toUpperCase();return{alpha:t,angle:n,blur:i,color:l,distance:s}}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=$m.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,s,l;const t=((r=this.view.children[0])==null?void 0:r.width)??0,n=((s=this.view.children[0])==null?void 0:s.height)??0,i=(((l=this.style.dropShadow)==null?void 0:l.distance)??0)*en;this.view.pivot={x:(t-i)*this._anchor.x,y:(n-i)*this._anchor.y}}set(t){return super.set(t)}};ka([Le()],pa.prototype,"text");ka([Le(ca)],pa.prototype,"font");ka([Le()],pa.prototype,"maxWidth");ka([Le()],pa.prototype,"textAlign");ka([Le()],pa.prototype,"padding");ka([Le()],pa.prototype,"textBaseline");ka([Le()],pa.prototype,"fillStyle");ka([Le()],pa.prototype,"anchor");ka([Le()],pa.prototype,"stroke");ka([Le()],pa.prototype,"textCase");ka([Le()],pa.prototype,"shadow");ka([Le()],pa.prototype,"fontSize");ka([Le()],pa.prototype,"leading");ka([is],pa.prototype,"update");let Po=pa;function Zs(o){const a=o.split(" ").map(t=>`${t} `);return a[a.length-1]=a[a.length-1].replace(/ $/,""),a}const fy={get(o,a){const t=o[a];return typeof t=="number"?t*en:Array.isArray(t)&&typeof t[0]=="number"?t.map(n=>n*en):t}};function hy(o){return new Proxy(o,fy)}class vy{constructor(){ee(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 Vc{constructor(){ee(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 gy{static fromJSON(a){return a.map(t=>(t.font&&(t.font=ca.fromJSON(t.font)),t))}}var by=Object.defineProperty,yy=Object.getOwnPropertyDescriptor,Uo=(o,a,t,n)=>{for(var i=n>1?void 0:n?yy(a,t):a,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(a,t,i):s(i))||i);return n&&i&&by(a,t,i),i};const lo=class Fm extends Po{constructor(t){super();ee(this,"type","complex_text");ee(this,"_maxWidth");ee(this,"_textAlign","left");ee(this,"_textBaseline","top");ee(this,"model",new Mt.Container);ee(this,"segments",[]);ee(this,"metrics",new Vc);ee(this,"background");ee(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=Mm[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 s of i.tokens)this.model.children[s.index].x=r,r+=s.metrics.lineWidths[0]}}get textBaseline(){return this._textBaseline}set textBaseline(t){this._textBaseline=t,this._anchor.y=Im[t];let n=0;for(const i of this.metrics.lines){const r=i.height;for(const s of i.tokens){let l=0;t=="middle"&&(l=(r-s.metrics.lineHeight)/2),t=="bottom"&&(l=r-s.metrics.lineHeight),this.model.children[s.index].y=n+l}n+=r}}copy(){const t=Fm.fromJSON(JSON.parse(JSON.stringify(this)));return t.filters=this.filters,t.font=this.font,t}createRenderSplits(t=[]){var r,s;const n=this.transformedText??"",i=[{index:void 0,tokens:Zs(n.substring(0,(r=t==null?void 0:t.at(0))==null?void 0:r.start))}];for(let l=0;l<t.length;l++)i.push({index:t[l].index,tokens:Zs(n.substring(t[l].start,t[l].stop))}),!((t[l].stop??n.length)>=n.length)&&i.push({index:void 0,tokens:Zs(n.substring(t[l].stop,(s=t.at(l+1))==null?void 0:s.start))});return i.filter(l=>l.tokens.join("").trim().length)}createTextMetrics(t,n){var r,s,l;const i=new Vc;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=hy(Mt.CanvasTextMetrics.measureText(d.tokens[u],c)),f=(((r=i.lines.at(-1))==null?void 0:r.width)??0)+m.lineWidths[0],p=this.maxWidth??Number.POSITIVE_INFINITY,h=(s=d.tokens.at(u-1))==null?void 0:s.match(/(\n|\\n).$/gim);(f>p||h||!i.lines.length)&&i.lines.push(new vy),this.model.addChild(new Mt.Text({text:d.tokens[u],style:c,resolution:en,scale:en})),(l=i.lines.at(-1))==null||l.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 l,d;if(this.view.children.length>1&&this.view.removeChildAt(0),!this.background)return;const t=this.model.width,n=this.model.height,i=((l=this.background.padding)==null?void 0:l.x)??40,r=((d=this.background.padding)==null?void 0:d.y)??10,s=new Mt.Graphics;s.roundRect(0-i/2,2-r/2,t+i,n+r,this.background.borderRadius??20),s.fill(this.background.fill??"#000000"),s.alpha=this.background.alpha??1,this.view.addChildAt(s,0)}reflectUpdate(){var l;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,s=(((l=this.style.dropShadow)==null?void 0:l.distance)??0)*en;this.view.pivot={x:(i-s)*this._anchor.x,y:(r-s)*this._anchor.y},this.drawBackground()}};Uo([Le()],lo.prototype,"background",2);Uo([Le(gy)],lo.prototype,"styles",2);Uo([Le()],lo.prototype,"text",1);Uo([Le()],lo.prototype,"maxWidth",1);Uo([Le()],lo.prototype,"textAlign",1);Uo([Le()],lo.prototype,"textBaseline",1);let ss=lo;const Dm="KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO3ZhciBtPSh0PT4odFt0LkFWTUVESUFfVFlQRV9VTktOT1dOPS0xXT0iQVZNRURJQV9UWVBFX1VOS05PV04iLHRbdC5BVk1FRElBX1RZUEVfVklERU89MF09IkFWTUVESUFfVFlQRV9WSURFTyIsdFt0LkFWTUVESUFfVFlQRV9BVURJTz0xXT0iQVZNRURJQV9UWVBFX0FVRElPIix0W3QuQVZNRURJQV9UWVBFX0RBVEE9Ml09IkFWTUVESUFfVFlQRV9EQVRBIix0W3QuQVZNRURJQV9UWVBFX1NVQlRJVExFPTNdPSJBVk1FRElBX1RZUEVfU1VCVElUTEUiLHRbdC5BVk1FRElBX1RZUEVfQVRUQUNITUVOVD00XT0iQVZNRURJQV9UWVBFX0FUVEFDSE1FTlQiLHRbdC5BVk1FRElBX1RZUEVfTkI9NV09IkFWTUVESUFfVFlQRV9OQiIsdCkpKG18fHt9KSxvPSh0PT4odC5GRm1wZWdXb3JrZXJMb2FkZWQ9IkZGbXBlZ1dvcmtlckxvYWRlZCIsdC5XQVNNUnVudGltZUluaXRpYWxpemVkPSJXQVNNUnVudGltZUluaXRpYWxpemVkIix0LkxvYWRXQVNNPSJMb2FkV0FTTSIsdC5HZXRBVlBhY2tldD0iR2V0QVZQYWNrZXQiLHQuR2V0QVZQYWNrZXRzPSJHZXRBVlBhY2tldHMiLHQuR2V0QVZTdHJlYW09IkdldEFWU3RyZWFtIix0LkdldEFWU3RyZWFtcz0iR2V0QVZTdHJlYW1zIix0LlJlYWRBVlBhY2tldD0iUmVhZEFWUGFja2V0Iix0LkFWUGFja2V0U3RyZWFtPSJBVlBhY2tldFN0cmVhbSIsdC5SZWFkTmV4dEFWUGFja2V0PSJSZWFkTmV4dEFWUGFja2V0Iix0LlN0b3BSZWFkQVZQYWNrZXQ9IlN0b3BSZWFkQVZQYWNrZXQiLHQpKShvfHx7fSk7Y29uc3QgQT0iS0daMWJtTjBhVzl1S0NsN0luVnpaU0J6ZEhKcFkzUWlPMnhsZENCbU8zTmxiR1l1Y0c5emRFMWxjM05oWjJVb2UzUjVjR1U2SWtaR2JYQmxaMWR2Y210bGNreHZZV1JsWkNKOUtTeHpaV3htTG1Ga1pFVjJaVzUwVEdsemRHVnVaWElvSW0xbGMzTmhaMlVpTEdGemVXNWpJR1oxYm1OMGFXOXVLR3dwZTJOdmJuTjBlM1I1Y0dVNmRDeGtZWFJoT21NOWUzMHNiWE5uU1dRNmIzMDliQzVrWVhSaE8zUnllWHRwWmloMFBUMDlJa3h2WVdSWFFWTk5JaWw3WTI5dWMzUjdkMkZ6YlV4dllXUmxjbEJoZEdnNlpYMDlZM3g4ZTMwN1pqMWhkMkZwZENoaGQyRnBkQ0JwYlhCdmNuUW9aU2twTG1SbFptRjFiSFFvS1gxbGJITmxJR2xtS0hROVBUMGlSMlYwUVZaVGRISmxZVzBpS1h0amIyNXpkSHRtYVd4bE9tVXNjM1J5WldGdFZIbHdaVHB6TEhOMGNtVmhiVWx1WkdWNE9tRjlQV01zY2oxbUxtZGxkRUZXVTNSeVpXRnRLR1VzY3l4aEtUdHpaV3htTG5CdmMzUk5aWE56WVdkbEtIdDBlWEJsT25Rc2JYTm5TV1E2Ynl4eVpYTjFiSFE2Y24wc1czSXVZMjlrWldOd1lYSXVaWGgwY21Ga1lYUmhMbUoxWm1abGNsMHBmV1ZzYzJVZ2FXWW9kRDA5UFNKSFpYUkJWbE4wY21WaGJYTWlLWHRqYjI1emRIdG1hV3hsT21WOVBXTXNjejFtTG1kbGRFRldVM1J5WldGdGN5aGxLVHR6Wld4bUxuQnZjM1JOWlhOellXZGxLSHQwZVhCbE9uUXNiWE5uU1dRNmJ5eHlaWE4xYkhRNmMzMHNjeTV0WVhBb1lUMCtZUzVqYjJSbFkzQmhjaTVsZUhSeVlXUmhkR0V1WW5WbVptVnlLU2w5Wld4elpTQnBaaWgwUFQwOUlrZGxkRUZXVUdGamEyVjBJaWw3WTI5dWMzUjdabWxzWlRwbExIUnBiV1U2Y3l4emRISmxZVzFVZVhCbE9tRXNjM1J5WldGdFNXNWtaWGc2Y24wOVl5eHVQV1l1WjJWMFFWWlFZV05yWlhRb1pTeHpMR0VzY2lrN2MyVnNaaTV3YjNOMFRXVnpjMkZuWlNoN2RIbHdaVHAwTEcxelowbGtPbThzY21WemRXeDBPbTU5TEZ0dUxtUmhkR0V1WW5WbVptVnlYU2w5Wld4elpTQnBaaWgwUFQwOUlrZGxkRUZXVUdGamEyVjBjeUlwZTJOdmJuTjBlMlpwYkdVNlpTeDBhVzFsT25OOVBXTXNZVDFtTG1kbGRFRldVR0ZqYTJWMGN5aGxMSE1wTzNObGJHWXVjRzl6ZEUxbGMzTmhaMlVvZTNSNWNHVTZkQ3h0YzJkSlpEcHZMSEpsYzNWc2REcGhmU3hoTG0xaGNDaHlQVDV5TG1SaGRHRXVZblZtWm1WeUtTbDlaV3h6WlNCcFppaDBQVDA5SWxKbFlXUkJWbEJoWTJ0bGRDSXBlMk52Ym5OMGUyWnBiR1U2WlN4emRHRnlkRHB6TEdWdVpEcGhMSE4wY21WaGJWUjVjR1U2Y2l4emRISmxZVzFKYm1SbGVEcHVmVDFqTEdROVppNXlaV0ZrUVZaUVlXTnJaWFFvYnl4bExITXNZU3h5TEc0cE8zTmxiR1l1Y0c5emRFMWxjM05oWjJVb2UzUjVjR1U2ZEN4dGMyZEpaRHB2TEhKbGMzVnNkRHBrZlNsOWZXTmhkR05vS0dVcGUzTmxiR1l1Y0c5emRFMWxjM05oWjJVb2UzUjVjR1U2ZEN4dGMyZEpaRHB2TEdWeWNrMXpaenBsSUdsdWMzUmhibU5sYjJZZ1JYSnliM0kvWlM1dFpYTnpZV2RsT2lKVmJtdHViM2R1SUVWeWNtOXlJbjBwZlgwcGZTa29LVHNLIixnPXQ9PlVpbnQ4QXJyYXkuZnJvbShhdG9iKHQpLGU9PmUuY2hhckNvZGVBdCgwKSksVj10eXBlb2Ygc2VsZjwidSImJnNlbGYuQmxvYiYmbmV3IEJsb2IoW2coQSldLHt0eXBlOiJ0ZXh0L2phdmFzY3JpcHQ7Y2hhcnNldD11dGYtOCJ9KTtmdW5jdGlvbiBFKHQpe2xldCBlO3RyeXtpZihlPVYmJihzZWxmLlVSTHx8c2VsZi53ZWJraXRVUkwpLmNyZWF0ZU9iamVjdFVSTChWKSwhZSl0aHJvdyIiO2NvbnN0IHM9bmV3IFdvcmtlcihlLHtuYW1lOnQ/Lm5hbWV9KTtyZXR1cm4gcy5hZGRFdmVudExpc3RlbmVyKCJlcnJvciIsKCk9Pnsoc2VsZi5VUkx8fHNlbGYud2Via2l0VVJMKS5yZXZva2VPYmplY3RVUkwoZSl9KSxzfWNhdGNoe3JldHVybiBuZXcgV29ya2VyKCJkYXRhOnRleHQvamF2YXNjcmlwdDtiYXNlNjQsIitBLHtuYW1lOnQ/Lm5hbWV9KX1maW5hbGx5e2UmJihzZWxmLlVSTHx8c2VsZi53ZWJraXRVUkwpLnJldm9rZU9iamVjdFVSTChlKX19Y29uc3QgdT0xZTY7Y2xhc3MgcHtmZm1wZWdXb3JrZXI7ZmZtcGVnV29ya2VyTG9hZFN0YXR1czttc2dJZDtmaWxlO2NvbnN0cnVjdG9yKGUpe3RoaXMuZmZtcGVnV29ya2VyPW5ldyBFLHRoaXMuZmZtcGVnV29ya2VyTG9hZFN0YXR1cz1uZXcgUHJvbWlzZSgocyxhKT0+e3RoaXMuZmZtcGVnV29ya2VyLmFkZEV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGk9Pntjb25zdHt0eXBlOnIsZXJyTXNnOmR9PWkuZGF0YTtyPT09by5GRm1wZWdXb3JrZXJMb2FkZWQmJnRoaXMucG9zdChvLkxvYWRXQVNNLHt3YXNtTG9hZGVyUGF0aDplLndhc21Mb2FkZXJQYXRofSkscj09PW8uV0FTTVJ1bnRpbWVJbml0aWFsaXplZCYmcyghMCkscj09PW8uTG9hZFdBU00mJmQmJmEoZCl9KX0pLHRoaXMubXNnSWQ9MH1wb3N0KGUscyxhKXt0aGlzLmZmbXBlZ1dvcmtlci5wb3N0TWVzc2FnZSh7dHlwZTplLG1zZ0lkOmE/P3RoaXMubXNnSWQrKyxkYXRhOnN9KX1hc3luYyBsb2FkKGUpe2NvbnN0IHM9YXdhaXQgdGhpcy5mZm1wZWdXb3JrZXJMb2FkU3RhdHVzO3JldHVybiB0aGlzLmZpbGU9ZSxzfWRlc3Ryb3koKXt0aGlzLmZpbGU9dm9pZCAwLHRoaXMuZmZtcGVnV29ya2VyLnRlcm1pbmF0ZSgpfWdldEFWU3RyZWFtKGU9bS5BVk1FRElBX1RZUEVfVklERU8scz0tMSl7cmV0dXJuIG5ldyBQcm9taXNlKChhLGkpPT57aWYoIXRoaXMuZmlsZSl7aSgiZmlsZSBpcyBub3QgbG9hZGVkIik7cmV0dXJufWNvbnN0IHI9dGhpcy5tc2dJZCxkPSh7ZGF0YTpufSk9PntuLnR5cGU9PT1vLkdldEFWU3RyZWFtJiZuLm1zZ0lkPT09ciYmKG4uZXJyTXNnP2kobi5lcnJNc2cpOmEobi5yZXN1bHQpLHRoaXMuZmZtcGVnV29ya2VyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGQpKX07dGhpcy5mZm1wZWdXb3JrZXIuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsZCksdGhpcy5wb3N0KG8uR2V0QVZTdHJlYW0se2ZpbGU6dGhpcy5maWxlLHN0cmVhbVR5cGU6ZSxzdHJlYW1JbmRleDpzfSl9KX1nZXRBVlN0cmVhbXMoKXtyZXR1cm4gbmV3IFByb21pc2UoKGUscyk9PntpZighdGhpcy5maWxlKXtzKCJmaWxlIGlzIG5vdCBsb2FkZWQiKTtyZXR1cm59Y29uc3QgYT10aGlzLm1zZ0lkLGk9KHtkYXRhOnJ9KT0+e3IudHlwZT09PW8uR2V0QVZTdHJlYW1zJiZyLm1zZ0lkPT09YSYmKHIuZXJyTXNnP3Moci5lcnJNc2cpOmUoci5yZXN1bHQpLHRoaXMuZmZtcGVnV29ya2VyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGkpKX07dGhpcy5mZm1wZWdXb3JrZXIuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsaSksdGhpcy5wb3N0KG8uR2V0QVZTdHJlYW1zLHtmaWxlOnRoaXMuZmlsZX0pfSl9Z2V0QVZQYWNrZXQoZSxzPW0uQVZNRURJQV9UWVBFX1ZJREVPLGE9LTEpe3JldHVybiBuZXcgUHJvbWlzZSgoaSxyKT0+e2lmKCF0aGlzLmZpbGUpe3IoImZpbGUgaXMgbm90IGxvYWRlZCIpO3JldHVybn1jb25zdCBkPXRoaXMubXNnSWQsbj1oPT57Y29uc3QgbD1oLmRhdGE7bC50eXBlPT09by5HZXRBVlBhY2tldCYmbC5tc2dJZD09PWQmJihsLmVyck1zZz9yKGwuZXJyTXNnKTppKGwucmVzdWx0KSx0aGlzLmZmbXBlZ1dvcmtlci5yZW1vdmVFdmVudExpc3RlbmVyKCJtZXNzYWdlIixuKSl9O3RoaXMuZmZtcGVnV29ya2VyLmFkZEV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLG4pLHRoaXMucG9zdChvLkdldEFWUGFja2V0LHtmaWxlOnRoaXMuZmlsZSx0aW1lOmUsc3RyZWFtVHlwZTpzLHN0cmVhbUluZGV4OmF9KX0pfWdldEFWUGFja2V0cyhlKXtyZXR1cm4gbmV3IFByb21pc2UoKHMsYSk9PntpZighdGhpcy5maWxlKXthKCJmaWxlIGlzIG5vdCBsb2FkZWQiKTtyZXR1cm59Y29uc3QgaT10aGlzLm1zZ0lkLHI9ZD0+e2NvbnN0IG49ZC5kYXRhO24udHlwZT09PW8uR2V0QVZQYWNrZXRzJiZuLm1zZ0lkPT09aSYmKG4uZXJyTXNnP2Eobi5lcnJNc2cpOnMobi5yZXN1bHQpLHRoaXMuZmZtcGVnV29ya2VyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLHIpKX07dGhpcy5mZm1wZWdXb3JrZXIuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsciksdGhpcy5wb3N0KG8uR2V0QVZQYWNrZXRzLHtmaWxlOnRoaXMuZmlsZSx0aW1lOmV9KX0pfXJlYWRBVlBhY2tldChlPTAscz0wLGE9bS5BVk1FRElBX1RZUEVfVklERU8saT0tMSl7Y29uc3Qgcj1uZXcgQ291bnRRdWV1aW5nU3RyYXRlZ3koe2hpZ2hXYXRlck1hcms6MX0pLGQ9dGhpcy5tc2dJZDtsZXQgbj0wO3JldHVybiBuZXcgUmVhZGFibGVTdHJlYW0oe3N0YXJ0Omg9PntpZighdGhpcy5maWxlKXtoLmVycm9yKCJmaWxlIGlzIG5vdCBsb2FkZWQiKTtyZXR1cm59Y29uc3QgbD1mPT57Y29uc3QgYz1mLmRhdGE7Yy50eXBlPT09by5SZWFkQVZQYWNrZXQmJmMubXNnSWQ9PT1kJiZjLmVyck1zZyYmKGguZXJyb3IoYy5lcnJNc2cpLHRoaXMuZmZtcGVnV29ya2VyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGwpKSxjLnR5cGU9PT1vLkFWUGFja2V0U3RyZWFtJiZjLm1zZ0lkPT09ZCYmKGMucmVzdWx0P2guZW5xdWV1ZShjLnJlc3VsdCk6aC5jbG9zZSgpKX07dGhpcy5mZm1wZWdXb3JrZXIuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsbCksdGhpcy5wb3N0KG8uUmVhZEFWUGFja2V0LHtmaWxlOnRoaXMuZmlsZSxzdGFydDplLGVuZDpzLHN0cmVhbVR5cGU6YSxzdHJlYW1JbmRleDppfSl9LHB1bGw6KCk9PntuPjAmJnRoaXMucG9zdChvLlJlYWROZXh0QVZQYWNrZXQsdm9pZCAwLGQpLG4rK30sY2FuY2VsOigpPT57dGhpcy5wb3N0KG8uU3RvcFJlYWRBVlBhY2tldCx2b2lkIDAsZCl9fSxyKX1nZXRWaWRlb1N0cmVhbShlKXtyZXR1cm4gdGhpcy5nZXRBVlN0cmVhbShtLkFWTUVESUFfVFlQRV9WSURFTyxlKX1nZXRBdWRpb1N0cmVhbShlKXtyZXR1cm4gdGhpcy5nZXRBVlN0cmVhbShtLkFWTUVESUFfVFlQRV9BVURJTyxlKX1zZWVrVmlkZW9QYWNrZXQoZSl7cmV0dXJuIHRoaXMuZ2V0QVZQYWNrZXQoZSxtLkFWTUVESUFfVFlQRV9WSURFTyl9c2Vla0F1ZGlvUGFja2V0KGUpe3JldHVybiB0aGlzLmdldEFWUGFja2V0KGUsbS5BVk1FRElBX1RZUEVfQVVESU8pfXJlYWRWaWRlb1BhY2tldChlLHMpe3JldHVybiB0aGlzLnJlYWRBVlBhY2tldChlLHMsbS5BVk1FRElBX1RZUEVfVklERU8pfXJlYWRBdWRpb1BhY2tldChlLHMpe3JldHVybiB0aGlzLnJlYWRBVlBhY2tldChlLHMsbS5BVk1FRElBX1RZUEVfQVVESU8pfWdlblZpZGVvRGVjb2RlckNvbmZpZyhlKXtyZXR1cm57Y29kZWM6ZS5jb2RlY3Bhci5jb2RlY19zdHJpbmcsY29kZWRXaWR0aDplLmNvZGVjcGFyLndpZHRoLGNvZGVkSGVpZ2h0OmUuY29kZWNwYXIuaGVpZ2h0LGRlc2NyaXB0aW9uOmUuY29kZWNwYXIuZXh0cmFkYXRhPy5sZW5ndGg+MD9lLmNvZGVjcGFyLmV4dHJhZGF0YTp2b2lkIDB9fWdlbkVuY29kZWRWaWRlb0NodW5rKGUpe3JldHVybiBuZXcgRW5jb2RlZFZpZGVvQ2h1bmsoe3R5cGU6ZS5rZXlmcmFtZT09PTE/ImtleSI6ImRlbHRhIix0aW1lc3RhbXA6ZS50aW1lc3RhbXAqdSxkdXJhdGlvbjplLmR1cmF0aW9uKnUsZGF0YTplLmRhdGF9KX1nZW5BdWRpb0RlY29kZXJDb25maWcoZSl7cmV0dXJue2NvZGVjOmUuY29kZWNwYXIuY29kZWNfc3RyaW5nfHwiIixzYW1wbGVSYXRlOmUuY29kZWNwYXIuc2FtcGxlX3JhdGUsbnVtYmVyT2ZDaGFubmVsczplLmNvZGVjcGFyLmNoYW5uZWxzLGRlc2NyaXB0aW9uOmUuY29kZWNwYXIuZXh0cmFkYXRhPy5sZW5ndGg+MD9lLmNvZGVjcGFyLmV4dHJhZGF0YTp2b2lkIDB9fWdlbkVuY29kZWRBdWRpb0NodW5rKGUpe3JldHVybiBuZXcgRW5jb2RlZEF1ZGlvQ2h1bmsoe3R5cGU6ZS5rZXlmcmFtZT09PTE/ImtleSI6ImRlbHRhIix0aW1lc3RhbXA6ZS50aW1lc3RhbXAqdSxkdXJhdGlvbjplLmR1cmF0aW9uKnUsZGF0YTplLmRhdGF9KX1hc3luYyBnZXRWaWRlb0RlY29kZXJDb25maWcoKXtjb25zdCBlPWF3YWl0IHRoaXMuZ2V0VmlkZW9TdHJlYW0oKTtyZXR1cm4gdGhpcy5nZW5WaWRlb0RlY29kZXJDb25maWcoZSl9YXN5bmMgc2Vla0VuY29kZWRWaWRlb0NodW5rKGUpe2NvbnN0IHM9YXdhaXQgdGhpcy5zZWVrVmlkZW9QYWNrZXQoZSk7cmV0dXJuIHRoaXMuZ2VuRW5jb2RlZFZpZGVvQ2h1bmsocyl9YXN5bmMgZ2V0QXVkaW9EZWNvZGVyQ29uZmlnKCl7Y29uc3QgZT1hd2FpdCB0aGlzLmdldEF1ZGlvU3RyZWFtKCk7cmV0dXJuIHRoaXMuZ2VuQXVkaW9EZWNvZGVyQ29uZmlnKGUpfWFzeW5jIHNlZWtFbmNvZGVkQXVkaW9DaHVuayhlKXtjb25zdCBzPWF3YWl0IHRoaXMuc2Vla0F1ZGlvUGFja2V0KGUpO3JldHVybiB0aGlzLmdlbkVuY29kZWRBdWRpb0NodW5rKHMpfX1jbGFzcyBre3ZpZGVvO2N1cnJlbnRGcmFtZXM9MDt0b3RhbEZyYW1lcztjdXJyZW50VGltZTtmcHM7Zmlyc3RUaW1lc3RhbXA7Y29uc3RydWN0b3IoZSxzKXt0aGlzLmN1cnJlbnRUaW1lPWVbMF0qMWU2LHRoaXMuZmlyc3RUaW1lc3RhbXA9ZVswXSoxZTYsdGhpcy50b3RhbEZyYW1lcz0oZVsxXS1lWzBdKSpzKzEsdGhpcy5mcHM9cyx0aGlzLnZpZGVvPW5ldyBWaWRlb0RlY29kZXIoe291dHB1dDp0aGlzLmhhbmRsZUZyYW1lT3V0cHV0LmJpbmQodGhpcyksZXJyb3I6dGhpcy5oYW5kbGVFcnJvci5iaW5kKHRoaXMpfSl9cG9zdEZyYW1lKGUpe3NlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImZyYW1lIixmcmFtZTplfSksdGhpcy5jdXJyZW50VGltZSs9TWF0aC5mbG9vcigxL3RoaXMuZnBzKjFlNiksdGhpcy5jdXJyZW50RnJhbWVzKz0xfWhhbmRsZUZyYW1lT3V0cHV0KGUpe2NvbnN0IHM9ZS50aW1lc3RhbXAsYT1lLmR1cmF0aW9uPz8wLGk9cythO2lmKCF0aGlzLmlzRnJhbWVJblJhbmdlKHMpKXtlLmNsb3NlKCk7cmV0dXJufWZvcig7aT50aGlzLmN1cnJlbnRUaW1lJiZ0aGlzLmN1cnJlbnRGcmFtZXM8PXRoaXMudG90YWxGcmFtZXM7KXRoaXMucG9zdEZyYW1lKGUpO2UuY2xvc2UoKX1pc0ZyYW1lSW5SYW5nZShlKXtyZXR1cm4gZT49dGhpcy5maXJzdFRpbWVzdGFtcH1oYW5kbGVFcnJvcihlKXtjb25zb2xlLmVycm9yKCJlcnJvciBpbiB3b3JrZXIiLGUpLHNlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImVycm9yIixtZXNzYWdlOmUubWVzc2FnZT8/IkFuIHVua25vd24gd29ya2VyIGVycm9yIG9jY3VycmVkIn0pLHNlbGYuY2xvc2UoKX19ZnVuY3Rpb24gSSh0KXtyZXR1cm4gYXN5bmMgZT0+e3RyeXthd2FpdCB0KGUpfWNhdGNoKHMpe3NlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImVycm9yIixtZXNzYWdlOnM/Lm1lc3NhZ2U/PyJBbiB1bmtvd24gd29ya2VyIGVycm9yIG9jY3VyZWQifSl9fX1mdW5jdGlvbiBXKHQpe3JldHVybiB0LmNvZGVjPT0idnAwOSImJih0LmNvZGVjPSJ2cDA5LjAwLjEwLjA4IiksdH1jb25zdCBaPTMwO2FzeW5jIGZ1bmN0aW9uIFAodCl7aWYodC5kYXRhPy50eXBlIT0iaW5pdCIpcmV0dXJuO2NvbnN0e2ZpbGU6ZSxyYW5nZTpzLGZwczphfT10LmRhdGEsaT1uZXcgcCh7d2FzbUxvYWRlclBhdGg6Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9ucG0vQGRpZmZ1c2lvbnN0dWRpby9mZm1wZWctd2FzbUAxLjAuMC9kaXN0L2ZmbXBlZy5qcyJ9KTthd2FpdCBpLmxvYWQoZSk7Y29uc3Qgcj1hd2FpdCBpLmdldFZpZGVvRGVjb2RlckNvbmZpZygpO1cocik7Y29uc3QgZD1uZXcgayhzLGEpO2QudmlkZW8uY29uZmlndXJlKHIpO2NvbnN0IG49aS5yZWFkQVZQYWNrZXQoc1swXSxzWzFdKS5nZXRSZWFkZXIoKTtuLnJlYWQoKS50aGVuKGFzeW5jIGZ1bmN0aW9uIGgoe2RvbmU6bCx2YWx1ZTpmfSl7aWYobCl7YXdhaXQgZC52aWRlby5mbHVzaCgpLHNlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImRvbmUifSksc2VsZi5jbG9zZSgpO3JldHVybn1jb25zdCBjPWkuZ2VuRW5jb2RlZFZpZGVvQ2h1bmsoZik7cmV0dXJuIGQudmlkZW8uZGVjb2RlUXVldWVTaXplPlomJmF3YWl0IG5ldyBQcm9taXNlKEw9PntkLnZpZGVvLm9uZGVxdWV1ZT0oKT0+TCgpfSksYy50aW1lc3RhbXA8PXNbMV0qMWU2JiZkLnZpZGVvLmRlY29kZShjKSxuLnJlYWQoKS50aGVuKGgpfSl9c2VsZi5hZGRFdmVudExpc3RlbmVyKCJtZXNzYWdlIixJKFApKX0pKCk7Cg==",wy=o=>Uint8Array.from(atob(o),a=>a.charCodeAt(0)),Nc=typeof self<"u"&&self.Blob&&new Blob([wy(Dm)],{type:"text/javascript;charset=utf-8"});function ky(o){let a;try{if(a=Nc&&(self.URL||self.webkitURL).createObjectURL(Nc),!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,"+Dm,{name:o==null?void 0:o.name})}finally{a&&(self.URL||self.webkitURL).revokeObjectURL(a)}}class _y{constructor(){ee(this,"frames",[]);ee(this,"state","active");ee(this,"onenqueue");ee(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 Ey(o,a,t){const n=t.value;return t.value=function(...i){var r,s,l,d;return(s=(r=this.track)==null?void 0:r.composition)!=null&&s.rendering&&this.sprite.texture.source.uid!=this.textrues.canvas.source.uid&&(this.sprite.texture=this.textrues.canvas),!((d=(l=this.track)==null?void 0:l.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 Sy=Object.defineProperty,Cy=Object.getOwnPropertyDescriptor,xy=(o,a,t,n)=>{for(var i=Cy(a,t),r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&Sy(a,t,i),i};const Rm=class Am extends os(ns){constructor(t,n={}){super();ee(this,"source",new Xn);ee(this,"type","video");ee(this,"worker");ee(this,"buffer");ee(this,"canvas",document.createElement("canvas"));ee(this,"context",this.canvas.getContext("2d"));ee(this,"element",document.createElement("video"));ee(this,"textrues",{html5:Mt.Texture.from(this.element),canvas:Mt.Texture.from(this.canvas)});ee(this,"sprite",new Mt.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 Xn&&(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 mn({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(Oe.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,s,l,d;if((i=(n=this.track)==null?void 0:n.composition)!=null&&i.playing&&!this.playing)this.element.play();else if(!((s=(r=this.track)==null?void 0:r.composition)!=null&&s.playing)&&this.playing)this.element.pause();else if((d=(l=this.track)==null?void 0:l.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=Am.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 _y,this.worker=new ky,this.worker.addEventListener("message",i=>{var r,s;i.data.type=="frame"?(r=this.buffer)==null||r.enqueue(i.data.frame):i.data.type=="error"?this.cancelDecoding():i.data.type=="done"&&((s=this.buffer)==null||s.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)??Ti}),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}};xy([is,Ey],Rm.prototype,"update");let Sl=Rm;class ki extends ns{constructor(t,n={}){super();ee(this,"type","audio");ee(this,"source",new xn);ee(this,"element",new Audio);t instanceof xn&&(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 mn({code:"sourceNotProcessable",message:"An error occurred while processing the input medium."});i(this.element.error??r)}})}update(){var t,n,i,r,s,l;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():!((l=(s=this.track)==null?void 0:s.composition)!=null&&l.playing)&&this.playing&&this.element.pause()}exit(){this.playing&&this.element.pause()}copy(){const t=ki.fromJSON(JSON.parse(JSON.stringify(this)));return t.source=this.source,t}}const Vy={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 Cl(o){if(!Object.keys(Vy.MIXED).includes(o??""))throw new Xt({message:`${o} is not an accepted mime type`,code:"invalid_mimetype"});return o}var Ny=Object.defineProperty,Ty=Object.getOwnPropertyDescriptor,By=(o,a,t,n)=>{for(var i=Ty(a,t),r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&Ny(a,t,i),i};const My=class Lm extends os(Li){constructor(t,n={}){super();ee(this,"type","html");ee(this,"source",new Cc);ee(this,"element",new Image);ee(this,"canvas",document.createElement("canvas"));ee(this,"context",this.canvas.getContext("2d"));ee(this,"sprite",new Mt.Sprite);this.view.addChild(this.sprite),Object.assign(this,n),t instanceof Cc&&(this.source=t),t instanceof File&&this.source.from(t),this.element.addEventListener("load",()=>{var s,l,d,c;const i=(l=(s=this.source.document)==null?void 0:s.body)==null?void 0:l.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=Mt.Texture.from(this.canvas,!0),this.trigger("load",void 0))}),this.element.addEventListener("error",i=>{this.state="ERROR",this.trigger("error",new mn({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 s,l,d,c;const i=(l=(s=this.source.document)==null?void 0:s.body)==null?void 0:l.scrollWidth,r=(c=(d=this.source.document)==null?void 0:d.body)==null?void 0:c.scrollHeight;if(!i||!r)return n(new mn({code:"sourceNotProcessable",message:"Cannot display source with height or width at 0"}));this.state="READY",t()},this.element.onerror=i=>{n(new mn({code:"sourceNotProcessable",message:"An error occurred while processing the input medium."}))}})}update(t){}copy(){const t=Lm.fromJSON(JSON.parse(JSON.stringify(this)));return t.filters=this.filters,t.source=this.source,t}};By([is],My.prototype,"update");const Pm=["DEFAULT","STACK"];class Tc{constructor(){ee(this,"mode",Pm[0]);ee(this,"pauseAlignmet",!1)}add(a,t){let n=!0;for(let i=0;i<t.clips.length&&(n=Ic(a,t.clips[i]),!!n);i++)Mc(a,t.clips[i]);n&&(t.clips.push(a),t.clips.sort(Bc))}update(a,t){if(!this.pauseAlignmet){t.clips.sort(Bc);for(let n=0;n<t.clips.length;n++)if(a.id!=t.clips[n].id){if(!Ic(a,t.clips[n]))break;Mc(a,t.clips[n])}}}offset(a,t){this.pauseAlignmet=!0;for(const n of t.clips)n.offsetBy(a);this.pauseAlignmet=!1}}class Iy{constructor(){ee(this,"mode",Pm[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 Oe(i-a.start.millis+1)),n==null?t.clips.push(a):(t.clips.splice(n,0,a),t.clips.slice(n+1).forEach(s=>{s.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 Oe(r))}n=i.stop.millis+1}}offset(){}}function Bc(o,a){return o.start.millis-a.start.millis}function Mc(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 Ic(o,a){var t,n,i,r,s;if(o.start.millis>=a.start.millis&&o.stop.millis<=a.stop.millis){const l=(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 l?(l.add(o.detach()),!1):((s=(r=(i=a.track)==null?void 0:i.composition)==null?void 0:r.createTrack(o.type))==null||s.add(o.detach()),!1)}return!0}class Oo extends Ri($a){constructor(){super(...arguments);ee(this,"_disabled",!1);ee(this,"view",new Mt.Container);ee(this,"clips",[]);ee(this,"pointer",0);ee(this,"composition");ee(this,"type","base");ee(this,"strategy",new Tc)}get disabled(){return this._disabled}set disabled(t){var n;t&&this.clipRef&&Xs(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 Iy,this.strategy.update(new Li,this)):this.strategy=new Tc,this.trigger("update",void 0),this}layer(t){var l,d;const n=((l=this.composition)==null?void 0:l.tracks)??[],i=n.findIndex(c=>c.id==this.id),r=n.length-1;if(i==-1)return this;let s=0;return t=="bottom"?s=r:t=="top"||t<0?s=0:t>r?s=r:s=t,O0(n,i,s),(d=this.composition)==null||d.stage.setChildIndex(this.view,r-s),this.trigger("update",void 0),this}seek(t){}offsetBy(t){return typeof t=="number"?this.strategy.offset(Oe.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(Xs(this.clipRef)&&(!Gs(n,this.clipRef)||(i=this.clipRef)!=null&&i.disabled)&&(this.clipRef&&this.view.removeChild(this.clipRef.view),(r=this.clipRef)==null||r.exit()),!!Gs(n,this))for(let s=0;s<this.clips.length;s++){const l=(this.pointer+s)%this.clips.length,d=this.clips[l],c=this.clips[l-1];if(Gs(n,d)&&!d.disabled)return this.pointer=l,Xs(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=l;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 Oe}get start(){var t;return((t=this.clips.at(0))==null?void 0:t.start)??new Oe}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 Gs(o,a){return a?o>=a.start.millis&&o<=a.stop.millis:!1}function Xs(o){return o?!!o.view.parent:!1}class $y{static fromType(a){switch(a.type){case"video":return new Fy;case"audio":return new Ry;case"html":return new Ay;case"image":return new Dy;case"text":return new $c;case"complex_text":return new $c;case"caption":return new Py;default:return new Oo}}}class Um extends Oo{constructor(){super(...arguments);ee(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 Fy extends Um{constructor(){super(...arguments);ee(this,"type","video")}async seek(t){var n;(n=this.composition)!=null&&n.rendering?this.view.removeChildren():super.seek(t)}}class Dy extends Oo{constructor(){super(...arguments);ee(this,"type","image")}}class Ry extends Um{constructor(){super(...arguments);ee(this,"type","audio")}}class $c extends Oo{constructor(){super(...arguments);ee(this,"type","text")}}class Ay extends Oo{constructor(){super(...arguments);ee(this,"type","html")}}var Ly=Object.defineProperty,hd=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&Ly(a,t,i),i};class Ui extends $a{constructor(t={}){super();ee(this,"generatorOptions");ee(this,"type","CLASSIC");ee(this,"position");this.generatorOptions=t.generatorOptions??{duration:[.2]},this.position=t.position??{x:"50%",y:"50%"}}async applyTo(t){var r,s,l;if(!((r=t.clip)!=null&&r.transcript)||!((s=t.composition)!=null&&s.width))throw new Xt({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((l=t.clip)==null?void 0:l.offset)??new Oe,i=await ca.fromFamily({family:"Figtree",weight:"700"}).load();for(const d of t.clip.transcript.iter(this.generatorOptions))await t.add(new Po({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 Xe([0,8],[.96,1],{easing:"easeOut"}),alpha:new Xe([0,4],[0,1],{easing:"easeOut"})}))}}hd([Le()],Ui.prototype,"generatorOptions");hd([Le()],Ui.prototype,"type");hd([Le()],Ui.prototype,"position");class Py extends Oo{constructor(){super(...arguments);ee(this,"clip");ee(this,"type","caption");ee(this,"preset",new Ui)}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 Uy=Object.defineProperty,ls=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&Uy(a,t,i),i};class Oi extends $a{constructor(t={}){super();ee(this,"generatorOptions");ee(this,"type","SPOTLIGHT");ee(this,"color");ee(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,s,l;if(!((r=t.clip)!=null&&r.transcript)||!((s=t.composition)!=null&&s.width))throw new Xt({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((l=t.clip)==null?void 0:l.offset)??new Oe,i=await ca.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 ss({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)}))}}}ls([Le()],Oi.prototype,"generatorOptions");ls([Le()],Oi.prototype,"type");ls([Le()],Oi.prototype,"color");ls([Le()],Oi.prototype,"position");var Oy=Object.defineProperty,vd=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&Oy(a,t,i),i};class ds extends $a{constructor(t={}){super();ee(this,"type","GUINEA");ee(this,"colors");ee(this,"position");this.colors=t.colors??["#1BD724","#FFEE0C","#FF2E17"],this.position=t.position??{x:"50%",y:"50%"}}async applyTo(t){var r,s,l,d,c,u,m;if(!((r=t.clip)!=null&&r.transcript)||!((s=t.composition)!=null&&s.width))throw new Xt({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((l=t.clip)==null?void 0:l.offset)??new Oe,i=await ca.fromFamily({family:"The Bold Font",weight:"500"}).load();for(const f of t.clip.transcript.iter({length:[18]})){const{segments:p,words:h}=this.splitSequence(f);for(let v=0;v<f.words.length;v++){const E=(c=(d=h[v])==null?void 0:d.at(0))==null?void 0:c.start,y=(m=(u=h[v])==null?void 0:u.at(-1))==null?void 0:m.stop;!E||!y||await t.add(new ss({text:p.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:y.add(n),start:E.add(n),styles:[{fillStyle:this.colors[0],fontSize:23},{fillStyle:this.colors[1],fontSize:23},{fillStyle:this.colors[2],fontSize:23}],segments:[{index:xr(0,2),start:p.slice(0,v).join(" ").length,stop:p.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 s=[...bc(n,r).map(d=>d.trim())],l=bc(t.words,s[0].split(/ /).length);return{segments:s,words:l}}}vd([Le()],ds.prototype,"type");vd([Le()],ds.prototype,"colors");vd([Le()],ds.prototype,"position");var zy=Object.defineProperty,gd=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&zy(a,t,i),i};class cs extends $a{constructor(t={}){super();ee(this,"generatorOptions");ee(this,"type","CASCADE");ee(this,"position");this.generatorOptions=t.generatorOptions??{duration:[1.4]},this.position=t.position??{x:"12%",y:"44%"}}async applyTo(t){var r,s,l;if(!((r=t.clip)!=null&&r.transcript)||!((s=t.composition)!=null&&s.width))throw new Xt({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((l=t.clip)==null?void 0:l.offset)??new Oe,i=await ca.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 Po({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)}))}}}gd([Le()],cs.prototype,"generatorOptions");gd([Le()],cs.prototype,"type");gd([Le()],cs.prototype,"position");var jy=Object.defineProperty,bd=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&jy(a,t,i),i};class us extends $a{constructor(t={}){super();ee(this,"generatorOptions");ee(this,"type","SOLAR");ee(this,"position");this.generatorOptions=t.generatorOptions??{duration:[.2]},this.position=t.position??{x:"50%",y:"50%"}}async applyTo(t){var s,l,d;if(!((s=t.clip)!=null&&s.transcript)||!((l=t.composition)!=null&&l.width))throw new Xt({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=await ca.fromFamily({family:"Urbanist",weight:"800"}).load(),i=((d=t.clip)==null?void 0:d.offset)??new Oe,r=new mh.GlowFilter({color:"#fffe41",alpha:.25,distance:90,quality:.05});for(const c of t.clip.transcript.iter(this.generatorOptions))await t.add(new Po({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 Xe([0,8],[.96,1],{easing:"easeOut"}),alpha:new Xe([0,4],[0,1],{easing:"easeOut"}),filters:r}))}}bd([Le()],us.prototype,"generatorOptions");bd([Le()],us.prototype,"type");bd([Le()],us.prototype,"position");var Wy=Object.defineProperty,ms=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&Wy(a,t,i),i};class zi extends $a{constructor(t={}){super();ee(this,"generatorOptions");ee(this,"type","WHISPER");ee(this,"color");ee(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,s,l;if(!((r=t.clip)!=null&&r.transcript)||!((s=t.composition)!=null&&s.width))throw new Xt({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((l=t.clip)==null?void 0:l.offset)??new Oe,i=await ca.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 ss({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}))}}}ms([Le()],zi.prototype,"generatorOptions");ms([Le()],zi.prototype,"type");ms([Le()],zi.prototype,"color");ms([Le()],zi.prototype,"position");var Hy=Object.defineProperty,ps=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&Hy(a,t,i),i};class fs extends $a{constructor(t={}){super();ee(this,"type","VERDANT");ee(this,"generatorOptions");ee(this,"color");ee(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,s,l;if(!((r=t.clip)!=null&&r.transcript)||!((s=t.composition)!=null&&s.width))throw new Xt({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((l=t.clip)==null?void 0:l.offset)??new Oe,i=await ca.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 ss({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}]}))}}}ps([Le()],fs.prototype,"type");ps([Le()],fs.prototype,"generatorOptions");ps([Le()],fs.prototype,"color");ps([Le()],fs.prototype,"position");class Zy extends Ri($a){constructor({height:t=1080,width:n=1920,background:i="#000000",backend:r="webgpu"}={}){super();ee(this,"_duration",new Oe);ee(this,"renderer");ee(this,"stage",new Mt.Container);ee(this,"settings");ee(this,"tracks",[]);ee(this,"frame",0);ee(this,"fixedDuration");ee(this,"state","IDLE");ee(this,"fps",Ti);ee(this,"canvas");ee(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)),Mt.autoDetectRenderer({...this.settings,preference:r}).then(s=>{this.renderer=s,this.trigger("init",void 0)}).catch(s=>{this.trigger("error",new Ro({code:"backendDetectionError",message:`${s}`}))})}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 Oe?this.fixedDuration=t:this.fixedDuration=Oe.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=$y.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 yc(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 s;yc(t)?s=r instanceof t:s=t(r),s&&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(Oe.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 Ro({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(Oe.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(Oe.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 s;const i=this.duration.seconds*n,r=new OfflineAudioContext({sampleRate:n,length:i,numberOfChannels:t}).createBuffer(t,i,n);for(const l of this.findClips(ns)){if(l.disabled||l.muted||(s=l.track)!=null&&s.disabled)continue;const d=Math.round(l.offset.seconds*r.sampleRate),c=Math.round(l.range[0].seconds*r.sampleRate),u=Math.round(l.range[1].seconds*r.sampleRate);try{const m=await l.source.decode(t,n),f=m.numberOfChannels-1;for(let p=0;p<t;p++){const h=r.getChannelData(p),v=m.getChannelData(p>f?f:p);for(let E=0;E<h.length-1;E++)E<d+c||E>d+u||E-d<0||(h[E]+=(v[E-d]??0)*l.volume,h[E]>1&&(h[E]=1),h[E]<-1&&(h[E]=-1));r.getChannelData(p).set(h)}}catch{}}return r}time(t){const n=Bo(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/Ti;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 Gy(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 xl=[8e3,12e3,16e3,24e3,48e3],Xy="https://cdn.jsdelivr.net/npm/@diffusionstudio/libopus-wasm@1.0.0/dist/opus.wasm",Ky="https://cdn.jsdelivr.net/npm/@diffusionstudio/libopus-wasm@1.0.0/dist/opus.js";class Jy{constructor(a){ee(this,"output");ee(this,"error");ee(this,"config");ee(this,"encoder");ee(this,"opus");ee(this,"meta");this.output=a.output,this.error=a.error}async configure(a){const t=await import(Ky),{numberOfChannels:n,sampleRate:i}=this.config=a;if(!xl.includes(i))throw new Or({code:"sampleRateNotSupported",message:`Unsupported sample rate, supported: ${xl.join()}`});this.opus=await t.default({locateFile(r,s){return r.endsWith(".wasm")?Xy:s+r}}),this.encoder=this.opus._opus_encoder_create(i,n,2048),this.meta={decoderConfig:{codec:"opus",description:Gy(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 Or({code:"unconfiguredEncoder",message:"Cannot encode samples using an unconfigured encoder"});const{sampleRate:i,numberOfChannels:r}=this.config,s=Math.floor(i/1e3*20);let l=0;const d=s/i*1e6;for(;l<t;){const c=a.subarray(l*r,(l+s)*r),u=this.opus._malloc(c.length*2);this.opus.HEAP16.set(c,u>>1);const m=4e3,f=this.opus._malloc(m),p=this.opus._opus_encode(this.encoder,u,s,f,m);if(p>0){const h=new Uint8Array(this.opus.HEAPU8.subarray(f,f+p));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(f),l+=s,n+=d}}}function qy(o){const a=xl;let t=48e3;for(const n of a)Math.abs(o-n)<Math.abs(o-t)&&(t=n);return t}class Yy{constructor(a,t){ee(this,"canvas");ee(this,"muxer");ee(this,"videoEncoder");ee(this,"frame",0);ee(this,"sampleRate");ee(this,"numberOfChannels");ee(this,"videoBitrate");ee(this,"gpuBatchSize");ee(this,"fps");ee(this,"height");ee(this,"width");ee(this,"audio");this.canvas=a,this.width=a.width,this.height=a.height,this.fps=(t==null?void 0:t.fps)??30,this.sampleRate=qy((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 W0({height:Math.round(this.height),width:Math.round(this.width),bitrate:this.videoBitrate,fps:this.fps});this.muxer=new xm({target:new id,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 Or({code:"initializationError",message:"Encoder must be initialized using {audio: true} to use this method"});this.muxer||await this.init();const t=j0(a,this.sampleRate,this.numberOfChannels),n=new Jy({output:(i,r)=>{var s;(s=this.muxer)==null||s.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:z0(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 Or({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 Qy(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 s=await r.json();return s.playback_url||s.url||void 0}}}catch{}}}const Vi=class Vi{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),s=n.easing||"linear",l=this.findTrackForClip(a),d=this.findTrackForClip(t);if(!l||!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,s);break;case"dissolve":case"cross-fade":await this.applyCrossFadeTransition(a,t,c,u,s);break;case"wipe-left":case"wipe-right":case"wipe-up":case"wipe-down":await this.applyWipeTransition(a,t,n.type,c,u,s);break;case"slide-left":case"slide-right":case"slide-up":case"slide-down":await this.applySlideTransition(a,t,n.type,c,u,s);break;case"zoom-in":case"zoom-out":await this.applyZoomTransition(a,t,n.type,c,u,s);break;case"dip-to-black":case"dip-to-white":await this.applyDipTransition(a,t,n.type,c,u,s);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 Xe([n,i],[1,0],{easing:r}),t.alpha=new Xe([n,i],[0,1],{easing:r}),t.start=Oe.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 Xe([n,i],[1,0],{easing:r}),t.alpha=new Xe([n,i],[0,1],{easing:r}),t.start=Oe.fromFrames(n)}async applyWipeTransition(a,t,n,i,r,s){if(!this.isVideoClip(a)||!this.isVideoClip(t))throw new Error("Wipe transitions require VideoClip instances");const l={x:0,y:0},d={x:0,y:0};switch(n){case"wipe-left":l.x=new Xe([i,r],[0,-1920],{easing:s}),d.x=new Xe([i,r],[1920,0],{easing:s});break;case"wipe-right":l.x=new Xe([i,r],[0,1920],{easing:s}),d.x=new Xe([i,r],[-1920,0],{easing:s});break;case"wipe-up":l.y=new Xe([i,r],[0,-1080],{easing:s}),d.y=new Xe([i,r],[1080,0],{easing:s});break;case"wipe-down":l.y=new Xe([i,r],[0,1080],{easing:s}),d.y=new Xe([i,r],[-1080,0],{easing:s});break}a.translate=l,t.translate=d,t.start=Oe.fromFrames(i)}async applySlideTransition(a,t,n,i,r,s){if(!this.isVideoClip(a)||!this.isVideoClip(t))throw new Error("Slide transitions require VideoClip instances");const l={x:0,y:0},d={x:0,y:0};switch(n){case"slide-left":l.x=new Xe([i,r],[0,-1920],{easing:s}),d.x=new Xe([i,r],[1920,0],{easing:s});break;case"slide-right":l.x=new Xe([i,r],[0,1920],{easing:s}),d.x=new Xe([i,r],[-1920,0],{easing:s});break;case"slide-up":l.y=new Xe([i,r],[0,-1080],{easing:s}),d.y=new Xe([i,r],[1080,0],{easing:s});break;case"slide-down":l.y=new Xe([i,r],[0,1080],{easing:s}),d.y=new Xe([i,r],[-1080,0],{easing:s});break}a.translate=l,t.translate=d,t.start=Oe.fromFrames(i)}async applyZoomTransition(a,t,n,i,r,s){if(!this.isVideoClip(a)||!this.isVideoClip(t))throw new Error("Zoom transitions require VideoClip instances");n==="zoom-in"?(a.scale=new Xe([i,r],[1,2],{easing:s}),a.alpha=new Xe([i,r],[1,0],{easing:s}),t.scale=new Xe([i,r],[.5,1],{easing:s}),t.alpha=new Xe([i,r],[0,1],{easing:s})):(a.scale=new Xe([i,r],[1,.5],{easing:s}),a.alpha=new Xe([i,r],[1,0],{easing:s}),t.scale=new Xe([i,r],[2,1],{easing:s}),t.alpha=new Xe([i,r],[0,1],{easing:s})),t.start=Oe.fromFrames(i)}async applyDipTransition(a,t,n,i,r,s){if(!this.isVideoClip(a)||!this.isVideoClip(t))throw new Error("Dip transitions require VideoClip instances");const l=Math.round((i+r)/2),d=n==="dip-to-black"?"#000000":"#ffffff",c=await _l.fromColor(d),u=new cy(c,{start:Oe.fromFrames(i),stop:Oe.fromFrames(r)});a.alpha=new Xe([i,l],[1,0],{easing:s}),u.alpha=new Xe([i,l,r],[0,1,0],{easing:s}),t.alpha=new Xe([l,r],[0,1],{easing:s}),await this.composition.add(u),t.start=Oe.fromFrames(l)}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[...Vi.TRANSITIONS]}static previewTransition(a){return Vi.TRANSITIONS.find(t=>t.type===a)}isVideoClip(a){return"alpha"in a&&"scale"in a&&"translate"in a}};Vi.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 Bi=Vi;function Ba(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 _i(o){return o>5?o/100:o}function e1(o){if(o.value!==void 0){const a=Ba(o.value,0);return a>=-1&&a<=1?1+a:_i(a)}return _i(Ba(o.brightness,1))}function Ra(o,a,t){return Math.min(t,Math.max(a,o))}function ga(){return new Gt.ColorMatrixFilter}function t1(o,a){switch(o){case"brightness":{const t=ga();return t.brightness(Ra(e1(a),0,5),!1),t}case"contrast":{const t=ga(),n=Ba(a.value??a.contrast,1);return t.contrast(Ra(_i(n),0,5),!1),t}case"saturation":{const t=ga(),n=Ba(a.value??a.saturation,1);return t.saturate(Ra(_i(n),0,5),!1),t}case"hue":{const t=ga(),n=Ba(a.degrees??a.value,0);return t.hue(Ra(n,-180,180),!1),t}case"blur":case"softFocus":{const t=o==="softFocus"?1:0,n=Ba(a.radius??a.blur??a.value,t);return new Gt.BlurFilter({strength:Ra(n,0,32),quality:4})}case"grayscale":{const t=ga(),n=Ra(Ba(a.amount,100),0,100);return n<=0?null:(n>=100?t.desaturate():t.saturate(1-n/100,!1),t)}case"sepia":{if(Ra(Ba(a.amount,100),0,100)<=0)return null;const n=ga();return n.sepia(!1),n}case"invert":{if(Ra(Ba(a.amount,100),0,100)<=0)return null;const n=ga();return n.negative(!1),n}case"warmth":{const t=ga(),n=Ra(Ba(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=ga(),n=Ra(Ba(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 s=parseInt(r.slice(0,2),16)/255,l=parseInt(r.slice(2,4),16)/255,d=parseInt(r.slice(4,6),16)/255;t.matrix=[1-n+n*s,0,0,0,0,0,1-n+n*l,0,0,0,0,0,1-n+n*d,0,0,0,0,0,1,0]}return t}case"vintage":{const t=ga();return t.sepia(!1),t.saturate(1.4,!1),t.contrast(1.1,!1),t}case"blackAndWhite":{const t=ga(),n=Ra(_i(Ba(a.contrast,120)),.5,3);return t.desaturate(),t.contrast(n,!1),t}case"cinematic":{const t=ga();return t.contrast(1.2,!1),t.brightness(.95,!1),t.saturate(.85,!1),t}case"dramatic":{const t=ga();return t.contrast(1.4,!1),t.brightness(.9,!1),t.saturate(1.1,!1),t.sepia(!1),t}case"dreamy":{const t=ga();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=Gt);class Om{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 Zy({width:a,height:t,background:"#000000"}),this.initPromise=new Promise(r=>{const s=()=>{this.isDebug()&&this.dbg("init:renderer-ready"),r()};this.composition.on("init",s),queueMicrotask(()=>{var d,c,u,m;const l=this.composition;((c=(d=l==null?void 0:l.app)==null?void 0:d.renderer)!=null&&c.view||(u=l==null?void 0:l.renderer)!=null&&u.view||(m=l==null?void 0:l.renderer)!=null&&m.canvas)&&s()})}),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 Qy(a);for(const s of a.timeline)await this.addTimelineClip(s,t);if(a.textOverlays)for(const s of a.textOverlays)await this.addTextOverlay(s);await new Promise(s=>requestAnimationFrame(s));for(const s of a.timeline)(r=s.filters)!=null&&r.length&&this.applyFiltersToClip(s.id,s.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 Bi(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),s=this.mapTransitionType(n.type);if(!i||!r||!s)continue;const l={type:s,duration:n.duration,easing:this.mapTransitionEasing(n.easing)};try{await t.applyTransition(i,r,l)}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 s=await((n=Xn.from)==null?void 0:n.call(Xn,r,{crossOrigin:"anonymous"}))??await Xn.from(r),l=new Sl(s,{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 f=Math.max(0,Math.floor((a.sourceIn||0)*this.fps)),p=a.sourceOut!==void 0?Math.max(f+1,Math.floor(a.sourceOut*this.fps)):null;d=f,c=p;try{if(l.offset=l.offset||{frames:0},l.offset.frames=f,p!==null){const h=Math.max(1,p-f);l.duration=l.duration||{frames:h},l.duration.frames=h}}catch{}}const u=await this.composition.add(l);if(c!==null&&d>=0)try{const f=Math.max(1,c-d);u.offset=u.offset||{frames:0},u.offset.frames=d,u.duration=u.duration||{frames:f},u.duration.frames=f}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(f=>requestAnimationFrame(f)),this.applyFiltersToClip(a.id,a.filters))}catch{}}async addTextOverlay(a){try{const t=ca.fromFamily({family:a.fontFamily||"Arial",weight:a.fontWeight||"400"}),n=new Po({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,s=0,l=r*this.fps,d=a.animation.easing||"linear";a.animation.type==="rotate"&&a.animation.rotation?n.rotation=new Xe([s,l],[a.animation.rotation.from,a.animation.rotation.to],{easing:d}):a.animation.type==="scale"&&a.animation.scale&&(n.scale=new Xe([s,l],[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 s=[];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&&s.push(m)}this.filterCache.set(a,i);const l=n.view??n.sprite??n.displayObject??null;if("filters"in n)try{n.filters=s}catch{}if(l&&"filters"in l)try{l.filters=s}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(oe.getFilter(a.filterId)&&!oe.isFilterCompatibleWithMedia(a.filterId,"video"))return null;let r=Dh(a.filterId,n);return r||(r=t1(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 s,l,d,c,u,m,f,p,h;const t=a.fps??this.fps,n=this.composition.canvas??((l=(s=this.composition)==null?void 0:s.renderer)==null?void 0:l.view)??((u=(c=(d=this.composition)==null?void 0:d.app)==null?void 0:c.renderer)==null?void 0:u.view)??((f=(m=this.composition)==null?void 0:m.renderer)==null?void 0:f.canvas);if(!n)throw new Error("Export failed: composition canvas is not initialized");(p=a.onProgress)==null||p.call(a,0);const i=new Yy(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,s=a.source,l=(s==null?void 0:s.width)??(s==null?void 0:s.videoWidth)??((t=this.recipeSourceDimensions)==null?void 0:t.width),d=(s==null?void 0:s.height)??(s==null?void 0:s.videoHeight)??((n=this.recipeSourceDimensions)==null?void 0:n.height);if(!l||!d)return;const c=Math.min(i/l,r/d),u=Math.max(i/l,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)),s=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:s-r},i.duration.frames=s-r,this.composition.computeFrame()}catch{}}resolveSourceFrame(a){var t,n;for(const[i,r]of this.clips.entries()){const s=this.clipTimelineStart.get(i)||0,l=Math.floor(s*this.fps),d=((t=r.duration)==null?void 0:t.frames)??Math.round(r.duration.seconds*this.fps),c=l+d;if(a>=l&&a<c){const u=a-l;return{sourceFrame:(((n=r.offset)==null?void 0:n.frames)??0)+u,clipId:i}}}return{sourceFrame:0,clipId:null}}}const a1=["src"],n1={class:"preview-controls"},o1=["aria-label"],i1={class:"time-display"},r1={class:"current-time"},s1={class:"total-time"},l1={key:2,class:"loading-overlay"},d1={key:3,class:"error-overlay"},c1=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(),s=e.ref(),l=e.ref(!1),d=e.ref("Initializing..."),c=e.ref(null),u=e.ref(!1),m=e.ref(0),f=e.ref(0);let p=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"}}),E=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 y(){var x,M,w;if(!(!r.value||!t.recipe))try{l.value=!0,d.value="Initializing video engine...";const F=((x=t.recipe.source)==null?void 0:x.original_width)||1920,P=((M=t.recipe.source)==null?void 0:M.original_height)||1080,D=((w=t.recipe.output)==null?void 0:w.fps)||30;p=new Om(F,P,D,{fitMode:t.fitMode}),p.attachPlayer(r.value),d.value="Loading composition...",await p.loadFromRecipe(t.recipe),f.value=p.durationInSeconds,n("duration-change",f.value),k(),l.value=!1,n("engine-ready",p),t.autoPlay&&(p.play(),u.value=!0)}catch(F){const P=F instanceof Error?F.message:String(F);c.value=`Failed to initialize: ${P}`,l.value=!1}}function k(){if(!p)return;const x=setInterval(()=>{p&&u.value&&(m.value=p.currentTimeInSeconds,n("time-update",m.value))},100);A.value=x}function g(){h.value&&p?(u.value?p.pause():p.play(),u.value=!u.value,n("play-state-change",u.value)):s.value&&(u.value?s.value.pause():s.value.play(),u.value=!u.value,n("play-state-change",u.value))}function b(x){const M=Math.floor(x/60),w=Math.floor(x%60);return`${M}:${w.toString().padStart(2,"0")}`}function R(){c.value=null,h.value&&y()}function N(){!h.value&&s.value&&(f.value=s.value.duration,n("duration-change",f.value))}function T(){!h.value&&s.value&&(m.value=s.value.currentTime,n("time-update",m.value))}function S(){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&&y()}),e.onUnmounted(()=>{p&&(p.destroy(),p=null),A.value&&(clearInterval(A.value),A.value=null),s.value&&(s.value.pause(),s.value.removeAttribute("src"),s.value.load())}),e.watch(()=>t.recipe,async x=>{if(h.value&&x)if(x.timeline,p)try{await p.loadFromRecipe(x),f.value=p.durationInSeconds,n("duration-change",f.value)}catch{}else await y()}),e.watch(()=>t.enableEngine,async x=>{x?(await e.nextTick(),await y()):p&&(A.value&&(clearInterval(A.value),A.value=null),p.destroy(),p=null)}),e.watch(()=>t.fitMode,async x=>{if(!(!h.value||!p))try{p.setFitMode(x||"contain")}catch{}});const A=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:s,src:E.value,onLoadedmetadata:N,onTimeupdate:T,onEnded:S,onError:B,style:e.normalizeStyle({width:"100%",height:"100%",objectFit:v.value}),playsinline:"",controls:""},null,44,a1)),e.createElementVNode("div",n1,[e.createElementVNode("button",{class:"play-button",onClick:g,"aria-label":u.value?"Pause":"Play"},[e.createVNode(e.unref(H.IonIcon),{icon:u.value?e.unref(rm):e.unref(sm)},null,8,["icon"])],8,o1),e.createElementVNode("div",i1,[e.createElementVNode("span",r1,e.toDisplayString(b(m.value)),1),M[0]||(M[0]=e.createElementVNode("span",{class:"separator"},"/",-1)),e.createElementVNode("span",s1,e.toDisplayString(b(f.value)),1)])]),l.value?(e.openBlock(),e.createElementBlock("div",l1,[e.createVNode(e.unref(H.IonSpinner),{name:"crescent"}),e.createElementVNode("p",null,e.toDisplayString(d.value),1)])):e.createCommentVNode("",!0),c.value?(e.openBlock(),e.createElementBlock("div",d1,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Ql)},null,8,["icon"]),e.createElementVNode("p",null,e.toDisplayString(c.value),1),e.createElementVNode("button",{onClick:R},"Retry")])):e.createCommentVNode("",!0)],512))}}),Vl=Fe(c1,[["__scopeId","data-v-e199ac48"]]),u1=["aria-label"],m1=["aria-label"],p1={class:"clip-content"},f1={key:0,class:"clip-thumbnail"},h1=["src","alt"],v1=["src"],g1=["data-visual-mode"],b1={class:"clip-info"},y1={class:"clip-label"},w1={class:"clip-duration"},k1={key:3,class:"filter-indicators"},_1={key:4,class:"speed-indicator"},E1=["aria-label","data-testid"],S1={key:1,class:"selection-overlay"},C1=420,x1=8,V1=48,N1=32,Fc=1,T1=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),s=e.ref(null),l=e.ref(0),d=e.ref(0),c=e.ref(0),u=e.ref(0),m=e.ref(!1),f=e.ref(!1),p=e.ref(null),h=e.computed(()=>{const U=(t.clip.timelineEnd-t.clip.timelineStart)*t.scale;return{left:`${t.clip.timelineStart*t.scale-t.scrollOffset}px`,width:`${U}px`}}),v=e.computed(()=>t.clip.label||`Clip ${t.clip.id.slice(-4)}`),E=e.computed(()=>{const C=t.clip.timelineEnd-t.clip.timelineStart;return T(C)}),y=e.computed(()=>t.clip.filters&&t.clip.filters.length>0),k=e.computed(()=>t.clip.filters||[]),g=e.computed(()=>t.clip.waveformSamples??[]),b=e.computed(()=>t.clip.filmstripFrames??[]),R=e.computed(()=>g.value.length>0),N=e.computed(()=>b.value.length>0);function T(C){if(C<1)return`${Math.round(C*30)}f`;if(C<60)return`${C.toFixed(1)}s`;{const U=Math.floor(C/60),j=Math.floor(C%60);return`${U}:${j.toString().padStart(2,"0")}`}}function S(C){return!C||typeof C!="string"?pc:C.includes("color")||C.includes("brightness")?Cn:C.includes("blur")?uv:C.includes("style")?ci:C.includes("effect")?Sn:pc}function B(){r.value||n("select")}function A(C){C.button===0&&(w("move",C.clientX),C.preventDefault())}function x(C){if(C.touches.length!==1)return;const U=C.touches[0];if(!t.isMobile){w("move",U.clientX),C.preventDefault();return}c.value=U.clientX,u.value=U.clientY,m.value=!1,f.value=!1,F(),P(),p.value=window.setTimeout(()=>{f.value=!0,P(),t.selected||n("select"),n("long-press")},C1),document.addEventListener("touchmove",D),document.addEventListener("touchend",O),document.addEventListener("touchcancel",O),C.preventDefault()}function M(C,U){const j="touches"in U?U.touches[0].clientX:U.clientX;s.value=C==="start"?"trim-start":"trim-end",w(s.value,j),U.preventDefault(),U.stopPropagation()}function w(C,U){F(),P(),r.value=!0,s.value=C,l.value=U,C==="move"?d.value=t.clip.timelineStart:C==="trim-start"?d.value=t.clip.sourceIn:C==="trim-end"&&(d.value=t.clip.sourceOut),document.addEventListener("mousemove",I),document.addEventListener("mouseup",z),document.addEventListener("touchmove",Z),document.addEventListener("touchend",z),t.selected||n("select")}function F(){p.value!==null&&(window.clearTimeout(p.value),p.value=null)}function P(){document.removeEventListener("touchmove",D),document.removeEventListener("touchend",O),document.removeEventListener("touchcancel",O)}function D(C){if(C.touches.length!==1)return;const U=C.touches[0],j=U.clientX-c.value,ne=U.clientY-u.value;Math.hypot(j,ne)<x1||(m.value=!0,F(),P(),w("move",U.clientX),I(C),C.preventDefault())}function O(){const C=!m.value&&!f.value&&!r.value;F(),P(),m.value=!1,f.value=!1,C&&n("select")}function I(C){if(!r.value||!s.value)return;const U="touches"in C?C.touches[0].clientX:C.clientX,j="touches"in C?C.touches[0].clientY:C.clientY,de=U-l.value;s.value==="move"?(n("drag",de),n("drag-abs",U,j)):s.value==="trim-start"?(n("trim-start",de),n("trim-start-abs",U)):s.value==="trim-end"&&(n("trim-end",de),n("trim-end-abs",U))}function Z(C){I(C)}function z(){r.value=!1,s.value=null,document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",z),document.removeEventListener("touchmove",Z),document.removeEventListener("touchend",z)}function K(){e.nextTick(()=>{Be()})}function se(C){var be,_e;const U=Math.max(0,t.clip.timelineEnd-t.clip.timelineStart),j=Math.max(1,Math.round(U*t.scale)),ne=t.isMobile?N1:V1,de=Math.max(1,Math.round(C.clientWidth||((be=C.parentElement)==null?void 0:be.clientWidth)||j)),Ke=Math.max(1,Math.round(C.clientHeight||((_e=C.parentElement)==null?void 0:_e.clientHeight)||ne));return{width:de,height:Ke}}function Be(){if(N.value||!i.value)return;const C=i.value,U=C.getContext("2d");if(!U)return;const{width:j,height:ne}=se(C),de=window.devicePixelRatio||1;if(C.width=Math.max(1,Math.round(j*de)),C.height=Math.max(1,Math.round(ne*de)),U.setTransform(de,0,0,de,0,0),U.clearRect(0,0,j,ne),g.value.length>0){ie(U,j,ne,g.value);return}ce(U,j,ne)}function ce(C,U,j){const ne=j/2;C.strokeStyle="rgba(255, 255, 255, 0.3)",C.lineWidth=1,C.beginPath(),C.moveTo(0,ne),C.lineTo(U,ne);for(let de=0;de<U;de+=4){const Ke=Math.sin(de*.05)*(j*.3);C.moveTo(de,ne-Ke),C.lineTo(de,ne+Ke)}C.stroke()}function ie(C,U,j,ne){const de=t.clip.sourceIn,Ke=t.clip.sourceOut,be=Math.max(.001,Ke-de),_e=ne.filter(Ae=>Ae.endTime>=de&&Ae.time<=Ke);if(_e.length===0){ce(C,U,j);return}const ve=j/2,xe=j*.44,Se=j*.32;C.fillStyle="rgba(255, 255, 255, 0.26)",_e.forEach(Ae=>{const re=Math.max(Ae.time,de),ge=Math.min(Ae.endTime,Ke),Ge=(re-de)/be*U,Ve=Math.max(Fc,(ge-re)/be*U),at=W(Ae.rms)*Se;C.fillRect(Ge,ve-at,Ve,at*2)}),C.fillStyle="rgba(255, 255, 255, 0.72)",_e.forEach(Ae=>{const re=Math.max(Ae.time,de),ge=Math.min(Ae.endTime,Ke),Ge=(re-de)/be*U,Ve=Math.max(Fc,(ge-re)/be*U),at=W(Ae.peak)*xe;C.fillRect(Ge,ve-at,Ve,at*2)})}function W(C){return Math.min(1,Math.max(0,C))}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",Be)}),e.onUnmounted(()=>{z(),F(),P(),window.removeEventListener("resize",Be)}),(C,U)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["timeline-clip",{selected:C.selected,mobile:C.isMobile,"has-filters":y.value}]),style:e.normalizeStyle(h.value),onClick:B,onMousedown:A,onTouchstart:x},[e.createElementVNode("div",{class:"trim-handle trim-start",onMousedown:U[0]||(U[0]=e.withModifiers(j=>M("start",j),["stop"])),onTouchstart:U[1]||(U[1]=e.withModifiers(j=>M("start",j),["stop"])),"aria-label":`Trim start of ${C.clip.label||"clip"}`},[...U[7]||(U[7]=[e.createElementVNode("div",{class:"trim-grip"},null,-1)])],40,u1),e.createElementVNode("div",{class:"trim-handle trim-end",onMousedown:U[2]||(U[2]=e.withModifiers(j=>M("end",j),["stop"])),onTouchstart:U[3]||(U[3]=e.withModifiers(j=>M("end",j),["stop"])),"aria-label":`Trim end of ${C.clip.label||"clip"}`},[...U[8]||(U[8]=[e.createElementVNode("div",{class:"trim-grip"},null,-1)])],40,m1),e.createElementVNode("div",p1,[C.clip.thumbnail?(e.openBlock(),e.createElementBlock("div",f1,[e.createElementVNode("img",{src:C.clip.thumbnail,alt:C.clip.label||"Video clip"},null,8,h1)])):e.createCommentVNode("",!0),N.value?(e.openBlock(),e.createElementBlock("div",{key:1,class:e.normalizeClass(["clip-analysis-strip clip-filmstrip",{compact:C.isMobile}]),"aria-hidden":"true"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(b.value,j=>(e.openBlock(),e.createElementBlock("img",{key:j.id,class:"clip-filmstrip-frame",src:j.uri,alt:"",draggable:"false"},null,8,v1))),128))],2)):(e.openBlock(),e.createElementBlock("div",{key:2,class:e.normalizeClass(["clip-analysis-strip clip-waveform",{compact:C.isMobile}]),"data-visual-mode":R.value?"waveform":"placeholder","aria-hidden":"true"},[e.createElementVNode("canvas",{ref_key:"waveformCanvas",ref:i},null,512)],10,g1)),e.createElementVNode("div",b1,[e.createElementVNode("span",y1,e.toDisplayString(v.value),1),e.createElementVNode("span",w1,e.toDisplayString(E.value),1)]),y.value?(e.openBlock(),e.createElementBlock("div",k1,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(k.value,j=>(e.openBlock(),e.createBlock(e.unref(H.IonIcon),{key:j.id||j.filterId,icon:S(j.filterId||j.id),title:`Filter: ${j.filterId||j.id}`},null,8,["icon","title"]))),128))])):e.createCommentVNode("",!0),C.clip.speed&&C.clip.speed!==1?(e.openBlock(),e.createElementBlock("div",_1,e.toDisplayString(C.clip.speed)+"x ",1)):e.createCommentVNode("",!0)]),C.selected&&C.canDelete?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"clip-delete-button","aria-label":`Delete ${C.clip.label||"clip"}`,"data-testid":`timeline-clip-delete-${C.clip.id}`,title:"Delete clip",onClick:U[4]||(U[4]=e.withModifiers(j=>n("delete"),["stop"])),onMousedown:U[5]||(U[5]=e.withModifiers(()=>{},["stop"])),onTouchstart:U[6]||(U[6]=e.withModifiers(()=>{},["stop"]))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Fr)},null,8,["icon"])],40,E1)):e.createCommentVNode("",!0),C.selected?(e.openBlock(),e.createElementBlock("div",S1)):e.createCommentVNode("",!0)],38))}}),Dc=Fe(T1,[["__scopeId","data-v-deeaa999"]]),B1={class:"timeline-track-header__meta"},M1=["data-testid"],I1=["data-testid","value","aria-label","onKeydown"],$1={class:"timeline-track-header__type"},F1=["aria-label"],D1=["aria-pressed","aria-label"],R1=["aria-pressed","aria-label"],A1=["aria-pressed","aria-label"],L1=["aria-pressed","aria-label"],P1={class:"timeline-track-header__menu-row"},U1=["data-testid","aria-label","aria-expanded"],O1=["aria-label"],z1=["data-testid"],j1=["data-testid"],W1=["data-testid"],H1=["data-testid"],Z1=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),s=e.ref(""),l=e.ref(null);function d(){i.value=!i.value}function c(){i.value=!1}function u(){c(),m()}async function m(){var y,k;s.value=t.track.name,r.value=!0,await e.nextTick(),(y=l.value)==null||y.focus(),(k=l.value)==null||k.select()}function f(y){const k=y.target;k&&(s.value=k.value)}function p(){if(!r.value)return;const y=s.value.trim();r.value=!1,!(y===""||y===t.track.name)&&n("rename-track",t.track.id,y)}function h(){r.value=!1}function v(y){c(),n("reorder-track",t.track.id,y)}function E(){c(),n("delete-track",t.track.id)}return(y,k)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["timeline-track-header",{"is-hidden":y.track.hidden===!0}])},[e.createElementVNode("div",B1,[r.value?(e.openBlock(),e.createElementBlock("input",{key:1,ref_key:"renameInput",ref:l,class:"timeline-track-header__rename-input","data-testid":`timeline-track-rename-${y.track.id}`,value:s.value,"aria-label":`Rename ${y.track.name}`,onInput:f,onKeydown:[e.withKeys(e.withModifiers(p,["prevent"]),["enter"]),e.withKeys(e.withModifiers(h,["prevent"]),["escape"])],onBlur:p},null,40,I1)):(e.openBlock(),e.createElementBlock("span",{key:0,class:"timeline-track-header__name","data-testid":`timeline-track-name-${y.track.id}`,onDblclick:m},e.toDisplayString(y.track.name),41,M1)),e.createElementVNode("span",$1,e.toDisplayString(y.track.type),1)]),e.createElementVNode("div",{class:"timeline-track-header__actions","aria-label":`Track controls for ${y.track.name}`},[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["timeline-track-header__button",{"is-active":y.track.locked===!0}]),"aria-pressed":y.track.locked===!0,"aria-label":y.track.locked===!0?`Unlock ${y.track.name}`:`Lock ${y.track.name}`,title:"Lock",onClick:k[0]||(k[0]=g=>n("toggle-lock",y.track.id))}," Lock ",10,D1),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["timeline-track-header__button",{"is-active":y.track.hidden===!0}]),"aria-pressed":y.track.hidden===!0,"aria-label":y.track.hidden===!0?`Show ${y.track.name}`:`Hide ${y.track.name}`,title:"Hide",onClick:k[1]||(k[1]=g=>n("toggle-hidden",y.track.id))}," Hide ",10,R1),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["timeline-track-header__button",{"is-active":y.track.muted===!0}]),"aria-pressed":y.track.muted===!0,"aria-label":y.track.muted===!0?`Unmute ${y.track.name}`:`Mute ${y.track.name}`,title:"Mute",onClick:k[2]||(k[2]=g=>n("toggle-muted",y.track.id))}," Mute ",10,A1),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["timeline-track-header__button",{"is-active":y.track.solo===!0}]),"aria-pressed":y.track.solo===!0,"aria-label":y.track.solo===!0?`Disable solo for ${y.track.name}`:`Solo ${y.track.name}`,title:"Solo",onClick:k[3]||(k[3]=g=>n("toggle-solo",y.track.id))}," Solo ",10,L1)],8,F1),e.createElementVNode("div",P1,[e.createElementVNode("button",{type:"button",class:"timeline-track-header__menu-button","data-testid":`timeline-track-menu-${y.track.id}`,"aria-label":`More actions for ${y.track.name}`,"aria-expanded":i.value,"aria-haspopup":!0,onClick:d}," ⋯ ",8,U1),i.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"timeline-track-header__menu",role:"menu","aria-label":`${y.track.name} actions`},[e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":`timeline-track-rename-action-${y.track.id}`,onClick:u}," Rename ",8,z1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":`timeline-track-move-up-${y.track.id}`,onClick:k[4]||(k[4]=g=>v("up"))}," Move up ",8,j1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":`timeline-track-move-down-${y.track.id}`,onClick:k[5]||(k[5]=g=>v("down"))}," Move down ",8,W1),e.createElementVNode("button",{type:"button",role:"menuitem",class:"timeline-track-header__menu-button--danger","data-testid":`timeline-track-delete-${y.track.id}`,onClick:E}," Delete track ",8,H1)],8,O1)):e.createCommentVNode("",!0)])],2))}}),G1=Fe(Z1,[["__scopeId","data-v-54e2bc6a"]]);class zm{constructor(a=30){this.fps=30,this.fps=a}setFps(a){this.fps=a}async convertTimelineClipToEngine(a,t){const n=new Sl(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 Xn.from(i.url),s=await this.convertTimelineClipToEngine(i,r);await t.add(s)}catch{}a.duration&&(t.duration=Oe.fromFrames(this.secondsToFrames(a.duration)))}extractTimelineFromComposition(a){const t=[];return(a.clips||[]).forEach((i,r)=>{var s,l;i instanceof Sl&&t.push(this.convertEngineClipToTimeline(i,`clip-${r}`,((s=i.source)==null?void 0:s.externalURL)||((l=i.source)==null?void 0:l.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,s]=t;n=parseInt(i)*3600+parseInt(r)*60+parseFloat(s)}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,s]=t;n=parseInt(i)*3600+parseInt(r)*60+parseFloat(s)}else n=parseFloat(a);return this.secondsToFrames(n)}}const X1={class:"time-markers"},K1=["data-track-id"],J1=["data-track-id"],q1=["aria-label","title"],Y1={key:0,class:"timeline-scrollbar"},Rc=152,Ac=80,Q1=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,s=e.ref(),l=e.ref(n.selectedClipId||null),d=e.ref(!1),c=e.ref(0),u=e.ref(),m=e.ref(0),f=e.computed(()=>n.selectedClipId??l.value);e.watch(()=>n.selectedClipId,Q=>{Q!==void 0&&(l.value=Q)});const p=new zm(n.fps);e.watch(()=>n.fps,Q=>{p.setFps(Q)});const h=e.ref(!1),v=e.ref(null),E=e.ref(0),y=e.ref(0),k=e.ref(null),g=e.ref(null),b=e.ref(0),R=e.ref(0),N=e.ref(0),T=e.ref(!1),S=e.ref(0),B=e.ref(n.zoomLevel),A=e.computed(()=>n.zoomLevel),x=e.computed(()=>n.tracks!==void 0&&n.tracks.length>0&&!i.value),M=e.computed(()=>x.value?Rc:0),w=e.computed(()=>Math.max(0,W.value-M.value));function F(Q){return Q.trackId??`legacy-track-${Q.track??0}`}function P(Q,he){return{id:Q,type:"video",name:`Track ${he+1}`,order:he}}const D=e.computed(()=>{const Q=new Map;for(const he of n.clips){const ue=F(he),le=Q.get(ue);if(le){le.push(he);continue}Q.set(ue,[he])}return Q}),O=e.computed(()=>{if(!x.value)return[];const Q=[...n.tracks??[]].sort((le,Te)=>le.order-Te.order),he=new Set(Q.map(le=>le.id)),ue=[];for(const le of D.value.keys())he.has(le)||ue.push(P(le,Q.length+ue.length));return[...Q,...ue].map(le=>({track:le,clips:D.value.get(le.id)??[],height:le.height??Ac}))}),I=e.computed(()=>new Set(O.value.filter(Q=>Q.track.locked===!0).map(Q=>Q.track.id)));function Z(Q){const he=n.clips.find(ue=>ue.id===Q);return he?!I.value.has(F(he)):!1}function z(Q){const he=n.clips.find(Te=>Te.id===Q);if(!he)return null;const ue=F(he),le=n.clips.filter(Te=>Te.id!==Q&&F(Te)===ue&&Te.timelineStart>=he.timelineEnd-1e-9).map(Te=>Te.timelineStart);return le.length?Math.min(...le):null}function K(Q){const he=Q.sourceMaxOut??n.duration,ue=Q.timelineStart+(he-Q.sourceIn),le=z(Q.id),Te=le!=null?Math.max(Q.timelineStart,le):1/0;return Math.min(ue,Te)}function se(Q,he=Ac){const ue=Q.sourceMinIn??0,Te=(Q.sourceMaxOut??n.duration)-ue,ze=Q.sourceIn-ue;return{left:`${(Q.timelineStart-ze)*A.value-c.value}px`,width:`${Te*A.value}px`,top:"0px",height:`${he}px`,opacity:f.value===Q.id?.25:.15}}const Be=e.computed(()=>n.useFrameMode?n.zoomLevel:n.zoomLevel/n.fps),ce=e.computed(()=>p.secondsToFrames(n.duration)),ie=e.computed(()=>n.useFrameMode?ce.value*Be.value:n.duration*A.value),W=e.computed(()=>{var Q;return m.value||((Q=s.value)==null?void 0:Q.clientWidth)||800}),C=e.computed(()=>ie.value>w.value),U=e.computed(()=>Math.max(0,ie.value-w.value)),j=e.computed(()=>c.value>0),ne=e.computed(()=>c.value<U.value),de=e.computed(()=>n.useFrameMode?p.secondsToFrames(n.playhead)*Be.value-c.value:n.playhead*A.value-c.value),Ke=e.computed(()=>k.value===null?null:n.useFrameMode?p.secondsToFrames(k.value)*Be.value-c.value:k.value*A.value-c.value),be=e.computed(()=>{const Q=w.value,he=Math.max(50,Q/ie.value*Q),ue=c.value/U.value*(Q-he);return{width:`${he}px`,left:`${ue}px`}}),_e=e.computed(()=>{const Q=[],he=ve();for(let ue=0;ue<=n.duration;ue+=he){const le=ue*A.value-c.value;le>=-50&&le<=w.value+50&&Q.push({position:le+M.value,label:xe(ue),time:ue})}return Q});function ve(){const he=80/A.value;return he<=1?1:he<=5?5:he<=10?10:he<=30?30:he<=60?60:Math.ceil(he/60)*60}function xe(Q){if(n.useFrameMode)return`F${p.secondsToFrames(Q)}`;{const he=Math.floor(Q/60),ue=Math.floor(Q%60),le=Math.floor(Q%1*n.fps);return A.value>100?`${he}:${ue.toString().padStart(2,"0")}:${le.toString().padStart(2,"0")}`:`${he}:${ue.toString().padStart(2,"0")}`}}function Se(Q){const he=s.value.getBoundingClientRect();let le=(Q.clientX-he.left-M.value+c.value)/A.value;const Te=n.clips.find(ze=>le>=ze.timelineStart&&le<=ze.timelineEnd);if(Te)le=Math.max(Te.timelineStart,Math.min(Te.timelineEnd,le));else if(n.selectedClipId){const ze=n.clips.find(ot=>ot.id===n.selectedClipId);if(ze){const ot=Math.abs(le-ze.timelineStart),St=Math.abs(le-ze.timelineEnd);le=ot<St?ze.timelineStart:ze.timelineEnd}}else le=Math.max(0,Math.min(le,n.duration));r("update:playhead",le)}function Ae(Q){if(!C.value)return;const he=Math.abs(Q.deltaX)>Math.abs(Q.deltaY)?Q.deltaX:Q.deltaY;he!==0&&(Q.preventDefault(),c.value=Math.max(0,Math.min(U.value,c.value+he)))}function re(Q){return[...Q===void 0?n.clips:n.clips.filter(ue=>F(ue)===Q)].sort((ue,le)=>ue.timelineStart-le.timelineStart)}function ge(Q){const he=n.clips.find(Te=>Te.id===Q),ue=re(he?F(he):void 0),le=ue.findIndex(Te=>Te.id===Q);return{previous:le>0?ue[le-1]:null,next:le!==-1&&le<ue.length-1?ue[le+1]:null}}function Ge(Q){const he=Q.timelineEnd-Q.timelineStart,{previous:ue,next:le}=ge(Q.id),Te=ue?ue.timelineEnd:0,ze=le?le.timelineStart-he:Math.max(Q.timelineStart,n.duration-he);return{minStart:Te,maxStart:Math.max(Te,ze)}}function Ve(){return 12/Math.max(A.value,1)}function at(Q){return Array.from(new Set(Q.filter(he=>typeof he=="number"&&Number.isFinite(he))))}function rt(Q,he,ue,le){const Te=Math.max(ue,Math.min(Q,le));if(!n.snapEnabled)return{value:Te,guideTime:null};const ze=Ve();let ot=Te,St=null,Ft=Number.POSITIVE_INFINITY;for(const Vt of at(he)){if(Vt<ue||Vt>le)continue;const Ct=Math.abs(Vt-Te);Ct<=ze&&Ct<Ft&&(ot=Vt,St=Vt,Ft=Ct)}return{value:ot,guideTime:St}}function gt(Q){if(Q.touches.length===2){T.value=!0;const he=Q.touches[0],ue=Q.touches[1];S.value=Math.hypot(ue.clientX-he.clientX,ue.clientY-he.clientY),B.value=n.zoomLevel}else Q.touches.length===1&&(b.value=Q.touches[0].clientX,R.value=Q.touches[0].clientY,N.value=b.value)}function lt(Q){if(T.value&&Q.touches.length===2){const he=Q.touches[0],ue=Q.touches[1],Te=Math.hypot(ue.clientX-he.clientX,ue.clientY-he.clientY)/S.value;Math.max(10,Math.min(200,B.value*Te)),r("update:playhead",n.playhead)}else if(Q.touches.length===1&&!T.value){const he=Q.touches[0],ue=N.value-he.clientX;Math.abs(ue)>Math.abs(he.clientY-R.value)&&(Q.preventDefault(),c.value=Math.max(0,Math.min(U.value,c.value+ue)),N.value=he.clientX)}}function Et(){T.value=!1}function Ee(Q){const he=Q.target;if(he.closest(".playhead-handle"))return;const ue=Q.button===1,le=!!he.closest(".video-track");(ue||!le&&C.value)&&Ce(Q)}function Ce(Q){h.value=!0,v.value="pan",E.value=Q.clientX,y.value=c.value,document.addEventListener("mousemove",qe),document.addEventListener("mouseup",Ze)}function Re(Q){Q.preventDefault(),Q.stopPropagation(),h.value=!0,v.value="playhead";const he="touches"in Q?Q.touches[0].clientX:Q.clientX;E.value=he,y.value=n.playhead,"touches"in Q?(document.addEventListener("touchmove",qe),document.addEventListener("touchend",Ze)):(document.addEventListener("mousemove",qe),document.addEventListener("mouseup",Ze))}function et(Q){Q.preventDefault(),Q.stopPropagation(),h.value=!0,v.value="scrollbar";const he="touches"in Q?Q.touches[0].clientX:Q.clientX;E.value=he,y.value=c.value,"touches"in Q?(document.addEventListener("touchmove",qe),document.addEventListener("touchend",Ze)):(document.addEventListener("mousemove",qe),document.addEventListener("mouseup",Ze))}function qe(Q){if(!h.value)return;const ue=("touches"in Q?Q.touches[0].clientX:Q.clientX)-E.value;if(v.value==="playhead"){const le=ue/A.value;let Te=y.value+le;if(n.selectedClipId){const ze=n.clips.find(ot=>ot.id===n.selectedClipId);ze?Te=Math.max(ze.timelineStart,Math.min(ze.timelineEnd,Te)):Te=Math.max(0,Math.min(n.duration,Te))}else{const ze=n.clips.find(ot=>n.playhead>=ot.timelineStart&&n.playhead<=ot.timelineEnd);ze?Te=Math.max(ze.timelineStart,Math.min(ze.timelineEnd,Te)):Te=Math.max(0,Math.min(n.duration,Te))}r("update:playhead",Te)}else if(v.value==="scrollbar"){const le=ue/w.value*ie.value;c.value=Math.max(0,Math.min(U.value,y.value+le))}else if(v.value==="pan"){const le=y.value-ue;c.value=Math.max(0,Math.min(U.value,le))}}function Ze(){h.value=!1,v.value=null,k.value=null,g.value=null,document.removeEventListener("mousemove",qe),document.removeEventListener("mouseup",Ze),document.removeEventListener("touchmove",qe),document.removeEventListener("touchend",Ze)}function bt(Q){l.value=l.value===Q?null:Q,r("clip-select",l.value)}function ct(Q){Z(Q)&&(l.value=Q,r("clip-select",Q),r("clip-long-press",Q))}function At(Q){!Z(Q)||n.clips.length<=1||(l.value=Q,r("clip-select",Q),r("clip-delete",Q))}function $t(Q,he){if(!Z(Q))return;const ue=n.clips.find(Te=>Te.id===Q);if(!ue||Math.abs(he)<2)return;const le=he/A.value*n.sensitivity;if(n.useFrameMode){const Te=p.secondsToFrames(ue.sourceIn),ze=p.secondsToFrames(le),ot=Math.max(0,Te+ze),St=p.framesToSeconds(ot);r("trim",Q,"start",St)}else{const Te=Math.max(0,ue.sourceIn+le);r("trim",Q,"start",Te)}}function Pt(Q,he){if(!Z(Q))return;const ue=n.clips.find(X=>X.id===Q);if(!ue||!s.value)return;const le=s.value.getBoundingClientRect(),Te=he-le.left-M.value,ze=80;Te<ze?c.value=Math.max(0,c.value-8):Te>le.width-M.value-ze&&(c.value=Math.min(U.value,c.value+8));const ot=Te+c.value,St=1/n.fps;let Ft=ot/A.value;const{previous:Vt}=ge(ue.id),Ct=rt(Ft,[0,Vt==null?void 0:Vt.timelineEnd,n.playhead],0,ue.timelineEnd-St);Ft=Ct.value,k.value=Ct.guideTime;let Ht=ue.sourceIn+(Ft-ue.timelineStart);Ht=Math.round(Ht*n.fps)/n.fps,r("trim",Q,"start",Ht)}function Ut(Q,he){if(!Z(Q))return;const ue=n.clips.find(ye=>ye.id===Q);if(!ue||!s.value)return;const le=s.value.getBoundingClientRect(),Te=he-le.left-M.value,ze=80;Te<ze?c.value=Math.max(0,c.value-8):Te>le.width-M.value-ze&&(c.value=Math.min(U.value,c.value+8));const ot=Te+c.value,St=1/n.fps,Ft=K(ue);let Vt=ot/A.value;const{next:Ct}=ge(ue.id),Ht=rt(Vt,[Ct==null?void 0:Ct.timelineStart,n.playhead],ue.timelineStart+St,Ft);Vt=Ht.value,k.value=Ht.guideTime;let X=ue.sourceIn+(Vt-ue.timelineStart);X=Math.round(X*n.fps)/n.fps,r("trim",Q,"end",X)}function ea(Q){var ue;if(!x.value||!s.value)return null;const he=Array.from(s.value.querySelectorAll(".timeline-track-lane__body"));for(const le of he){const Te=le.getBoundingClientRect();if(Q>=Te.top&&Q<=Te.bottom){const ze=le.getAttribute("data-track-id");if(!ze)continue;return((ue=n.tracks)==null?void 0:ue.find(St=>St.id===ze))??null}}return null}function Jt(Q,he,ue){if(!Z(Q))return;const le=n.clips.find(ye=>ye.id===Q);if(!le||!s.value)return;const Te=s.value.getBoundingClientRect(),ze=he-Te.left-M.value,ot=80;ze<ot?c.value=Math.max(0,c.value-8):ze>Te.width-M.value-ot&&(c.value=Math.min(U.value,c.value+8));const St=ze+c.value,Ft=le.timelineEnd-le.timelineStart,Vt=Ge(le);let Ct=St/A.value;const Ht=rt(Ct,[Vt.minStart,Vt.maxStart,n.playhead,n.playhead-Ft],Vt.minStart,Vt.maxStart);Ct=Ht.value,k.value=Ht.guideTime,Ct=Math.round(Ct*n.fps)/n.fps;let X;if(typeof ue=="number"){const ye=ea(ue);g.value=(ye==null?void 0:ye.id)??null,ye&&ye.id!==(le.trackId??null)&&ye.locked!==!0&&(X=ye.id)}X!==void 0?r("clip-move",Q,Ct,X):r("clip-move",Q,Ct)}function ta(Q,he){if(!Z(Q))return;const ue=n.clips.find(ze=>ze.id===Q);if(!ue||Math.abs(he)<2)return;const le=he/A.value*n.sensitivity,Te=ze=>Math.max(0,Math.round(ze*n.fps)/n.fps);if(n.useFrameMode){const ze=p.secondsToFrames(ue.sourceOut),ot=p.secondsToFrames(le),St=K(ue),Ft=ue.sourceIn+(St-ue.timelineStart),Vt=p.secondsToFrames(Ft),Ct=Math.min(Vt,ze+ot),Ht=p.framesToSeconds(Ct);r("trim",Q,"end",Ht)}else{const ze=K(ue),ot=ue.sourceIn+(ze-ue.timelineStart),St=Math.min(ot,ue.sourceOut+le),Ft=Te(St);r("trim",Q,"end",Ft)}}function fa(Q,he){if(!Z(Q))return;const ue=n.clips.find(ze=>ze.id===Q);if(!ue||Math.abs(he)<2)return;const le=he/A.value*n.sensitivity,Te=ze=>Math.max(0,Math.round(ze*n.fps)/n.fps);if(n.useFrameMode){const ze=p.secondsToFrames(ue.timelineStart),ot=p.secondsToFrames(le),St=Math.max(0,ze+ot),Ft=p.framesToSeconds(St);r("clip-move",Q,Ft)}else{const ze=Math.max(0,ue.timelineStart+le),ot=Te(ze);r("clip-move",Q,ot)}}return a({handleTrimStart:$t,handleTrimEnd:ta,handleClipDrag:fa,handleTrimStartAbs:Pt,handleTrimEndAbs:Ut,handleClipDragAbs:Jt,handleClipLongPress:ct}),e.watch(()=>n.playhead,Q=>{const he=Q*A.value;he<c.value+50?c.value=Math.max(0,he-50):he>c.value+w.value-50&&(c.value=Math.min(U.value,he-w.value+50))}),e.onMounted(()=>{const Q=new ResizeObserver(he=>{he[0]&&(m.value=Math.round(he[0].contentRect.width))});s.value&&Q.observe(s.value),e.onUnmounted(()=>Q.disconnect())}),e.onUnmounted(()=>{Ze()}),e.watch([ie,W],()=>{c.value>U.value&&(c.value=U.value)}),e.watch(k,(Q,he)=>{const ue=Q!==null;ue!==(he!==null)&&r("snap-state-change",ue)}),(Q,he)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-timeline",{mobile:i.value}]),ref_key:"timelineRef",ref:s,onWheel:Ae},[e.createElementVNode("div",{class:"timeline-ruler",onClick:Se},[e.createElementVNode("div",X1,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(_e.value,ue=>(e.openBlock(),e.createElementBlock("span",{key:ue.position,class:"time-marker",style:e.normalizeStyle({left:`${ue.position}px`})},e.toDisplayString(ue.label),5))),128))])]),e.createElementVNode("div",{class:e.normalizeClass(["timeline-content",{"is-pannable":C.value,"is-panning":h.value&&v.value==="pan","overflow-left":j.value,"overflow-right":ne.value}]),onTouchstart:gt,onTouchmove:lt,onTouchend:Et,onMousedown:Ee},[x.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"timeline-track-lanes",style:e.normalizeStyle({"--timeline-track-header-width":`${Rc}px`})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(O.value,ue=>(e.openBlock(),e.createElementBlock("div",{key:ue.track.id,class:e.normalizeClass(["timeline-track-lane",{"timeline-track-lane--locked":ue.track.locked,"timeline-track-lane--hidden":ue.track.hidden,"timeline-track-lane--drop-target":g.value===ue.track.id&&ue.track.locked!==!0,"timeline-track-lane--drop-rejected":g.value===ue.track.id&&ue.track.locked===!0}]),style:e.normalizeStyle({height:`${ue.height}px`}),"data-track-id":ue.track.id},[e.createVNode(G1,{class:"timeline-track-lane__header",track:ue.track,onToggleLock:he[0]||(he[0]=le=>r("toggle-lock",le)),onToggleHidden:he[1]||(he[1]=le=>r("toggle-hidden",le)),onToggleMuted:he[2]||(he[2]=le=>r("toggle-muted",le)),onToggleSolo:he[3]||(he[3]=le=>r("toggle-solo",le)),onRenameTrack:he[4]||(he[4]=(le,Te)=>r("rename-track",le,Te)),onDeleteTrack:he[5]||(he[5]=le=>r("delete-track",le)),onReorderTrack:he[6]||(he[6]=(le,Te)=>r("reorder-track",le,Te))},null,8,["track"]),e.createElementVNode("div",{class:"video-track timeline-track-lane__body","data-track-id":ue.track.id},[ue.track.hidden?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(ue.clips,le=>(e.openBlock(),e.createElementBlock("div",{key:`${le.id}-extent`,class:"clip-extent",style:e.normalizeStyle(se(le,ue.height)),"aria-hidden":"true"},null,4))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(ue.clips,le=>(e.openBlock(),e.createBlock(Dc,{key:le.id,clip:le,scale:A.value,"scroll-offset":c.value,selected:f.value===le.id,"is-mobile":i.value,"can-delete":n.clips.length>1&&Z(le.id),"data-locked":ue.track.locked===!0?"true":void 0,onSelect:Te=>bt(le.id),onDelete:Te=>At(le.id),onLongPress:Te=>ct(le.id),onTrimStartAbs:Te=>Pt(le.id,Te),onTrimEndAbs:Te=>Ut(le.id,Te),onDragAbs:(Te,ze)=>Jt(le.id,Te,ze)},null,8,["clip","scale","scroll-offset","selected","is-mobile","can-delete","data-locked","onSelect","onDelete","onLongPress","onTrimStartAbs","onTrimEndAbs","onDragAbs"]))),128))],64))],8,J1)],14,K1))),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(Q.clips,ue=>(e.openBlock(),e.createElementBlock("div",{key:`${ue.id}-extent`,class:"clip-extent",style:e.normalizeStyle(se(ue)),"aria-hidden":"true"},null,4))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Q.clips,ue=>(e.openBlock(),e.createBlock(Dc,{key:ue.id,clip:ue,scale:A.value,"scroll-offset":c.value,selected:f.value===ue.id,"is-mobile":i.value,"can-delete":n.clips.length>1&&Z(ue.id),onSelect:le=>bt(ue.id),onDelete:le=>At(ue.id),onLongPress:le=>ct(ue.id),onTrimStartAbs:le=>Pt(ue.id,le),onTrimEndAbs:le=>Ut(ue.id,le),onDragAbs:(le,Te)=>Jt(ue.id,le,Te)},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+de.value}px`}),onMousedown:Re,onTouchstart:Re},[...he[8]||(he[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+de.value}px`})},null,4)):e.createCommentVNode("",!0),Ke.value!==null?(e.openBlock(),e.createElementBlock("div",{key:3,class:"snap-guide",style:e.normalizeStyle({left:`${M.value+Ke.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:he[7]||(he[7]=ue=>Q.$emit("toggle-frame-mode")),"aria-label":Q.useFrameMode?"Switch to time mode":"Switch to frame mode",title:Q.useFrameMode?"Switch to time mode":"Switch to frame mode"},e.toDisplayString(Q.useFrameMode?"F":"T"),9,q1))],34),C.value?(e.openBlock(),e.createElementBlock("div",Y1,[e.createElementVNode("div",{class:"scrollbar-thumb",style:e.normalizeStyle(be.value),onMousedown:et,onTouchstart:et},null,36)])):e.createCommentVNode("",!0)],34))}}),Nl=Fe(Q1,[["__scopeId","data-v-2484f443"]]),ew={key:0,class:"control-group primary-controls"},tw=["disabled"],aw=["disabled"],nw=["disabled"],ow=["disabled"],iw=["disabled"],rw=["disabled"],sw={key:1,class:"control-group mobile-action-controls"},lw=["aria-expanded"],dw={key:0,class:"mobile-action-menu",role:"menu","aria-label":"Clip actions","data-testid":"timeline-mobile-action-menu"},cw=["disabled"],uw=["disabled"],mw=["disabled"],pw=["disabled"],fw=["disabled"],hw=["disabled"],vw={class:"control-group zoom-controls"},gw={class:"zoom-slider"},bw=["value"],yw={class:"control-group playback-controls"},ww=["aria-label"],kw={key:2,class:"control-group speed-control"},_w=["value"],Ew=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(f){switch(f){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(f){const p=f.target;t("zoom-change",Number(p.value))}function s(){t("fit-to-window")}function l(){t("frame-forward")}function d(){t("frame-backward")}function c(){t("skip-to-start")}function u(){t("skip-to-end")}function m(f){const p=f.target;t("speed-change",Number(p.value))}return(f,p)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["timeline-controls",{mobile:f.isMobile}])},[f.isMobile?(e.openBlock(),e.createElementBlock("div",sw,[e.createElementVNode("button",{class:"control-button","data-testid":"timeline-btn-mobile-actions","aria-expanded":n.value?"true":"false","aria-label":"Clip actions",onClick:p[6]||(p[6]=h=>n.value=!n.value)},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(lv)},null,8,["icon"]),p[20]||(p[20]=e.createElementVNode("span",{class:"control-label"},"Actions",-1))],8,lw),n.value?(e.openBlock(),e.createElementBlock("div",dw,[f.showAddTrack?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",role:"menuitem",disabled:!f.canAddTrack,"data-testid":"timeline-mobile-btn-add-track",onClick:p[7]||(p[7]=h=>i("add-track"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(wr)},null,8,["icon"]),p[21]||(p[21]=e.createTextVNode(" Add Track ",-1))],8,cw)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",role:"menuitem",disabled:!f.canUndo,"data-testid":"timeline-mobile-btn-undo",onClick:p[8]||(p[8]=h=>i("undo"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(sc)},null,8,["icon"]),p[22]||(p[22]=e.createTextVNode(" Undo ",-1))],8,uw),e.createElementVNode("button",{type:"button",role:"menuitem",disabled:!f.canRedo,"data-testid":"timeline-mobile-btn-redo",onClick:p[9]||(p[9]=h=>i("redo"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(rc)},null,8,["icon"]),p[23]||(p[23]=e.createTextVNode(" Redo ",-1))],8,mw),e.createElementVNode("button",{type:"button",role:"menuitem",disabled:!f.canSplit,"data-testid":"timeline-mobile-btn-split",onClick:p[10]||(p[10]=h=>i("split"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref($r)},null,8,["icon"]),p[24]||(p[24]=e.createTextVNode(" Split ",-1))],8,pw),e.createElementVNode("button",{type:"button",role:"menuitem",disabled:!f.selectedClip,"data-testid":"timeline-mobile-btn-duplicate",onClick:p[11]||(p[11]=h=>i("duplicate"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(cl)},null,8,["icon"]),p[25]||(p[25]=e.createTextVNode(" Duplicate ",-1))],8,fw),e.createElementVNode("button",{type:"button",role:"menuitem",class:"danger-menu-item",disabled:!f.canDelete,"data-testid":"timeline-mobile-btn-delete",onClick:p[12]||(p[12]=h=>i("delete"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Fr)},null,8,["icon"]),p[26]||(p[26]=e.createTextVNode(" Delete ",-1))],8,hw)])):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("div",ew,[f.showAddTrack?(e.openBlock(),e.createElementBlock("button",{key:0,class:"control-button",disabled:!f.canAddTrack,"data-testid":"timeline-btn-add-track","aria-label":"Add video track",title:"Add Track",onClick:p[0]||(p[0]=h=>f.$emit("add-track"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(wr)},null,8,["icon"]),p[16]||(p[16]=e.createElementVNode("span",{class:"control-label"},"Add Track",-1))],8,tw)):e.createCommentVNode("",!0),e.createElementVNode("button",{class:"control-button",disabled:!f.canUndo,"data-testid":"timeline-btn-undo","aria-label":"Undo",title:"Undo",onClick:p[1]||(p[1]=h=>f.$emit("undo"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(sc)},null,8,["icon"])],8,aw),e.createElementVNode("button",{class:"control-button",disabled:!f.canRedo,"data-testid":"timeline-btn-redo","aria-label":"Redo",title:"Redo",onClick:p[2]||(p[2]=h=>f.$emit("redo"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(rc)},null,8,["icon"])],8,nw),e.createElementVNode("button",{class:"control-button",disabled:!f.canSplit,"data-testid":"timeline-btn-split","aria-label":"Split selected clip at playhead",title:"Split",onClick:p[3]||(p[3]=h=>f.$emit("split"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref($r)},null,8,["icon"]),p[17]||(p[17]=e.createElementVNode("span",{class:"control-label"},"Split",-1))],8,ow),e.createElementVNode("button",{class:"control-button",disabled:!f.selectedClip,"data-testid":"timeline-btn-duplicate","aria-label":"Duplicate selected clip",title:"Duplicate",onClick:p[4]||(p[4]=h=>f.$emit("duplicate"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(cl)},null,8,["icon"]),p[18]||(p[18]=e.createElementVNode("span",{class:"control-label"},"Duplicate",-1))],8,iw),e.createElementVNode("button",{class:"control-button danger-button",disabled:!f.canDelete,"data-testid":"timeline-btn-delete","aria-label":"Delete selected clip",title:"Delete",onClick:p[5]||(p[5]=h=>f.$emit("delete"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Fr)},null,8,["icon"]),p[19]||(p[19]=e.createElementVNode("span",{class:"control-label"},"Delete",-1))],8,rw)])),e.createElementVNode("div",vw,[e.createElementVNode("button",{class:"control-button zoom-button",onClick:p[13]||(p[13]=h=>f.$emit("zoom-out")),"aria-label":"Zoom out"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(xv)},null,8,["icon"])]),e.createElementVNode("div",gw,[e.createElementVNode("input",{type:"range",value:f.zoomLevel,onInput:r,min:"10",max:"200",step:"5","aria-label":"Timeline zoom"},null,40,bw)]),e.createElementVNode("button",{class:"control-button zoom-button",onClick:p[14]||(p[14]=h=>f.$emit("zoom-in")),"aria-label":"Zoom in"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(wr)},null,8,["icon"])]),e.createElementVNode("button",{class:"control-button",onClick:s,"aria-label":"Fit timeline to window"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(cv)},null,8,["icon"]),p[27]||(p[27]=e.createElementVNode("span",{class:"control-label"},"Fit",-1))])]),e.createElementVNode("div",yw,[e.createElementVNode("button",{class:"control-button",onClick:c,"aria-label":"Skip to start"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Sv)},null,8,["icon"])]),e.createElementVNode("button",{class:"control-button",onClick:d,"aria-label":"Previous frame"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(wv)},null,8,["icon"])]),e.createElementVNode("button",{class:"control-button play-button",onClick:p[15]||(p[15]=h=>f.$emit("play-pause")),"aria-label":f.isPlaying?"Pause":"Play"},[e.createVNode(e.unref(H.IonIcon),{icon:f.isPlaying?e.unref(ed):e.unref(td)},null,8,["icon"])],8,ww),e.createElementVNode("button",{class:"control-button",onClick:l,"aria-label":"Next frame"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Ev)},null,8,["icon"])]),e.createElementVNode("button",{class:"control-button",onClick:u,"aria-label":"Skip to end"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Cv)},null,8,["icon"])])]),f.isMobile?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",kw,[p[29]||(p[29]=e.createElementVNode("label",{class:"speed-label"},"Speed:",-1)),e.createElementVNode("select",{value:f.playbackSpeed,onChange:m,class:"speed-select","aria-label":"Playback speed"},[...p[28]||(p[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,_w)]))],2))}}),Tl=Fe(Ew,[["__scopeId","data-v-c7b0395a"]]),Sw={key:0,class:"category-section"},Cw={class:"category-carousel-wrapper"},xw=["disabled"],Vw=["onClick","data-testid","aria-label"],Nw={class:"category-name"},Tw=["disabled"],Bw={class:"filter-section"},Mw={class:"filter-carousel-wrapper"},Iw=["disabled"],$w=["onClick","onKeydown","data-testid","aria-label"],Fw=["onClick"],Dw={class:"filter-preview"},Rw={class:"filter-placeholder"},Aw={class:"filter-name"},Lw=["disabled"],Pw={class:"carousel-pagination"},Uw=["onClick"],Ow={key:1,class:"filter-adjustments"},zw={class:"adjustment-header"},jw={class:"adjustment-actions"},Ww={key:0},Hw={key:0,class:"slider-control"},Zw={class:"control-label"},Gw={class:"slider-wrapper"},Xw={class:"slider-value"},Kw={key:1,class:"color-control"},Jw={class:"control-label"},qw={class:"color-wrapper"},Yw=["value","onInput","disabled"],Qw={class:"color-value"},ek={key:2,class:"toggle-control"},tk={class:"control-label"},ak={key:3,class:"select-control"},nk={class:"control-label"},ok=["value","onChange","disabled"],ik=["value"],rk={key:1,class:"no-params"},sk=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),s=e.ref(0),l=e.ref(0),d=e.ref(new Map),c=e.ref(),u=e.ref(),m={all:Sn,adjust:ti,color:Cn,blur:rr,light:ai,effects:Us,stylize:ci,advanced:Sn,distortion:ui,transform:ui};function f(I){return I.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function p(I){return I.replace(/[-_]/g," ").replace(/\b\w/g,Z=>Z.toUpperCase())}function h(I){return m[I.toLowerCase()]??Sn}const v=e.computed(()=>{const I=Array.from(new Set(t.filters.map(Z=>Z.category).filter(Z=>typeof Z=="string"&&Z.length>0))).sort((Z,z)=>Z.localeCompare(z));return[{id:"all",name:"All",icon:Sn},...I.map(Z=>({id:Z,name:p(Z),icon:h(Z)}))]}),E=e.computed(()=>i.value==="all"?t.filters:t.filters.filter(I=>I.category===i.value));e.watch(v,I=>{new Set(I.map(K=>K.id)).has(i.value)||(i.value="all");const z=Math.max(0,I.length-3);s.value>z&&(s.value=z)},{immediate:!0});function y(I){var Z;return((Z=t.activeFilters)==null?void 0:Z.has(I))||!1}function k(I){if(r.value=I,!y(I.id)&&(n("apply-filter",I),I.params&&I.params.length>0)){const Z=new Map;I.params.forEach(z=>{Z.set(z.id,z.default)}),d.value.set(I.id,Z)}n("preview-filter",I)}function g(I){var Z;n("remove-filter",I),d.value.delete(I),((Z=r.value)==null?void 0:Z.id)===I&&(r.value=null)}function b(I){if(typeof I=="number"&&Number.isFinite(I))return I;if(typeof I=="string"){const Z=Number(I);return Number.isFinite(Z)?Z:null}return null}function R(I,Z){var W;const z=t.filters.find(C=>C.id===I),K=z==null?void 0:z.params.find(C=>C.id===Z),se=(K==null?void 0:K.default)??0,Be=C=>typeof se=="number"?b(C)??se:typeof se=="boolean"?typeof C=="boolean"?C:se:typeof C=="string"?C:se,ce=(W=t.activeFilters)==null?void 0:W.get(I);if(ce&&ce.params){const C=ce.params[Z];if(C!=null)return Be(C)}const ie=d.value.get(I);if(ie){const C=ie.get(Z);if(C!=null)return Be(C)}return se}function N(I,Z,z){var K;d.value.has(I)||d.value.set(I,new Map),(K=d.value.get(I))==null||K.set(Z,z),n("update-param",I,Z,z)}function T(I){if(typeof I=="boolean")return I?"On":"Off";if(typeof I=="string"){const z=b(I);return z===null?"0":Number.isInteger(z)?z.toString():z.toFixed(2)}const Z=b(I);return Z===null?"0":Number.isInteger(Z)?Z.toString():Z.toFixed(2)}function S(){if(r.value&&(n("apply-filter",r.value),r.value.params&&r.value.params.length>0)){const I=new Map;r.value.params.forEach(Z=>{I.set(Z.id,Z.default)}),d.value.set(r.value.id,I)}}function B(I){const Z=t.filters.find(z=>z.id===I);Z&&Z.params&&Z.params.forEach(z=>{N(I,z.id,z.default)})}function A(I){return{basic:ti,color:Cn,blur:rr,light:ai,effects:Us,stylize:ci,adjustment:ti,"color-matrix":Cn,glow:Sn,distortion:ui}[I]||Sn}function x(I){return{adjustment:ti,brightness:ai,contrast:ti,saturation:Cn,blur:rr,"gaussian-blur":rr,"color-matrix":Cn,grayscale:ci,sepia:ci,vignette:ui,glow:Sn,glitch:Us,godray:ai,lightmap:ai}[I.id]||A(I.category)}function M(){s.value>0&&(s.value--,O(c.value,s.value))}function w(){s.value<v.value.length-3&&(s.value++,O(c.value,s.value))}function F(){l.value>0&&(l.value--,O(u.value,l.value))}function P(){l.value<E.value.length-4&&(l.value++,O(u.value,l.value))}function D(I){l.value=I*4,O(u.value,l.value)}function O(I,Z){var z;if(I){const K=((z=I.querySelector(".category-chip, .filter-card"))==null?void 0:z.clientWidth)||100;I.scrollTo({left:Z*(K+8),behavior:"smooth"})}}return(I,Z)=>{var z;return e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-filter-carousel-container",{compact:I.compact}])},[I.showCategories?(e.openBlock(),e.createElementBlock("div",Sw,[e.createElementVNode("div",Cw,[e.createElementVNode("button",{onClick:M,class:"carousel-nav carousel-nav-left",disabled:s.value===0,"aria-label":"Previous categories","data-testid":"btn-filter-category-prev"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(lc)},null,8,["icon"])],8,xw),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-${f(K.id)}`,"aria-label":`Filter category ${K.name}`},[e.createVNode(e.unref(H.IonIcon),{icon:K.icon,class:"category-icon"},null,8,["icon"]),e.createElementVNode("span",Nw,e.toDisplayString(K.name),1)],10,Vw))),128))],512),e.createElementVNode("button",{onClick:w,class:"carousel-nav carousel-nav-right",disabled:s.value>=v.value.length-3,"aria-label":"Next categories","data-testid":"btn-filter-category-next"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(dc)},null,8,["icon"])],8,Tw)])])):e.createCommentVNode("",!0),e.createElementVNode("div",Bw,[e.createElementVNode("div",Mw,[e.createElementVNode("button",{onClick:F,class:"carousel-nav carousel-nav-left",disabled:l.value===0,"aria-label":"Previous filters","data-testid":"btn-filter-carousel-prev"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(lc)},null,8,["icon"])],8,Iw),e.createElementVNode("div",{ref_key:"filterCarouselRef",ref:u,class:"filter-carousel"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(E.value,K=>{var se;return e.openBlock(),e.createElementBlock("div",{key:K.id,class:e.normalizeClass(["filter-card",{active:y(K.id),selected:((se=r.value)==null?void 0:se.id)===K.id}]),onClick:Be=>k(K),onKeydown:[e.withKeys(Be=>k(K),["enter"]),e.withKeys(e.withModifiers(Be=>k(K),["prevent"]),["space"])],role:"button",tabindex:"0","data-testid":`btn-video-filter-${f(K.id)}`,"aria-label":`Select filter ${K.name}`},[y(K.id)?(e.openBlock(),e.createElementBlock("div",{key:0,class:"filter-checkmark",onClick:e.withModifiers(Be=>g(K.id),["stop"])},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(om)},null,8,["icon"])],8,Fw)):e.createCommentVNode("",!0),e.createElementVNode("div",Dw,[e.createElementVNode("div",Rw,[e.createVNode(e.unref(H.IonIcon),{icon:x(K),class:"filter-icon"},null,8,["icon"])])]),e.createElementVNode("span",Aw,e.toDisplayString(K.name),1)],42,$w)}),128))],512),e.createElementVNode("button",{onClick:P,class:"carousel-nav carousel-nav-right",disabled:l.value>=Math.max(0,E.value.length-4),"aria-label":"Next filters","data-testid":"btn-filter-carousel-next"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(dc)},null,8,["icon"])],8,Lw)]),e.createElementVNode("div",Pw,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Math.ceil(E.value.length/4),(K,se)=>(e.openBlock(),e.createElementBlock("span",{key:se,class:e.normalizeClass(["pagination-dot",{active:Math.floor(l.value/4)===se}]),onClick:Be=>D(se)},null,10,Uw))),128))])]),r.value?(e.openBlock(),e.createElementBlock("div",Ow,[e.createElementVNode("div",zw,[e.createElementVNode("h4",null,e.toDisplayString(r.value.name),1),e.createElementVNode("div",jw,[y(r.value.id)?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("button",{key:0,onClick:S,class:"apply-btn","data-testid":"btn-apply-selected-filter"}," Apply Filter ")),y(r.value.id)?(e.openBlock(),e.createElementBlock("button",{key:1,onClick:Z[0]||(Z[0]=K=>g(r.value.id)),class:"remove-btn","data-testid":"btn-remove-selected-filter"}," Remove Filter ")):e.createCommentVNode("",!0),y(r.value.id)&&((z=r.value.params)==null?void 0:z.length)>0?(e.openBlock(),e.createElementBlock("button",{key:2,onClick:Z[1]||(Z[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",Ww,[(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",Hw,[e.createElementVNode("label",Zw,e.toDisplayString(K.label||K.id),1),e.createElementVNode("div",Gw,[e.createVNode(e.unref(H.IonRange),{value:R(r.value.id,K.id),onIonChange:se=>N(r.value.id,K.id,se.detail.value),min:K.min,max:K.max,step:K.step||.01,color:"primary",class:"compact-slider",disabled:!y(r.value.id),"data-testid":`range-filter-${f(r.value.id)}-${f(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",Xw,e.toDisplayString(T(R(r.value.id,K.id))),1)])])):K.type==="color"?(e.openBlock(),e.createElementBlock("div",Kw,[e.createElementVNode("label",Jw,e.toDisplayString(K.label||K.id),1),e.createElementVNode("div",qw,[e.createElementVNode("input",{type:"color",value:R(r.value.id,K.id),onInput:se=>N(r.value.id,K.id,se.target.value),disabled:!y(r.value.id),class:"color-input"},null,40,Yw),e.createElementVNode("span",Qw,e.toDisplayString(R(r.value.id,K.id)),1)])])):K.type==="toggle"?(e.openBlock(),e.createElementBlock("div",ek,[e.createElementVNode("label",tk,e.toDisplayString(K.label||K.id),1),e.createVNode(e.unref(H.IonToggle),{checked:!!R(r.value.id,K.id),onIonChange:se=>N(r.value.id,K.id,se.detail.checked),disabled:!y(r.value.id),color:"primary"},null,8,["checked","onIonChange","disabled"])])):K.type==="select"?(e.openBlock(),e.createElementBlock("div",ak,[e.createElementVNode("label",nk,e.toDisplayString(K.label||K.id),1),e.createElementVNode("select",{value:R(r.value.id,K.id),onChange:se=>N(r.value.id,K.id,se.target.value),disabled:!y(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,ik))),128))],40,ok)])):e.createCommentVNode("",!0)]))),128))])):(e.openBlock(),e.createElementBlock("div",rk," This filter has no adjustable parameters "))])):e.createCommentVNode("",!0)],2)}}}),Bl=Fe(sk,[["__scopeId","data-v-9efd15d9"]]);class lk{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",s=this.filterIntensity.get(n)??1;a.push({id:n,filterId:r,params:i,intensity:s})}),a}async importFilterConfig(a){await this.applyFilters(a)}destroy(){this.clearFilters(),this.composition=null}}const dk={class:"video-filter-preview"},ck={class:"preview-title"},uk={class:"filter-controls"},mk={class:"control-input"},pk=["value","onInput","min","max","step"],fk={class:"param-value"},hk={class:"preview-container"},vk={key:0,class:"filter-presets"},gk=["onClick"],bk={class:"preview-actions"},yk=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),s=e.ref({});let l,d,c=null,u=null;const m=e.computed(()=>{var S;return((S=t.filter)==null?void 0:S.paramRanges)||{}}),f=e.computed(()=>p.value.length>0),p=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 S;if(i.value){t.useVideoEngine&&t.composition&&(u=new lk(t.composition));try{if(l=new Gt.Application,await l.init({width:i.value.clientWidth,height:i.value.clientHeight,background:0,resolution:window.devicePixelRatio||1,autoDensity:!0,canvas:i.value}),(S=t.currentFrame)!=null&&S.dataUrl){const B=await Gt.Assets.load(t.currentFrame.dataUrl);d=new Gt.Sprite(B);const A=Math.min(l.screen.width/d.texture.width,l.screen.height/d.texture.height);d.scale.set(A),d.anchor.set(.5),d.position.set(l.screen.width/2,l.screen.height/2),l.stage.addChild(d)}v()}catch{}}}function v(){if(!(!d||!t.filter))if(t.useVideoEngine&&u){const S={id:t.filter.id,filterId:t.filter.id,params:s.value,intensity:s.value.value??s.value.intensity??1};u.applyFilters([S]).then(()=>{}).catch(B=>{}),c&&(c.destroy(),c=null),c=E(t.filter.id,s.value),c&&(d.filters=r.value?null:[c])}else c&&(c.destroy(),c=null),c=E(t.filter.id,s.value),c&&(d.filters=r.value?null:[c])}function E(S,B){switch(S){case"brightness":{const A=new Gt.ColorMatrixFilter,x=1+(B.value??0);return typeof A.brightness=="function"&&A.brightness(x,!1),A}case"contrast":{const A=new Gt.ColorMatrixFilter,x=B.value??1;return typeof A.contrast=="function"&&A.contrast(x,!1),A}case"saturation":{const A=new Gt.ColorMatrixFilter,x=B.value??1;return typeof A.saturate=="function"&&A.saturate(x,!1),A}case"hue":{const A=new Gt.ColorMatrixFilter,x=B.value??0;return typeof A.hue=="function"&&A.hue(x,!1),A}case"gaussian-blur":{const A=B.value??5;return new Gt.BlurFilter({strength:A,quality:4})}case"sepia":{const A=new Gt.ColorMatrixFilter;return typeof A.sepia=="function"&&A.sepia(!1),A}case"grayscale":{const A=new Gt.ColorMatrixFilter;return typeof A.desaturate=="function"&&A.desaturate(),A}default:return null}}function y(S,B){const A=B.target,x=Number.parseFloat(A.value),M=Number.isFinite(x)?x:0;s.value={...s.value,[S]:M},t.useVideoEngine&&u&&t.filter&&u.updateFilterParams(t.filter.id,s.value),n("update-params",s.value),v()}function k(S){return S.charAt(0).toUpperCase()+S.slice(1).replace(/_/g," ")}function g(S,B){var x;const A=typeof S=="number"?S:Number(S);return Number.isFinite(A)?B==="hue"||B==="angle"?`${A}°`:B==="value"&&((x=t.filter)==null?void 0:x.id)==="brightness"?`${Math.round((1+A)*100)}%`:Number.isInteger(A)?A.toString():A.toFixed(2):"0"}function b(){var S;s.value=((S=t.filter)==null?void 0:S.defaultParams)||{},n("update-params",s.value),v()}function R(S){s.value={...S.params},n("update-params",s.value),v()}function N(S){return JSON.stringify(S.params)===JSON.stringify(s.value)}function T(){n("apply")}return e.watch(()=>t.filter,S=>{S&&(s.value={...S.defaultParams},v())}),e.watch(()=>t.currentFrame,async S=>{if(S!=null&&S.dataUrl&&d){const B=await Gt.Assets.load(S.dataUrl);d.texture=B}}),e.watch(r,v),e.onMounted(()=>{t.filter&&(s.value={...t.filter.defaultParams}),h()}),e.onUnmounted(()=>{l&&l.destroy(!0,{children:!0,texture:!0}),c&&c.destroy(),u&&u.destroy()}),(S,B)=>{var A;return e.openBlock(),e.createElementBlock("div",dk,[e.createElementVNode("h4",ck,e.toDisplayString((A=S.filter)==null?void 0:A.name)+" Settings",1),e.createElementVNode("div",uk,[(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(k(M)),1),e.createElementVNode("div",mk,[e.createElementVNode("input",{type:"range",value:s.value[M],onInput:w=>y(M,w),min:x.min,max:x.max,step:x.step,class:"param-slider"},null,40,pk),e.createElementVNode("span",fk,e.toDisplayString(g(s.value[M],M)),1)])]))),128))]),e.createElementVNode("div",hk,[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(H.IonIcon),{icon:e.unref(ui)},null,8,["icon"]),B[4]||(B[4]=e.createTextVNode(" Hold to compare ",-1))],32)]),f.value?(e.openBlock(),e.createElementBlock("div",vk,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(p.value,x=>(e.openBlock(),e.createElementBlock("button",{key:x.name,class:e.normalizeClass(["preset-button",{active:N(x)}]),onClick:M=>R(x)},e.toDisplayString(x.name),11,gk))),128))])):e.createCommentVNode("",!0),e.createElementVNode("div",bk,[e.createElementVNode("button",{class:"action-button",onClick:b},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(io)},null,8,["icon"]),B[5]||(B[5]=e.createTextVNode(" Reset ",-1))]),e.createElementVNode("button",{class:"action-button primary",onClick:T},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(im)},null,8,["icon"]),B[6]||(B[6]=e.createTextVNode(" Apply Filter ",-1))])])])}}}),Ml=Fe(yk,[["__scopeId","data-v-3de3dd04"]]),jm={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"}},Wm={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"}},Hm={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"}},Zm={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"}},Gm=[jm,Wm,Hm,Zm],yd={"mobile-share":jm,"hd-web":Wm,original:Hm,"server-master":Zm},wk=["mobile-share","hd-web"],kk=["hd-web","original","mobile-share"],_k=["server-master","hd-web","original","mobile-share"];function hs(o){return typeof o=="string"?yd[o]:o}function Ek(o){const{bitrate:a,codec:t,format:n,fps:i,quality:r}=hs(o).settings,s={format:n,codec:t,quality:r,fps:i};return typeof a=="number"&&(s.bitrate=a),s}function Sk(o){const a=hs(o);return a.settings.mobileSuitable&&a.settings.advancedVisibility==="standard"}function Ck(o=Gm){return o.filter(a=>Sk(a))}function xk(o,a){const t=hs(o).settings.maxClientDurationSeconds;return t!==null&&Number.isFinite(a)&&a>=0&&a<=t}function Vk(o,a){const t=hs(o),n=a.endpoints.client&&xk(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 Nk(o,a){return Vk(o,a)!==null}function Tk(o){const a=Bk(o);for(const t of a){const n=yd[t];if(Mk(n,o.includeAdvanced===!0)&&!(o.device==="mobile"&&!n.settings.mobileSuitable)&&Nk(n,o))return n}return null}function Bk(o){return o.device==="mobile"?wk:o.includeAdvanced===!0?_k:kk}function Mk(o,a){return o.settings.advancedVisibility==="hidden"?!1:o.settings.advancedVisibility==="standard"||a}const Ik={class:"export-settings"},$k={class:"setting-group preset-setting"},Fk={class:"setting-copy"},Dk={class:"setting-description"},Rk=["value"],Ak={key:0,class:"advanced-toggle","data-testid":"export-advanced-toggle"},Lk={class:"preset-summary","data-testid":"export-preset-summary"},Pk={class:"estimated-size"},Uk={key:0,class:"export-progress"},Ok={class:"progress-header"},zk={class:"progress-percentage"},jk={class:"progress-time"},Wk={class:"action-buttons"},Hk=["disabled"],Zk=["disabled"],Gk=["disabled"],Xk={class:"export-options"},Kk="hd-web",Jk=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=Gm,s={"360p":1,"480p":2.5,"720p":5,"1080p":8,"1440p":16,"2160p":35},l=e.ref(!1),d=e.ref(b()),c=e.ref(!0),u=e.ref(!1),m=e.ref(0),f=e.ref(0),p=e.ref(0);let h=null;const v=e.computed(()=>t.isMobile?Ck():r.filter(x=>x.settings.advancedVisibility==="hidden"?!1:x.settings.advancedVisibility==="standard"||l.value)),E=e.computed(()=>v.value.find(x=>x.id===d.value)??yd[b()]),y=e.computed(()=>Ek(E.value)),k=e.computed(()=>{const x=y.value,M=[x.quality,x.format.toUpperCase(),x.codec.toUpperCase(),`${x.fps} fps`],w=R(x.bitrate);return w!==null&&M.push(w),M.join(" / ")}),g=e.computed(()=>{const x=y.value,w=(typeof x.bitrate=="number"?x.bitrate/1e6:s[x.quality])*t.duration/8;return w<1e3?`~${Math.round(w)} MB`:`~${(w/1e3).toFixed(1)} GB`});function b(){var x;return((x=Tk({durationSeconds:t.duration,device:t.isMobile?"mobile":"desktop",endpoints:i,includeAdvanced:l.value}))==null?void 0:x.id)??Kk}function R(x){return typeof x!="number"?null:`${Number((x/1e6).toFixed(1))} Mbps`}function N(){t.isExporting?(n("cancel-export"),B()):T()}function T(){const x=y.value,M={quality:x.quality,format:x.format,optimizeForWeb:c.value,includeWatermark:u.value,presetId:E.value.id,codec:x.codec,fps:x.fps};typeof x.bitrate=="number"&&(M.bitrate=x.bitrate),n("export",M),S()}function S(){m.value=Date.now(),f.value=0,h=window.setInterval(()=>{if(f.value=Math.floor((Date.now()-m.value)/1e3),t.exportProgress>0){const x=f.value/t.exportProgress*100;p.value=Math.max(0,x-f.value)}},1e3)}function B(){h&&(clearInterval(h),h=null)}function A(x){const M=Math.floor(x/60),w=Math.floor(x%60);return`${M}:${w.toString().padStart(2,"0")}`}return e.watch([()=>t.isMobile,()=>l.value],()=>{v.value.some(M=>M.id===d.value)||(d.value=b())},{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",Ik,[M[8]||(M[8]=e.createElementVNode("h3",{class:"section-title"},"Export Settings",-1)),e.createElementVNode("div",$k,[e.createElementVNode("div",Fk,[M[6]||(M[6]=e.createElementVNode("label",{for:"export-preset-select"},"Preset",-1)),e.createElementVNode("span",Dk,e.toDisplayString(E.value.description),1)]),e.withDirectives(e.createElementVNode("select",{id:"export-preset-select","onUpdate:modelValue":M[0]||(M[0]=w=>d.value=w),class:"setting-select preset-select","data-testid":"export-preset-select"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(v.value,w=>(e.openBlock(),e.createElementBlock("option",{key:w.id,value:w.id},e.toDisplayString(w.label),9,Rk))),128))],512),[[e.vModelSelect,d.value]])]),x.isMobile?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("label",Ak,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":M[1]||(M[1]=w=>l.value=w),type:"checkbox","data-testid":"export-advanced-toggle-input"},null,512),[[e.vModelCheckbox,l.value]]),M[7]||(M[7]=e.createElementVNode("span",null,"Advanced presets",-1))])),e.createElementVNode("div",Lk,e.toDisplayString(k.value),1),e.createElementVNode("div",Pk,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(fv)},null,8,["icon"]),e.createElementVNode("span",null,"Estimated size: "+e.toDisplayString(g.value),1)])]),x.isExporting?(e.openBlock(),e.createElementBlock("div",Uk,[e.createElementVNode("div",Ok,[M[9]||(M[9]=e.createElementVNode("span",null,"Exporting...",-1)),e.createElementVNode("span",zk,e.toDisplayString(x.exportProgress??0)+"%",1)]),e.createVNode(e.unref(H.IonProgressBar),{value:(x.exportProgress??0)/100},null,8,["value"]),e.createElementVNode("div",jk,[e.createElementVNode("span",null,e.toDisplayString(A(f.value))+" elapsed",1),e.createElementVNode("span",null,e.toDisplayString(A(p.value))+" remaining",1)])])):e.createCommentVNode("",!0),e.createElementVNode("div",Wk,[e.createElementVNode("button",{class:"control-button secondary",onClick:M[2]||(M[2]=w=>x.$emit("save-draft")),disabled:!x.canExport||x.isExporting},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Qr)},null,8,["icon"]),M[10]||(M[10]=e.createTextVNode(" Save Draft ",-1))],8,Hk),e.createElementVNode("button",{class:"control-button secondary",onClick:M[3]||(M[3]=w=>x.$emit("reset")),disabled:x.isExporting},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(io)},null,8,["icon"]),M[11]||(M[11]=e.createTextVNode(" Reset ",-1))],8,Zk),e.createElementVNode("button",{class:"control-button primary",onClick:N,disabled:!x.canExport&&!x.isExporting,"data-testid":"video-export-button"},[e.createVNode(e.unref(H.IonIcon),{icon:x.isExporting?e.unref(Yn):e.unref($o)},null,8,["icon"]),e.createTextVNode(" "+e.toDisplayString(x.isExporting?"Cancel":"Export Video"),1)],8,Gk)]),e.createElementVNode("div",Xk,[e.createVNode(e.unref(H.IonItem),{lines:"none"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonCheckbox),{modelValue:c.value,"onUpdate:modelValue":M[4]||(M[4]=w=>c.value=w)},null,8,["modelValue"]),e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...M[12]||(M[12]=[e.createTextVNode("Optimize for web streaming",-1)])]),_:1})]),_:1}),e.createVNode(e.unref(H.IonItem),{lines:"none"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonCheckbox),{modelValue:u.value,"onUpdate:modelValue":M[5]||(M[5]=w=>u.value=w)},null,8,["modelValue"]),e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...M[13]||(M[13]=[e.createTextVNode("Include watermark",-1)])]),_:1})]),_:1})])],2))}}),Il=Fe(Jk,[["__scopeId","data-v-d26ca1bc"]]),qk={class:"thumbnail-picker"},Yk={class:"thumbnail-grid"},Qk=["onClick"],e_=["src","alt"],t_={key:1,class:"thumbnail-placeholder"},a_={class:"thumbnail-time"},n_={class:"custom-selector"},o_={class:"time-input-group"},i_=["max"],r_={class:"time-value"},s_=["disabled"],l_={class:"picker-actions"},d_=["disabled"],c_=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),s=e.ref(t.currentTime),l=e.ref(!1);function d(){const y=[];if(t.duration<=10)for(let g=0;g<Math.min(9,t.duration);g++)y.push(g);else{const g=t.duration/10;for(let b=1;b<=9;b++)y.push(g*b)}return y}async function c(y){try{const k=document.createElement("video");return k.crossOrigin="anonymous",k.src=await u(),new Promise(g=>{k.addEventListener("loadedmetadata",()=>{k.currentTime=y}),k.addEventListener("seeked",()=>{const b=document.createElement("canvas");b.width=k.videoWidth,b.height=k.videoHeight;const R=b.getContext("2d");R?(R.drawImage(k,0,0),g(b.toDataURL("image/jpeg",.8))):g(null),k.remove()}),k.addEventListener("error",()=>{g(null),k.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 y=d();i.value=y.map(g=>({time:g,loading:!0}));const k=3;for(let g=0;g<i.value.length;g+=k){const b=i.value.slice(g,g+k);await Promise.all(b.map(async R=>{const N=await c(R.time);N&&(R.dataUrl=N),R.loading=!1}))}}function f(y){r.value=y,s.value=i.value[y].time}function p(){r.value=-1}async function h(){l.value=!0;try{const y=await c(s.value);if(y){const k=i.value.findIndex(g=>Math.abs(g.time-s.value)<.1);k>=0?(i.value[k].dataUrl=y,r.value=k):(i.value.push({time:s.value,dataUrl:y}),r.value=i.value.length-1,i.value.sort((g,b)=>g.time-b.time),r.value=i.value.findIndex(g=>g.time===s.value))}}finally{l.value=!1}}function v(){const y=r.value>=0?i.value[r.value].time:s.value;n("select",y)}function E(y){const k=Math.floor(y/60),g=Math.floor(y%60),b=Math.floor(y%1*100);return k>0?`${k}:${g.toString().padStart(2,"0")}.${b.toString().padStart(2,"0")}`:`${g}.${b.toString().padStart(2,"0")}s`}return e.onMounted(()=>{m()}),(y,k)=>(e.openBlock(),e.createElementBlock("div",qk,[k[5]||(k[5]=e.createElementVNode("h4",{class:"picker-title"},"Select Video Thumbnail",-1)),e.createElementVNode("div",Yk,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,(g,b)=>(e.openBlock(),e.createElementBlock("div",{key:b,class:e.normalizeClass(["thumbnail-item",{selected:r.value===b}]),onClick:R=>f(b)},[g.dataUrl?(e.openBlock(),e.createElementBlock("img",{key:0,src:g.dataUrl,alt:`Frame at ${E(g.time)}`},null,8,e_)):(e.openBlock(),e.createElementBlock("div",t_,[e.createVNode(e.unref(H.IonSpinner),{name:"crescent"})])),e.createElementVNode("div",a_,e.toDisplayString(E(g.time)),1)],10,Qk))),128))]),e.createElementVNode("div",n_,[k[3]||(k[3]=e.createElementVNode("label",null,"Custom time:",-1)),e.createElementVNode("div",o_,[e.withDirectives(e.createElementVNode("input",{type:"range","onUpdate:modelValue":k[0]||(k[0]=g=>s.value=g),min:0,max:y.duration,step:.1,onInput:p,class:"time-slider"},null,40,i_),[[e.vModelText,s.value]]),e.createElementVNode("span",r_,e.toDisplayString(E(s.value)),1)]),e.createElementVNode("button",{class:"capture-button",onClick:h,disabled:l.value},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(av)},null,8,["icon"]),k[2]||(k[2]=e.createTextVNode(" Capture Frame ",-1))],8,s_)]),e.createElementVNode("div",l_,[e.createElementVNode("button",{class:"action-button",onClick:k[1]||(k[1]=g=>y.$emit("cancel"))}," Cancel "),e.createElementVNode("button",{class:"action-button primary",onClick:v,disabled:r.value===-1},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(im)},null,8,["icon"]),k[4]||(k[4]=e.createTextVNode(" Set Thumbnail ",-1))],8,d_)])]))}}),u_=Fe(c_,[["__scopeId","data-v-336c322c"]]),m_={class:"text-overlay-panel p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg"},p_={class:"mb-4"},f_={class:"space-y-2 max-h-64 overflow-y-auto"},h_={class:"flex items-center justify-between"},v_={class:"flex-1"},g_={class:"font-medium text-gray-900 dark:text-white"},b_={class:"text-sm text-gray-500 dark:text-gray-400"},y_={class:"flex items-center space-x-2"},w_=["onClick"],k_=["onClick"],__={key:0,class:"text-center py-8 text-gray-500 dark:text-gray-400"},E_={class:"bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 w-full max-w-lg mx-4"},S_={class:"text-lg font-semibold text-gray-900 dark:text-white mb-4"},C_={class:"space-y-4"},x_={class:"grid grid-cols-2 gap-4"},V_={class:"grid grid-cols-2 gap-4"},N_={key:0,class:"p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"},T_={class:"grid grid-cols-2 gap-3"},B_={class:"flex justify-end space-x-3 mt-6"},M_=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"}),s=e.reactive(r());function l(f){Object.assign(s,f),i.value=f}function d(){n.value=!1,i.value=null,Object.assign(s,r())}function c(){const f={text:s.text,fontSize:s.fontSize,color:s.color,position:s.position,startTime:s.startTime,duration:s.duration};if(s.animationType&&(f.animation={type:s.animationType},s.animationDuration!==void 0&&(f.animation.duration=s.animationDuration),s.animationEasing&&(f.animation.easing=s.animationEasing),f.animation))switch(s.animationType){case"rotate":f.animation.rotation={from:0,to:360};break;case"scale":f.animation.scale={from:.5,to:1};break;case"slide":f.animation.translate={fromX:-100,toX:0,fromY:0,toY:0};break}i.value?t("update-overlay",i.value.id,f):t("add-overlay",f),d()}function u(f){confirm("Are you sure you want to remove this text overlay?")&&t("remove-overlay",f)}function m(f){const p=Math.floor(f/60),h=Math.floor(f%60);return`${p}:${h.toString().padStart(2,"0")}`}return(f,p)=>(e.openBlock(),e.createElementBlock("div",m_,[e.createElementVNode("div",p_,[p[11]||(p[11]=e.createElementVNode("h3",{class:"text-lg font-semibold text-gray-900 dark:text-white mb-2"}," Text Overlays ",-1)),e.createElementVNode("button",{onClick:p[0]||(p[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"},[...p[10]||(p[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",f_,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(f.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",h_,[e.createElementVNode("div",v_,[e.createElementVNode("div",g_,e.toDisplayString(h.text.substring(0,30))+e.toDisplayString(h.text.length>30?"...":""),1),e.createElementVNode("div",b_,e.toDisplayString(m(h.startTime??0))+" - "+e.toDisplayString(m((h.startTime||0)+(h.duration||5))),1)]),e.createElementVNode("div",y_,[e.createElementVNode("button",{onClick:v=>l(h),class:"p-1 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900 rounded",title:"Edit"},[...p[12]||(p[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,w_),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"},[...p[13]||(p[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,k_)])])]))),128)),f.overlays.length===0?(e.openBlock(),e.createElementBlock("div",__," 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",E_,[e.createElementVNode("h4",S_,e.toDisplayString(i.value?"Edit":"Add")+" Text Overlay ",1),e.createElementVNode("div",C_,[e.createElementVNode("div",null,[p[14]||(p[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":p[1]||(p[1]=h=>s.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,s.text]])]),e.createElementVNode("div",x_,[e.createElementVNode("div",null,[p[15]||(p[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":p[2]||(p[2]=h=>s.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,s.fontSize,void 0,{number:!0}]])]),e.createElementVNode("div",null,[p[16]||(p[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":p[3]||(p[3]=h=>s.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,s.color]])])]),e.createElementVNode("div",null,[p[18]||(p[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":p[4]||(p[4]=h=>s.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"},[...p[17]||(p[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,s.position]])]),e.createElementVNode("div",V_,[e.createElementVNode("div",null,[p[19]||(p[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":p[5]||(p[5]=h=>s.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,s.startTime,void 0,{number:!0}]])]),e.createElementVNode("div",null,[p[20]||(p[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":p[6]||(p[6]=h=>s.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,s.duration,void 0,{number:!0}]])])]),e.createElementVNode("div",null,[p[22]||(p[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":p[7]||(p[7]=h=>s.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"},[...p[21]||(p[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,s.animationType]])]),s.animationType?(e.openBlock(),e.createElementBlock("div",N_,[p[26]||(p[26]=e.createElementVNode("div",{class:"text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"}," Animation Settings ",-1)),e.createElementVNode("div",T_,[e.createElementVNode("div",null,[p[23]||(p[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":p[8]||(p[8]=h=>s.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,s.animationDuration,void 0,{number:!0}]])]),e.createElementVNode("div",null,[p[25]||(p[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":p[9]||(p[9]=h=>s.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"},[...p[24]||(p[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,s.animationEasing]])])])])):e.createCommentVNode("",!0)]),e.createElementVNode("div",B_,[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)]))}}),$l=Fe(M_,[["__scopeId","data-v-f86e688c"]]),I_={class:"transition-selector p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg"},$_={class:"grid grid-cols-3 gap-3 max-h-96 overflow-y-auto"},F_=["onClick"],D_={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"},R_={key:0,class:"w-8 h-8 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},A_={key:0,"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"},L_={key:1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M14 5l7 7m0 0l-7 7m7-7H3"},P_={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"},U_={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"},O_={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"},z_={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"},W_={class:"space-y-3"},H_={class:"flex items-center space-x-2"},Z_=["disabled"],G_=["disabled"],X_={key:1,class:"mt-4"},K_={class:"space-y-2 max-h-32 overflow-y-auto"},J_={class:"text-sm text-gray-700 dark:text-gray-300"},q_=["onClick"],Y_=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(Bi.getAvailableTransitions()),r=e.ref(null),s=e.ref(.5),l=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:s.value,easing:l.value};n("apply-transition",h),r.value=null}function m(){if(!r.value)return;const h={type:r.value.type,duration:s.value,easing:l.value};n("preview-transition",h)}function f(h){n("remove-transition",h)}function p(h){return["fade","wipe","slide","zoom"].some(v=>h.includes(v))}return(h,v)=>(e.openBlock(),e.createElementBlock("div",I_,[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",$_,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,E=>{var y;return e.openBlock(),e.createElementBlock("div",{key:E.type,onClick:k=>c(E),class:e.normalizeClass(["transition-item cursor-pointer rounded-lg p-3 border-2 transition-all",((y=r.value)==null?void 0:y.type)===E.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",D_,[p(E.type)?(e.openBlock(),e.createElementBlock("svg",R_,[E.type.includes("fade")?(e.openBlock(),e.createElementBlock("path",A_)):E.type.includes("wipe")?(e.openBlock(),e.createElementBlock("path",L_)):E.type.includes("slide")?(e.openBlock(),e.createElementBlock("path",P_)):E.type.includes("zoom")?(e.openBlock(),e.createElementBlock("path",U_)):(e.openBlock(),e.createElementBlock("path",O_))])):e.createCommentVNode("",!0)]),e.createElementVNode("div",z_,e.toDisplayString(E.name),1)],10,F_)}),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",W_,[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",H_,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":v[0]||(v[0]=E=>s.value=E),type:"range",min:"0.1",max:"3",step:"0.1",class:"flex-1"},null,512),[[e.vModelText,s.value,void 0,{number:!0}]]),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":v[1]||(v[1]=E=>s.value=E),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,s.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]=E=>l.value=E),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,l.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,Z_),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,G_)])])):e.createCommentVNode("",!0),h.appliedTransitions.length>0?(e.openBlock(),e.createElementBlock("div",X_,[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",K_,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(h.appliedTransitions,(E,y)=>(e.openBlock(),e.createElementBlock("div",{key:y,class:"flex items-center justify-between p-2 bg-gray-50 dark:bg-gray-700 rounded"},[e.createElementVNode("div",J_,e.toDisplayString(E.name)+" ("+e.toDisplayString(E.duration)+"s) ",1),e.createElementVNode("button",{onClick:k=>f(y),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,q_)]))),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))]))}}),Fl=Fe(Y_,[["__scopeId","data-v-ffcc612d"]]),Q_={class:"audio-track-manager p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg"},e2={class:"mb-4"},t2={class:"mb-4 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"},a2={class:"flex items-center justify-between mb-2"},n2={class:"text-sm text-gray-600 dark:text-gray-400"},o2={class:"flex items-center space-x-2"},i2={class:"space-y-3 max-h-64 overflow-y-auto"},r2={class:"flex items-center justify-between mb-2"},s2={class:"font-medium text-gray-900 dark:text-white"},l2={class:"flex items-center space-x-2"},d2=["onClick","title"],c2={key:0,class:"w-5 h-5",fill:"currentColor",viewBox:"0 0 20 20"},u2={key:1,class:"w-5 h-5",fill:"currentColor",viewBox:"0 0 20 20"},m2=["onClick"],p2=["onClick"],f2={class:"flex items-center space-x-2"},h2={class:"text-xs text-gray-500 dark:text-gray-400 w-10"},v2=["value","onInput","disabled"],g2={class:"mt-2 text-xs text-gray-500 dark:text-gray-400"},b2={key:0,class:"ml-2"},y2={key:1,class:"ml-2"},w2={key:0,class:"text-center py-8 text-gray-500 dark:text-gray-400"},k2={class:"bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 w-full max-w-lg mx-4"},_2={class:"text-lg font-semibold text-gray-900 dark:text-white mb-4"},E2={class:"space-y-4"},S2={class:"space-y-2"},C2={class:"flex items-center"},x2={class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"},V2={class:"grid grid-cols-2 gap-4"},N2={class:"grid grid-cols-2 gap-4"},T2={class:"flex items-center"},B2={class:"flex justify-end space-x-3 mt-6"},M2=["disabled"],I2=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),s=e.ref(t.masterVolume),l=()=>({id:"",source:"",sourceUrl:"",name:"Background Music",volume:.7,startTime:0,fadeIn:0,fadeOut:0,loop:!1}),d=e.reactive(l()),c=e.computed(()=>d.sourceUrl||d.sourceFile);function u(g){const b=g.target;b.files&&b.files[0]&&(d.sourceFile=b.files[0],d.name=d.name||b.files[0].name.replace(/\.[^/.]+$/,""))}function m(g){Object.assign(d,g),r.value=g}function f(){i.value=!1,r.value=null,Object.assign(d,l())}function p(){if(!c.value)return;const g={source:d.sourceFile??d.sourceUrl??"",name:d.name,volume:d.volume,startTime:d.startTime,loop:d.loop};d.duration!==void 0&&(g.duration=d.duration),d.fadeIn>0&&(g.fadeIn=d.fadeIn),d.fadeOut>0&&(g.fadeOut=d.fadeOut),r.value?n("update-track",r.value.id,g):n("add-track",g),f()}function h(g){confirm("Are you sure you want to remove this audio track?")&&n("remove-track",g)}function v(g,b){const R=b.target,N=parseFloat(R.value);n("update-volume",g.id,N)}function E(g){n("toggle-mute",g.id,!g.muted)}function y(){n("update-master-volume",s.value)}function k(g){const b=Math.floor(g/60),R=Math.floor(g%60);return`${b}:${R.toString().padStart(2,"0")}`}return(g,b)=>(e.openBlock(),e.createElementBlock("div",Q_,[e.createElementVNode("div",e2,[b[11]||(b[11]=e.createElementVNode("h3",{class:"text-lg font-semibold text-gray-900 dark:text-white mb-2"}," Audio Tracks ",-1)),e.createElementVNode("button",{onClick:b[0]||(b[0]=R=>i.value=!0),class:"w-full px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"},[...b[10]||(b[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",t2,[e.createElementVNode("div",a2,[b[12]||(b[12]=e.createElementVNode("label",{class:"text-sm font-medium text-gray-700 dark:text-gray-300"}," Master Volume ",-1)),e.createElementVNode("span",n2,e.toDisplayString(Math.round(s.value*100))+"% ",1)]),e.createElementVNode("div",o2,[b[13]||(b[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":b[1]||(b[1]=R=>s.value=R),onInput:y,type:"range",min:"0",max:"1",step:"0.01",class:"flex-1"},null,544),[[e.vModelText,s.value,void 0,{number:!0}]]),b[14]||(b[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",i2,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(g.audioLayers,R=>(e.openBlock(),e.createElementBlock("div",{key:R.id,class:"p-3 border border-gray-200 dark:border-gray-700 rounded-lg"},[e.createElementVNode("div",r2,[e.createElementVNode("div",s2,e.toDisplayString(R.name),1),e.createElementVNode("div",l2,[e.createElementVNode("button",{onClick:N=>E(R),class:e.normalizeClass(["p-1 rounded",R.muted?"text-red-600 bg-red-50 dark:bg-red-900":"text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700"]),title:R.muted?"Unmute":"Mute"},[R.muted?(e.openBlock(),e.createElementBlock("svg",u2,[...b[16]||(b[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",c2,[...b[15]||(b[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,d2),e.createElementVNode("button",{onClick:N=>m(R),class:"p-1 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900 rounded",title:"Settings"},[...b[17]||(b[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,m2),e.createElementVNode("button",{onClick:N=>h(R.id),class:"p-1 text-red-600 hover:bg-red-50 dark:hover:bg-red-900 rounded",title:"Remove"},[...b[18]||(b[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,p2)])]),e.createElementVNode("div",f2,[e.createElementVNode("span",h2,e.toDisplayString(Math.round((R.volume||1)*100))+"% ",1),e.createElementVNode("input",{value:R.volume||1,onInput:N=>v(R,N),type:"range",min:"0",max:"1",step:"0.01",class:"flex-1",disabled:R.muted},null,40,v2)]),e.createElementVNode("div",g2,[e.createTextVNode(e.toDisplayString(k(R.startTime||0))+" - "+e.toDisplayString(k((R.startTime||0)+(R.duration||0)))+" ",1),R.fadeIn?(e.openBlock(),e.createElementBlock("span",b2,"Fade In: "+e.toDisplayString(R.fadeIn)+"s",1)):e.createCommentVNode("",!0),R.fadeOut?(e.openBlock(),e.createElementBlock("span",y2,"Fade Out: "+e.toDisplayString(R.fadeOut)+"s",1)):e.createCommentVNode("",!0)])]))),128)),g.audioLayers.length===0?(e.openBlock(),e.createElementBlock("div",w2," 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(f,["self"])},[e.createElementVNode("div",k2,[e.createElementVNode("h4",_2,e.toDisplayString(r.value?"Edit":"Add")+" Audio Track ",1),e.createElementVNode("div",E2,[e.createElementVNode("div",null,[b[20]||(b[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",S2,[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",C2,[b[19]||(b[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":b[2]||(b[2]=R=>d.sourceUrl=R),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,[b[21]||(b[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":b[3]||(b[3]=R=>d.name=R),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",x2," Volume: "+e.toDisplayString(Math.round(d.volume*100))+"% ",1),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":b[4]||(b[4]=R=>d.volume=R),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",V2,[e.createElementVNode("div",null,[b[22]||(b[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":b[5]||(b[5]=R=>d.startTime=R),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,[b[23]||(b[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":b[6]||(b[6]=R=>d.duration=R),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",N2,[e.createElementVNode("div",null,[b[24]||(b[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":b[7]||(b[7]=R=>d.fadeIn=R),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,[b[25]||(b[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":b[8]||(b[8]=R=>d.fadeOut=R),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",T2,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":b[9]||(b[9]=R=>d.loop=R),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]]),b[26]||(b[26]=e.createElementVNode("label",{for:"loop-checkbox",class:"text-sm text-gray-700 dark:text-gray-300"}," Loop audio track ",-1))])]),e.createElementVNode("div",B2,[e.createElementVNode("button",{onClick:f,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:p,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,M2)])])])):e.createCommentVNode("",!0)]))}}),Dl=Fe(I2,[["__scopeId","data-v-593719ac"]]);function yt(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 Lc(o){return typeof o=="boolean"?o?"On":"Off":typeof o=="number"?Number.isInteger(o)?String(o):o.toFixed(2):String(o??"")}let Pc=!1;function $2(){if(Pc)return;Pc=!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 F2{constructor({filters:a=[],callbacks:t={}}){$2(),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=yt("div",{className:"mvfp"}),this._catRow=yt("div",{className:"mvfp-row"}),this._root.appendChild(this._catRow),this._filterRow=yt("div",{className:"mvfp-row"}),this._root.appendChild(this._filterRow),this._activeRow=yt("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=yt("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=yt("div",{className:`mvfp-filter${t?" active":""}${n?" selected":""}`,onClick:()=>this._selectFilter(a)});if(t){const r=yt("div",{className:"mvfp-check",onClick:s=>{s.stopPropagation(),this._removeFilter(a.id)}});r.innerHTML="✓",i.appendChild(r)}i.appendChild(yt("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(yt("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=yt("div",{className:`mvfp-achip${i?" selected":""}`}),s=yt("span",{style:{cursor:"pointer"},onClick:()=>{this._selectedFilterId=t,this._renderFilters(),n.params&&n.params.length>0&&this.openDrawer(t)}},n.name),l=yt("button",{className:"mvfp-achip-x","aria-label":`Remove ${n.name}`,onClick:d=>{d.stopPropagation(),this._removeFilter(t)}});l.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(s),r.appendChild(l),this._activeRow.appendChild(r)})}_buildDrawer(){this._drawer=yt("div",{className:"mvfp-drawer"});const a=yt("div",{className:"mvfp-drawer-hdr"});this._drawerTitle=yt("span",{className:"mvfp-drawer-title"},"Filter");const t=yt("div",{className:"mvfp-drawer-actions"});t.appendChild(yt("button",{className:"mvfp-drawer-btn",onClick:()=>this._resetDrawerFilter()},"Reset")),t.appendChild(yt("button",{className:"mvfp-drawer-btn danger",onClick:()=>{this._drawerFilterId&&(this._removeFilter(this._drawerFilterId),this.closeDrawer())}},"Remove"));const n=yt("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=yt("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(yt("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,s=yt("div",{className:"mvfp-ctl"}),l=yt("label",{className:"mvfp-ctl-label"},i.label||i.id);s.appendChild(l);const d=i.type||"slider";if(d==="slider"||d==="range"){const c=yt("div",{className:"mvfp-slider-row"}),u=yt("span",{className:"mvfp-range-val"},Lc(r)),m=yt("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:f=>{var h,v;const p=parseFloat(f.target.value);u.textContent=Lc(p),(v=(h=this._cb).onUpdateParam)==null||v.call(h,a.id,i.id,p)}});c.appendChild(m),c.appendChild(u),s.appendChild(c)}else if(d==="toggle"||d==="checkbox"){const c=yt("div",{className:"mvfp-toggle-row"}),u=yt("input",{type:"checkbox",checked:r?"checked":void 0,onChange:m=>{var f,p;return(p=(f=this._cb).onUpdateParam)==null?void 0:p.call(f,a.id,i.id,m.target.checked)}});c.appendChild(u),s.appendChild(c)}else if(d==="color"){const c=yt("div",{className:"mvfp-color-row"}),u=yt("input",{type:"color",className:"mvfp-color-input",value:typeof r=="string"?r:"#000000",onInput:m=>{var f,p;return(p=(f=this._cb).onUpdateParam)==null?void 0:p.call(f,a.id,i.id,m.target.value)}});c.appendChild(u),s.appendChild(c)}else if(d==="select"||d==="dropdown"){const c=yt("div",{className:"mvfp-select-row"}),u=yt("select",{className:"mvfp-select",onChange:m=>{var f,p;return(p=(f=this._cb).onUpdateParam)==null?void 0:p.call(f,a.id,i.id,m.target.value)}});for(const m of i.options||[]){const f=yt("option",{value:m.value},m.label||String(m.value));m.value===r&&(f.selected=!0),u.appendChild(f)}c.appendChild(u),s.appendChild(c)}this._drawerBody.appendChild(s)}}_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 D2=[200,500,1e3];function R2(o){return{"360p":[640,360],"480p":[854,480],"720p":[1280,720],"1080p":[1920,1080],"1440p":[2560,1440],"2160p":[3840,2160]}[o??""]??[1920,1080]}function Uc(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 A2(o){return new Promise(a=>{window.setTimeout(a,o)})}async function Oc(){return await Promise.resolve().then(()=>require("./PixiFrameExporter-vNJtMooF.cjs"))}function zc(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 Xm(o){let a=null;return{canExportClientSide:async()=>{try{const{isWebCodecsSupported:i}=await Oc();return i()}catch{return!1}},renderRecipeWithPixi:async(i,r,s)=>{var p,h,v,E;const l=i.timeline[0],d=l?Math.max(0,l.sourceIn):0,c=l?l.sourceOut:void 0,[u,m]=R2((r==null?void 0:r.quality)??((p=i.output)==null?void 0:p.quality)),f=((h=i.output)==null?void 0:h.fps)||30;o.setPlaying(!1),o.forcePixiPreview.value=!0,await e.nextTick();try{let y=!1;for(const F of D2){await A2(F);const P=o.getPreviewRef();if(!(!P||typeof P.captureFrameAt!="function")){if(typeof P.ensureReadyForCapture=="function"){if(y=await P.ensureReadyForCapture(),y)break;continue}y=!0;break}}const k=o.getPreviewRef();if(!k||typeof k.captureFrameAt!="function")throw new Error("PIXI preview not available for export. Ensure the preview is mounted.");if(!y)throw new Error("PIXI preview not ready for frame capture after retries. The video may still be loading.");const{exportWithPixiFrames:g,isWebCodecsSupported:b}=await Oc();if(!b())throw new Error("WebCodecs is not supported in this browser. Export requires Chrome 94+ or equivalent.");a=new AbortController;const R={width:u,height:m,fps:f,trimStart:d,signal:a.signal};c!==void 0&&(R.trimEnd=c),s&&(R.onProgress=s);const N=o.getSourceUrl();N!==""&&(R.sourceUrl=N);const T=Uc(k)??((v=i.source)==null?void 0:v.duration)??c??0,S=await g({captureFrameAt:F=>{var P;return((P=k.captureFrameAt)==null?void 0:P.call(k,F))??Promise.resolve(null)},duration:{value:T}},R),B=new File([S],`edited-video-${Date.now()}.mp4`,{type:"video/mp4"}),A=Uc(k),x=((E=i.source)==null?void 0:E.duration)??0,w=Math.max(0,(c??A??x)-d);return{file:B,recipe:i,meta:{duration:w,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 Ao="default-video-track",Vn="default-media-source";function Km(o){var r,s;const a=P2(o),t=U2(o),n=O2(o.timeline,((r=t[0])==null?void 0:r.id)??Ao,((s=a[0])==null?void 0:s.id)??Vn),i={version:o.version,source:{...o.source},mediaSources:a,tracks:z2(t,n),clips:n,markers:o.markers?o.markers.map(l=>({...l})):[],transitions:o.transitions?o.transitions.map(Ym):[],filters:o.filters.map(l=>({...l,params:{...l.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(Qm)),o.visualLayers&&(i.visualLayers=o.visualLayers.map(ep)),o.audioTracks&&(i.audioTracks=[...o.audioTracks]),o.posterFrame&&(i.posterFrame=o.posterFrame),o.metadata&&(i.metadata={...o.metadata}),i}function L2(o){const a={version:"1.0",source:{...o.source},timeline:o.clips.map(t=>({...t})),mediaSources:o.mediaSources.map(Jm),tracks:o.tracks.map(qm),markers:o.markers.map(t=>({...t})),transitions:o.transitions.map(Ym),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(Qm)),o.visualLayers&&(a.visualLayers=o.visualLayers.map(ep)),o.audioTracks&&(a.audioTracks=[...o.audioTracks]),o.posterFrame&&(a.posterFrame=o.posterFrame),o.metadata&&(a.metadata={...o.metadata}),a}function P2(o){var t,n;if(o.mediaSources&&o.mediaSources.length>0)return o.mediaSources.map(Jm);const a={id:((t=o.timeline.find(i=>i.sourceRefId))==null?void 0:t.sourceRefId)??Vn,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 U2(o){var a;return o.tracks&&o.tracks.length>0?o.tracks.map(qm):[{id:((a=o.timeline.find(t=>t.trackId))==null?void 0:a.trackId)??Ao,type:"video",name:"Video",order:0}]}function O2(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 z2(o,a){return o.map(t=>{const n=a.filter(i=>i.trackId===t.id).map(i=>i.id);return{...t,clipIds:n}})}function Jm(o){const a={...o};return o.metadata&&(a.metadata={...o.metadata}),a}function qm(o){const a={...o};return o.clipIds&&(a.clipIds=[...o.clipIds]),a}function Ym(o){const a={...o};return o.params&&(a.params={...o.params}),a}function Qm(o){return{...o,segments:o.segments.map(t=>{const n={...t};return t.words&&(n.words=t.words.map(i=>({...i}))),n})}}function ep(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 tp="video-project-draft-snapshot:v1",Rl="mediables:video-project-drafts",j2=(o,a={})=>{var f,p;const t=pn(a.now)??Date.now(),n=pn(a.createdAt)??t,i=pn(a.updatedAt)??t,r=tE(o),s={id:Ia(a.id)??iE(i),payloadKind:r,createdAt:new Date(n).toISOString(),updatedAt:new Date(i).toISOString(),deviceKind:a.deviceKind??"unknown"},l=Ia(a.projectId),d=Ia(a.sourceMediaUuid)??Ia(o.source.media_uuid),c=Al(a.durationSeconds)??aE(o),u=Ia(a.editorVersion)??Ia((f=o.metadata)==null?void 0:f.editor_version),m=Ia(a.title)??Ia((p=o.metadata)==null?void 0:p.title);return l!==null&&(s.projectId=l),d!==null&&(s.sourceMediaUuid=d),c!==null&&(s.durationSeconds=c),u!==null&&(s.editorVersion=u),m!==null&&(s.title=m),a.saveReason!==void 0&&(s.saveReason=a.saveReason),{schemaVersion:tp,metadata:s,payload:o}},ap=(o,a=Rl)=>{const t=Ia(a)??Rl,n=Gc(o.metadata.projectId??"unsaved-project"),i=Gc(o.metadata.id);return`${t}:${n}:${i}`},W2=o=>JSON.stringify(o),H2=o=>{if(typeof o!="string"||o.trim().length===0)return null;try{const a=JSON.parse(o);return Y2(a)?a:null}catch{return null}},Z2=o=>{const a=[];for(const t of o){const n=Ia(t.key),i=H2(t.value);n===null||i===null||a.push({key:n,snapshot:i})}return Ei(a)},G2=(o,a)=>{const t=oE(a.maxCount),n=pn(a.now)??Date.now(),i=sp(a.maxAgeMs),r=[],s=[];let l=0;for(const d of Ei(o)){if(!ip(d,a.projectId)){r.push(d);continue}if(rp(d.snapshot,n,i)||l>=t){s.push(d);continue}r.push(d),l+=1}return{retained:Ei(r),removed:Ei(s)}},X2=(o,a={})=>{const t={key:ap(o),snapshot:o};if(!ip(t,a.projectId))return!1;const n=pn(a.now)??Date.now(),i=sp(a.maxAgeMs);if(rp(o,n,i))return!1;const r=a.savedAt===null?null:pn(a.savedAt);return r===null?!0:zr(o)>r},K2=(o,a={})=>Ei(o).filter(t=>X2(t.snapshot,a)),J2=(o,a,t={})=>{const n=K2(o,t);if(a==="mobile"){const i=n[0]??null;return i===null?[]:[i]}return n},q2=async(o,a,t=ap(a))=>(await o.setItem(t,W2(a)),{key:t,snapshot:a}),jc=async(o,a=Rl)=>{const t=await o.listKeys(a),n=[];for(const i of t)n.push({key:i,value:await o.getItem(i)});return Z2(n)},Wc=async(o,a)=>{for(const t of a)await o.removeItem(t.key)},Y2=o=>!fn(o)||o.schemaVersion!==tp||!Q2(o.metadata)?!1:o.metadata.payloadKind==="project"?np(o.payload):eE(o.payload),Q2=o=>fn(o)?wd(o.id)&&sE(o.payloadKind)&&Zc(o.createdAt)&&Zc(o.updatedAt)&&lE(o.deviceKind)&&ur(o.projectId)&&ur(o.sourceMediaUuid)&&rE(o.durationSeconds)&&ur(o.editorVersion)&&ur(o.title)&&dE(o.saveReason):!1,eE=o=>fn(o)?o.version==="1.0"&&op(o.source)&&Array.isArray(o.timeline)&&Array.isArray(o.filters)&&fn(o.audio)&&fn(o.output):!1,np=o=>fn(o)?o.version==="1.0"&&op(o.source)&&Array.isArray(o.mediaSources)&&Array.isArray(o.tracks)&&Array.isArray(o.clips)&&Array.isArray(o.markers)&&Array.isArray(o.filters)&&fn(o.audio)&&fn(o.output):!1,op=o=>fn(o)?wd(o.media_uuid)&&Si(o.duration)&&Si(o.original_width)&&Si(o.original_height):!1,tE=o=>np(o)?"project":"recipe",aE=o=>Al(o.duration)??Al(o.source.duration),ip=(o,a)=>{const t=Ia(a);return t===null?!0:o.snapshot.metadata.projectId===t},rp=(o,a,t)=>t===null?!1:a-zr(o)>t,Ei=o=>[...o].sort(nE),nE=(o,a)=>{const t=zr(a.snapshot)-zr(o.snapshot);if(t!==0)return t;const n=Hc(a.snapshot)-Hc(o.snapshot);return n!==0?n:o.snapshot.metadata.id.localeCompare(a.snapshot.metadata.id)},zr=o=>pn(o.metadata.updatedAt)??0,Hc=o=>pn(o.metadata.createdAt)??0,oE=o=>!Number.isFinite(o)||o<0?0:Math.floor(o),sp=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},Zc=o=>typeof o=="string"&&pn(o)!==null,iE=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}`},Gc=o=>encodeURIComponent(o.trim()),Ia=o=>{if(typeof o!="string")return null;const a=o.trim();return a.length>0?a:null},wd=o=>Ia(o)!==null,ur=o=>o===void 0||wd(o),Al=o=>{if(!Si(o))return null;const a=Number(o.toFixed(6));return Object.is(a,-0)?0:a},Si=o=>typeof o=="number"&&Number.isFinite(o)&&o>=0,rE=o=>o===void 0||Si(o),sE=o=>o==="recipe"||o==="project",lE=o=>o==="desktop"||o==="mobile"||o==="tablet"||o==="unknown",dE=o=>o===void 0||o==="autosave"||o==="manual"||o==="before-export"||o==="before-close",fn=o=>typeof o=="object"&&o!==null&&!Array.isArray(o),cE=1,uE="master",Mi=-60,Ll=12,kd=0,Nn=-90,jr=6,mE=4,lp=8;function dp(){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:lp}}}function pE(o,a=dp()){return Ul(a[o])}function cp(o){return Number.isNaN(o)?kd:o<=0||o===Number.NEGATIVE_INFINITY?Mi:Ii(20*Math.log10(o))}function Pl(o){const a=Ii(o);return a<=Mi?0:Bn(Math.pow(10,a/20),6)}function Ii(o){return Number.isNaN(o)?kd:o===Number.NEGATIVE_INFINITY?Mi:o===Number.POSITIVE_INFINITY?Ll:Bn(ji(o,Mi,Ll),3)}function up(o){return Number.isFinite(o)?Bn(ji(o,-1,1),3):0}function fE(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,s=a||i||r,l=s?0:n.controls.fader.linearGain;return{trackId:n.id,soloed:n.controls.solo,mutedByTrack:i,mutedBySolo:r,mutedByMaster:a,effectivelyMuted:s,audible:!s,effectiveGainLinear:l}})}function hE(o,a={}){const t=xE(a.effectSlotCount),n=new Set;return{schemaVersion:cE,capabilities:a.capabilities?BE(a.capabilities):dp(),tracks:o.map((i,r)=>gE(i,r,t,n)),master:bE(a.master,t)}}function mp(o){const a=Ii(o);return{valueDb:a,minDb:Mi,maxDb:Ll,unityDb:kd,linearGain:Pl(a)}}function vE(o,a="constant-power"){return{value:up(o),mode:a}}function pp(o=Nn,a=Nn,t=o){const n=Ks(o),i=Ks(a),r=Ks(t);return{peakDb:n,rmsDb:i,peakHoldDb:r,clipping:n>=0||r>=0}}function fp(o){const a=gp(o);return{id:`empty-effect-slot-${a}`,index:a,kind:"empty",label:"Empty",enabled:!1,bypassed:!0,wetMix:0,parameters:{}}}function gE(o,a,t,n){const i=vp(o.id),s={id:CE(i??`legacy-audio-track-${a+1}`,n),kind:"legacy-url",name:_E(o.name,a),order:a,source:yE(o.source),controls:{fader:mp(o.faderDb??cp(o.volume??1)),pan:vE(o.pan??0),muted:o.muted??!1,solo:o.solo??!1,meter:pp(o.peakDb,o.rmsDb,o.peakHoldDb)},timeline:wE(o),effectSlots:hp(o.effectSlots,t)};return i!==void 0&&(s.legacyTrackId=i),s}function bE(o,a){return{id:uE,name:EE(o==null?void 0:o.name),fader:mp((o==null?void 0:o.faderDb)??cp((o==null?void 0:o.volume)??1)),muted:(o==null?void 0:o.muted)??!1,meter:pp(o==null?void 0:o.peakDb,o==null?void 0:o.rmsDb,o==null?void 0:o.peakHoldDb),effectSlots:hp(o==null?void 0:o.effectSlots,a)}}function yE(o){const a=o.trim();return a===""?{type:"missing"}:{type:"url",url:a}}function wE(o){const a={startTime:NE(o.startTime??0),loop:o.loop??!1},t=VE(o.duration);t!==void 0&&(a.duration=t);const n=Xc(o.fadeIn);n!==void 0&&(a.fadeIn=n);const i=Xc(o.fadeOut);return i!==void 0&&(a.fadeOut=i),a}function hp(o,a){const t=new Map;for(const n of o??[]){const i=kE(n,a);t.set(i.index,i)}return Array.from({length:a},(n,i)=>t.get(i)??fp(i))}function kE(o,a){const t=gp(o.index),n=a>0?Math.min(t,a-1):0,i=o.kind;return i==="empty"?fp(n):{id:vp(o.id)??`${i}-effect-slot-${n}`,index:n,kind:i,label:SE(o.label,i),enabled:o.enabled,bypassed:o.bypassed,wetMix:TE(o.wetMix),parameters:{...o.parameters}}}function _E(o,a){const t=o==null?void 0:o.trim();return t&&t!==""?t:`Audio ${a+1}`}function EE(o){const a=o==null?void 0:o.trim();return a&&a!==""?a:"Master"}function SE(o,a){const t=o.trim();return t!==""?t:a}function CE(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 vp(o){const a=o==null?void 0:o.trim();if(!(!a||a===""))return a}function xE(o){return o===void 0||!Number.isFinite(o)?mE:Math.trunc(ji(o,0,lp))}function gp(o){return!Number.isFinite(o)||o<0?0:Math.trunc(o)}function VE(o){if(!(o===void 0||!Number.isFinite(o)||o<=0))return Bn(o,3)}function Xc(o){if(!(o===void 0||!Number.isFinite(o)||o<0))return Bn(o,3)}function NE(o){return!Number.isFinite(o)||o<0?0:Bn(o,3)}function TE(o){return Number.isFinite(o)?Bn(ji(o,0,1),3):1}function Ks(o){return Number.isNaN(o)||o===Number.NEGATIVE_INFINITY?Nn:o===Number.POSITIVE_INFINITY?jr:Bn(ji(o,Nn,jr),3)}function BE(o){return{mobile:Ul(o.mobile),desktop:Ul(o.desktop)}}function Ul(o){return{...o}}function ji(o,a,t){return Math.min(t,Math.max(a,o))}function Bn(o,a){const t=10**a;return Math.round(o*t)/t}const ME=/^(\d{2,}:[0-5]\d:[0-5]\d,\d{3})\s+-->\s+(\d{2,}:[0-5]\d:[0-5]\d,\d{3})$/,IE=/^(\d{2,}):([0-5]\d):([0-5]\d),(\d{3})$/,$E="srt-cue";class Tn extends Error{constructor(a,t,n={}){super(t),this.name="CaptionSrtError",this.code=a,this.context=n}}function FE(o,a={}){var s,l;const t=DE(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&&Qc(n[r]);)r+=1;if(r>=n.length)break;const d=r+1,c=RE(((s=n[r])==null?void 0:s.trim())??"",d);if(r+=1,r>=n.length)throw new Tn("missing-timing",`Cue ${c} is missing its timing line.`,{cueIndex:i.length,cueNumber:c,lineNumber:d});const u=r+1,m=AE(((l=n[r])==null?void 0:l.trim())??"",c,u);r+=1;const f=[];for(;r<n.length&&!Qc(n[r]);)f.push(n[r]??""),r+=1;i.push({cueNumber:c,id:`${t}-${i.length+1}`,startTime:m.startTime,endTime:m.endTime,text:f.join(`
|
|
339
|
+
`)})}return bp(i),i}function Kc(o){return bp(o),o.length===0?"":`${o.map((a,t)=>PE(a,t+1)).join(`
|
|
340
|
+
|
|
341
|
+
`)}
|
|
342
|
+
`}function bp(o){const a=o.map((t,n)=>{const i=Yc(t,n),r=Ol(t.startTime,"startTime",i),s=Ol(t.endTime,"endTime",i);if(s<=r)throw new Tn("invalid-duration",`Caption cue "${t.id}" must end after it starts.`,i);return{cue:t,cueIndex:n,startMilliseconds:r,endMilliseconds:s}}).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 Tn("overlapping-cues",`Caption cue "${i.cue.id}" overlaps cue "${n.cue.id}".`,Yc(i.cue,i.cueIndex))}}function Jc(o){const a=Ol(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 DE(o){return o===void 0||o.trim()===""?$E:o.trim()}function RE(o,a){if(!/^[1-9]\d*$/.test(o))throw new Tn("invalid-cue-number",`Invalid SRT cue number at line ${a}.`,{lineNumber:a});return Number.parseInt(o,10)}function AE(o,a,t){const n=ME.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 Tn("invalid-timing",`Invalid SRT timing line for cue ${a} at line ${t}.`,{cueNumber:a,lineNumber:t});return{startTime:qc(i,a,t),endTime:qc(r,a,t)}}function qc(o,a,t){const n=IE.exec(o),i=n==null?void 0:n[1],r=n==null?void 0:n[2],s=n==null?void 0:n[3],l=n==null?void 0:n[4];if(i===void 0||r===void 0||s===void 0||l===void 0)throw new Tn("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(s,10),m=Number.parseInt(l,10);return d*60*60+c*60+u+m/1e3}function Ol(o,a,t){if(!Number.isFinite(o)||o<0)throw new Tn("invalid-time",`Caption cue ${a} must be a finite, non-negative number.`,t);return Math.round(o*1e3)}function Yc(o,a){const t={cueIndex:a,segmentId:o.id},n=LE(o);return n!==void 0&&(t.cueNumber=n),t}function LE(o){if(!(!("cueNumber"in o)||typeof o.cueNumber!="number"))return o.cueNumber}function PE(o,a){return[a.toString(),`${Jc(o.startTime)} --> ${Jc(o.endTime)}`,UE(o.text)].join(`
|
|
343
|
+
`)}function UE(o){return o.replace(/\r\n?/g,`
|
|
344
|
+
`)}function Qc(o){return o===void 0||o.trim()===""}const OE=["linear","ease-in","ease-out","ease-in-out"];class Wr extends Error{constructor(a,t="Invalid keyframe automation."){super(t),this.name="KeyframeAutomationError",this.issues=a}}const zE={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"&&OE.includes(o)}function WE(o){return o==="mobile"?{platform:o,editingMode:"preset-only",canApplyPresets:!0,canEditKeyframes:!1}:{platform:o,editingMode:"detailed",canApplyPresets:!0,canEditKeyframes:!0}}function HE(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 yp(o,a={}){const t=[],n=new Set,i={...zE,...a.ranges};return o.forEach((r,s)=>{if(r.id.trim()===""&&t.push({code:"empty-id",message:"Keyframe id cannot be empty.",index:s,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:s,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:s,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:s,keyframeId:r.id,target:r.target,time:r.time});else{const l=`${r.target}:${r.time}`;n.has(l)&&t.push({code:"duplicate-time",message:`Keyframe target ${r.target} already has a point at ${r.time}.`,index:s,keyframeId:r.id,target:r.target,time:r.time}),n.add(l)}if(!Number.isFinite(r.value))t.push({code:"invalid-value",message:"Keyframe value must be a finite number.",index:s,keyframeId:r.id,target:r.target,time:r.time});else{const l=i[r.target];l.min!==void 0&&r.value<l.min&&t.push({code:"invalid-value",message:`Keyframe value for ${r.target} must be greater than or equal to ${l.min}.`,index:s,keyframeId:r.id,target:r.target,time:r.time}),l.max!==void 0&&r.value>l.max&&t.push({code:"invalid-value",message:`Keyframe value for ${r.target} must be less than or equal to ${l.max}.`,index:s,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:s,keyframeId:r.id,target:r.target,time:r.time})}),{valid:t.length===0,issues:t}}function ZE(o,a={}){const t=HE(o),n=yp(t,a);if(!n.valid)throw new Wr(n.issues);return t}function GE(o={}){return _d({id:"fade-in",label:"Fade in",target:"opacity",startValue:o.fromOpacity??0,endValue:o.toOpacity??1,timing:Ed(o,"ease-out")})}function XE(o={}){return _d({id:"fade-out",label:"Fade out",target:"opacity",startValue:o.fromOpacity??1,endValue:o.toOpacity??0,timing:Ed(o,"ease-in")})}function KE(o={}){return _d({id:"zoom-in",label:"Zoom in",target:"scale",startValue:o.fromScale??1,endValue:o.toScale??1.1,timing:Ed(o,"ease-out")})}function _d(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=yp(a,{target:o.target});if(!t.valid)throw new Wr(t.issues);return{id:o.id,label:o.label,target:o.target,editingMode:"preset-only",keyframes:a}}function Ed(o,a){const t=o.startTime??0,n=o.duration??1;if(!Number.isFinite(t)||t<0)throw new Wr([{code:"invalid-time",message:"Preset start time must be a finite non-negative number.",time:t}]);if(!Number.isFinite(n)||n<=0)throw new Wr([{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 eo extends Error{constructor(a,t){super(t),this.name="VisualLayerSchemaError",this.code=a}}function JE(o){Cd(o.id,"caption track id");const a={id:o.id,source:o.source,stylePreset:o.stylePreset??"default",animation:o.animation??"none",segments:qE(o.segments)};return o.language!==void 0&&(a.language=o.language),a}function qE(o){const a=o.map(t=>{Cd(t.id,"caption segment id");const n=Sd(t.startTime,"caption segment startTime"),i=wp(t.endTime,"caption segment endTime");if(i<=n)throw new eo("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=YE(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 eo("invalid-caption-segment",`Caption segment "${i.id}" overlaps segment "${n.id}".`)}return a}function YE(o,a){return a.map(t=>{Cd(t.id,"caption word id");const n=Sd(t.startTime,"caption word startTime"),i=wp(t.endTime,"caption word endTime");if(i<=n)throw new eo("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 Sd(o,a){const t=QE(o,a);if(t<0)throw new eo("invalid-time",`${a} must be non-negative.`);return Math.round(t*1e3)/1e3}function wp(o,a){const t=Sd(o,a);if(t<=0)throw new eo("invalid-duration",`${a} must be greater than zero.`);return t}function QE(o,a){if(!eS(o))throw new eo("invalid-time",`${a} must be a finite number.`);return o}function Cd(o,a){if(o.trim()==="")throw new eo("empty-id",`${a} cannot be empty.`)}function eS(o){return Number.isFinite(o)}function eu(o){var m,f,p,h;tS(o);const a=oS(o),t=iS(o),n=((m=a[0])==null?void 0:m.id)??Vn,i=((f=t[0])==null?void 0:f.id)??Ao,r=aS(o.clips,i,n),s=rS(t,r),l=[],d=cS(o),c=uS(o),u={version:"1.0",source:{media_uuid:o.mediaUuid,duration:o.originalDuration,original_width:((p=o.media)==null?void 0:p.width)||1920,original_height:((h=o.media)==null?void 0:h.height)||1080},timeline:r,mediaSources:a,tracks:s,filters:l,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(E=>{const y={...E};return E.words&&(y.words=E.words.map(k=>({...k}))),y})}))),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(dS)),u}function tS(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=nS(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 aS(o,a,t){return o.map(n=>{const i=n.speed||1,r=typeof n.sourceIn=="number"&&!Number.isNaN(n.sourceIn),s=typeof n.sourceOut=="number"&&!Number.isNaN(n.sourceOut),l=Math.max(0,n.timelineEnd-n.timelineStart),d=n,c=d.sourceOffset??d.trimStart??0;let u=Number(r?n.sourceIn:c),m=s?Number(n.sourceOut):Number(c)+l/i;m>u||(m=u+Math.max(.033,l/Math.max(1e-6,i)));const f={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&&(f.keyframes=n.keyframes.map(p=>({...p}))),f})}function nS(o){return o.trackId??`legacy-track-${o.track??0}`}function oS(o){var t,n,i,r,s,l,d,c;if(o.mediaSources&&o.mediaSources.length>0)return o.mediaSources.map(sS);const a={id:((t=o.clips.find(u=>u.sourceRefId))==null?void 0:t.sourceRefId)??Vn,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),(s=o.media)!=null&&s.mime_type&&(a.mimeType=o.media.mime_type),typeof((l=o.media)==null?void 0:l.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 iS(o){var a;return o.tracks&&o.tracks.length>0?o.tracks.map(lS):[{id:((a=o.clips.find(t=>t.trackId))==null?void 0:a.trackId)??Ao,type:"video",name:"Video",order:0}]}function rS(o,a){return o.map(t=>({...t,clipIds:a.filter(n=>n.trackId===t.id).map(n=>n.id)}))}function sS(o){const a={...o};return o.metadata&&(a.metadata={...o.metadata}),a}function lS(o){const a={...o};return o.clipIds&&(a.clipIds=[...o.clipIds]),a}function dS(o){const a={...o};return o.params&&(a.params={...o.params}),a}function cS(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 uS(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 Ga(o){return arguments.length===0?{ok:!0,value:void 0}:{ok:!0,value:o}}function jt(o,a){return{ok:!1,reason:o,message:a}}const mS={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 da(o){return mS[o]}const Ci=1e-6;function Js(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(pS(a,o.desiredDuration,t))return{ok:!0,start:a};let n=a;for(const i of t)if(!(i.timelineEnd<=n+Ci)){if(i.timelineStart-n>=o.desiredDuration-Ci&&n+Ci>=a)return{ok:!0,start:n};n=Math.max(n,i.timelineEnd)}return{ok:!0,start:n}}function pS(o,a,t){const n=o+a;for(const i of t)if(!(i.timelineEnd<=o+Ci)&&!(i.timelineStart>=n-Ci))return!1;return!0}const fS={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 tu(o,a){return fS[a].has(o)}function hS(o){const a=new Set;for(const t of o.clips)typeof t.sourceRefId=="string"&&t.sourceRefId!==""&&a.add(t.sourceRefId);return a}function vS(o,a){return hS(o).has(a)}function mr(o,a=30){const t=typeof o=="number"?o:Number(o);return Number.isFinite(t)&&t>0?t:a}function kp(o,a,t){var wt,Ot,_a;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),s=e.ref([]),l=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=mr(((wt=a==null?void 0:a.output)==null?void 0:wt.fps)??(t==null?void 0:t.frame_rate)),f=e.shallowRef(null),p=new zm(m),h=e.ref(m),v=e.ref(!1),E=e.ref(!1);a&&a.timeline&&a.timeline.length>0?(M(a),(Ot=a.output)!=null&&Ot.fps&&(h.value=mr(a.output.fps,h.value),p.setFps(h.value))):(R(),a&&((_a=a.output)!=null&&_a.fps&&(h.value=mr(a.output.fps,h.value),p.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 y=e.ref(1),k=e.computed(()=>i.selectedClipId?i.clips.find(G=>G.id===i.selectedClipId)??null:null);e.watch(k,G=>{y.value=(G==null?void 0:G.speed)??1},{immediate:!0});const g=e.computed(()=>s.value.length>0),b=e.computed(()=>l.value.length>0);function R(){const G=typeof(t==null?void 0:t.duration)=="number"&&t.duration>0?t.duration:1;t&&(i.media=t),i.originalDuration=G,i.totalDuration=G;const J=ea();i.mediaSources=[N(G)],i.tracks=[T([J])];const me={id:J,type:"clip",trackId:Ao,sourceRefId:Vn,timelineStart:0,timelineEnd:G,sourceIn:0,sourceOut:G,sourceMinIn:0,sourceMaxOut:G,speed:1};i.clips=[me],i.selectedClipId=J,d.value=J,!(t||n.startsWith("temp-"))&&(async()=>{try{const pe=await fetch(`/api/v1/video/${encodeURIComponent(n)}`);if(!pe.ok)throw new Error(`Failed to fetch media: ${pe.status}`);const Ne=await pe.json(),We=typeof Ne=="object"&&Ne!==null&&"data"in Ne?Ne.data:Ne;if(!We||typeof We!="object")throw new Error("Failed to parse media payload");const st=We;i.media=st,a||(h.value=mr(st.frame_rate,h.value),p.setFps(h.value));const Ye=typeof st.duration=="number"&&st.duration>0?st.duration:G;if(i.hasChanges||i.clips.length!==1||i.clips[0].id!==J)return;i.originalDuration=Ye,i.totalDuration=Ye,i.mediaSources=[N(Ye,st)],i.tracks=[T([J])];const He=i.clips[0];He.timelineStart=0,He.timelineEnd=Ye,He.sourceIn=0,He.sourceOut=Ye,He.sourceMinIn=0,He.sourceMaxOut=Ye,Ce(),c=!0}catch{}})()}function N(G,J=t){const me={id:Vn,type:"media",mediaUuid:n,duration:G,width:(J==null?void 0:J.width)??1920,height:(J==null?void 0:J.height)??1080};return J!=null&&J.filename&&(me.filename=J.filename),J!=null&&J.mime_type&&(me.mimeType=J.mime_type),typeof(J==null?void 0:J.frame_rate)=="number"&&(me.frameRate=J.frame_rate),typeof(J==null?void 0:J.has_audio)=="boolean"&&(me.hasAudio=J.has_audio),J!=null&&J.thumbnail_url&&(me.thumbnailUrl=J.thumbnail_url),me}function T(G){return{id:Ao,type:"video",name:"Video",order:0,clipIds:G}}function S(G){return`track-${G}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function B(G,J){const me=G.charAt(0).toUpperCase()+G.slice(1),pe=J.filter(Ne=>Ne.type===G).length;return pe===0?me:`${me} ${pe+1}`}function A(G,J){if(G.originalDuration!==1)return;G.originalDuration=J,G.totalDuration===1&&(G.totalDuration=J);const me=G.clips[0],pe=!a&&G.clips.length===1&&me!==void 0&&me.timelineStart===0&&me.timelineEnd===1&&me.sourceIn===0&&me.sourceOut===1;for(const Ne of G.clips)(Ne.sourceMaxOut===1||Ne.sourceMaxOut===void 0)&&(Ne.sourceMaxOut=J);if(G.mediaSources)for(const Ne of G.mediaSources)Ne.id===Vn&&(Ne.duration===1||Ne.duration===void 0)&&(Ne.duration=J);pe&&me!==void 0&&(me.sourceOut=J,me.timelineEnd=J)}function x(G){if(!Number.isFinite(G)||G<=0||c)return;const J=i.hasChanges;i.originalDuration=G,i.totalDuration=Math.max(i.totalDuration,G),i.media&&(i.media.duration=G);for(const Ne of i.clips)Ne.sourceMaxOut=G;if(i.mediaSources)for(const Ne of i.mediaSources)(Ne.id===Vn||Ne.mediaUuid===n)&&(Ne.duration=G);const me=i.clips[0];!a&&i.clips.length===1&&me!==void 0&&me.timelineStart===0&&me.timelineEnd===1&&me.sourceIn===0&&me.sourceOut===1&&me!==void 0&&(me.sourceOut=G,me.timelineEnd=me.timelineStart+(me.sourceOut-me.sourceIn)),Ce();for(const Ne of s.value)A(Ne,G);for(const Ne of l.value)A(Ne,G);c=!0,e.nextTick(()=>{J||(i.hasChanges=!1)})}function M(G){const J=Km(G);i.mediaSources=J.mediaSources,i.tracks=J.tracks,i.transitions=J.transitions,i.clips=J.clips.map(me=>({...me,sourceMinIn:me.sourceMinIn??0,sourceMaxOut:me.sourceMaxOut??G.source.duration})),i.filters=[],i.audioVolume=G.audio.volume,i.audioFadeIn=G.audio.fadeIn||0,i.audioFadeOut=G.audio.fadeOut||0,i.exportFormat=G.output.format,i.exportQuality=G.output.quality,i.originalDuration=G.source.duration,i.textOverlays=G.textOverlays?[...G.textOverlays]:[],i.audioTracks=G.audioTracks?[...G.audioTracks]:[],i.captionTracks=G.captionTracks?G.captionTracks.map(te):[],i.visualLayers=G.visualLayers?G.visualLayers.map(me=>({...me})):[],i.clips.length>0?(i.selectedClipId=i.clips[0].id,d.value=i.selectedClipId):(delete i.selectedClipId,d.value=void 0),Ce()}function w(){s.value.push(JSON.parse(JSON.stringify(i))),l.value=[],i.hasChanges=!0}function F(){if(!g.value)return;const G=s.value.pop();l.value.push(JSON.parse(JSON.stringify(i))),Object.assign(i,G)}function P(){if(!b.value)return;const G=l.value.pop();s.value.push(JSON.parse(JSON.stringify(i))),Object.assign(i,G)}function D(G,J,me){w();const pe=i.clips.find(Ye=>Ye.id===G);if(!pe)return;const Ne=1/h.value,We=pe.sourceMinIn??0,st=pe.sourceMaxOut??i.originalDuration;if(J==="start"){const Ye=pe.sourceIn,He=Math.max(We,Math.min(me,pe.sourceOut-Ne));pe.sourceIn=He;const ut=He-Ye;pe.timelineStart+=ut}else{const Ye=Math.max(pe.sourceIn+Ne,Math.min(me,st));pe.sourceOut=Ye;const He=pe.sourceOut-pe.sourceIn;pe.timelineEnd=pe.timelineStart+He}Ce(),f.value&&f.value.trimClip(G,pe.sourceIn,pe.sourceOut)}function O(G){w();const J=i.clips.find(st=>G>st.timelineStart&&G<st.timelineEnd);if(!J)return;const me=G-J.timelineStart,pe=J.sourceIn+me,Ne={id:ea(),type:"clip",timelineStart:G,timelineEnd:J.timelineEnd,sourceIn:pe,sourceOut:J.sourceOut,speed:J.speed??1,sourceMinIn:J.sourceMinIn??0,sourceMaxOut:J.sourceMaxOut??i.originalDuration,filters:[...J.filters||[]]};J.trackId&&(Ne.trackId=J.trackId),J.sourceRefId&&(Ne.sourceRefId=J.sourceRefId),J.timelineEnd=G,J.sourceOut=pe;const We=i.clips.indexOf(J);i.clips.splice(We+1,0,Ne),ce(),i.selectedClipId=Ne.id}function I(){O(i.playheadPosition)}function Z(G){var me;const J=G??i.selectedClipId??d.value??((me=i.clips[0])==null?void 0:me.id);J&&(i.selectedClipId=J,d.value=J)}function z(){return i.selectedClipId?K(i.selectedClipId):jt("no_selection",da("no_selection"))}function K(G){const J=i.clips.findIndex(me=>me.id===G);return J===-1?jt("source_not_found","Clip not found."):(w(),i.clips.splice(J,1),ce(),se(J),Ce(),Ga())}function se(G){if(!i.clips.length){delete i.selectedClipId,d.value=void 0;return}const J=Math.max(0,Math.min(G,i.clips.length-1)),me=i.clips[J];me&&(i.selectedClipId=me.id,d.value=me.id)}function Be(G){return G.trackId??`legacy-track-${G.track??0}`}function ce(){const G=i.tracks;if(G)for(const J of G)J.clipIds=i.clips.filter(me=>Be(me)===J.id).map(me=>me.id)}function ie(G="video"){w();const J=i.tracks??[],me=J.reduce((Ne,We)=>Math.max(Ne,We.order),-1),pe={id:S(G),type:G,name:B(G,J),order:me+1,clipIds:[]};return i.tracks=[...J,pe],i.hasChanges=!0,pe}function W(G){if(G.length===0)return;const J=new Set(G),me=i.clips.findIndex(pe=>J.has(pe.id));i.clips=i.clips.filter(pe=>!J.has(pe.id)),i.transitions&&i.transitions.length>0&&(i.transitions=i.transitions.filter(pe=>!J.has(pe.fromClipId)&&!J.has(pe.toClipId))),ce(),i.selectedClipId!==void 0&&J.has(i.selectedClipId)&&se(me>=0?me:0),Ce()}function C(G){const J=i.tracks??[],me=J.find(Ne=>Ne.id===G);if(!me)return jt("track_missing",da("track_missing"));if(J.length<=1)return jt("invariant_violation","Can't delete the last remaining track. Add another track first.");w();const pe=i.clips.filter(Ne=>Be(Ne)===me.id).map(Ne=>Ne.id);return W(pe),i.tracks=J.filter(Ne=>Ne.id!==me.id),i.hasChanges=!0,Ga()}function U(G,J){const pe=(i.tracks??[]).find(We=>We.id===G);if(!pe)return jt("track_missing",da("track_missing"));const Ne=J.trim();return Ne===""?jt("invariant_violation","Track name cannot be empty."):(pe.name===Ne||(w(),pe.name=Ne,i.hasChanges=!0),Ga())}function j(G,J){const me=i.tracks??[],pe=me.find(ut=>ut.id===G);if(!pe)return jt("track_missing",da("track_missing"));const Ne=[...me].sort((ut,ht)=>ut.order-ht.order),We=Ne.findIndex(ut=>ut.id===pe.id),st=J==="up"?We+1:We-1,Ye=Ne[st];if(!Ye)return jt("invariant_violation","Track is already at the edge.");w();const He=pe.order;return pe.order=Ye.order,Ye.order=He,i.hasChanges=!0,Ga()}function ne(G){let J=i.tracks??[];if(J.length===0){const pe=T([]);i.tracks=[pe],J=i.tracks}if(G){const pe=J.find(Ne=>Ne.id===G);return pe?pe.locked===!0?{ok:!1,reason:"track_locked"}:{ok:!0,track:pe}:{ok:!1,reason:"track_missing"}}const me=J.find(pe=>pe.type==="video"&&pe.locked!==!0)??J.find(pe=>pe.locked!==!0);return me?{ok:!0,track:me}:{ok:!1,reason:"no_editable_track"}}function de(G){const J=1/h.value;return typeof G.duration=="number"&&Number.isFinite(G.duration)&&G.duration>J?G.duration:i.originalDuration>J?i.originalDuration:Math.max(J,i.totalDuration)}function Ke(G){const J=i.clips.filter(me=>Be(me)===G);return J.length>0?J.reduce((me,pe)=>Math.max(me,pe.timelineEnd),0):Math.max(0,Math.min(i.playheadPosition,i.totalDuration))}function be(G){const J=i.mediaSources??[],me=J.find(pe=>pe.id===G.id);return me||(i.mediaSources=[...J,G],i.hasChanges=!0,G)}function _e(G,J){return xe(G,"clip",J)}function ve(G,J){if(!(i.mediaSources??[]).find(Ne=>Ne.id===G))return jt("source_not_found",da("source_not_found"));let pe=J;if(!pe){const Ne=(i.tracks??[]).find(We=>We.type==="audio"&&We.locked!==!0);pe=(Ne==null?void 0:Ne.id)??ie("audio").id}return xe(G,"audio",pe)}function xe(G,J,me){const pe=(i.mediaSources??[]).find(Yt=>Yt.id===G);if(!pe)return jt("source_not_found",da("source_not_found"));const Ne=ne(me);if(!Ne.ok){const Yt=Ne.reason==="no_editable_track"?"track_missing":Ne.reason;return jt(Yt,da(Yt))}const We=Ne.track;if(!tu(J,We.type))return jt("track_type_mismatch",da("track_type_mismatch"));const st=i.clips.filter(Yt=>Be(Yt)===We.id),Ye=de(pe),He=Ke(We.id),ut=Js({trackClips:st,desiredDuration:Ye,preferredStart:He});if(!ut.ok)return jt("overlap",da("overlap"));w();const ht=ea(),tt={id:ht,type:J,trackId:We.id,sourceRefId:pe.id,timelineStart:ut.start,timelineEnd:ut.start+Ye,sourceIn:0,sourceOut:Ye,sourceMinIn:0,sourceMaxOut:Ye,speed:1};return i.clips.push(tt),i.selectedClipId=ht,d.value=ht,ce(),Ce(),Ga(tt)}function Se(G){const J=k.value,me=(i.mediaSources??[]).find(Ye=>Ye.id===G);if(!J||!me)return!1;w();const pe=1/h.value,Ne=de(me),We=Math.max(pe,J.timelineEnd-J.timelineStart),st=Math.max(pe,Math.min(We,Ne));return J.sourceRefId=me.id,J.sourceIn=0,J.sourceOut=st,J.sourceMinIn=0,J.sourceMaxOut=Ne,J.timelineEnd=J.timelineStart+st,Ce(),!0}function Ae(G){const J=i.mediaSources??[];return J.length<=1||vS({clips:i.clips},G)?!1:(w(),i.mediaSources=J.filter(me=>me.id!==G),!0)}function re(G,J){const me=(i.tracks??[]).find(pe=>pe.id===G);return me?(w(),me[J]=me[J]!==!0,!0):!1}function ge(G){return re(G,"locked")}function Ge(G){return re(G,"hidden")}function Ve(G){return re(G,"muted")}function at(G){return re(G,"solo")}function rt(G){if(i.clips.length<=1)return!1;const J=i.clips.findIndex(We=>We.id===G),me=J===-1?void 0:i.clips[J];if(!me)return!1;const pe=Math.max(0,me.timelineEnd-me.timelineStart),Ne=Be(me);if(w(),i.clips.splice(J,1),ce(),pe>0)for(const We of i.clips)Be(We)!==Ne||We.timelineStart<me.timelineEnd||(We.timelineStart=Math.max(0,We.timelineStart-pe),We.timelineEnd=Math.max(We.timelineStart,We.timelineEnd-pe));return i.playheadPosition>=me.timelineEnd?i.playheadPosition=Math.max(0,i.playheadPosition-pe):i.playheadPosition>me.timelineStart&&(i.playheadPosition=me.timelineStart),se(J),Ce(),i.hasChanges=!0,!0}function gt(){return i.selectedClipId?rt(i.selectedClipId):!1}function lt(){return[...i.clips].sort((G,J)=>G.timelineStart-J.timelineStart)}function Et(G){const J=i.clips.find(tt=>tt.id===G);if(!J)return null;const me=Be(J),pe=lt().filter(tt=>Be(tt)===me),Ne=pe.findIndex(tt=>tt.id===G);if(Ne===-1)return null;const We=pe[Ne],st=We.timelineEnd-We.timelineStart,Ye=Ne>0?pe[Ne-1]:null,He=Ne<pe.length-1?pe[Ne+1]:null,ut=Ye?Ye.timelineEnd:0,ht=He?He.timelineStart-st:Math.max(We.timelineStart,i.totalDuration-st);return{minStart:ut,maxStart:Math.max(ut,ht)}}function Ee(G,J,me){const pe=i.clips.find(ht=>ht.id===G);if(!pe)return jt("source_not_found","Clip not found.");if(me===void 0||me===pe.trackId){const ht=Et(G),tt=ht?Math.min(ht.maxStart,Math.max(ht.minStart,J)):Math.max(0,J);if(tt===pe.timelineStart)return Ga();w();const Yt=tt-pe.timelineStart;return pe.timelineStart=tt,pe.timelineEnd+=Yt,Ce(),f.value&&f.value.moveClip(G,tt),Ga()}const We=(i.tracks??[]).find(ht=>ht.id===me);if(!We)return jt("track_missing",da("track_missing"));if(We.locked===!0)return jt("track_locked",da("track_locked"));if(!tu(pe.type,We.type))return jt("track_type_mismatch",da("track_type_mismatch"));const st=i.clips.filter(ht=>Be(ht)===We.id&&ht.id!==pe.id),Ye=pe.timelineEnd-pe.timelineStart,He=Js({trackClips:st,desiredDuration:Ye,preferredStart:Math.max(0,J),ignoreClipId:pe.id});if(!He.ok)return jt("overlap",da("overlap"));w(),pe.trackId=We.id;const ut=pe.timelineStart;return pe.timelineStart=He.start,pe.timelineEnd=He.start+Ye,ce(),Ce(),f.value&&ut!==He.start&&f.value.moveClip(G,He.start),Ga()}function Ce(){if(i.clips.length===0){i.totalDuration=0;return}const G=i.clips.reduce((J,me)=>me.timelineEnd>J.timelineEnd?me:J);i.totalDuration=G.timelineEnd}function Re(){i.zoomLevel=Math.min(200,i.zoomLevel*1.2)}function et(){i.zoomLevel=Math.max(10,i.zoomLevel/1.2)}function qe(G){i.zoomLevel=Math.max(10,Math.min(600,Math.round(G)))}function Ze(){i.isPlaying=!i.isPlaying}function bt(G){i.isPlaying=G}function ct(G){i.playheadPosition=Math.max(0,Math.min(G,i.totalDuration))}function At(){const G=eu(i);try{localStorage.setItem(`video-draft-${n}`,JSON.stringify(G))}catch{}return G}function $t(){i.hasChanges=!1}function Pt(){return confirm("Are you sure you want to reset all changes?")?(w(),R(),i.hasChanges=!1,!0):!1}function Ut(){return eu(i)}function ea(){return`clip-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}async function Jt(G=1920,J=1080){if(u.value)try{f.value=new Om(G,J,h.value),await ta()}catch{f.value=null}}async function ta(){if(!(!f.value||E.value)){E.value=!0;try{const G=Ut();await f.value.loadFromRecipe(G);const J=p.secondsToFrames(i.playheadPosition);f.value.seek(J)}catch{}finally{E.value=!1}}}function fa(G){}function Q(G){return p.secondsToFrames(G)}function he(G){return p.framesToSeconds(G)}function ue(G){const J=he(G);ct(J),f.value&&f.value.seek(G)}function le(){v.value=!v.value}function Te(){ta()}function ze(G){u.value=!1,f.value=null}e.watch(()=>i.clips,()=>{i.hasChanges=!0,u.value&&f.value&&ta()},{deep:!0}),e.watch(()=>i.filters,()=>{i.hasChanges=!0,u.value&&f.value&&ta()},{deep:!0}),e.watch(()=>i.clips.map(G=>G.id),()=>{var J;if(!i.clips.length){delete i.selectedClipId,d.value=void 0;return}if(!i.clips.some(me=>me.id===i.selectedClipId)){const me=d.value&&((J=i.clips.find(pe=>pe.id===d.value))==null?void 0:J.id);i.selectedClipId=me??i.clips[0].id,d.value=i.selectedClipId}},{deep:!0});function ot(G){const J=i.selectedClipId?i.clips.find(me=>me.id===i.selectedClipId):i.clips[0];J&&(J.filters=[...G],i.hasChanges=!0)}function St(G){i.textOverlays=[...G]}function Ft(G){i.audioTracks=[...G]}function Vt(G){i.captionTracks=G.map(te),i.hasChanges=!0}function Ct(G){i.visualLayers=G.map(J=>({...J})),i.hasChanges=!0}function Ht(G){i.transitions=G.map(J=>{const me={...J};return J.params&&(me.params={...J.params}),me}),i.hasChanges=!0}function X(G,J){const me=i.clips.find(pe=>pe.id===G);me&&(me.keyframes=J.map(pe=>({...pe})),i.hasChanges=!0)}function ye(G){w(),M(G),i.hasChanges=!0}function te(G){return{...G,segments:G.segments.map(J=>{const me={...J};return J.words&&(me.words=J.words.map(pe=>({...pe}))),me})}}e.watch(u,G=>{G?Jt():f.value&&(f.value.destroy(),f.value=null)}),e.watch(v,()=>{}),e.watch(h,G=>{p.setFps(G)});function De(){if(!i.selectedClipId)return jt("no_selection",da("no_selection"));const G=i.clips.find(Ye=>Ye.id===i.selectedClipId);if(!G)return jt("no_selection",da("no_selection"));const J=Be(G),me=i.clips.filter(Ye=>Be(Ye)===J),pe=G.timelineEnd-G.timelineStart,Ne=Js({trackClips:me,desiredDuration:pe,preferredStart:G.timelineEnd});if(!Ne.ok)return jt("overlap",da("overlap"));w();const We={...G,id:ea(),timelineStart:Ne.start,timelineEnd:Ne.start+pe,filters:[...G.filters||[]]},st=i.clips.indexOf(G);return i.clips.splice(st+1,0,We),ce(),i.selectedClipId=We.id,i.hasChanges=!0,Ga(We)}function Tt(G){const J=G??800,me=i.totalDuration;if(me<=0){i.zoomLevel=50;return}const pe=J*.8/me;i.zoomLevel=Math.max(10,Math.min(600,Math.round(pe)))}function Dt(){const G=1/h.value;ct(Math.min(i.playheadPosition+G,i.totalDuration))}function Bt(){const G=1/h.value;ct(Math.max(i.playheadPosition-G,0))}function pt(){ct(0)}function ft(){ct(i.totalDuration)}function qt(G){if(!Number.isFinite(G)||G<=0)return;const J=k.value??i.clips[0];if(!J){y.value=G;return}const me=J.speed??1;if(me===G){y.value=G;return}w();const pe=Math.max(1/h.value,J.sourceOut-J.sourceIn),Ne=pe/me,We=pe/G,st=We-Ne;J.speed=G,J.timelineEnd=J.timelineStart+We;const Ye=i.clips.findIndex(He=>He.id===J.id);if(Ye!==-1&&st!==0)for(let He=Ye+1;He<i.clips.length;He+=1){const ut=i.clips[He];ut.timelineStart+=st,ut.timelineEnd+=st}Ce(),i.playheadPosition=Math.max(0,Math.min(i.playheadPosition,i.totalDuration)),i.hasChanges=!0,y.value=G}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:k,zoomLevel:e.computed(()=>i.zoomLevel),playbackSpeed:y,useVideoEngine:u,compositionAdapter:e.computed(()=>f.value),fps:h,useFrameMode:v,handleTrim:D,handleSplit:O,handleClipSelect:Z,splitAtPlayhead:I,deleteSelectedClip:z,deleteClip:K,rippleDeleteClip:rt,rippleDeleteSelectedClip:gt,duplicateSelectedClip:De,addTimelineTrack:ie,deleteTimelineTrack:C,renameTimelineTrack:U,reorderTimelineTrack:j,appendMediaSourceToTimeline:_e,appendAudioSourceToTimeline:ve,registerMediaSource:be,replaceSelectedClipSource:Se,removeMediaSource:Ae,toggleTrackLock:ge,toggleTrackHidden:Ge,toggleTrackMuted:Ve,toggleTrackSolo:at,setFilters:ot,setTextOverlays:St,setAudioTracks:Ft,setCaptionTracks:Vt,setVisualLayers:Ct,setTransitions:Ht,setClipKeyframes:X,loadRecipe:ye,moveClip:Ee,saveDraft:At,clearHasChanges:$t,resetChanges:Pt,generateRecipe:Ut,zoomIn:Re,zoomOut:et,setZoomLevel:qe,fitToWindow:Tt,togglePlayback:Ze,setPlaying:bt,seekTo:ct,frameForward:Dt,frameBackward:Bt,skipToStart:pt,skipToEnd:ft,setPlaybackSpeed:qt,updateSourceDuration:x,undo:F,redo:P,canUndo:g,canRedo:b,initializeComposition:Jt,syncCompositionWithState:ta,syncWithComposition:fa,convertToFrames:Q,convertToSeconds:he,seekToFrame:ue,toggleFrameMode:le,onCompositionReady:Te,onCompositionError:ze}}const gS=[{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}}}],bS={dropShadow:"drop-shadow",softFocus:"blur",blackAndWhite:"grayscale",gaussianBlur:"blur","gaussian-blur":"blur"};function vs(o){return typeof o=="object"&&o!==null}function yS(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 gs(o){if(typeof o=="number"||typeof o=="string"||typeof o=="boolean")return o}function wS(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=gs(o.default);return t!==void 0&&(a.default=t),o.options!==void 0&&(a.options=o.options),a}function _p(o,a,t){const n=oe.getFilter(o),i={},r=(n==null?void 0:n.defaultParams)??t;if(r&&vs(r))for(const[s,l]of Object.entries(r))i[s]=gs(l)??null;for(const s of a){const l=s.property??s.id;i[l]===void 0&&s.default!==void 0&&(i[l]=s.default)}return i}function Ep(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 kS(o,a,t,n){const i=n.map(wS);return{id:o,name:a,category:t,controls:i,params:i,defaultParams:_p(o,i),paramRanges:Ep(i)}}function _S(o){const a=o.paramRanges??{},t=Object.entries(a).map(([n,i])=>{var l;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},s=gs((l=o.defaultParams)==null?void 0:l[n]);return s!==void 0&&(r.default=s),r});return{id:o.id,name:o.name,category:o.category,controls:t,params:t,defaultParams:_p(o.id,t,o.defaultParams),paramRanges:Ep(t)}}function ES(o,a){return a.toLowerCase()==="unlisted"?!1:oe.isFilterCompatibleWithMedia(o,"video")}function qs(o){return bS[o]??o}function fi(o){const a=yS(o,1);return Math.max(0,Math.min(1,a))}function hi(o){if(!vs(o))return{};const a={};for(const[t,n]of Object.entries(o))a[t]=gs(n)??null;return a}function SS(o){return!vs(o)||typeof o.filterId!="string"?null:{filterId:o.filterId,params:hi(o.params),intensity:fi(o.intensity)}}function CS(o){if(!vs(o)||typeof o.id!="string"||typeof o.name!="string")return null;const t=(Array.isArray(o.filters)?o.filters:[]).map(i=>SS(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 Sp(){oe.initializeFilterRegistry();const o=e.ref([]),a=e.ref(null),t=e.ref(null),n=e.ref([]),i=e.ref(null),r=e.reactive({}),s=e.computed(()=>{const w=new Map,F=oe.getRegisteredFilters();for(const P of F)ES(P.id,P.category)&&w.set(P.id,kS(P.id,P.name,P.category,P.controls));for(const P of gS)w.has(P.id)||w.set(P.id,_S(P));return Array.from(w.values())}),l=e.computed(()=>{const w=new Map;for(const F of s.value)w.set(F.id,F);return w}),d=e.computed(()=>o.value.length>0),c=e.computed(()=>{const w={};for(const F of s.value)w[F.category]||(w[F.category]=[]),w[F.category].push(F);return w});function u(w){const F=l.value.get(w);if(F)return F;const P=qs(w);return l.value.get(P)??null}function m(w){const F=l.value.get(w);if(F)return F.id;const P=qs(w),D=l.value.get(P);return D?D.id:null}function f(w){const F=w?u(w):a.value;if(!F)return;const P=F.defaultParams||{},D={id:B(),filterId:F.id,params:{...P},intensity:1};return o.value.push(D),i.value=D.id,a.value=F,Object.keys(r).forEach(O=>delete r[O]),Object.assign(r,D.params),t.value=null,D}function p(w){const F=u(w);if(!F)return;a.value=F;const P=F.defaultParams||x(w);Object.assign(r,P),t.value={id:"preview",filterId:F.id,params:{...P},intensity:1}}function h(w){if(Object.assign(r,w),t.value&&(t.value.params={...r}),i.value){const F=o.value.find(P=>P.id===i.value);F&&(F.params={...r})}}function v(w){const F=o.value.findIndex(P=>P.id===w);F!==-1&&o.value.splice(F,1)}function E(w,F){if(w<0||w>=o.value.length||F<0||F>=o.value.length)return;const[P]=o.value.splice(w,1);o.value.splice(F,0,P)}function y(w,F){const P=o.value.find(D=>D.id===w);P&&(P.intensity=Math.max(0,Math.min(1,F)))}function k(w){const F=o.value.find(P=>P.id===w);F&&(F.intensity=F.intensity>0?0:1)}function g(){o.value=[],t.value=null,a.value=null,i.value=null,Object.keys(r).forEach(w=>delete r[w])}function b(w){const F={id:A(),name:w,filters:o.value.map(D=>({filterId:D.filterId,params:hi(D.params),intensity:fi(D.intensity)})),created_at:new Date().toISOString()};n.value.push(F);const P=n.value.map(D=>({...D}));return localStorage.setItem("video-filter-presets",JSON.stringify(P)),F}function R(w){const F=n.value.find(P=>P.id===w);if(F){g();for(const P of F.filters){const D=u(P.filterId);D&&o.value.push({id:B(),filterId:D.id,params:{...P.params},intensity:fi(P.intensity)})}}}function N(w){const F=n.value.findIndex(P=>P.id===w);F!==-1&&(n.value.splice(F,1),localStorage.setItem("video-filter-presets",JSON.stringify(n.value)))}function T(){try{const w=localStorage.getItem("video-filter-presets");if(!w)return;const F=JSON.parse(w);if(!Array.isArray(F))return;n.value=F.map(P=>CS(P)).filter(P=>P!==null)}catch{}}function S(){if(o.value.length===0)return"No filters applied";const w=o.value.map(F=>{const P=M(F.filterId);return(P==null?void 0:P.name)||F.filterId});return w.length===1?w[0]:w.length===2?`${w[0]} + ${w[1]}`:`${w[0]} + ${w.length-1} more`}function B(){return`filter-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function A(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function x(w){const F=u(w);return F?F.defaultParams||{}:{}}function M(w){return u(w)}return T(),{videoCompatibleFilters:s,activeFilters:o,selectedFilter:a,previewFilter:t,filterPresets:n,filterParams:r,hasActiveFilters:d,filtersByCategory:c,applyFilter:f,previewFilterEffect:p,updateFilterParams:h,removeFilter:v,reorderFilters:E,updateFilterIntensity:y,toggleFilter:k,clearAllFilters:g,saveFilterPreset:b,loadFilterPreset:R,deleteFilterPreset:N,getFilterSummary:S,setActiveFilters(w){var P;const F=[];for(const D of w){const O=m(D.filterId);if(!O){const I=qs(D.filterId);F.push({...D,filterId:I,params:hi(D.params),intensity:fi(D.intensity)});continue}F.push({...D,filterId:O,params:hi(D.params),intensity:fi(D.intensity)})}o.value=F,i.value=((P=o.value[0])==null?void 0:P.id)??null,Object.keys(r).forEach(D=>delete r[D]),o.value[0]&&Object.assign(r,hi(o.value[0].params))}}}class Cp{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 ca({source:"https://fonts.googleapis.com/css2?family=Inter:wght@400",family:"Inter",weight:"400"})),this.fonts.set("bold",new ca({source:"https://fonts.googleapis.com/css2?family=Inter:wght@700",family:"Inter",weight:"700"})),this.fonts.set("serif",new ca({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 ca({source:t,family:n,weight:i});this.fonts.set(a,r)}loadLocalFont(a,t,n="400"){const i=new ca({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 Po(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=Oe.fromSeconds(a.startTime)),a.duration!==void 0){const r=a.startTime||0;t.stop=Oe.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,s=Math.round(r*30),l=i+s,d=t.easing||"linear";switch(t.type){case"fade-in":a.alpha=new Xe([i,l],[0,1],{easing:d});break;case"fade-out":a.alpha=new Xe([i,l],[1,0],{easing:d});break;case"rotate":t.rotation&&(a.rotation=new Xe([i,l],[t.rotation.from,t.rotation.to],{easing:d}));break;case"scale":t.scale&&(a.scale=new Xe([i,l],[t.scale.from,t.scale.to],{easing:d}));break;case"slide":t.translate&&(a.translate={x:new Xe([i,l],[t.translate.fromX,t.translate.toX],{easing:d}),y:new Xe([i,l],[t.translate.fromY,t.translate.toY],{easing:d})});break;case"typewriter":a.alpha=new Xe([i,l],[0,1],{easing:"linear"});break;case"custom":t.rotation&&(a.rotation=new Xe([i,l],[t.rotation.from,t.rotation.to],{easing:d})),t.scale&&(a.scale=new Xe([i,l],[t.scale.from,t.scale.to],{easing:d})),t.translate&&(a.translate={x:new Xe([i,l],[t.translate.fromX,t.translate.toX],{easing:d}),y:new Xe([i,l],[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:Ui,cascade:cs,guinea:ds,solar:us,spotlight:Oi,whisper:zi}[t],s=await this.composition.createTrack("caption"),l=new ns({transcript:a});if(await s.add(l),await((d=s.generate)==null?void 0:d.call(s,r)),n&&s.clips.length>0){const c=s.clips[0];c==null||c.set(n)}}}class xp{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 xn.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 ki(i);let s=this.findAudioTrack();s||(s=await this.composition.createTrack("audio")),await s.add(r);const l={id:t,name:a.name||`Audio Track ${this.audioLayers.size+1}`,clip:r,track:s,config:a};return this.audioLayers.set(t,l),t}async resolveAudioSource(a){try{if(a instanceof xn)return a;if(typeof a=="string"&&a.trim()!=="")return await xn.from(a);if(a instanceof File)return await xn.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=Oe.fromSeconds(a.startTime)),a.duration!==void 0){const i=a.startTime||0;n.stop=Oe.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=[],s=[];if(a.fadeIn){const l=Math.round(a.fadeIn*30);r.push(n,n+l),s.push(0,t)}else r.push(n),s.push(t);if(a.fadeOut&&i){const l=n+Math.round(i*30),d=Math.round(a.fadeOut*30);a.fadeIn||(r.push(l-d),s.push(t)),r.push(l),s.push(0)}return new Xe(r,s,{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),s=new ki(this.createAudioClipConfig(i,r));this.removeClipFromTrack(n.track,n.clip),await n.track.add(s),n.clip=s,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 s=new ki(this.createAudioClipConfig(n.config,n.clip.source)),l=n.track.clips.indexOf(n.clip);l!==-1&&(n.track.clips[l]=s,n.clip=s)}}}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 Vp(o,a){return function(){return o.apply(a,arguments)}}const{toString:xS}=Object.prototype,{getPrototypeOf:xd}=Object,{iterator:bs,toStringTag:Np}=Symbol,ys=(o=>a=>{const t=xS.call(a);return o[t]||(o[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),La=o=>(o=o.toLowerCase(),a=>ys(a)===o),ws=o=>a=>typeof a===o,{isArray:zo}=Array,$i=ws("undefined");function Wi(o){return o!==null&&!$i(o)&&o.constructor!==null&&!$i(o.constructor)&&ya(o.constructor.isBuffer)&&o.constructor.isBuffer(o)}const Tp=La("ArrayBuffer");function VS(o){let a;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?a=ArrayBuffer.isView(o):a=o&&o.buffer&&Tp(o.buffer),a}const NS=ws("string"),ya=ws("function"),Bp=ws("number"),Hi=o=>o!==null&&typeof o=="object",TS=o=>o===!0||o===!1,Nr=o=>{if(ys(o)!=="object")return!1;const a=xd(o);return(a===null||a===Object.prototype||Object.getPrototypeOf(a)===null)&&!(Np in o)&&!(bs in o)},BS=o=>{if(!Hi(o)||Wi(o))return!1;try{return Object.keys(o).length===0&&Object.getPrototypeOf(o)===Object.prototype}catch{return!1}},MS=La("Date"),IS=La("File"),$S=La("Blob"),FS=La("FileList"),DS=o=>Hi(o)&&ya(o.pipe),RS=o=>{let a;return o&&(typeof FormData=="function"&&o instanceof FormData||ya(o.append)&&((a=ys(o))==="formdata"||a==="object"&&ya(o.toString)&&o.toString()==="[object FormData]"))},AS=La("URLSearchParams"),[LS,PS,US,OS]=["ReadableStream","Request","Response","Headers"].map(La),zS=o=>o.trim?o.trim():o.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Zi(o,a,{allOwnKeys:t=!1}={}){if(o===null||typeof o>"u")return;let n,i;if(typeof o!="object"&&(o=[o]),zo(o))for(n=0,i=o.length;n<i;n++)a.call(null,o[n],n,o);else{if(Wi(o))return;const r=t?Object.getOwnPropertyNames(o):Object.keys(o),s=r.length;let l;for(n=0;n<s;n++)l=r[n],a.call(null,o[l],l,o)}}function Mp(o,a){if(Wi(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 Kn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Ip=o=>!$i(o)&&o!==Kn;function zl(){const{caseless:o}=Ip(this)&&this||{},a={},t=(n,i)=>{const r=o&&Mp(a,i)||i;Nr(a[r])&&Nr(n)?a[r]=zl(a[r],n):Nr(n)?a[r]=zl({},n):zo(n)?a[r]=n.slice():a[r]=n};for(let n=0,i=arguments.length;n<i;n++)arguments[n]&&Zi(arguments[n],t);return a}const jS=(o,a,t,{allOwnKeys:n}={})=>(Zi(a,(i,r)=>{t&&ya(i)?o[r]=Vp(i,t):o[r]=i},{allOwnKeys:n}),o),WS=o=>(o.charCodeAt(0)===65279&&(o=o.slice(1)),o),HS=(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)},ZS=(o,a,t,n)=>{let i,r,s;const l={};if(a=a||{},o==null)return a;do{for(i=Object.getOwnPropertyNames(o),r=i.length;r-- >0;)s=i[r],(!n||n(s,o,a))&&!l[s]&&(a[s]=o[s],l[s]=!0);o=t!==!1&&xd(o)}while(o&&(!t||t(o,a))&&o!==Object.prototype);return a},GS=(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},XS=o=>{if(!o)return null;if(zo(o))return o;let a=o.length;if(!Bp(a))return null;const t=new Array(a);for(;a-- >0;)t[a]=o[a];return t},KS=(o=>a=>o&&a instanceof o)(typeof Uint8Array<"u"&&xd(Uint8Array)),JS=(o,a)=>{const n=(o&&o[bs]).call(o);let i;for(;(i=n.next())&&!i.done;){const r=i.value;a.call(o,r[0],r[1])}},qS=(o,a)=>{let t;const n=[];for(;(t=o.exec(a))!==null;)n.push(t);return n},YS=La("HTMLFormElement"),QS=o=>o.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,n,i){return n.toUpperCase()+i}),au=(({hasOwnProperty:o})=>(a,t)=>o.call(a,t))(Object.prototype),eC=La("RegExp"),$p=(o,a)=>{const t=Object.getOwnPropertyDescriptors(o),n={};Zi(t,(i,r)=>{let s;(s=a(i,r,o))!==!1&&(n[r]=s||i)}),Object.defineProperties(o,n)},tC=o=>{$p(o,(a,t)=>{if(ya(o)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const n=o[t];if(ya(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+"'")})}})},aC=(o,a)=>{const t={},n=i=>{i.forEach(r=>{t[r]=!0})};return zo(o)?n(o):n(String(o).split(a)),t},nC=()=>{},oC=(o,a)=>o!=null&&Number.isFinite(o=+o)?o:a;function iC(o){return!!(o&&ya(o.append)&&o[Np]==="FormData"&&o[bs])}const rC=o=>{const a=new Array(10),t=(n,i)=>{if(Hi(n)){if(a.indexOf(n)>=0)return;if(Wi(n))return n;if(!("toJSON"in n)){a[i]=n;const r=zo(n)?[]:{};return Zi(n,(s,l)=>{const d=t(s,i+1);!$i(d)&&(r[l]=d)}),a[i]=void 0,r}}return n};return t(o,0)},sC=La("AsyncFunction"),lC=o=>o&&(Hi(o)||ya(o))&&ya(o.then)&&ya(o.catch),Fp=((o,a)=>o?setImmediate:a?((t,n)=>(Kn.addEventListener("message",({source:i,data:r})=>{i===Kn&&r===t&&n.length&&n.shift()()},!1),i=>{n.push(i),Kn.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",ya(Kn.postMessage)),dC=typeof queueMicrotask<"u"?queueMicrotask.bind(Kn):typeof process<"u"&&process.nextTick||Fp,cC=o=>o!=null&&ya(o[bs]),fe={isArray:zo,isArrayBuffer:Tp,isBuffer:Wi,isFormData:RS,isArrayBufferView:VS,isString:NS,isNumber:Bp,isBoolean:TS,isObject:Hi,isPlainObject:Nr,isEmptyObject:BS,isReadableStream:LS,isRequest:PS,isResponse:US,isHeaders:OS,isUndefined:$i,isDate:MS,isFile:IS,isBlob:$S,isRegExp:eC,isFunction:ya,isStream:DS,isURLSearchParams:AS,isTypedArray:KS,isFileList:FS,forEach:Zi,merge:zl,extend:jS,trim:zS,stripBOM:WS,inherits:HS,toFlatObject:ZS,kindOf:ys,kindOfTest:La,endsWith:GS,toArray:XS,forEachEntry:JS,matchAll:qS,isHTMLForm:YS,hasOwnProperty:au,hasOwnProp:au,reduceDescriptors:$p,freezeMethods:tC,toObjectSet:aC,toCamelCase:QS,noop:nC,toFiniteNumber:oC,findKey:Mp,global:Kn,isContextDefined:Ip,isSpecCompliantForm:iC,toJSONObject:rC,isAsyncFn:sC,isThenable:lC,setImmediate:Fp,asap:dC,isIterable:cC};function nt(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)}fe.inherits(nt,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:fe.toJSONObject(this.config),code:this.code,status:this.status}}});const Dp=nt.prototype,Rp={};["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=>{Rp[o]={value:o}});Object.defineProperties(nt,Rp);Object.defineProperty(Dp,"isAxiosError",{value:!0});nt.from=(o,a,t,n,i,r)=>{const s=Object.create(Dp);return fe.toFlatObject(o,s,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),nt.call(s,o.message,a,t,n,i),s.cause=o,s.name=o.name,r&&Object.assign(s,r),s};const uC=null;function jl(o){return fe.isPlainObject(o)||fe.isArray(o)}function Ap(o){return fe.endsWith(o,"[]")?o.slice(0,-2):o}function nu(o,a,t){return o?o.concat(a).map(function(i,r){return i=Ap(i),!t&&r?"["+i+"]":i}).join(t?".":""):a}function mC(o){return fe.isArray(o)&&!o.some(jl)}const pC=fe.toFlatObject(fe,{},null,function(a){return/^is[A-Z]/.test(a)});function ks(o,a,t){if(!fe.isObject(o))throw new TypeError("target must be an object");a=a||new FormData,t=fe.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(v,E){return!fe.isUndefined(E[v])});const n=t.metaTokens,i=t.visitor||u,r=t.dots,s=t.indexes,d=(t.Blob||typeof Blob<"u"&&Blob)&&fe.isSpecCompliantForm(a);if(!fe.isFunction(i))throw new TypeError("visitor must be a function");function c(h){if(h===null)return"";if(fe.isDate(h))return h.toISOString();if(fe.isBoolean(h))return h.toString();if(!d&&fe.isBlob(h))throw new nt("Blob is not supported. Use a Buffer instead.");return fe.isArrayBuffer(h)||fe.isTypedArray(h)?d&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,v,E){let y=h;if(h&&!E&&typeof h=="object"){if(fe.endsWith(v,"{}"))v=n?v:v.slice(0,-2),h=JSON.stringify(h);else if(fe.isArray(h)&&mC(h)||(fe.isFileList(h)||fe.endsWith(v,"[]"))&&(y=fe.toArray(h)))return v=Ap(v),y.forEach(function(g,b){!(fe.isUndefined(g)||g===null)&&a.append(s===!0?nu([v],b,r):s===null?v:v+"[]",c(g))}),!1}return jl(h)?!0:(a.append(nu(E,v,r),c(h)),!1)}const m=[],f=Object.assign(pC,{defaultVisitor:u,convertValue:c,isVisitable:jl});function p(h,v){if(!fe.isUndefined(h)){if(m.indexOf(h)!==-1)throw Error("Circular reference detected in "+v.join("."));m.push(h),fe.forEach(h,function(y,k){(!(fe.isUndefined(y)||y===null)&&i.call(a,y,fe.isString(k)?k.trim():k,v,f))===!0&&p(y,v?v.concat(k):[k])}),m.pop()}}if(!fe.isObject(o))throw new TypeError("data must be an object");return p(o),a}function ou(o){const a={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(o).replace(/[!'()~]|%20|%00/g,function(n){return a[n]})}function Vd(o,a){this._pairs=[],o&&ks(o,this,a)}const Lp=Vd.prototype;Lp.append=function(a,t){this._pairs.push([a,t])};Lp.toString=function(a){const t=a?function(n){return a.call(this,n,ou)}:ou;return this._pairs.map(function(i){return t(i[0])+"="+t(i[1])},"").join("&")};function fC(o){return encodeURIComponent(o).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Pp(o,a,t){if(!a)return o;const n=t&&t.encode||fC;fe.isFunction(t)&&(t={serialize:t});const i=t&&t.serialize;let r;if(i?r=i(a,t):r=fe.isURLSearchParams(a)?a.toString():new Vd(a,t).toString(n),r){const s=o.indexOf("#");s!==-1&&(o=o.slice(0,s)),o+=(o.indexOf("?")===-1?"?":"&")+r}return o}class iu{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){fe.forEach(this.handlers,function(n){n!==null&&a(n)})}}const Up={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},hC=typeof URLSearchParams<"u"?URLSearchParams:Vd,vC=typeof FormData<"u"?FormData:null,gC=typeof Blob<"u"?Blob:null,bC={isBrowser:!0,classes:{URLSearchParams:hC,FormData:vC,Blob:gC},protocols:["http","https","file","blob","url","data"]},Nd=typeof window<"u"&&typeof document<"u",Wl=typeof navigator=="object"&&navigator||void 0,yC=Nd&&(!Wl||["ReactNative","NativeScript","NS"].indexOf(Wl.product)<0),wC=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",kC=Nd&&window.location.href||"http://localhost",_C=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Nd,hasStandardBrowserEnv:yC,hasStandardBrowserWebWorkerEnv:wC,navigator:Wl,origin:kC},Symbol.toStringTag,{value:"Module"})),ua={..._C,...bC};function EC(o,a){return ks(o,new ua.classes.URLSearchParams,{visitor:function(t,n,i,r){return ua.isNode&&fe.isBuffer(t)?(this.append(n,t.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)},...a})}function SC(o){return fe.matchAll(/\w+|\[(\w*)]/g,o).map(a=>a[0]==="[]"?"":a[1]||a[0])}function CC(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 Op(o){function a(t,n,i,r){let s=t[r++];if(s==="__proto__")return!0;const l=Number.isFinite(+s),d=r>=t.length;return s=!s&&fe.isArray(i)?i.length:s,d?(fe.hasOwnProp(i,s)?i[s]=[i[s],n]:i[s]=n,!l):((!i[s]||!fe.isObject(i[s]))&&(i[s]=[]),a(t,n,i[s],r)&&fe.isArray(i[s])&&(i[s]=CC(i[s])),!l)}if(fe.isFormData(o)&&fe.isFunction(o.entries)){const t={};return fe.forEachEntry(o,(n,i)=>{a(SC(n),i,t,0)}),t}return null}function xC(o,a,t){if(fe.isString(o))try{return(a||JSON.parse)(o),fe.trim(o)}catch(n){if(n.name!=="SyntaxError")throw n}return(t||JSON.stringify)(o)}const Gi={transitional:Up,adapter:["xhr","http","fetch"],transformRequest:[function(a,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=fe.isObject(a);if(r&&fe.isHTMLForm(a)&&(a=new FormData(a)),fe.isFormData(a))return i?JSON.stringify(Op(a)):a;if(fe.isArrayBuffer(a)||fe.isBuffer(a)||fe.isStream(a)||fe.isFile(a)||fe.isBlob(a)||fe.isReadableStream(a))return a;if(fe.isArrayBufferView(a))return a.buffer;if(fe.isURLSearchParams(a))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),a.toString();let l;if(r){if(n.indexOf("application/x-www-form-urlencoded")>-1)return EC(a,this.formSerializer).toString();if((l=fe.isFileList(a))||n.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return ks(l?{"files[]":a}:a,d&&new d,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),xC(a)):a}],transformResponse:[function(a){const t=this.transitional||Gi.transitional,n=t&&t.forcedJSONParsing,i=this.responseType==="json";if(fe.isResponse(a)||fe.isReadableStream(a))return a;if(a&&fe.isString(a)&&(n&&!this.responseType||i)){const s=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(a)}catch(l){if(s)throw l.name==="SyntaxError"?nt.from(l,nt.ERR_BAD_RESPONSE,this,null,this.response):l}}return a}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ua.classes.FormData,Blob:ua.classes.Blob},validateStatus:function(a){return a>=200&&a<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};fe.forEach(["delete","get","head","post","put","patch"],o=>{Gi.headers[o]={}});const VC=fe.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"]),NC=o=>{const a={};let t,n,i;return o&&o.split(`
|
|
345
|
+
`).forEach(function(s){i=s.indexOf(":"),t=s.substring(0,i).trim().toLowerCase(),n=s.substring(i+1).trim(),!(!t||a[t]&&VC[t])&&(t==="set-cookie"?a[t]?a[t].push(n):a[t]=[n]:a[t]=a[t]?a[t]+", "+n:n)}),a},ru=Symbol("internals");function oi(o){return o&&String(o).trim().toLowerCase()}function Tr(o){return o===!1||o==null?o:fe.isArray(o)?o.map(Tr):String(o)}function TC(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 BC=o=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(o.trim());function Ys(o,a,t,n,i){if(fe.isFunction(n))return n.call(this,a,t);if(i&&(a=t),!!fe.isString(a)){if(fe.isString(n))return a.indexOf(n)!==-1;if(fe.isRegExp(n))return n.test(a)}}function MC(o){return o.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(a,t,n)=>t.toUpperCase()+n)}function IC(o,a){const t=fe.toCamelCase(" "+a);["get","set","has"].forEach(n=>{Object.defineProperty(o,n+t,{value:function(i,r,s){return this[n].call(this,a,i,r,s)},configurable:!0})})}let wa=class{constructor(a){a&&this.set(a)}set(a,t,n){const i=this;function r(l,d,c){const u=oi(d);if(!u)throw new Error("header name must be a non-empty string");const m=fe.findKey(i,u);(!m||i[m]===void 0||c===!0||c===void 0&&i[m]!==!1)&&(i[m||d]=Tr(l))}const s=(l,d)=>fe.forEach(l,(c,u)=>r(c,u,d));if(fe.isPlainObject(a)||a instanceof this.constructor)s(a,t);else if(fe.isString(a)&&(a=a.trim())&&!BC(a))s(NC(a),t);else if(fe.isObject(a)&&fe.isIterable(a)){let l={},d,c;for(const u of a){if(!fe.isArray(u))throw TypeError("Object iterator must return a key-value pair");l[c=u[0]]=(d=l[c])?fe.isArray(d)?[...d,u[1]]:[d,u[1]]:u[1]}s(l,t)}else a!=null&&r(t,a,n);return this}get(a,t){if(a=oi(a),a){const n=fe.findKey(this,a);if(n){const i=this[n];if(!t)return i;if(t===!0)return TC(i);if(fe.isFunction(t))return t.call(this,i,n);if(fe.isRegExp(t))return t.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(a,t){if(a=oi(a),a){const n=fe.findKey(this,a);return!!(n&&this[n]!==void 0&&(!t||Ys(this,this[n],n,t)))}return!1}delete(a,t){const n=this;let i=!1;function r(s){if(s=oi(s),s){const l=fe.findKey(n,s);l&&(!t||Ys(n,n[l],l,t))&&(delete n[l],i=!0)}}return fe.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||Ys(this,this[r],r,a,!0))&&(delete this[r],i=!0)}return i}normalize(a){const t=this,n={};return fe.forEach(this,(i,r)=>{const s=fe.findKey(n,r);if(s){t[s]=Tr(i),delete t[r];return}const l=a?MC(r):String(r).trim();l!==r&&delete t[r],t[l]=Tr(i),n[l]=!0}),this}concat(...a){return this.constructor.concat(this,...a)}toJSON(a){const t=Object.create(null);return fe.forEach(this,(n,i)=>{n!=null&&n!==!1&&(t[i]=a&&fe.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[ru]=this[ru]={accessors:{}}).accessors,i=this.prototype;function r(s){const l=oi(s);n[l]||(IC(i,s),n[l]=!0)}return fe.isArray(a)?a.forEach(r):r(a),this}};wa.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);fe.reduceDescriptors(wa.prototype,({value:o},a)=>{let t=a[0].toUpperCase()+a.slice(1);return{get:()=>o,set(n){this[t]=n}}});fe.freezeMethods(wa);function Qs(o,a){const t=this||Gi,n=a||t,i=wa.from(n.headers);let r=n.data;return fe.forEach(o,function(l){r=l.call(t,r,i.normalize(),a?a.status:void 0)}),i.normalize(),r}function zp(o){return!!(o&&o.__CANCEL__)}function jo(o,a,t){nt.call(this,o??"canceled",nt.ERR_CANCELED,a,t),this.name="CanceledError"}fe.inherits(jo,nt,{__CANCEL__:!0});function jp(o,a,t){const n=t.config.validateStatus;!t.status||!n||n(t.status)?o(t):a(new nt("Request failed with status code "+t.status,[nt.ERR_BAD_REQUEST,nt.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function $C(o){const a=/^([-+\w]{1,25})(:?\/\/|:)/.exec(o);return a&&a[1]||""}function FC(o,a){o=o||10;const t=new Array(o),n=new Array(o);let i=0,r=0,s;return a=a!==void 0?a:1e3,function(d){const c=Date.now(),u=n[r];s||(s=c),t[i]=d,n[i]=c;let m=r,f=0;for(;m!==i;)f+=t[m++],m=m%o;if(i=(i+1)%o,i===r&&(r=(r+1)%o),c-s<a)return;const p=u&&c-u;return p?Math.round(f*1e3/p):void 0}}function DC(o,a){let t=0,n=1e3/a,i,r;const s=(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?s(c,u):(i=c,r||(r=setTimeout(()=>{r=null,s(i)},n-m)))},()=>i&&s(i)]}const Hr=(o,a,t=3)=>{let n=0;const i=FC(50,250);return DC(r=>{const s=r.loaded,l=r.lengthComputable?r.total:void 0,d=s-n,c=i(d),u=s<=l;n=s;const m={loaded:s,total:l,progress:l?s/l:void 0,bytes:d,rate:c||void 0,estimated:c&&l&&u?(l-s)/c:void 0,event:r,lengthComputable:l!=null,[a?"download":"upload"]:!0};o(m)},t)},su=(o,a)=>{const t=o!=null;return[n=>a[0]({lengthComputable:t,total:o,loaded:n}),a[1]]},lu=o=>(...a)=>fe.asap(()=>o(...a)),RC=ua.hasStandardBrowserEnv?((o,a)=>t=>(t=new URL(t,ua.origin),o.protocol===t.protocol&&o.host===t.host&&(a||o.port===t.port)))(new URL(ua.origin),ua.navigator&&/(msie|trident)/i.test(ua.navigator.userAgent)):()=>!0,AC=ua.hasStandardBrowserEnv?{write(o,a,t,n,i,r){const s=[o+"="+encodeURIComponent(a)];fe.isNumber(t)&&s.push("expires="+new Date(t).toGMTString()),fe.isString(n)&&s.push("path="+n),fe.isString(i)&&s.push("domain="+i),r===!0&&s.push("secure"),document.cookie=s.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 LC(o){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(o)}function PC(o,a){return a?o.replace(/\/?\/$/,"")+"/"+a.replace(/^\/+/,""):o}function Wp(o,a,t){let n=!LC(a);return o&&(n||t==!1)?PC(o,a):a}const du=o=>o instanceof wa?{...o}:o;function to(o,a){a=a||{};const t={};function n(c,u,m,f){return fe.isPlainObject(c)&&fe.isPlainObject(u)?fe.merge.call({caseless:f},c,u):fe.isPlainObject(u)?fe.merge({},u):fe.isArray(u)?u.slice():u}function i(c,u,m,f){if(fe.isUndefined(u)){if(!fe.isUndefined(c))return n(void 0,c,m,f)}else return n(c,u,m,f)}function r(c,u){if(!fe.isUndefined(u))return n(void 0,u)}function s(c,u){if(fe.isUndefined(u)){if(!fe.isUndefined(c))return n(void 0,c)}else return n(void 0,u)}function l(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:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(c,u,m)=>i(du(c),du(u),m,!0)};return fe.forEach(Object.keys({...o,...a}),function(u){const m=d[u]||i,f=m(o[u],a[u],u);fe.isUndefined(f)&&m!==l||(t[u]=f)}),t}const Hp=o=>{const a=to({},o);let{data:t,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:r,headers:s,auth:l}=a;a.headers=s=wa.from(s),a.url=Pp(Wp(a.baseURL,a.url,a.allowAbsoluteUrls),o.params,o.paramsSerializer),l&&s.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):"")));let d;if(fe.isFormData(t)){if(ua.hasStandardBrowserEnv||ua.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if((d=s.getContentType())!==!1){const[c,...u]=d?d.split(";").map(m=>m.trim()).filter(Boolean):[];s.setContentType([c||"multipart/form-data",...u].join("; "))}}if(ua.hasStandardBrowserEnv&&(n&&fe.isFunction(n)&&(n=n(a)),n||n!==!1&&RC(a.url))){const c=i&&r&&AC.read(r);c&&s.set(i,c)}return a},UC=typeof XMLHttpRequest<"u",OC=UC&&function(o){return new Promise(function(t,n){const i=Hp(o);let r=i.data;const s=wa.from(i.headers).normalize();let{responseType:l,onUploadProgress:d,onDownloadProgress:c}=i,u,m,f,p,h;function v(){p&&p(),h&&h(),i.cancelToken&&i.cancelToken.unsubscribe(u),i.signal&&i.signal.removeEventListener("abort",u)}let E=new XMLHttpRequest;E.open(i.method.toUpperCase(),i.url,!0),E.timeout=i.timeout;function y(){if(!E)return;const g=wa.from("getAllResponseHeaders"in E&&E.getAllResponseHeaders()),R={data:!l||l==="text"||l==="json"?E.responseText:E.response,status:E.status,statusText:E.statusText,headers:g,config:o,request:E};jp(function(T){t(T),v()},function(T){n(T),v()},R),E=null}"onloadend"in E?E.onloadend=y:E.onreadystatechange=function(){!E||E.readyState!==4||E.status===0&&!(E.responseURL&&E.responseURL.indexOf("file:")===0)||setTimeout(y)},E.onabort=function(){E&&(n(new nt("Request aborted",nt.ECONNABORTED,o,E)),E=null)},E.onerror=function(){n(new nt("Network Error",nt.ERR_NETWORK,o,E)),E=null},E.ontimeout=function(){let b=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const R=i.transitional||Up;i.timeoutErrorMessage&&(b=i.timeoutErrorMessage),n(new nt(b,R.clarifyTimeoutError?nt.ETIMEDOUT:nt.ECONNABORTED,o,E)),E=null},r===void 0&&s.setContentType(null),"setRequestHeader"in E&&fe.forEach(s.toJSON(),function(b,R){E.setRequestHeader(R,b)}),fe.isUndefined(i.withCredentials)||(E.withCredentials=!!i.withCredentials),l&&l!=="json"&&(E.responseType=i.responseType),c&&([f,h]=Hr(c,!0),E.addEventListener("progress",f)),d&&E.upload&&([m,p]=Hr(d),E.upload.addEventListener("progress",m),E.upload.addEventListener("loadend",p)),(i.cancelToken||i.signal)&&(u=g=>{E&&(n(!g||g.type?new jo(null,o,E):g),E.abort(),E=null)},i.cancelToken&&i.cancelToken.subscribe(u),i.signal&&(i.signal.aborted?u():i.signal.addEventListener("abort",u)));const k=$C(i.url);if(k&&ua.protocols.indexOf(k)===-1){n(new nt("Unsupported protocol "+k+":",nt.ERR_BAD_REQUEST,o));return}E.send(r||null)})},zC=(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,l();const u=c instanceof Error?c:this.reason;n.abort(u instanceof nt?u:new jo(u instanceof Error?u.message:u))}};let s=a&&setTimeout(()=>{s=null,r(new nt(`timeout ${a} of ms exceeded`,nt.ETIMEDOUT))},a);const l=()=>{o&&(s&&clearTimeout(s),s=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=()=>fe.asap(l),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},WC=async function*(o,a){for await(const t of HC(o))yield*jC(t,a)},HC=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()}},cu=(o,a,t,n)=>{const i=WC(o,a);let r=0,s,l=d=>{s||(s=!0,n&&n(d))};return new ReadableStream({async pull(d){try{const{done:c,value:u}=await i.next();if(c){l(),d.close();return}let m=u.byteLength;if(t){let f=r+=m;t(f)}d.enqueue(new Uint8Array(u))}catch(c){throw l(c),c}},cancel(d){return l(d),i.return()}},{highWaterMark:2})},_s=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Zp=_s&&typeof ReadableStream=="function",ZC=_s&&(typeof TextEncoder=="function"?(o=>a=>o.encode(a))(new TextEncoder):async o=>new Uint8Array(await new Response(o).arrayBuffer())),Gp=(o,...a)=>{try{return!!o(...a)}catch{return!1}},GC=Zp&&Gp(()=>{let o=!1;const a=new Request(ua.origin,{body:new ReadableStream,method:"POST",get duplex(){return o=!0,"half"}}).headers.has("Content-Type");return o&&!a}),uu=64*1024,Hl=Zp&&Gp(()=>fe.isReadableStream(new Response("").body)),Zr={stream:Hl&&(o=>o.body)};_s&&(o=>{["text","arrayBuffer","blob","formData","stream"].forEach(a=>{!Zr[a]&&(Zr[a]=fe.isFunction(o[a])?t=>t[a]():(t,n)=>{throw new nt(`Response type '${a}' is not supported`,nt.ERR_NOT_SUPPORT,n)})})})(new Response);const XC=async o=>{if(o==null)return 0;if(fe.isBlob(o))return o.size;if(fe.isSpecCompliantForm(o))return(await new Request(ua.origin,{method:"POST",body:o}).arrayBuffer()).byteLength;if(fe.isArrayBufferView(o)||fe.isArrayBuffer(o))return o.byteLength;if(fe.isURLSearchParams(o)&&(o=o+""),fe.isString(o))return(await ZC(o)).byteLength},KC=async(o,a)=>{const t=fe.toFiniteNumber(o.getContentLength());return t??XC(a)},JC=_s&&(async o=>{let{url:a,method:t,data:n,signal:i,cancelToken:r,timeout:s,onDownloadProgress:l,onUploadProgress:d,responseType:c,headers:u,withCredentials:m="same-origin",fetchOptions:f}=Hp(o);c=c?(c+"").toLowerCase():"text";let p=zC([i,r&&r.toAbortSignal()],s),h;const v=p&&p.unsubscribe&&(()=>{p.unsubscribe()});let E;try{if(d&&GC&&t!=="get"&&t!=="head"&&(E=await KC(u,n))!==0){let R=new Request(a,{method:"POST",body:n,duplex:"half"}),N;if(fe.isFormData(n)&&(N=R.headers.get("content-type"))&&u.setContentType(N),R.body){const[T,S]=su(E,Hr(lu(d)));n=cu(R.body,uu,T,S)}}fe.isString(m)||(m=m?"include":"omit");const y="credentials"in Request.prototype;h=new Request(a,{...f,signal:p,method:t.toUpperCase(),headers:u.normalize().toJSON(),body:n,duplex:"half",credentials:y?m:void 0});let k=await fetch(h,f);const g=Hl&&(c==="stream"||c==="response");if(Hl&&(l||g&&v)){const R={};["status","statusText","headers"].forEach(B=>{R[B]=k[B]});const N=fe.toFiniteNumber(k.headers.get("content-length")),[T,S]=l&&su(N,Hr(lu(l),!0))||[];k=new Response(cu(k.body,uu,T,()=>{S&&S(),v&&v()}),R)}c=c||"text";let b=await Zr[fe.findKey(Zr,c)||"text"](k,o);return!g&&v&&v(),await new Promise((R,N)=>{jp(R,N,{data:b,headers:wa.from(k.headers),status:k.status,statusText:k.statusText,config:o,request:h})})}catch(y){throw v&&v(),y&&y.name==="TypeError"&&/Load failed|fetch/i.test(y.message)?Object.assign(new nt("Network Error",nt.ERR_NETWORK,o,h),{cause:y.cause||y}):nt.from(y,y&&y.code,o,h)}}),Zl={http:uC,xhr:OC,fetch:JC};fe.forEach(Zl,(o,a)=>{if(o){try{Object.defineProperty(o,"name",{value:a})}catch{}Object.defineProperty(o,"adapterName",{value:a})}});const mu=o=>`- ${o}`,qC=o=>fe.isFunction(o)||o===null||o===!1,Xp={getAdapter:o=>{o=fe.isArray(o)?o:[o];const{length:a}=o;let t,n;const i={};for(let r=0;r<a;r++){t=o[r];let s;if(n=t,!qC(t)&&(n=Zl[(s=String(t)).toLowerCase()],n===void 0))throw new nt(`Unknown adapter '${s}'`);if(n)break;i[s||"#"+r]=n}if(!n){const r=Object.entries(i).map(([l,d])=>`adapter ${l} `+(d===!1?"is not supported by the environment":"is not available in the build"));let s=a?r.length>1?`since :
|
|
347
|
+
`+r.map(mu).join(`
|
|
348
|
+
`):" "+mu(r[0]):"as no adapter specified";throw new nt("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return n},adapters:Zl};function el(o){if(o.cancelToken&&o.cancelToken.throwIfRequested(),o.signal&&o.signal.aborted)throw new jo(null,o)}function pu(o){return el(o),o.headers=wa.from(o.headers),o.data=Qs.call(o,o.transformRequest),["post","put","patch"].indexOf(o.method)!==-1&&o.headers.setContentType("application/x-www-form-urlencoded",!1),Xp.getAdapter(o.adapter||Gi.adapter)(o).then(function(n){return el(o),n.data=Qs.call(o,o.transformResponse,n),n.headers=wa.from(n.headers),n},function(n){return zp(n)||(el(o),n&&n.response&&(n.response.data=Qs.call(o,o.transformResponse,n.response),n.response.headers=wa.from(n.response.headers))),Promise.reject(n)})}const Kp="1.11.0",Es={};["object","boolean","number","function","string","symbol"].forEach((o,a)=>{Es[o]=function(n){return typeof n===o||"a"+(a<1?"n ":" ")+o}});const fu={};Es.transitional=function(a,t,n){function i(r,s){return"[Axios v"+Kp+"] Transitional option '"+r+"'"+s+(n?". "+n:"")}return(r,s,l)=>{if(a===!1)throw new nt(i(s," has been removed"+(t?" in "+t:"")),nt.ERR_DEPRECATED);return t&&!fu[s]&&(fu[s]=!0),a?a(r,s,l):!0}};Es.spelling=function(a){return(t,n)=>!0};function YC(o,a,t){if(typeof o!="object")throw new nt("options must be an object",nt.ERR_BAD_OPTION_VALUE);const n=Object.keys(o);let i=n.length;for(;i-- >0;){const r=n[i],s=a[r];if(s){const l=o[r],d=l===void 0||s(l,r,o);if(d!==!0)throw new nt("option "+r+" must be "+d,nt.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new nt("Unknown option "+r,nt.ERR_BAD_OPTION)}}const Br={assertOptions:YC,validators:Es},Xa=Br.validators;let qn=class{constructor(a){this.defaults=a||{},this.interceptors={request:new iu,response:new iu}}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=to(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;n!==void 0&&Br.assertOptions(n,{silentJSONParsing:Xa.transitional(Xa.boolean),forcedJSONParsing:Xa.transitional(Xa.boolean),clarifyTimeoutError:Xa.transitional(Xa.boolean)},!1),i!=null&&(fe.isFunction(i)?t.paramsSerializer={serialize:i}:Br.assertOptions(i,{encode:Xa.function,serialize:Xa.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Br.assertOptions(t,{baseUrl:Xa.spelling("baseURL"),withXsrfToken:Xa.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&fe.merge(r.common,r[t.method]);r&&fe.forEach(["delete","get","head","post","put","patch","common"],h=>{delete r[h]}),t.headers=wa.concat(s,r);const l=[];let d=!0;this.interceptors.request.forEach(function(v){typeof v.runWhen=="function"&&v.runWhen(t)===!1||(d=d&&v.synchronous,l.unshift(v.fulfilled,v.rejected))});const c=[];this.interceptors.response.forEach(function(v){c.push(v.fulfilled,v.rejected)});let u,m=0,f;if(!d){const h=[pu.bind(this),void 0];for(h.unshift(...l),h.push(...c),f=h.length,u=Promise.resolve(t);m<f;)u=u.then(h[m++],h[m++]);return u}f=l.length;let p=t;for(m=0;m<f;){const h=l[m++],v=l[m++];try{p=h(p)}catch(E){v.call(this,E);break}}try{u=pu.call(this,p)}catch(h){return Promise.reject(h)}for(m=0,f=c.length;m<f;)u=u.then(c[m++],c[m++]);return u}getUri(a){a=to(this.defaults,a);const t=Wp(a.baseURL,a.url,a.allowAbsoluteUrls);return Pp(t,a.params,a.paramsSerializer)}};fe.forEach(["delete","get","head","options"],function(a){qn.prototype[a]=function(t,n){return this.request(to(n||{},{method:a,url:t,data:(n||{}).data}))}});fe.forEach(["post","put","patch"],function(a){function t(n){return function(r,s,l){return this.request(to(l||{},{method:a,headers:n?{"Content-Type":"multipart/form-data"}:{},url:r,data:s}))}}qn.prototype[a]=t(),qn.prototype[a+"Form"]=t(!0)});let QC=class Jp{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 s=new Promise(l=>{n.subscribe(l),r=l}).then(i);return s.cancel=function(){n.unsubscribe(r)},s},a(function(r,s,l){n.reason||(n.reason=new jo(r,s,l),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 Jp(function(i){a=i}),cancel:a}}};function ex(o){return function(t){return o.apply(null,t)}}function tx(o){return fe.isObject(o)&&o.isAxiosError===!0}const Gl={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(Gl).forEach(([o,a])=>{Gl[a]=o});function qp(o){const a=new qn(o),t=Vp(qn.prototype.request,a);return fe.extend(t,qn.prototype,a,{allOwnKeys:!0}),fe.extend(t,a,null,{allOwnKeys:!0}),t.create=function(i){return qp(to(o,i))},t}const Wt=qp(Gi);Wt.Axios=qn;Wt.CanceledError=jo;Wt.CancelToken=QC;Wt.isCancel=zp;Wt.VERSION=Kp;Wt.toFormData=ks;Wt.AxiosError=nt;Wt.Cancel=Wt.CanceledError;Wt.all=function(a){return Promise.all(a)};Wt.spread=ex;Wt.isAxiosError=tx;Wt.mergeConfig=to;Wt.AxiosHeaders=wa;Wt.formToJSON=o=>Op(fe.isHTMLForm(o)?new FormData(o):o);Wt.getAdapter=Xp.getAdapter;Wt.HttpStatusCode=Gl;Wt.default=Wt;const{Axios:tU,AxiosError:aU,CanceledError:nU,isCancel:oU,CancelToken:iU,VERSION:rU,all:sU,Cancel:lU,isAxiosError:dU,spread:cU,toFormData:uU,AxiosHeaders:mU,HttpStatusCode:pU,formToJSON:fU,getAdapter:hU,mergeConfig:vU}=Wt;class Ss{constructor(a="/api/v1"){this.eventSource=null,this.progressCallbacks=new Map,this.api=Wt.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((s,l)=>{const d=setInterval(async()=>{try{const c=await this.getJob(a);t==null||t(c.progress,c.status),c.status==="completed"?(clearInterval(d),s(c)):c.status==="failed"?(clearInterval(d),l(new Error(c.error_message??"Render job failed"))):c.status==="cancelled"?(clearInterval(d),l(new Error("Render job cancelled"))):Date.now()-r>i&&(clearInterval(d),l(new Error("Render job timed out")))}catch(c){clearInterval(d),l(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 s=t.progress_message??t.progressMessage;typeof s=="string"&&s!==""&&(n.progress_message=s);const l=t.progress_detail??t.progressDetail;l&&typeof l=="object"&&(n.progress_detail=l);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 Ss;const ax={key:0,class:"mobile-layout"},nx={class:"mobile-toolbar"},ox={class:"mobile-toolbar-left"},ix=["aria-label"],rx={class:"mobile-toolbar-right"},sx=["disabled"],lx=["disabled"],dx={class:"preview-section"},cx={key:0,class:"mobile-export-overlay"},ux={class:"mobile-export-progress"},mx={class:"mobile-export-bar"},px={class:"mobile-timeline-zoom"},fx={class:"mobile-edit-strip"},hx={class:"mobile-selection-summary"},vx={class:"mobile-selection-title"},gx={class:"mobile-selection-meta"},bx={class:"mobile-readout-row"},yx=["disabled"],wx={class:"mobile-readout-grid"},kx={class:"mobile-readout-chip","data-testid":"mobile-playhead-readout"},_x={class:"mobile-readout-chip","data-testid":"mobile-clip-in-readout"},Ex={class:"mobile-readout-chip","data-testid":"mobile-clip-out-readout"},Sx={class:"mobile-readout-chip","data-testid":"mobile-duration-readout"},Cx=["disabled"],xx={class:"mobile-speed-strip"},Vx={class:"mobile-speed-chips"},Nx=["data-testid","onClick"],Tx={class:"mobile-edit-actions"},Bx=["disabled"],Mx=["disabled"],Ix=["disabled"],$x=["disabled"],Fx=["disabled"],Dx={class:"mobile-action-sheet-header"},Rx={class:"mobile-action-sheet-title"},Ax={class:"mobile-action-sheet-subtitle"},Lx={class:"mobile-action-sheet-actions"},Px=["disabled"],Ux=["disabled"],Ox=["disabled"],zx=["disabled"],jx=["disabled"],Wx={key:1,class:"desktop-layout"},Hx={class:"desktop-main-row"},Zx={class:"preview-panel"},Gx={class:"fit-toggle"},Xx={class:"editor-content"},Kx={class:"editor-tabs"},Jx={class:"tab-header"},qx=["onClick"],Yx={class:"tab-content-area"},Qx={class:"filter-controls"},eV={class:"text-controls"},tV={class:"transition-controls"},aV={class:"audio-controls"},nV={class:"adjustments-controls"},oV={key:1,class:"no-filter-selected"},iV={class:"export-controls"},rV={key:0,"data-testid":"video-export-status-completed"},sV={key:1,"data-testid":"video-export-status-message",class:"export-status-message"},lV={class:"desktop-timeline-row"},dV={class:"timeline-zoom"},cV=["value"],uV={class:"zoom-readout"},mV={key:0,class:"dev-editor-controls","data-testid":"video-editor-dev-controls"},pV={class:"dev-editor-row"},fV={class:"dev-editor-field"},hV={class:"dev-editor-field"},vV=["disabled"],gV=["disabled"],bV=["disabled"],yV={class:"dev-editor-row"},wV={class:"dev-editor-field dev-editor-field--wide"},kV=["value"],_V=["disabled"],EV=["disabled"],SV=["disabled"],CV=["disabled"],xV=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}),s=e.computed(()=>{const V=typeof n.mediaUuid=="string"?n.mediaUuid.trim():"";return V!==""?V:r.value??`temp-${Date.now()}`}),l=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},L=n.featureFlags;return L?{filters:typeof L.filters=="boolean"?L.filters:V.filters,adjustments:typeof L.adjustments=="boolean"?L.adjustments:V.adjustments,text:typeof L.text=="boolean"?L.text:V.text,transitions:typeof L.transitions=="boolean"?L.transitions:V.transitions,audio:typeof L.audio=="boolean"?L.audio:V.audio,export:typeof L.export=="boolean"?L.export:V.export}:V}),m=e.computed(()=>l.value?d.value:c.value),f=e.computed(()=>m.value==="filters"||E.value),p=e.computed(()=>m.value!=="filters"&&!E.value),h=e.ref(null),v=e.ref(null),E=e.ref(!1),y=e.computed(()=>l.value?h.value:v.value);function k(V){return V==="contain"||V==="cover"||V==="none"}function g(V){if(!(V!=null&&V.metadata))return null;const L=V.metadata.fit_mode;return k(L)?L:null}const b=e.shallowRef(null),R=e.ref(null),N=e.ref(g(n.initialRecipe)??"contain"),T=e.ref(null),S=e.ref(null),B=e.ref(null),A=e.ref(!1),x=new Map,M=e.ref([]),w=e.ref([]),F=e.ref([]),P=e.ref([]),D=e.ref(1),O=()=>{l.value=window.innerWidth<768},I=[{id:"filters",label:"Filters",icon:Cn},{id:"adjustments",label:"Adjust",icon:hv},{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:$o}],Z=[{id:"filters",label:"Filters"},{id:"adjustments",label:"Adjustments"},{id:"text",label:"Text"},{id:"transitions",label:"Transitions"},{id:"audio",label:"Audio"},{id:"export",label:"Export"}],z=e.computed(()=>I.filter(V=>u.value[V.id])),K=e.computed(()=>Z.filter(V=>u.value[V.id])),se=e.computed(()=>{var V,L;return((V=K.value[0])==null?void 0:V.id)??((L=z.value[0])==null?void 0:L.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 Be=e.computed(()=>typeof window>"u"?!1:window.__MEDIABLES_EDITOR_DEV__===!0),ce=cm(),{currentFrame:ie,playheadPosition:W,timelineClips:C,totalDuration:U,hasChanges:j,isPlaying:ne,selectedClip:de,zoomLevel:Ke,playbackSpeed:be,fps:_e,handleTrim:ve,handleSplit:xe,handleClipSelect:Se,splitAtPlayhead:Ae,deleteSelectedClip:re,duplicateSelectedClip:ge,setZoomLevel:Ge,moveClip:Ve,setFilters:at,setTextOverlays:rt,setAudioTracks:gt,saveDraft:lt,clearHasChanges:Et,resetChanges:Ee,generateRecipe:Ce,zoomIn:Re,zoomOut:et,fitToWindow:qe,togglePlayback:Ze,setPlaying:bt,seekTo:ct,frameForward:At,frameBackward:$t,skipToStart:Pt,skipToEnd:Ut,setPlaybackSpeed:ea,updateSourceDuration:Jt,undo:ta,redo:fa,canUndo:Q,canRedo:he}=kp(s.value,n.initialRecipe,n.media),{videoCompatibleFilters:ue,activeFilters:le,selectedFilter:Te,previewFilter:ze,previewFilterEffect:ot,applyFilter:St,updateFilterParams:Ft,removeFilter:Vt,clearAllFilters:Ct,setActiveFilters:Ht}=Sp();function X(V){var ae,ke;const L=((ae=de.value)==null?void 0:ae.id)??((ke=C.value[0])==null?void 0:ke.id);L&&(A.value=!0,typeof V=="object"&&V.id?St(V.id):typeof V=="string"&&St(V),at(le.value),b.value?b.value.setClipFilters(L,le.value):x.set(L,[...le.value]),Se(L),A.value=!1,Za())}function ye(){var L,ae;const V=((L=de.value)==null?void 0:L.id)??((ae=C.value[0])==null?void 0:ae.id);V&&Se(V)}function te(V){const L=le.value.find(ae=>ae.filterId===V);L&&Vt(L.id)}const De=e.computed(()=>ue.value.map(L=>{var ke;const ae=[];if(L.controls&&L.controls.length>0)for(const $e of L.controls){const Me=$e.type;if(Me==="button"||Me==="text"||Me==="range")continue;const Ie={id:$e.property||$e.id,label:$e.label||$e.id,type:Me,default:$e.default??(Me==="toggle"?!1:Me==="color"?"#ffffff":0)};Me==="slider"&&(Ie.min=$e.min??0,Ie.max=$e.max??1,Ie.step=$e.step??.01),Me==="select"&&$e.options&&(Ie.options=$e.options),ae.push(Ie)}else if(L.paramRanges){const $e=Object.entries(L.paramRanges);for(const[Me,Ie]of $e){const xt=Me.replace(/[-_]/g," ").replace(/\b\w/g,Pn=>Pn.toUpperCase()),Sa=(ke=L.defaultParams)==null?void 0:ke[Me],Eo=(Ie.min+Ie.max)/2;ae.push({id:Me,label:xt,min:Ie.min,max:Ie.max,step:Ie.step??.01,default:typeof Sa=="number"?Sa:Eo})}}return{id:L.id,name:L.name,category:L.category,params:ae}})),Tt=e.ref("0.00"),Dt=e.ref("0.00"),Bt=e.ref("");e.watch(De,V=>{if(V.length===0){Bt.value="";return}V.some(ae=>ae.id===Bt.value)||(Bt.value=V[0].id)},{immediate:!0});const pt=e.ref(!1),ft=e.ref(0),qt=e.ref(!1),wt=e.ref(null),Ot=e.ref(null);let _a=null,G=!1;const J=e.computed(()=>{const V=new Map;return le.value.forEach(L=>V.set(L.filterId,L)),V}),me=e.computed(()=>{var V,L;return ie.value?ie.value:((V=n.media)==null?void 0:V.thumbnail_url)||((L=n.media)==null?void 0:L.url)}),pe=e.ref("");e.watch(()=>{var V,L;return{file:(V=n.media)==null?void 0:V.file,url:(L=n.media)==null?void 0:L.url}},(V,L,ae)=>{var $e,Me;const ke=pe.value;ae(()=>{ke&&ke.startsWith("blob:")&&URL.revokeObjectURL(ke)}),($e=n.media)!=null&&$e.file?pe.value=URL.createObjectURL(n.media.file):(Me=n.media)!=null&&Me.url?pe.value=n.media.url:pe.value=""},{immediate:!0}),e.onUnmounted(()=>{pe.value&&pe.value.startsWith("blob:")&&URL.revokeObjectURL(pe.value)});const Ne=e.computed(()=>pe.value),We=Xm({forcePixiPreview:E,getPreviewRef:()=>y.value,getSourceUrl:()=>pe.value,setPlaying:bt}),st=e.computed(()=>{if(!n.media)return null;const{file:V,...L}=n.media;return{...L,url:pe.value}}),Ye=e.computed(()=>{var L;const V=(L=n.media)==null?void 0:L.url;return!!(V&&/^https?:/i.test(V))}),He=e.computed(()=>le.value),ut=e.computed(()=>W.value),ht=e.computed(()=>!!de.value&&W.value>0),tt=e.computed(()=>!!de.value&&C.value.length>1),Yt=e.computed(()=>!!de.value),It=e.ref(!0),Pa=[.5,1,1.5,2],Fa=e.computed(()=>{const V=new Set([0,va.value]);for(const L of C.value)V.add(L.timelineStart),V.add(L.timelineEnd);return Array.from(V).filter(L=>Number.isFinite(L)).sort((L,ae)=>L-ae)}),co=e.computed(()=>Fa.value.some(V=>V<W.value-.001)),Da=e.computed(()=>Fa.value.some(V=>V>W.value+.001)),on=e.ref(!1),Ua=e.ref(null);function ha(V){if(!Number.isFinite(V)||V<0)return"0:00";const L=Math.floor(V/60),ae=Math.floor(V%60);return`${L}:${ae.toString().padStart(2,"0")}`}const Mn=e.computed(()=>{var ae;const V=de.value??C.value[0];if(!V)return"No clip selected";const L=(ae=V.label)==null?void 0:ae.trim();return L&&L.length>0?L:`Clip ${V.id.slice(-4)}`}),uo=e.computed(()=>{const V=de.value??C.value[0];if(!V)return"Tap a clip to start editing";const L=Math.max(0,V.timelineEnd-V.timelineStart);return`${ha(V.timelineStart)} - ${ha(V.timelineEnd)} • ${L.toFixed(1)}s`});function In(V){return!Number.isFinite(V)||V<0?"0.0s":V<60?`${V.toFixed(1)}s`:ha(V)}const mo=e.computed(()=>ha(W.value)),hn=e.computed(()=>{const V=de.value??C.value[0];return V?ha(V.sourceIn):"0:00"}),Oa=e.computed(()=>{const V=de.value??C.value[0];return V?ha(V.sourceOut):"0:00"}),Ts=e.computed(()=>{const V=de.value??C.value[0];return V?In(V.timelineEnd-V.timelineStart):"0.0s"}),Wo=e.computed(()=>Ua.value===null?de.value??C.value[0]??null:C.value.find(V=>V.id===Ua.value)??null),Bs=e.computed(()=>{var ae;const V=Wo.value;if(!V)return"Clip actions";const L=(ae=V.label)==null?void 0:ae.trim();return L&&L.length>0?L:`Clip ${V.id.slice(-4)}`}),Ms=e.computed(()=>{const V=Wo.value;return V?`${ha(V.timelineStart)} - ${ha(V.timelineEnd)} • ${In(V.timelineEnd-V.timelineStart)}`:"Choose an action"}),$n=e.ref(0),va=e.computed(()=>{try{const V=U.value??U;return V&&typeof V=="number"&&V>0?V:$n.value}catch{return $n.value}}),vn=e.ref(),Ho=e.ref(),Zo=e.ref(),gn=e.ref(),po=e.ref(0),rn=e.ref(!1);let ra=null,Ta=null;e.watch(va,V=>{var ae;if(rn.value||!V||V<=0)return;const L=po.value||((ae=vn.value)==null?void 0:ae.clientWidth)||0;L>0&&(rn.value=!0,qe(L))}),e.watch(po,V=>{if(rn.value||!V||V<=0)return;va.value>0&&(rn.value=!0,qe(V))}),e.watch(l,V=>{V||Wa()}),e.watch(()=>{var V;return(V=Wo.value)==null?void 0:V.id},V=>{on.value&&!V&&Wa()});function sn(V){return Number.isFinite(V)?V.toFixed(2):"0.00"}function Xi(V){const L=Number(V);return Number.isFinite(L)?L:null}function oa(V){V&&(Tt.value=sn(V.sourceIn),Dt.value=sn(V.sourceOut))}e.watch(()=>{var V,L,ae;return[(V=de.value)==null?void 0:V.id,(L=de.value)==null?void 0:L.sourceIn,(ae=de.value)==null?void 0:ae.sourceOut]},()=>{oa(de.value)},{immediate:!0});function bn(V){const L=de.value;if(!L)return;const ae=1/30,ke=L.sourceMinIn??0,$e=L.sourceMaxOut??va.value,Me=L.sourceIn+(W.value-L.timelineStart);if(V==="start"){const xt=Math.max(ke,Math.min(Me,L.sourceOut-ae));Tt.value=sn(xt);return}const Ie=Math.max(L.sourceIn+ae,Math.min(Me,$e));Dt.value=sn(Ie)}function za(){const V=de.value;if(!V)return;const L=Xi(Tt.value),ae=Xi(Dt.value);if(L===null||ae===null)return;const ke=1/30,$e=V.sourceMinIn??0,Me=V.sourceMaxOut??va.value,Ie=Math.max($e,Math.min(L,Me-ke)),xt=Math.max(Ie+ke,Math.min(ae,Me));ve(V.id,"start",Ie),ve(V.id,"end",xt),Tt.value=sn(Ie),Dt.value=sn(xt),de.value&&ct(de.value.timelineStart)}function Lt(){Bt.value.trim()!==""&&X(Bt.value)}function ln(){var V;Ct(),at(le.value),(V=de.value)!=null&&V.id&&(b.value?b.value.setClipFilters(de.value.id,le.value):x.set(de.value.id,[...le.value])),Za()}function fo(V,L,ae){var $e,Me;const ke=le.value.find(Ie=>Ie.filterId===V);ke?(ke.params={...ke.params,[L]:ae},at(le.value),b.value&&(($e=de.value)!=null&&$e.id)?b.value.setClipFilters(de.value.id,le.value):(Me=de.value)!=null&&Me.id&&x.set(de.value.id,[...le.value]),Za(),ye()):ze.value&&ze.value.filterId===V&&(ze.value.params={...ze.value.params||{},[L]:ae})}function Fn(V){ct(V)}function ja(V){!V||!Number.isFinite(V.timestamp)||ct(V.timestamp)}function Go(V){bt(V)}function ho(V){!Number.isFinite(V)||V<=0||($n.value=V,Jt(V))}function Wa(){on.value=!1,Ua.value=null}function Ea(V){l.value&&(Ua.value=V,on.value=!0)}function Xo(V){var ke,$e,Me,Ie;const L=((ke=de.value)==null?void 0:ke.id)??(($e=C.value[0])==null?void 0:$e.id)??null;Se(V),(((Me=de.value)==null?void 0:Me.id)??((Ie=C.value[0])==null?void 0:Ie.id)??null)!==L&&ce.selection()}function Ki(V){Xo(V),Ea(V)}function Dn(V){V&&ce.selection()}function vo(){It.value=!It.value,ce.selection()}function Ha(){const V=Fa.value.filter(ae=>ae<W.value-.001),L=V.length>0?V[V.length-1]:0;ct(L)}function Ji(){const V=Fa.value.find(L=>L>W.value+.001);ct(V??va.value)}function go(){ta()}function bo(){fa()}function yn(){const V=C.value.length;Ae(),C.value.length>V&&(ce.success(),Wa())}function Ko(V){const L=C.value.length;xe(V),C.value.length>L&&ce.success()}function Rn(){const V=C.value.length;ge(),C.value.length>V&&(ce.selection(),Wa())}function yo(){const V=C.value.length;re(),C.value.length<V&&(ce.error(),Wa())}function An(V){const L=be.value;ea(V),be.value!==L&&ce.selection()}function wo(V){return V instanceof HTMLElement?V.closest('input, textarea, select, button, [contenteditable="true"]')!==null:!1}function wn(V){if(l.value||wo(V.target))return;const L=V.key.toLowerCase(),ae=V.metaKey||V.ctrlKey;if(V.code==="Space"){V.preventDefault(),Ze();return}if(!ae&&L==="s"){V.preventDefault(),yn();return}if(L==="arrowleft"){V.preventDefault(),$t();return}if(L==="arrowright"){V.preventDefault(),At();return}if(L==="home"){V.preventDefault(),Pt();return}if(L==="end"){V.preventDefault(),Ut();return}if(!ae&&L==="["){V.preventDefault(),Ha();return}if(!ae&&L==="]"){V.preventDefault(),Ji();return}if(ae&&L==="z"&&V.shiftKey){V.preventDefault(),bo();return}ae&&L==="z"&&(V.preventDefault(),go())}function qi(){var L;const V=po.value||((L=vn.value)==null?void 0:L.clientWidth)||800;qe(V)}function Jo(V){rn.value=!0,Ge(V)}function Zd(){rn.value=!0,Re()}function Gd(){rn.value=!0,et()}function ko(V){const L=V.target,ae=Number(L.value);Jo(ae)}function qo(V){const L=Math.min(600,Math.max(10,Ke.value+V));Jo(L)}function Yo(){Ta==null||Ta(),Ta=null;const V=Zo.value,L=gn.value;if(!l.value||!V||!L)return;const ae=()=>{qo(-20)},ke=()=>{qo(20)};V.addEventListener("click",ae),L.addEventListener("click",ke),Ta=()=>{V.removeEventListener("click",ae),L.removeEventListener("click",ke)}}e.watch([l,Zo,gn],()=>{Yo()},{flush:"post"});function Yi(V){var L;b.value=V,(L=b.value)!=null&&L.composition&&(T.value=new Cp(b.value.composition),S.value=new Bi(b.value.composition),B.value=new xp(b.value.composition));try{x.size&&(x.forEach((ae,ke)=>{b.value.setClipFilters(ke,ae)}),x.clear(),b.value.composition.computeFrame())}catch{}}function Qi(V){V!=null&&V.id&&ot(V.id)}function er(V){Ft(V),Za()}async function tr(V){if(!T.value)return;const L=await T.value.addTextOverlay(V);M.value.push({id:L,...V})}async function ar(V,L){if(!T.value)return;await T.value.updateTextOverlay(V,L);const ae=M.value.findIndex(ke=>ke.id===V);ae!==-1&&(M.value[ae]={...M.value[ae],...L})}async function _(V){T.value&&(await T.value.removeTextOverlay(V),M.value=M.value.filter(L=>L.id!==V))}async function $(V){if(!S.value||P.value.length<2)return;const[L,ae]=P.value,ke=await S.value.applyTransition(L,ae,V);w.value.push({id:ke,...V,name:V.type})}function Y(V){if(!S.value)return;const L=w.value[V];L&&(S.value.removeTransition(L.id),w.value.splice(V,1))}function we(V){}async function Pe(V){if(!B.value)return;const L=await B.value.addAudioTrack(V);F.value.push({id:L,...V})}async function Ue(V,L){if(!B.value)return;const ae=F.value.findIndex(ke=>ke.id===V);ae!==-1&&(F.value[ae]={...F.value[ae],...L})}async function dt(V){B.value&&(await B.value.removeAudioTrack(V),F.value=F.value.filter(L=>L.id!==V))}async function Nt(V,L){if(!B.value)return;await B.value.updateVolume(V,L);const ae=F.value.find(ke=>ke.id===V);ae&&(ae.volume=L)}async function Zt(V,L){if(!B.value)return;await B.value.muteTrack(V,L);const ae=F.value.find(ke=>ke.id===V);ae&&(ae.muted=L)}function ma(V){B.value&&(B.value.setMasterVolume(V),D.value=V)}function _o(V){i("thumbnail-selected",V)}function kn(){_a!==null&&(clearInterval(_a),_a=null)}function Zf(V,L){return L?{...V,output:{...V.output,format:L.format,quality:L.quality}}:V}function Qo(V){var L;return V.metadata||(V.metadata={created_at:new Date().toISOString(),editor_version:"2.0.0"}),V.metadata.fit_mode=N.value,(L=n.media)!=null&&L.url&&/^https?:/i.test(n.media.url)?V.metadata.source_url=n.media.url:delete V.metadata.source_url,V}function zt(V,L,ae){return Math.min(ae,Math.max(L,V))}function Is(V,L){if(typeof V=="number"&&Number.isFinite(V))return V;if(typeof V=="string"){const ae=Number(V);if(Number.isFinite(ae))return ae}return L}function sa(V,L,ae){for(const ke of L)if(ke in V)return Is(V[ke],ae);return ae}function Gf(V){const L=typeof V.params=="object"&&V.params!==null?V.params:{};switch(V.filterId.trim().toLowerCase()){case"brightness":return[{type:"brightness",value:zt(sa(L,["value","brightness"],0),-1,1)}];case"contrast":return[{type:"contrast",value:zt(sa(L,["value","contrast"],1),.1,3)}];case"saturation":return[{type:"saturation",value:zt(sa(L,["value","saturation"],1),0,3)}];case"blur":case"gaussian-blur":case"kawase-blur":case"radial-blur":return[{type:"blur",value:zt(sa(L,["value","blur","radius"],0),0,25)}];case"sharpen":return[{type:"sharpen",value:zt(sa(L,["value","amount"],1),0,5)}];case"sepia":return[{type:"sepia",value:1}];case"grayscale":return[{type:"grayscale",value:1}];case"adjustment":{const ke=zt(sa(L,["brightness"],1)-1,-1,1),$e=zt(sa(L,["contrast"],1),.1,3),Me=zt(sa(L,["saturation"],1),0,3);return[{type:"brightness",value:ke},{type:"contrast",value:$e},{type:"saturation",value:Me}]}default:return[]}}function Xf(V){const L=V.timeline[0],ae=Array.isArray(L==null?void 0:L.filters)?L.filters:[],ke=[];for(const Me of ae)if(ke.push(...Gf(Me)),ke.length>=12)break;const $e={...V,filters:ke.slice(0,12)};if(V.timeline.length===1&&L){const Me=Math.max(0,Is(L.sourceIn,0)),Ie=Is(L.sourceOut,Me);Ie>Me&&($e.trim={start:Me,end:Ie})}return $e}async function Xd(V,L,ae){return We.renderRecipeWithPixi(V,L,ae)}async function Kf(V,L){var ei;kn(),G=!1,We.resetClientExport(),Ot.value=null,wt.value=null,qt.value=!1,ft.value=0;const ae=Qo(V??Ce()),ke=tc(ae),$e=Array.isArray(ke.filters)&&ke.filters.length>0,Me=Ds(ke);if(!(j.value||$e||Me))return Et(),i("video-exported",null),null;const xt=ke.timeline[0],Sa=xt?Math.max(0,xt.sourceIn):0,Pn=((xt==null?void 0:xt.sourceOut)??((ei=ke.source)==null?void 0:ei.duration)??va.value)-Sa,Ls=n.serverRenderEndpoint!=null&&n.clientExportThreshold>0&&Pn>n.clientExportThreshold;if(Ls){pt.value=!0;try{return await Jf(ke),null}catch(la){const Ca=la instanceof Error?la.message:"Server render failed";throw wt.value=Ca,i("server-render-failed",Ca),la}finally{pt.value=!1}}if(n.maxDuration>0&&Pn>n.maxDuration&&!Ls){const la=`This video is too long for in-browser export (${Math.round(Pn)}s). Server rendering is not available. Try a shorter clip.`;return wt.value=la,i("video-exported",null),null}pt.value=!0;try{const la=await Xd(ke,L,Ca=>{G||(ft.value=Ca)});return G?(wt.value="Export canceled.",ft.value=0,i("video-exported",null),null):(Et(),i("recipe-generated",ke),i("video-exported",la),ft.value=100,qt.value=!0,la)}catch(la){if(G)return wt.value="Export canceled.",ft.value=0,i("video-exported",null),null;const Ca=la instanceof Error?la.message:"Local WebGL export failed.";throw wt.value=Ca,new Error(`Video export failed: ${Ca}`)}finally{pt.value=!1}}function nr(){return new Ss(n.serverRenderEndpoint??"/api/v1")}async function Jf(V){const L=nr();wt.value="Starting server render...",ft.value=0;const ae=await L.createRenderJob({source_media_uuid:s.value,recipe:V});Ot.value=ae.id,i("server-render-started",ae.id),i("export-started",ae.id),wt.value="Rendering on server...";const ke=await L.pollRenderJob(ae.id,(Me,Ie)=>{ft.value=Me,Ie==="processing"&&(wt.value=`Server rendering: ${Me}%`)},3e3,(n.maxDuration>0?n.maxDuration*3:1800)*1e3);ft.value=100,qt.value=!0,wt.value="Server render complete!",Et(),i("recipe-generated",V);const $e={id:ke.id};typeof ke.output_media_id=="string"&&ke.output_media_id!==""&&($e.output_media_id=ke.output_media_id),i("server-render-completed",$e)}async function Kd(){if(!pt.value)return;G=!0,E.value=!1,We.cancelClientExport(),kn();const V=Ot.value;if(V)try{await nr().cancelJob(V)}catch(L){const ae=L instanceof Error?L.message:"Failed to cancel export";wt.value=ae,pt.value=!1,Ot.value=null;return}pt.value=!1,ft.value=0,qt.value=!1,Ot.value=null,wt.value="Export canceled."}async function Jd(V){kn(),G=!1,We.resetClientExport(),Ot.value=null,wt.value=null,qt.value=!1,pt.value=!0,ft.value=0;try{const L=Qo(Zf(Ce(),V));i("recipe-generated",L);const ae=s.value.startsWith("temp-"),ke=L.timeline[0],$e=Array.isArray(ke==null?void 0:ke.filters)?ke.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 Ca=await Xd(L,V,dh=>{G||(ft.value=dh)});if(G){wt.value="Export canceled.",pt.value=!1,ft.value=0;return}i("video-exported",Ca);const nc=URL.createObjectURL(Ca.file),Ps=document.createElement("a");Ps.href=nc,Ps.download=`edited-video-${Date.now()}.mp4`,Ps.click(),setTimeout(()=>URL.revokeObjectURL(nc),100),pt.value=!1,ft.value=100,qt.value=!0;return}catch(Ca){if(G){wt.value="Export canceled.",pt.value=!1,ft.value=0;return}if(ae||!Ie)throw Ca;ft.value=0,wt.value="Local filter export failed, falling back to server render."}const xt={"360p":"low","480p":"low","720p":"medium","1080p":"high","1440p":"ultra","2160p":"ultra"},Sa=(V==null?void 0:V.quality)??L.output.quality,Eo=xt[Sa]??"high",Pn={...Xf(L),export:{format:(V==null?void 0:V.format)??L.output.format,quality:Eo,resolution:Sa,framerate:L.output.fps}},ei=await nr().createJob({source_media_id:s.value,recipe:Pn}),la=typeof ei.id=="string"?ei.id:null;if(!la)throw new Error("Export failed: missing job id");Ot.value=la,i("export-started",la),sh(la)}catch(L){if(E.value=!1,We.resetClientExport(),G){wt.value="Export canceled.",pt.value=!1,ft.value=0,Ot.value=null;return}try{const ae=Qo(Ce()),ke=new Blob([JSON.stringify(ae,null,2)],{type:"application/json"}),$e=URL.createObjectURL(ke),Me=document.createElement("a");Me.href=$e,Me.download=`video-recipe-${Date.now()}.json`,Me.click(),setTimeout(()=>URL.revokeObjectURL($e),100)}finally{pt.value=!1,ft.value=0,Ot.value=null,wt.value=L instanceof Error?L.message:"Export failed"}}}const $s=async V=>{await new Promise(L=>{window.setTimeout(L,V)})},Fs=V=>{if(!V||V.width<=0||V.height<=0)return null;try{return V.toDataURL("image/jpeg",.85)}catch{return null}},qf=V=>{if(!V||typeof V!="object")return null;const ae=V.pixiCanvas;if(ae&&typeof ae=="object"&&"value"in ae){const ke=ae.value;return ke instanceof HTMLCanvasElement?ke:null}return ae instanceof HTMLCanvasElement?ae:null},Yf=V=>{if(!V||typeof V!="object")return null;const L=V.duration;if(typeof L=="number"&&Number.isFinite(L))return L;if(L&&typeof L=="object"&&"value"in L){const ae=L.value;if(typeof ae=="number"&&Number.isFinite(ae))return ae}return null},Qf=V=>{if(!V||typeof V!="object")return null;const ae=V.videoElement;if(ae&&typeof ae=="object"&&"value"in ae){const ke=ae.value;return ke instanceof HTMLVideoElement?ke:null}return ae instanceof HTMLVideoElement?ae:null},qd=V=>typeof V.params=="object"&&V.params!==null?V.params:{},eh=V=>{const L=[];for(const ae of V){const ke=qd(ae),$e=ae.filterId.trim().toLowerCase();if($e==="brightness"){const Ie=(zt(sa(ke,["value","brightness"],0),-1,1)+1)*100;L.push(`brightness(${Ie.toFixed(2)}%)`);continue}if($e==="contrast"){const Me=zt(sa(ke,["value","contrast"],1),.1,4);L.push(`contrast(${(Me*100).toFixed(2)}%)`);continue}if($e==="saturation"||$e==="saturate"){const Me=zt(sa(ke,["value","saturation"],1),0,4);L.push(`saturate(${(Me*100).toFixed(2)}%)`);continue}if($e==="grayscale"){L.push("grayscale(100%)");continue}if($e==="sepia"){L.push("sepia(100%)");continue}if($e==="blur"||$e==="gaussian-blur"||$e==="kawase-blur"){const Me=zt(sa(ke,["value","blur","radius"],0),0,30);Me>.01&&L.push(`blur(${Me.toFixed(2)}px)`);continue}if($e==="adjustment"){const Me=sa(ke,["brightness"],1),Ie=sa(ke,["contrast"],1),xt=sa(ke,["saturation"],1);Math.abs(Me-1)>.01&&L.push(`brightness(${(zt(Me,0,5)*100).toFixed(2)}%)`),Math.abs(Ie-1)>.01&&L.push(`contrast(${(zt(Ie,.1,5)*100).toFixed(2)}%)`),Math.abs(xt-1)>.01&&L.push(`saturate(${(zt(xt,0,5)*100).toFixed(2)}%)`);continue}if($e==="cinematic"){L.push("contrast(120%) brightness(95%) saturate(85%)");continue}if($e==="dramatic"){L.push("contrast(140%) brightness(90%) saturate(110%) sepia(10%)");continue}if($e==="dreamy"){L.push("blur(0.5px) brightness(105%) saturate(90%) contrast(95%)");continue}}return L.join(" ")},th=V=>{const L=V.find($e=>$e.filterId.trim().toLowerCase()==="noise");if(!L)return 0;const ae=qd(L),ke=sa(ae,["noise","value","amount","intensity"],.2);return ke<=1?zt(ke,0,1):zt(ke/100,0,1)},ah=(V,L,ae,ke)=>{if(ke<=0)return;const $e=V.getImageData(0,0,L,ae),Me=255*ke;for(let Ie=0;Ie<$e.data.length;Ie+=4){const xt=(Math.random()*2-1)*Me;$e.data[Ie]=zt($e.data[Ie]+xt,0,255),$e.data[Ie+1]=zt($e.data[Ie+1]+xt,0,255),$e.data[Ie+2]=zt($e.data[Ie+2]+xt,0,255)}V.putImageData($e,0,0)},Yd=async V=>{V.readyState>=2&&V.videoWidth>0&&V.videoHeight>0||await new Promise(L=>{let ae=!1,ke=0;const $e=()=>{ae||(ae=!0,V.removeEventListener("loadedmetadata",Me),V.removeEventListener("loadeddata",Me),V.removeEventListener("canplay",Me),window.clearTimeout(ke),L())},Me=()=>{$e()};V.addEventListener("loadedmetadata",Me),V.addEventListener("loadeddata",Me),V.addEventListener("canplay",Me),ke=window.setTimeout(()=>$e(),800),V.play().catch(()=>{})})},nh=async(V,L)=>{await new Promise(ae=>{let ke=!1,$e=0;const Me=()=>{ke||(ke=!0,V.removeEventListener("seeked",Ie),window.clearTimeout($e),ae())},Ie=()=>{Me()};if(Math.abs(V.currentTime-L)<.016){requestAnimationFrame(()=>Me());return}V.addEventListener("seeked",Ie),$e=window.setTimeout(()=>Me(),700),V.currentTime=L})},Qd=async(V,L)=>{await Yd(V);const ae=Math.floor(V.videoWidth),ke=Math.floor(V.videoHeight);if(ae<=0||ke<=0)return null;const $e=Number.isFinite(V.duration)&&V.duration>0?V.duration:0,Me=$e>0?zt(L,0,$e):0;await nh(V,Me);const Ie=document.createElement("canvas");Ie.width=ae,Ie.height=ke;const xt=Ie.getContext("2d");if(!xt)return null;const Sa=eh(le.value);Sa!==""&&(xt.filter=Sa);try{xt.drawImage(V,0,0,ae,ke)}catch{return null}const Eo=th(le.value);return ah(xt,ae,ke,Eo),Fs(Ie)},oh=async(V,L)=>{const ae=document.createElement("video");ae.src=V,ae.muted=!0,ae.playsInline=!0,ae.preload="auto",V.startsWith("blob:")||(ae.crossOrigin="anonymous");try{return await Yd(ae),await Qd(ae,L)}catch{return null}finally{ae.pause(),ae.removeAttribute("src"),ae.load()}},ih=async V=>{const L=y.value,ae=Fs(qf(L));if(ae)return ae;if(L!=null&&L.captureFrameAt)for(let Me=0;Me<4;Me+=1){const Ie=Yf(L);if(Ie!==null&&Ie<=0&&Me<2){await $s(80);continue}const xt=await Promise.race([L.captureFrameAt(V),$s(450).then(()=>null)]),Sa=Fs(xt);if(Sa)return Sa;await $s(80)}const ke=Qf(L);if(ke){const Me=await Qd(ke,V);if(Me)return Me}const $e=Ne.value.trim();if($e!==""){const Me=await oh($e,V);if(Me)return Me}return null},ec=V=>V.map(L=>({...L,params:L.params&&typeof L.params=="object"?{...L.params}:L.params}));function tc(V){const L=ec(le.value);if(!Ds(V)&&L.length>0&&Array.isArray(V.timeline)&&V.timeline.length>0){const ke=V.timeline[0];ke&&(V.timeline=[{...ke,filters:L},...V.timeline.slice(1)])}return V}const Ds=V=>Array.isArray(V.timeline)?V.timeline.some(L=>Array.isArray(L.filters)&&L.filters.length>0):!1,rh=V=>{if(!V||typeof V!="object")return null;const L=V.posterFrame;if(typeof L!="string")return null;const ae=L.trim();return ae!==""?ae:null};async function Rs(){const V=Qo(tc(lt())),L=ec(le.value),ae=Ds(V)||L.length>0,ke=rh(n.initialRecipe);if(ae){const $e=W.value>0?W.value:.1;try{const Me=await ih($e);Me?V.posterFrame=Me:ke&&(V.posterFrame=ke)}catch{ke&&(V.posterFrame=ke)}}else delete V.posterFrame;return Et(),i("draft-saved",V),V}function ac(){Ee()&&(Ct(),Za())}async function sh(V){kn();const L=nr();_a=window.setInterval(async()=>{try{if(G){kn();return}const ae=await L.getJob(V),ke=Number(ae.progress??0);if(ft.value=Number.isFinite(ke)?ke:0,ae.status==="completed"||ae.status==="failed"||ae.status==="cancelled")if(kn(),pt.value=!1,Ot.value=null,ae.status==="completed")ft.value=100,qt.value=!0,wt.value=null;else{const $e=ae.status==="cancelled"||typeof ae.error_message=="string"&&/cancel/i.test(ae.error_message);wt.value=$e?"Export canceled.":typeof ae.error_message=="string"&&ae.error_message.trim()!==""?ae.error_message:"Export failed"}}catch(ae){kn(),pt.value=!1,Ot.value=null,wt.value=ae instanceof Error?ae.message:"Failed to check export progress"}},2e3)}function As(){const V=Qo(Ce());try{const L=V.timeline??[]}catch{}R.value=V}let Ln=null;function Za(){Ln&&clearTimeout(Ln),Ln=setTimeout(()=>{As(),Ln=null},200)}e.watch(()=>C.value,Za,{deep:!0}),e.watch(()=>de.value,V=>{if(A.value||!V)return;const L=(V==null?void 0:V.filters)??[];Ht(L)},{immediate:!0}),e.watch(()=>le.value,V=>{at(V),Za()},{deep:!0}),e.watch(()=>M.value,V=>{rt(V),Za()},{deep:!0}),e.watch(()=>F.value,V=>{const L=V.map(ae=>({...ae,source:typeof ae.source=="string"?ae.source:void 0}));gt(L),Za()},{deep:!0}),e.watch(()=>W.value,Za),a({saveDraft:Rs,exportForUpload:Kf}),As(),e.onUnmounted(()=>{kn(),G=!0,We.cancelClientExport(),Ln&&(clearTimeout(Ln),Ln=null),b.value&&(b.value.destroy(),b.value=null),T.value=null,S.value=null,B.value=null});function lh(){ra||!Ho.value||(ra=new F2({filters:De.value,callbacks:{onApplyFilter:V=>{X(V.id)},onRemoveFilter:V=>{te(V)},onUpdateParam:(V,L,ae)=>{fo(V,L,ae)},onPreviewFilter:V=>{ot(V.id)}}}),ra.mount(Ho.value),ra.setActiveFilters(J.value))}e.watch(J,V=>{ra==null||ra.setActiveFilters(V)},{deep:!0}),e.watch(De,V=>{ra==null||ra.setFilters(V)});let _n=null;return e.onMounted(()=>{window.addEventListener("resize",O),window.addEventListener("keydown",wn);const V=()=>{!vn.value||_n||(_n=new ResizeObserver(L=>{L[0]&&(po.value=Math.round(L[0].contentRect.width))}),_n.observe(vn.value))};V(),_n||e.nextTick(V),l.value&&(Yo(),Ta||e.nextTick(Yo)),n.media&&As(),l.value&&e.nextTick(()=>{lh()}),e.nextTick(()=>{const L=document.querySelector(".video-editor");L&&L.getBoundingClientRect();const ae=document.querySelector(".mobile-layout");ae&&ae.getBoundingClientRect()})}),e.onUnmounted(()=>{window.removeEventListener("resize",O),window.removeEventListener("keydown",wn),_n==null||_n.disconnect(),_n=null,Ta==null||Ta(),Ta=null,ra==null||ra.destroy(),ra=null}),(V,L)=>{var ae,ke,$e,Me;return e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-editor",{mobile:l.value}])},[l.value?(e.openBlock(),e.createElementBlock("div",ax,[e.createElementVNode("div",nx,[e.createElementVNode("div",ox,[e.createElementVNode("button",{class:e.normalizeClass(["mobile-toolbar-btn",{active:e.unref(ne)}]),onClick:L[0]||(L[0]=(...Ie)=>e.unref(Ze)&&e.unref(Ze)(...Ie)),"aria-label":e.unref(ne)?"Pause":"Play","data-testid":"btn-mobile-play"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(ne)?e.unref(ed):e.unref(td)},null,8,["icon"])],10,ix),e.createElementVNode("button",{class:"mobile-toolbar-btn",onClick:ac,"aria-label":"Reset all changes","data-testid":"btn-mobile-reset"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(io)},null,8,["icon"])])]),e.createElementVNode("div",rx,[e.createElementVNode("button",{class:"mobile-toolbar-btn mobile-toolbar-save",onClick:Rs,"aria-label":"Save","data-testid":"btn-mobile-save",disabled:!e.unref(j)},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Qr)},null,8,["icon"]),L[13]||(L[13]=e.createElementVNode("span",null,"Save",-1))],8,sx),e.createElementVNode("button",{class:"mobile-toolbar-btn",onClick:L[1]||(L[1]=Ie=>Jd()),"aria-label":"Export","data-testid":"btn-mobile-export",disabled:pt.value||!e.unref(j)},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref($o)},null,8,["icon"])],8,lx),e.createElementVNode("button",{class:"mobile-toolbar-btn",onClick:L[2]||(L[2]=Ie=>i("close")),"aria-label":"Close","data-testid":"btn-mobile-close"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Yn)},null,8,["icon"])])])]),e.createElementVNode("div",dx,[e.withDirectives(e.createVNode(ul,{ref_key:"pixiPreviewMobileRef",ref:h,"aria-hidden":!f.value,class:"preview-host-child",source:Ne.value,"fallback-duration":va.value,filters:He.value,playhead:ut.value,"is-playing":e.unref(ne),"fit-mode":N.value,active:f.value,onPlayPause:e.unref(Ze),onFrameUpdate:ja,onDurationChange:ho},null,8,["aria-hidden","source","fallback-duration","filters","playhead","is-playing","fit-mode","active","onPlayPause"]),[[e.vShow,f.value]]),e.withDirectives(e.createVNode(Vl,{"aria-hidden":!p.value,class:"preview-host-child","media-uuid":s.value,recipe:R.value,media:st.value,"enable-engine":p.value&&Ye.value,"fit-mode":N.value,onTimeUpdate:Fn,onPlayStateChange:Go,onDurationChange:ho,onEngineReady:Yi},null,8,["aria-hidden","media-uuid","recipe","media","enable-engine","fit-mode"]),[[e.vShow,p.value]]),pt.value?(e.openBlock(),e.createElementBlock("div",cx,[e.createElementVNode("div",ux,[e.createElementVNode("span",null,"Exporting "+e.toDisplayString(ft.value)+"%",1),e.createElementVNode("div",mx,[e.createElementVNode("div",{class:"mobile-export-bar-fill",style:e.normalizeStyle({width:ft.value+"%"})},null,4)]),e.createElementVNode("button",{class:"mobile-export-cancel",onClick:Kd},"Cancel")])])):e.createCommentVNode("",!0)]),e.createElementVNode("div",{ref_key:"timelineContainerRef",ref:vn,class:"timeline-section"},[e.createElementVNode("div",px,[e.createElementVNode("button",{ref_key:"mobileZoomOutButtonRef",ref:Zo,type:"button",class:"mobile-zoom-btn","aria-label":"Zoom out timeline","data-testid":"btn-timeline-zoom-out"},[...L[14]||(L[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:gn,type:"button",class:"mobile-zoom-btn","aria-label":"Zoom in timeline","data-testid":"btn-timeline-zoom-in"},[...L[15]||(L[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(Nl,{playhead:e.unref(W),clips:e.unref(C),"selected-clip-id":((ae=e.unref(de))==null?void 0:ae.id)??((ke=e.unref(C)[0])==null?void 0:ke.id)??null,duration:va.value,fps:e.unref(_e),"zoom-level":e.unref(Ke),"snap-enabled":It.value,sensitivity:.25,"is-mobile":!0,"onUpdate:playhead":e.unref(ct),onTrim:e.unref(ve),onSplit:Ko,onClipSelect:Xo,onClipMove:e.unref(Ve),onClipLongPress:Ki,onSnapStateChange:Dn},null,8,["playhead","clips","selected-clip-id","duration","fps","zoom-level","snap-enabled","onUpdate:playhead","onTrim","onClipMove"])],512),e.createElementVNode("div",fx,[e.createElementVNode("div",hx,[e.createElementVNode("span",vx,e.toDisplayString(Mn.value),1),e.createElementVNode("span",gx,e.toDisplayString(uo.value),1)]),e.createElementVNode("div",bx,[e.createElementVNode("button",{type:"button",class:"mobile-cut-nav-btn","data-testid":"btn-mobile-prev-cut","aria-label":"Jump to previous cut",disabled:!co.value,onClick:Ha}," Prev Cut ",8,yx),e.createElementVNode("div",wx,[e.createElementVNode("span",kx,"Playhead "+e.toDisplayString(mo.value),1),e.createElementVNode("span",_x,"In "+e.toDisplayString(hn.value),1),e.createElementVNode("span",Ex,"Out "+e.toDisplayString(Oa.value),1),e.createElementVNode("span",Sx,"Duration "+e.toDisplayString(Ts.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:!Da.value,onClick:Ji}," Next Cut ",8,Cx)]),e.createElementVNode("div",xx,[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["mobile-snap-toggle",{active:It.value}]),"data-testid":"btn-mobile-snap-toggle",onClick:vo},e.toDisplayString(It.value?"Snap On":"Snap Off"),3),e.createElementVNode("div",Vx,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(Pa,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:xt=>An(Ie)},e.toDisplayString(Ie)+"x ",11,Nx)),64))])]),e.createElementVNode("div",Tx,[e.createElementVNode("button",{type:"button",class:"mobile-edit-btn","data-testid":"btn-mobile-undo","aria-label":"Undo",disabled:!e.unref(Q),onClick:go}," Undo ",8,Bx),e.createElementVNode("button",{type:"button",class:"mobile-edit-btn","data-testid":"btn-mobile-redo","aria-label":"Redo",disabled:!e.unref(he),onClick:bo}," Redo ",8,Mx),e.createElementVNode("button",{type:"button",class:"mobile-edit-btn","data-testid":"btn-mobile-split","aria-label":"Split at playhead",disabled:!ht.value,onClick:yn}," Split ",8,Ix),e.createElementVNode("button",{type:"button",class:"mobile-edit-btn","data-testid":"btn-mobile-duplicate","aria-label":"Duplicate selected clip",disabled:!Yt.value,onClick:Rn}," Duplicate ",8,$x),e.createElementVNode("button",{type:"button",class:"mobile-edit-btn mobile-edit-btn--danger","data-testid":"btn-mobile-delete","aria-label":"Delete selected clip",disabled:!tt.value,onClick:yo}," Delete ",8,Fx)])]),e.createElementVNode("div",{ref_key:"mobileControlsRef",ref:Ho,class:"controls-section mobile-controls"},null,512),on.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"mobile-action-sheet-backdrop","data-testid":"video-mobile-action-sheet",onClick:Wa},[e.createElementVNode("div",{class:"mobile-action-sheet",onClick:L[3]||(L[3]=e.withModifiers(()=>{},["stop"]))},[L[16]||(L[16]=e.createElementVNode("div",{class:"mobile-action-sheet-handle"},null,-1)),e.createElementVNode("div",Dx,[e.createElementVNode("span",Rx,e.toDisplayString(Bs.value),1),e.createElementVNode("span",Ax,e.toDisplayString(Ms.value),1)]),e.createElementVNode("div",Lx,[e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-undo",disabled:!e.unref(Q),onClick:go},"Undo",8,Px),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-redo",disabled:!e.unref(he),onClick:bo},"Redo",8,Ux),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-split",disabled:!ht.value,onClick:yn},"Split",8,Ox),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-duplicate",disabled:!Yt.value,onClick:Rn},"Duplicate",8,zx),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn mobile-action-sheet-btn--danger","data-testid":"btn-mobile-sheet-delete",disabled:!tt.value,onClick:yo},"Delete",8,jx),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-close",onClick:Wa},"Close")])])])):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("div",Wx,[e.createElementVNode("div",Hx,[e.createElementVNode("div",Zx,[e.createElementVNode("div",Gx,[e.createElementVNode("label",null,[e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":L[4]||(L[4]=Ie=>N.value=Ie),"aria-label":"Fit mode","data-testid":"select-video-fit-mode"},[...L[17]||(L[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,N.value]])])]),e.withDirectives(e.createVNode(ul,{ref_key:"pixiPreviewDesktopRef",ref:v,"aria-hidden":!f.value,class:"preview-host-child",source:Ne.value,"fallback-duration":va.value,filters:He.value,playhead:ut.value,"is-playing":e.unref(ne),"fit-mode":N.value,active:f.value,onPlayPause:e.unref(Ze),onFrameUpdate:ja,onDurationChange:ho},null,8,["aria-hidden","source","fallback-duration","filters","playhead","is-playing","fit-mode","active","onPlayPause"]),[[e.vShow,f.value]]),e.withDirectives(e.createVNode(Vl,{"aria-hidden":!p.value,class:"preview-host-child","media-uuid":s.value,recipe:R.value,media:st.value,"enable-engine":p.value&&Ye.value,"fit-mode":N.value,onTimeUpdate:Fn,onPlayStateChange:Go,onDurationChange:ho,onEngineReady:Yi},null,8,["aria-hidden","media-uuid","recipe","media","enable-engine","fit-mode"]),[[e.vShow,p.value]]),V.showThumbnailPicker?(e.openBlock(),e.createBlock(u_,{key:0,"media-uuid":s.value,duration:va.value,onSelect:_o},null,8,["media-uuid","duration"])):e.createCommentVNode("",!0)]),e.createElementVNode("div",Xx,[e.createElementVNode("div",Kx,[e.createElementVNode("div",Jx,[(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:xt=>c.value=Ie.id},e.toDisplayString(Ie.label),11,qx))),128))]),e.createElementVNode("div",Yx,[e.withDirectives(e.createElementVNode("div",Qx,[e.createVNode(Bl,{filters:De.value,"active-filters":J.value,"thumbnail-url":me.value,onApplyFilter:X,onRemoveFilter:te,onUpdateParam:fo,onPreviewFilter:Qi},null,8,["filters","active-filters","thumbnail-url"])],512),[[e.vShow,c.value==="filters"]]),e.withDirectives(e.createElementVNode("div",eV,[e.createVNode($l,{overlays:M.value,onAddOverlay:tr,onUpdateOverlay:ar,onRemoveOverlay:_},null,8,["overlays"])],512),[[e.vShow,c.value==="text"]]),e.withDirectives(e.createElementVNode("div",tV,[e.createVNode(Fl,{"selected-clips":P.value,"applied-transitions":w.value,onApplyTransition:$,onRemoveTransition:Y,onPreviewTransition:we},null,8,["selected-clips","applied-transitions"])],512),[[e.vShow,c.value==="transitions"]]),e.withDirectives(e.createElementVNode("div",aV,[e.createVNode(Dl,{"audio-layers":F.value,"master-volume":D.value,onAddTrack:Pe,onUpdateTrack:Ue,onRemoveTrack:dt,onUpdateVolume:Nt,onToggleMute:Zt,onUpdateMasterVolume:ma},null,8,["audio-layers","master-volume"])],512),[[e.vShow,c.value==="audio"]]),e.withDirectives(e.createElementVNode("div",nV,[e.unref(Te)?(e.openBlock(),e.createBlock(Ml,{key:0,filter:e.unref(Te),"current-frame":e.unref(ie),onUpdateParams:er},null,8,["filter","current-frame"])):(e.openBlock(),e.createElementBlock("div",oV,[...L[18]||(L[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",iV,[e.createVNode(Il,{"can-export":e.unref(j),"is-exporting":pt.value,"export-progress":ft.value,onExport:Jd,onCancelExport:Kd,onSaveDraft:Rs,onReset:ac},null,8,["can-export","is-exporting","export-progress"]),qt.value?(e.openBlock(),e.createElementBlock("div",rV," Export complete ")):e.createCommentVNode("",!0),wt.value&&!qt.value?(e.openBlock(),e.createElementBlock("div",sV,e.toDisplayString(wt.value),1)):e.createCommentVNode("",!0)],512),[[e.vShow,c.value==="export"]])])])])]),e.createElementVNode("div",lV,[e.createElementVNode("div",{ref_key:"timelineContainerRef",ref:vn,class:"timeline-container"},[e.createElementVNode("div",dV,[e.createElementVNode("label",null,[L[19]||(L[19]=e.createTextVNode(" Zoom ",-1)),e.createElementVNode("input",{type:"range",min:"10",max:"600",value:e.unref(Ke),onInput:L[5]||(L[5]=Ie=>ko(Ie))},null,40,cV)]),e.createElementVNode("span",uV,e.toDisplayString(Math.round(e.unref(Ke)))+" px/s",1),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["desktop-snap-toggle",{active:It.value}]),"data-testid":"btn-desktop-snap-toggle",onClick:vo},e.toDisplayString(It.value?"Snap On":"Snap Off"),3)]),e.createVNode(Nl,{playhead:e.unref(W),clips:e.unref(C),"selected-clip-id":(($e=e.unref(de))==null?void 0:$e.id)??((Me=e.unref(C)[0])==null?void 0:Me.id)??null,duration:va.value,fps:e.unref(_e),"zoom-level":e.unref(Ke),"snap-enabled":It.value,sensitivity:.25,"onUpdate:playhead":e.unref(ct),onTrim:e.unref(ve),onSplit:Ko,onClipSelect:Xo,onClipMove:e.unref(Ve),onClipLongPress:Ki,onSnapStateChange:Dn},null,8,["playhead","clips","selected-clip-id","duration","fps","zoom-level","snap-enabled","onUpdate:playhead","onTrim","onClipMove"]),e.createVNode(Tl,{"selected-clip":e.unref(de),"can-split":ht.value,"can-delete":tt.value,"is-playing":e.unref(ne),"zoom-level":e.unref(Ke),"playback-speed":e.unref(be),onSplit:yn,onDelete:yo,onDuplicate:Rn,onZoomIn:Zd,onZoomOut:Gd,onZoomChange:Jo,onFitToWindow:qi,onPlayPause:e.unref(Ze),onFrameForward:e.unref(At),onFrameBackward:e.unref($t),onSkipToStart:e.unref(Pt),onSkipToEnd:e.unref(Ut),onSpeedChange:e.unref(ea)},null,8,["selected-clip","can-split","can-delete","is-playing","zoom-level","playback-speed","onPlayPause","onFrameForward","onFrameBackward","onSkipToStart","onSkipToEnd","onSpeedChange"]),Be.value?(e.openBlock(),e.createElementBlock("div",mV,[e.createElementVNode("div",pV,[e.createElementVNode("label",fV,[L[20]||(L[20]=e.createElementVNode("span",null,"Trim start (s)",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":L[6]||(L[6]=Ie=>Tt.value=Ie),type:"number",step:"0.01",min:"0",inputmode:"decimal","data-testid":"video-dev-trim-start"},null,512),[[e.vModelText,Tt.value]])]),e.createElementVNode("label",hV,[L[21]||(L[21]=e.createElementVNode("span",null,"Trim end (s)",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":L[7]||(L[7]=Ie=>Dt.value=Ie),type:"number",step:"0.01",min:"0",inputmode:"decimal","data-testid":"video-dev-trim-end"},null,512),[[e.vModelText,Dt.value]])]),e.createElementVNode("button",{class:"dev-editor-button",type:"button","data-testid":"video-dev-trim-start-playhead",disabled:!e.unref(de),onClick:L[8]||(L[8]=Ie=>bn("start"))}," Start = Playhead ",8,vV),e.createElementVNode("button",{class:"dev-editor-button",type:"button","data-testid":"video-dev-trim-end-playhead",disabled:!e.unref(de),onClick:L[9]||(L[9]=Ie=>bn("end"))}," End = Playhead ",8,gV),e.createElementVNode("button",{class:"dev-editor-button dev-editor-button--primary",type:"button","data-testid":"video-dev-apply-trim",disabled:!e.unref(de),onClick:za}," Apply Trim ",8,bV)]),e.createElementVNode("div",yV,[e.createElementVNode("label",wV,[L[22]||(L[22]=e.createElementVNode("span",null,"Quick filter",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":L[10]||(L[10]=Ie=>Bt.value=Ie),"data-testid":"video-dev-filter-select"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(De.value,Ie=>(e.openBlock(),e.createElementBlock("option",{key:Ie.id,value:Ie.id},e.toDisplayString(Ie.name),9,kV))),128))],512),[[e.vModelSelect,Bt.value]])]),e.createElementVNode("button",{class:"dev-editor-button dev-editor-button--primary",type:"button","data-testid":"video-dev-apply-filter",disabled:!e.unref(de)||Bt.value==="",onClick:Lt}," Apply Filter ",8,_V),e.createElementVNode("button",{class:"dev-editor-button",type:"button","data-testid":"video-dev-clear-filters",disabled:e.unref(le).length===0,onClick:ln}," Clear Filters ",8,EV),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(de),onClick:L[11]||(L[11]=Ie=>X("noise"))}," QA: Noise ",8,SV),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(de),onClick:L[12]||(L[12]=Ie=>X("grayscale"))}," QA: Grayscale ",8,CV)])])):e.createCommentVNode("",!0)],512)])]))],2)}}}),Yp=Fe(xV,[["__scopeId","data-v-1bb4247b"]]),VV={key:0,class:"video-editor-v2-toolbar"},NV={class:"video-editor-v2-body"},TV={key:0,class:"video-editor-v2-assets","data-testid":"v2-assets-panel"},BV={class:"video-editor-v2-main"},MV={class:"video-editor-v2-canvas"},IV={key:1,class:"video-editor-v2-timeline"},$V=["aria-expanded"],FV=["aria-hidden","inert"],DV="(max-width: 900px)",RV=e.defineComponent({__name:"SplitPanelLayout",setup(o,{expose:a}){const t=e.ref(!1),n=e.ref(!1);let i=null,r=null;const s=c=>{t.value=c,c&&(n.value=!1)},l=()=>{n.value=!0},d=()=>{n.value=!1};return e.onMounted(()=>{typeof window>"u"||!window.matchMedia||(i=window.matchMedia(DV),s(i.matches),r=c=>s(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",VV,[e.renderSlot(c.$slots,"toolbar",{},void 0,!0)])):e.createCommentVNode("",!0),e.createElementVNode("div",NV,[!t.value&&c.$slots.assets?(e.openBlock(),e.createElementBlock("aside",TV,[e.renderSlot(c.$slots,"assets",{},void 0,!0)])):e.createCommentVNode("",!0),e.createElementVNode("div",BV,[e.createElementVNode("div",MV,[e.renderSlot(c.$slots,"canvas",{},void 0,!0)])])]),c.$slots.timeline?(e.openBlock(),e.createElementBlock("div",IV,[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:l}," Tools ",8,$V)),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,FV)],64)):e.createCommentVNode("",!0),t.value?e.renderSlot(c.$slots,"drawer",{key:3},void 0,!0):e.createCommentVNode("",!0)],2))}}),AV=Fe(RV,[["__scopeId","data-v-ed83bde0"]]),LV=["aria-selected"],PV={class:"asset-rail-item__main"},UV={class:"asset-rail-item__type","data-testid":"asset-rail-item-type"},OV={class:"asset-rail-item__label","data-testid":"asset-rail-item-label"},zV={key:0,class:"asset-rail-item__details","data-testid":"asset-rail-item-details"},jV={class:"asset-rail-item__actions","aria-label":"Asset actions"},WV=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")}`}),s=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)}`),l=e.computed(()=>[r.value,s.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",PV,[e.createElementVNode("span",UV,e.toDisplayString(c.source.type),1),e.createElementVNode("span",OV,e.toDisplayString(i.value),1),l.value.length>0?(e.openBlock(),e.createElementBlock("span",zV,e.toDisplayString(l.value.join(" / ")),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",jV,[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,LV))}}),HV=Fe(WV,[["__scopeId","data-v-3ba2fd25"]]),ZV={class:"asset-rail__header"},GV={key:0,class:"asset-rail__list","data-testid":"asset-rail-list"},XV={key:1,class:"asset-rail__empty","data-testid":"asset-rail-empty"},KV=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,f)=>{if(m==="add"){t("add",f);return}if(m==="replaceSelected"){t("replaceSelected",f);return}t("remove",f)},s=()=>{var m;(m=n.value)==null||m.click()},l=m=>{const f=m.target;if(!(f!=null&&f.files)||f.files.length===0)return;const p=Array.from(f.files);t("importFiles",p),f.value=""},d=m=>{m.preventDefault(),m.dataTransfer&&(m.dataTransfer.dropEffect="copy"),i.value=!0},c=()=>{i.value=!1},u=m=>{var p;m.preventDefault(),i.value=!1;const f=Array.from(((p=m.dataTransfer)==null?void 0:p.files)??[]);f.length!==0&&t("importFiles",f)};return(m,f)=>(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",ZV,[f[3]||(f[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:s}," 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:l},null,544)):e.createCommentVNode("",!0)]),m.sources.length>0?(e.openBlock(),e.createElementBlock("div",GV,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(m.sources,p=>(e.openBlock(),e.createBlock(HV,{key:p.id,source:p,selected:p.id===m.selectedSourceId,onAdd:f[0]||(f[0]=h=>r("add",h)),onReplaceSelected:f[1]||(f[1]=h=>r("replaceSelected",h)),onRemove:f[2]||(f[2]=h=>r("remove",h))},null,8,["source","selected"]))),128))])):(e.openBlock(),e.createElementBlock("p",XV,e.toDisplayString(m.uploadsEnabled?"Drop files here or click Upload to add media.":"No assets"),1))],34))}}),JV=Fe(KV,[["__scopeId","data-v-3db665c6"]]),qV={class:"audio-mixer-panel__tracks","data-testid":"audio-mixer-tracks"},YV={key:0,class:"audio-mixer-panel__empty","data-testid":"audio-mixer-empty"},QV=["data-testid"],eN={class:"audio-mixer-strip__header"},tN={class:"audio-mixer-strip__identity"},aN={class:"audio-mixer-strip__kind"},nN=["data-testid"],oN=["data-testid"],iN=["data-testid"],rN={class:"audio-mixer-meter__rail","aria-hidden":"true"},sN={class:"audio-mixer-meter__value"},lN={class:"audio-mixer-strip__controls"},dN=["for"],cN=["id","min","max","value","data-testid","onInput"],uN={class:"audio-mixer-control__value"},mN={class:"audio-mixer-buttons"},pN=["aria-pressed","aria-label","data-testid","onClick"],fN=["aria-pressed","aria-label","data-testid","onClick"],hN=["for"],vN=["id","value","data-testid","onInput"],gN={class:"audio-mixer-control__value"},bN=["data-testid"],yN={key:0},wN={key:1},kN=["data-testid"],_N=["data-testid"],EN=["data-testid"],SN={class:"audio-mixer-routing__target"},CN={class:"audio-mixer-strip__header"},xN={class:"audio-mixer-strip__identity"},VN={class:"audio-mixer-strip__name","data-testid":"audio-mixer-master-name"},NN={class:"audio-mixer-meter__rail","aria-hidden":"true"},TN={class:"audio-mixer-meter__value"},BN={class:"audio-mixer-strip__controls"},MN={key:0,class:"audio-mixer-control audio-mixer-control--fader",for:"audio-mixer-master-fader"},IN=["min","max","value"],$N={class:"audio-mixer-control__value"},FN={class:"audio-mixer-buttons"},DN=["aria-pressed","aria-label"],RN={key:1,class:"audio-mixer-effects","data-testid":"audio-mixer-master-effects"},AN=["data-testid"],LN=e.defineComponent({__name:"AudioMixerPanel",props:{state:{},deviceClass:{}},emits:["update"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>pE(t.deviceClass,t.state.capabilities)),r=e.computed(()=>t.deviceClass==="desktop"),s=e.computed(()=>[...t.state.tracks].sort((D,O)=>D.order-O.order)),l=e.computed(()=>{const D=new Map(fE(s.value,t.state.master.muted).map(O=>[O.trackId,O]));return s.value.map(O=>({track:O,effectiveState:D.get(O.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),f=e.computed(()=>r.value&&i.value.canAdjustPan),p=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),E=D=>{if(!(D.target instanceof HTMLInputElement))return null;const O=Number(D.target.value);return Number.isFinite(O)?O:null},y=(D,O)=>{if(!d.value)return;const I=E(O);I!==null&&n("update",{type:"track-fader-db",trackId:D.id,valueDb:Ii(I)})},k=D=>{u.value&&n("update",{type:"track-mute",trackId:D.id,muted:!D.controls.muted})},g=D=>{m.value&&n("update",{type:"track-solo",trackId:D.id,solo:!D.controls.solo})},b=(D,O)=>{if(!f.value)return;const I=E(O);I!==null&&n("update",{type:"track-pan",trackId:D.id,pan:up(I)})},R=D=>{if(!c.value)return;const O=E(D);O!==null&&n("update",{type:"master-fader-db",valueDb:Ii(O)})},N=D=>{u.value&&n("update",{type:"master-mute",muted:!D.muted})},T=D=>{const O=Math.round(D*10)/10;return O>0?`+${O.toFixed(O%1===0?0:1)} dB`:`${O.toFixed(O%1===0?0:1)} dB`},S=D=>D===0?"C":`${D<0?"L":"R"} ${Math.round(Math.abs(D)*100)}`,B=D=>{if(D===void 0)return"";const O=Math.round(D*10)/10;return`${O.toFixed(O%1===0?0:1)}s`},A=D=>T(D),x=D=>{if(!Number.isFinite(D))return 0;const O=Math.min(jr,Math.max(Nn,D)),I=jr-Nn;return Math.round((O-Nn)/I*100)},M=D=>D.slice(0,i.value.maxEffectSlots),w=D=>h.value&&M(D).length>0,F=D=>D.timeline.fadeIn!==void 0||D.timeline.fadeOut!==void 0,P=D=>D===null?"Unknown":D.mutedByMaster?"Master muted":D.mutedByTrack?"Muted":D.mutedBySolo?"Muted by solo":D.soloed?"Solo active":"Audible";return(D,O)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["audio-mixer-panel",`audio-mixer-panel--${D.deviceClass}`]),"data-testid":"audio-mixer-panel","aria-label":"Audio mixer"},[e.createElementVNode("div",qV,[l.value.length===0?(e.openBlock(),e.createElementBlock("p",YV," No audio tracks ")):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(l.value,({track:I,effectiveState:Z})=>(e.openBlock(),e.createElementBlock("article",{key:I.id,class:e.normalizeClass(["audio-mixer-strip",{"is-muted":(Z==null?void 0:Z.effectivelyMuted)===!0,"is-soloed":I.controls.solo}]),"data-testid":`audio-mixer-track-${I.id}`},[e.createElementVNode("header",eN,[e.createElementVNode("div",tN,[e.createElementVNode("span",aN,e.toDisplayString(I.kind),1),e.createElementVNode("h3",{class:"audio-mixer-strip__name","data-testid":`audio-mixer-track-name-${I.id}`},e.toDisplayString(I.name),9,nN)]),e.createElementVNode("span",{class:e.normalizeClass(["audio-mixer-strip__status",{"is-active":(Z==null?void 0:Z.audible)===!0}]),"data-testid":`audio-mixer-track-status-${I.id}`},e.toDisplayString(P(Z)),11,oN)]),p.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:e.normalizeClass(["audio-mixer-meter",{"is-clipping":I.controls.meter.clipping}]),"data-testid":`audio-mixer-track-meter-${I.id}`,"aria-label":"Track meter"},[e.createElementVNode("span",rN,[e.createElementVNode("span",{class:"audio-mixer-meter__fill",style:e.normalizeStyle({width:`${x(I.controls.meter.peakDb)}%`})},null,4)]),e.createElementVNode("span",sN,e.toDisplayString(A(I.controls.meter.peakDb)),1)],10,iN)):e.createCommentVNode("",!0),e.createElementVNode("div",lN,[d.value?(e.openBlock(),e.createElementBlock("label",{key:0,class:"audio-mixer-control audio-mixer-control--fader",for:`audio-mixer-track-fader-${I.id}`},[O[2]||(O[2]=e.createElementVNode("span",{class:"audio-mixer-control__label"},"Level",-1)),e.createElementVNode("input",{id:`audio-mixer-track-fader-${I.id}`,type:"range",class:"audio-mixer-control__range",min:I.controls.fader.minDb,max:I.controls.fader.maxDb,value:I.controls.fader.valueDb,step:"0.5","data-testid":`audio-mixer-track-fader-${I.id}`,onInput:z=>y(I,z)},null,40,cN),e.createElementVNode("span",uN,e.toDisplayString(T(I.controls.fader.valueDb)),1)],8,dN)):e.createCommentVNode("",!0),e.createElementVNode("div",mN,[u.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:e.normalizeClass(["audio-mixer-button",{"is-active":I.controls.muted}]),"aria-pressed":I.controls.muted?"true":"false","aria-label":I.controls.muted?`Unmute ${I.name}`:`Mute ${I.name}`,"data-testid":`audio-mixer-track-mute-${I.id}`,onClick:z=>k(I)}," M ",10,pN)):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":I.controls.solo}]),"aria-pressed":I.controls.solo?"true":"false","aria-label":I.controls.solo?`Clear solo on ${I.name}`:`Solo ${I.name}`,"data-testid":`audio-mixer-track-solo-${I.id}`,onClick:z=>g(I)}," S ",10,fN)):e.createCommentVNode("",!0)])]),f.value?(e.openBlock(),e.createElementBlock("label",{key:1,class:"audio-mixer-control audio-mixer-control--pan",for:`audio-mixer-track-pan-${I.id}`},[O[3]||(O[3]=e.createElementVNode("span",{class:"audio-mixer-control__label"},"Pan",-1)),e.createElementVNode("input",{id:`audio-mixer-track-pan-${I.id}`,type:"range",class:"audio-mixer-control__range",min:"-1",max:"1",step:"0.01",value:I.controls.pan.value,"data-testid":`audio-mixer-track-pan-${I.id}`,onInput:z=>b(I,z)},null,40,vN),e.createElementVNode("span",gN,e.toDisplayString(S(I.controls.pan.value)),1)],8,hN)):e.createCommentVNode("",!0),F(I)?(e.openBlock(),e.createElementBlock("div",{key:2,class:"audio-mixer-strip__fades","data-testid":`audio-mixer-track-fades-${I.id}`},[I.timeline.fadeIn!==void 0?(e.openBlock(),e.createElementBlock("span",yN," In "+e.toDisplayString(B(I.timeline.fadeIn)),1)):e.createCommentVNode("",!0),I.timeline.fadeOut!==void 0?(e.openBlock(),e.createElementBlock("span",wN," Out "+e.toDisplayString(B(I.timeline.fadeOut)),1)):e.createCommentVNode("",!0)],8,bN)):e.createCommentVNode("",!0),w(I.effectSlots)?(e.openBlock(),e.createElementBlock("div",{key:3,class:"audio-mixer-effects","data-testid":`audio-mixer-track-effects-${I.id}`},[O[4]||(O[4]=e.createElementVNode("span",{class:"audio-mixer-effects__label"},"FX",-1)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(M(I.effectSlots),z=>(e.openBlock(),e.createElementBlock("span",{key:z.id,class:e.normalizeClass(["audio-mixer-effect",{"is-empty":z.kind==="empty","is-bypassed":z.bypassed,"is-enabled":z.enabled&&!z.bypassed}]),"data-testid":`audio-mixer-track-effect-${I.id}-${z.index}`},e.toDisplayString(z.label),11,_N))),128))],8,kN)):e.createCommentVNode("",!0),v.value?(e.openBlock(),e.createElementBlock("div",{key:4,class:"audio-mixer-routing","data-testid":`audio-mixer-track-routing-${I.id}`},[O[5]||(O[5]=e.createElementVNode("span",{class:"audio-mixer-routing__label"},"Route",-1)),e.createElementVNode("span",SN,e.toDisplayString(D.state.master.name),1)],8,EN)):e.createCommentVNode("",!0)],10,QV))),128))]),e.createElementVNode("article",{class:e.normalizeClass(["audio-mixer-strip audio-mixer-strip--master",{"is-muted":D.state.master.muted}]),"data-testid":"audio-mixer-master-strip"},[e.createElementVNode("header",CN,[e.createElementVNode("div",xN,[O[6]||(O[6]=e.createElementVNode("span",{class:"audio-mixer-strip__kind"},"master",-1)),e.createElementVNode("h3",VN,e.toDisplayString(D.state.master.name),1)]),e.createElementVNode("span",{class:e.normalizeClass(["audio-mixer-strip__status",{"is-active":!D.state.master.muted}]),"data-testid":"audio-mixer-master-status"},e.toDisplayString(D.state.master.muted?"Muted":"Active"),3)]),p.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:e.normalizeClass(["audio-mixer-meter",{"is-clipping":D.state.master.meter.clipping}]),"data-testid":"audio-mixer-master-meter","aria-label":"Master meter"},[e.createElementVNode("span",NN,[e.createElementVNode("span",{class:"audio-mixer-meter__fill",style:e.normalizeStyle({width:`${x(D.state.master.meter.peakDb)}%`})},null,4)]),e.createElementVNode("span",TN,e.toDisplayString(A(D.state.master.meter.peakDb)),1)],2)):e.createCommentVNode("",!0),e.createElementVNode("div",BN,[c.value?(e.openBlock(),e.createElementBlock("label",MN,[O[7]||(O[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:D.state.master.fader.minDb,max:D.state.master.fader.maxDb,value:D.state.master.fader.valueDb,step:"0.5","data-testid":"audio-mixer-master-fader",onInput:O[0]||(O[0]=I=>R(I))},null,40,IN),e.createElementVNode("span",$N,e.toDisplayString(T(D.state.master.fader.valueDb)),1)])):e.createCommentVNode("",!0),e.createElementVNode("div",FN,[u.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:e.normalizeClass(["audio-mixer-button",{"is-active":D.state.master.muted}]),"aria-pressed":D.state.master.muted?"true":"false","aria-label":D.state.master.muted?`Unmute ${D.state.master.name}`:`Mute ${D.state.master.name}`,"data-testid":"audio-mixer-master-mute",onClick:O[1]||(O[1]=I=>N(D.state.master))}," M ",10,DN)):e.createCommentVNode("",!0)])]),w(D.state.master.effectSlots)?(e.openBlock(),e.createElementBlock("div",RN,[O[8]||(O[8]=e.createElementVNode("span",{class:"audio-mixer-effects__label"},"FX",-1)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(M(D.state.master.effectSlots),I=>(e.openBlock(),e.createElementBlock("span",{key:I.id,class:e.normalizeClass(["audio-mixer-effect",{"is-empty":I.kind==="empty","is-bypassed":I.bypassed,"is-enabled":I.enabled&&!I.bypassed}]),"data-testid":`audio-mixer-master-effect-${I.index}`},e.toDisplayString(I.label),11,AN))),128))])):e.createCommentVNode("",!0)],2)],2))}}),hu=Fe(LN,[["__scopeId","data-v-e5c785e8"]]),PN={class:"caption-srt-panel__header"},UN={class:"caption-srt-panel__title-group"},ON={class:"caption-srt-panel__title"},zN=["id"],jN={key:0,class:"caption-srt-panel__stats","data-testid":"caption-srt-desktop-stats"},WN={key:0,class:"caption-srt-panel__desktop-controls","data-testid":"caption-srt-desktop-controls"},HN={class:"caption-srt-panel__field"},ZN={class:"caption-srt-panel__field"},GN=["for"],XN=["id","aria-describedby","aria-invalid"],KN=["id"],JN=["id"],qN={key:3,class:"caption-srt-panel__cue-summary","data-testid":"caption-srt-cue-summary","aria-label":"Current caption cue summary"},YN={key:0,class:"caption-srt-panel__cue-list"},QN={class:"caption-srt-panel__cue-time"},eT={class:"caption-srt-panel__cue-text"},tT={key:1,class:"caption-srt-panel__empty"},aT=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),s=e.ref(null),l=e.ref(""),d=e.ref(""),c=e.ref(!1),u=e.computed(()=>t.layout==="mobile"),m=e.computed(()=>`${t.panelId}-textarea`),f=e.computed(()=>`${t.panelId}-helper`),p=e.computed(()=>`${t.panelId}-error`),h=e.computed(()=>`${t.panelId}-status`),v=e.computed(()=>{const w=[f.value,h.value];return r.value!==null&&w.push(p.value),w.join(" ")}),E=e.computed(()=>t.captionTrack!==null?t.captionTrack.segments:t.segments??[]),y=e.computed(()=>{try{return{text:Kc(E.value),errorMessage:null}}catch(w){return{text:"",errorMessage:A(w)}}}),k=e.computed(()=>E.value.length),g=e.computed(()=>E.value.reduce((w,F)=>Math.max(w,F.endTime),0)),b=e.computed(()=>E.value.slice(0,5));e.watch(()=>{var w,F;return[(w=t.captionTrack)==null?void 0:w.id,(F=t.captionTrack)==null?void 0:F.language,t.trackId]},([w,F,P])=>{l.value=w??P,d.value=F??""},{immediate:!0}),e.watch(y,w=>{if(w.errorMessage!==null){r.value=w.errorMessage;return}c.value||(i.value=w.text)},{immediate:!0});const R=()=>{c.value=!0,s.value=null,r.value!==null&&(r.value=null)},N=()=>{const w=i.value;if(r.value=null,s.value=null,w.trim()===""){r.value="Paste SRT text before importing captions.";return}try{const F=FE(w,{idPrefix:t.idPrefix}),P=JE(B(F)),D=Kc(P.segments);i.value=D,c.value=!1,s.value=`Imported ${x(P.segments.length)}.`,n("update:captionTrack",P),n("update:segments",P.segments),n("import",{track:P,segments:P.segments,sourceText:w})}catch(F){r.value=A(F)}},T=()=>{const w=y.value;if(r.value=w.errorMessage,w.errorMessage!==null){s.value=null;return}i.value=w.text,c.value=!1,s.value=w.text===""?"No captions to export.":`Exported ${x(k.value)}.`,n("export",w.text)},S=()=>{i.value="",c.value=!0,r.value=null,s.value="SRT text cleared.",n("clear")};function B(w){var D,O;const F={id:l.value.trim(),source:"srt-import",stylePreset:((D=t.captionTrack)==null?void 0:D.stylePreset)??"default",animation:((O=t.captionTrack)==null?void 0:O.animation)??"none",segments:w},P=d.value.trim();return P!==""&&(F.language=P),F}function A(w){return w instanceof Tn||w instanceof Error?w.message:"Unable to process SRT captions."}function x(w){return w===1?"1 cue":`${w} cues`}function M(w){const F=Math.floor(w/60),P=Math.floor(w%60);return`${F}:${P.toString().padStart(2,"0")}`}return(w,F)=>(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",PN,[e.createElementVNode("div",UN,[e.createElementVNode("h2",ON,e.toDisplayString(w.title),1),e.createElementVNode("p",{id:f.value,class:"caption-srt-panel__helper"}," Paste SRT, import it as captions, or export the current caption track. ",8,zN)]),u.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",jN,[e.createElementVNode("span",null,e.toDisplayString(x(k.value)),1),e.createElementVNode("span",null,e.toDisplayString(M(g.value)),1)]))]),u.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",WN,[e.createElementVNode("label",HN,[F[3]||(F[3]=e.createElementVNode("span",null,"Track ID",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":F[0]||(F[0]=P=>l.value=P),class:"caption-srt-panel__input",type:"text",autocomplete:"off","data-testid":"caption-srt-track-id"},null,512),[[e.vModelText,l.value]])]),e.createElementVNode("label",ZN,[F[4]||(F[4]=e.createElementVNode("span",null,"Language",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":F[1]||(F[1]=P=>d.value=P),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(w.textareaLabel),9,GN),e.withDirectives(e.createElementVNode("textarea",{id:m.value,"onUpdate:modelValue":F[2]||(F[2]=P=>i.value=P),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:R},null,42,XN),[[e.vModelText,i.value]]),r.value!==null?(e.openBlock(),e.createElementBlock("p",{key:1,id:p.value,class:"caption-srt-panel__error",role:"alert","data-testid":"caption-srt-error"},e.toDisplayString(r.value),9,KN)):(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(s.value??"Ready for caption import or export."),9,JN)),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:N}," Import "),e.createElementVNode("button",{type:"button",class:"caption-srt-panel__button","data-testid":"caption-srt-export",onClick:T}," Export "),e.createElementVNode("button",{type:"button",class:"caption-srt-panel__button","data-testid":"caption-srt-clear",onClick:S}," Clear ")]),u.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",qN,[F[5]||(F[5]=e.createElementVNode("p",{class:"caption-srt-panel__cue-summary-title"},"Cue summary",-1)),b.value.length>0?(e.openBlock(),e.createElementBlock("ol",YN,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(b.value,P=>(e.openBlock(),e.createElementBlock("li",{key:P.id,class:"caption-srt-panel__cue"},[e.createElementVNode("span",QN,e.toDisplayString(M(P.startTime))+"-"+e.toDisplayString(M(P.endTime)),1),e.createElementVNode("span",eT,e.toDisplayString(P.text),1)]))),128))])):(e.openBlock(),e.createElementBlock("p",tT," No captions loaded. "))]))],2))}}),vu=Fe(aT,[["__scopeId","data-v-1d5fdb3b"]]),nT=["aria-label"],oT={class:"draft-recovery-banner__header"},iT={class:"draft-recovery-banner__heading"},rT={class:"draft-recovery-banner__title"},sT={class:"draft-recovery-banner__summary","data-testid":"draft-recovery-summary"},lT={key:0,class:"draft-recovery-banner__list","data-testid":"draft-recovery-list"},dT={class:"draft-recovery-banner__record-copy"},cT={class:"draft-recovery-banner__record-title","data-testid":"draft-recovery-record-title"},uT={class:"draft-recovery-banner__record-meta"},mT={"data-testid":"draft-recovery-record-updated"},pT={"data-testid":"draft-recovery-record-reason"},fT={class:"draft-recovery-banner__actions"},hT=["onClick"],vT=["onClick"],gT={key:1,class:"draft-recovery-banner__mobile-prompt","data-testid":"draft-recovery-mobile-prompt"},bT={class:"draft-recovery-banner__record-copy"},yT={class:"draft-recovery-banner__record-title","data-testid":"draft-recovery-record-title"},wT={class:"draft-recovery-banner__record-meta"},kT={"data-testid":"draft-recovery-record-updated"},_T={"data-testid":"draft-recovery-record-reason"},ET={class:"draft-recovery-banner__actions draft-recovery-banner__actions--mobile"},ST={key:2,class:"draft-recovery-banner__empty","data-testid":"draft-recovery-empty"},CT=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"}),s=e.computed(()=>{const N={};return t.projectId!==void 0&&(N.projectId=t.projectId),t.savedAt!==void 0&&(N.savedAt=t.savedAt),t.maxAgeMs!==void 0&&(N.maxAgeMs=t.maxAgeMs),t.now!==void 0&&(N.now=t.now),N}),l=e.computed(()=>{const N=t.maxDesktopItems;return!Number.isFinite(N)||N<1?1:Math.floor(N)}),d=e.computed(()=>J2(t.records,t.surface,s.value)),c=e.computed(()=>t.surface==="mobile"?d.value:d.value.slice(0,l.value)),u=e.computed(()=>t.surface==="mobile"),m=e.computed(()=>c.value.length>0),f=e.computed(()=>u.value?c.value[0]??null:null),p=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=N=>{var T;return((T=N.snapshot.metadata.title)==null?void 0:T.trim())||"Untitled video draft"},E=N=>{const T=N.snapshot.metadata.saveReason;return T===void 0?"Saved draft":i[T]},y=N=>{const T=new Date(N.snapshot.metadata.updatedAt);return Number.isFinite(T.getTime())?r.format(T):"Updated time unavailable"},k=N=>{n("restore",N)},g=N=>{N.length!==0&&n("dismiss",N)},b=N=>{g([N])},R=()=>{g(c.value)};return(N,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":p.value},[e.createElementVNode("header",oT,[e.createElementVNode("div",iT,[T[2]||(T[2]=e.createElementVNode("p",{class:"draft-recovery-banner__eyebrow"},"Draft recovery",-1)),e.createElementVNode("h2",rT,e.toDisplayString(p.value),1),e.createElementVNode("p",sT,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:R}," Dismiss all ")):e.createCommentVNode("",!0)]),!u.value&&m.value?(e.openBlock(),e.createElementBlock("ul",lT,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.value,S=>(e.openBlock(),e.createElementBlock("li",{key:S.key,class:"draft-recovery-banner__record","data-testid":"draft-recovery-record"},[e.createElementVNode("div",dT,[e.createElementVNode("h3",cT,e.toDisplayString(v(S)),1),e.createElementVNode("p",uT,[e.createElementVNode("span",mT,"Updated "+e.toDisplayString(y(S)),1),T[3]||(T[3]=e.createElementVNode("span",{"aria-hidden":"true"},"·",-1)),e.createElementVNode("span",pT,e.toDisplayString(E(S)),1)])]),e.createElementVNode("div",fT,[e.createElementVNode("button",{type:"button",class:"draft-recovery-banner__primary-action","data-testid":"draft-recovery-restore",onClick:B=>k(S)}," Restore ",8,hT),e.createElementVNode("button",{type:"button",class:"draft-recovery-banner__secondary-action","data-testid":"draft-recovery-dismiss",onClick:B=>b(S)}," Dismiss ",8,vT)])]))),128))])):f.value?(e.openBlock(),e.createElementBlock("article",gT,[e.createElementVNode("div",bT,[e.createElementVNode("h3",yT,e.toDisplayString(v(f.value)),1),e.createElementVNode("p",wT,[e.createElementVNode("span",kT,"Updated "+e.toDisplayString(y(f.value)),1),T[4]||(T[4]=e.createElementVNode("span",{"aria-hidden":"true"},"·",-1)),e.createElementVNode("span",_T,e.toDisplayString(E(f.value)),1)])]),e.createElementVNode("div",ET,[e.createElementVNode("button",{type:"button",class:"draft-recovery-banner__primary-action","data-testid":"draft-recovery-restore",onClick:T[0]||(T[0]=S=>k(f.value))}," Restore "),e.createElementVNode("button",{type:"button",class:"draft-recovery-banner__secondary-action","data-testid":"draft-recovery-dismiss",onClick:T[1]||(T[1]=S=>b(f.value))}," Dismiss ")])])):(e.openBlock(),e.createElementBlock("p",ST," No recoverable drafts "))],10,nT))}}),gu=Fe(CT,[["__scopeId","data-v-3ed3c273"]]),xT={class:"inspector-tabs",role:"tablist","aria-label":"Editor tools"},VT=["aria-selected","data-testid","onClick"],NT=["aria-labelledby"],TT={class:"inspector-placeholder","data-testid":"v2-inspector-placeholder"},BT=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(s=>s.enabled)),r=s=>{s!==t.activeTab&&n("update:activeTab",s)};return(s,l)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["inspector-panel",{"inspector-panel--compact":s.compact}]),"data-testid":"v2-inspector-panel"},[e.createElementVNode("nav",xT,[(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":s.activeTab===d.id}]),"aria-selected":s.activeTab===d.id?"true":"false","data-testid":`v2-inspector-tab-${d.id}`,onClick:c=>r(d.id)},e.toDisplayString(d.label),11,VT))),128))]),e.createElementVNode("div",{class:"inspector-body",role:"tabpanel","aria-labelledby":`v2-inspector-tab-${s.activeTab}`},[e.renderSlot(s.$slots,s.activeTab,{},()=>[e.createElementVNode("div",TT,[e.createElementVNode("p",null,e.toDisplayString(s.activeTab)+" controls — coming soon",1)])],!0)],8,NT)],2))}}),MT=Fe(BT,[["__scopeId","data-v-7f5b0e50"]]),IT={class:"keyframe-preset-panel__header"},$T={class:"keyframe-preset-panel__target","data-testid":"keyframe-preset-target"},FT={key:0,class:"keyframe-preset-panel__notice","data-testid":"keyframe-preset-invalid-duration"},DT={class:"keyframe-preset-panel__grid","data-testid":"keyframe-preset-buttons"},RT=["disabled","aria-disabled","data-testid","onClick"],AT={class:"keyframe-preset-panel__preset-label"},LT={class:"keyframe-preset-panel__preset-summary"},PT={key:1,class:"keyframe-preset-panel__compact-summary","data-testid":"keyframe-preset-mobile-summary"},UT={key:2,class:"keyframe-preset-panel__desktop-summary","data-testid":"keyframe-preset-desktop-summary"},OT={class:"keyframe-preset-panel__summary-list"},zT=["data-testid"],jT={key:0,class:"keyframe-preset-panel__summary-empty","data-testid":"keyframe-preset-summary-empty"},WT=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:N=>{const T=GE({duration:R(N)});return y("fade-in","Fade in",T,N)}},{id:"fade-out",label:"Fade out",target:"opacity",summary:"Opacity 100 -> 0%",create:N=>{const T=R(N),S=XE({startTime:N-T,duration:T});return y("fade-out","Fade out",S,N)}},{id:"push-in",label:"Push in",target:"scale",summary:"Scale 100 -> 108%",create:N=>{const T=KE({duration:N,fromScale:1,toScale:1.08,easing:"ease-out"});return y("push-in","Push in",T,N)}},{id:"push-out",label:"Push out",target:"scale",summary:"Scale 108 -> 100%",create:N=>g({id:"push-out",label:"Push out",target:"scale",duration:N,startValue:1.08,endValue:1,easing:"ease-in"})},{id:"pan-x-left",label:"Pan left",target:"x",summary:"X 55 -> 45%",create:N=>g({id:"pan-x-left",label:"Pan left",target:"x",duration:N,startValue:.55,endValue:.45,easing:"ease-in-out"})},{id:"pan-x-right",label:"Pan right",target:"x",summary:"X 45 -> 55%",create:N=>g({id:"pan-x-right",label:"Pan right",target:"x",duration:N,startValue:.45,endValue:.55,easing:"ease-in-out"})},{id:"pan-y-up",label:"Pan up",target:"y",summary:"Y 55 -> 45%",create:N=>g({id:"pan-y-up",label:"Pan up",target:"y",duration:N,startValue:.55,endValue:.45,easing:"ease-in-out"})},{id:"pan-y-down",label:"Pan down",target:"y",summary:"Y 45 -> 55%",create:N=>g({id:"pan-y-down",label:"Pan down",target:"y",duration:N,startValue:.45,endValue:.55,easing:"ease-in-out"})},{id:"audio-fade-in",label:"Audio fade in",target:"audioVolume",summary:"Volume 0 -> 100%",create:N=>g({id:"audio-fade-in",label:"Audio fade in",target:"audioVolume",duration:R(N),startValue:0,endValue:1,easing:"ease-out"})},{id:"audio-fade-out",label:"Audio fade out",target:"audioVolume",summary:"Volume 100 -> 0%",create:N=>{const T=R(N);return g({id:"audio-fade-out",label:"Audio fade out",target:"audioVolume",duration:T,startTime:N-T,startValue:1,endValue:0,easing:"ease-in"})}}],s=e.computed(()=>WE(t.deviceClass)),l=e.computed(()=>s.value.platform==="mobile"),d=e.computed(()=>Number.isFinite(t.duration)&&t.duration>0),c=e.computed(()=>t.target==="all"?r:r.filter(N=>N.target===t.target)),u=e.computed(()=>d.value?c.value.map(N=>({definition:N,automation:N.create(t.duration)})):[]),m=e.computed(()=>i[t.target]),f=e.computed(()=>{const N=c.value.length,T=N===1?"preset":"presets";return d.value?`${N} ${T} - ${h(t.duration)} clip.`:`${N} ${T} available when duration is set.`}),p=N=>{if(!d.value)return;const T=N.create(t.duration);n("apply-preset",{presetId:T.id,target:T.target,keyframes:T.keyframes,automation:T})},h=N=>{const T=Math.round(N*100)/100;return`${T.toFixed(T%1===0?0:2)}s`},v=(N,T)=>N==="opacity"||N==="audioVolume"?`${Math.round(T*100)}%`:N==="scale"?`${Math.round(T*100)}%`:N==="x"||N==="y"?`${Math.round(T*100)}%`:`${Math.round(T*100)/100}`,E=N=>{const[T,S]=N.keyframes;return`${h(T.time)} ${v(N.target,T.value)} -> ${h(S.time)} ${v(N.target,S.value)}`};function y(N,T,S,B){return k({id:N,label:T,target:S.target,duration:B,keyframes:S.keyframes})}function k(N){const T=ZE(N.keyframes,{target:N.target,minTime:0,maxTime:N.duration}),S=T[0],B=T[1];if(T.length!==2||S===void 0||B===void 0)throw new Error("Keyframe preset panel presets must generate exactly two keyframes.");return{id:N.id,label:N.label,target:N.target,editingMode:"preset-only",keyframes:[S,B]}}function g(N){const T=N.startTime??0,S=[b(`${N.id}:start`,N.target,T,N.startValue,"linear"),b(`${N.id}:end`,N.target,T+N.duration,N.endValue,N.easing)];return k({id:N.id,label:N.label,target:N.target,duration:T+N.duration,keyframes:S})}function b(N,T,S,B,A){return{id:N,target:T,time:S,value:B,easing:A}}function R(N){return Math.min(N,1)}return(N,T)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["keyframe-preset-panel",{"keyframe-preset-panel--mobile":l.value}]),"data-testid":"keyframe-preset-panel","aria-label":"Keyframe presets"},[e.createElementVNode("header",IT,[T[0]||(T[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",$T,e.toDisplayString(m.value),1)]),d.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("p",FT," Set a valid clip duration to apply automation presets. ")),e.createElementVNode("div",DT,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.value,S=>(e.openBlock(),e.createElementBlock("button",{key:S.id,type:"button",class:"keyframe-preset-panel__preset",disabled:!d.value,"aria-disabled":d.value?void 0:"true","data-testid":`keyframe-preset-button-${S.id}`,onClick:B=>p(S)},[e.createElementVNode("span",AT,e.toDisplayString(S.label),1),e.createElementVNode("span",LT,e.toDisplayString(S.summary),1)],8,RT))),128))]),l.value?(e.openBlock(),e.createElementBlock("p",PT,e.toDisplayString(f.value),1)):(e.openBlock(),e.createElementBlock("div",UT,[T[1]||(T[1]=e.createElementVNode("p",{class:"keyframe-preset-panel__summary-title"},"Generated keyframes",-1)),e.createElementVNode("ul",OT,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(u.value,S=>(e.openBlock(),e.createElementBlock("li",{key:S.definition.id,class:"keyframe-preset-panel__summary-row","data-testid":`keyframe-preset-summary-${S.definition.id}`},[e.createElementVNode("span",null,e.toDisplayString(S.definition.label),1),e.createElementVNode("span",null,e.toDisplayString(E(S.automation)),1)],8,zT))),128))]),u.value.length===0?(e.openBlock(),e.createElementBlock("p",jT," No generated keyframes until duration is valid. ")):e.createCommentVNode("",!0)]))],2))}}),bu=Fe(WT,[["__scopeId","data-v-79615683"]]),HT={class:"mobile-clip-summary__main"},ZT={class:"mobile-clip-summary__title","data-testid":"v2-mobile-clip-label"},GT={class:"mobile-clip-summary__stats","aria-label":"Selected clip timing"},XT={class:"mobile-clip-summary__stat"},KT={"data-testid":"v2-mobile-clip-start"},JT={class:"mobile-clip-summary__stat"},qT={"data-testid":"v2-mobile-clip-end"},YT={class:"mobile-clip-summary__stat"},QT={"data-testid":"v2-mobile-clip-duration"},eB={key:1,class:"mobile-clip-summary__empty","data-testid":"v2-mobile-no-clip"},tB=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,f,p;return((f=(m=t.selectedClip)==null?void 0:m.label)==null?void 0:f.trim())||((p=t.selectedClip)==null?void 0:p.id)||""}),s=e.computed(()=>t.selectedClip?i(t.selectedClip.timelineStart)??i(t.selectedClip.startTime):null),l=e.computed(()=>t.selectedClip?i(t.selectedClip.timelineEnd)??i(t.selectedClip.endTime):null),d=e.computed(()=>{const m=s.value,f=l.value;return m!==null&&f!==null?Math.max(0,f-m):t.selectedClip?i(t.selectedClip.duration):null}),c=m=>{if(m===null)return"--";const f=Math.round(m*100)/100;return`${f.toFixed(f%1===0?0:2)}s`},u=()=>{t.selectedClip&&n("open-actions",t.selectedClip.id)};return(m,f)=>(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",HT,[f[0]||(f[0]=e.createElementVNode("p",{class:"mobile-clip-summary__eyebrow"},"Selected clip",-1)),e.createElementVNode("h2",ZT,e.toDisplayString(r.value),1)]),e.createElementVNode("dl",GT,[e.createElementVNode("div",XT,[f[1]||(f[1]=e.createElementVNode("dt",null,"Start",-1)),e.createElementVNode("dd",KT,e.toDisplayString(c(s.value)),1)]),e.createElementVNode("div",JT,[f[2]||(f[2]=e.createElementVNode("dt",null,"End",-1)),e.createElementVNode("dd",qT,e.toDisplayString(c(l.value)),1)]),e.createElementVNode("div",YT,[f[3]||(f[3]=e.createElementVNode("dt",null,"Duration",-1)),e.createElementVNode("dd",QT,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",eB," No clip selected "))],2))}}),aB=Fe(tB,[["__scopeId","data-v-433c7812"]]),nB=["aria-label"],oB=["aria-pressed","data-testid","onClick"],iB={class:"mobile-tool-picker__label"},rB=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=s=>{s!==n.modelValue&&i("update:modelValue",s)};return(s,l)=>(e.openBlock(),e.createElementBlock("div",{class:"mobile-tool-picker",role:"group","aria-label":s.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":s.modelValue===d.id}]),"aria-pressed":s.modelValue===d.id?"true":"false","data-testid":`v2-mobile-tool-${d.id}`,onClick:c=>r(d.id)},[e.createElementVNode("span",iB,e.toDisplayString(d.label),1)],10,oB)),64))],8,nB))}}),sB=Fe(rB,[["__scopeId","data-v-ec597c70"]]),lB=["aria-label","data-snap"],dB=["aria-expanded"],cB={class:"drawer-header"},uB={class:"drawer-body"},mB=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,s=e.ref(null),l=e.ref(null),d=e.ref(i.initialSnap);let c=!1,u=!1,m=null,f=0,p=0,h=0;const v=B=>{const A=h||(typeof window<"u"?window.innerHeight:600);switch(B){case"collapsed":return 80;case"half":return Math.round(A*.45);case"full":return Math.round(A*.85)}},E=(B,{animate:A=!0}={})=>{var w;if(!s.value)return;const x=d.value;d.value=B;const M=typeof window<"u"&&((w=window.matchMedia)==null?void 0:w.call(window,"(prefers-reduced-motion: reduce)").matches);s.value.style.transition=A&&!M?"height 0.25s cubic-bezier(0.33, 1, 0.68, 1)":"none",s.value.style.height=`${v(B)}px`,B!==x&&r("snap-change",B,x)},y=B=>{let A=n[0],x=1/0;for(const M of n){const w=Math.abs(v(M)-B);w<x&&(x=w,A=M)}return A},k=()=>{const B=n.indexOf(d.value);E(n[(B+1)%n.length])},g=B=>{if(u){u=!1,B.preventDefault();return}k()},b=B=>{var A,x,M;if(B.button===0){c=!0,u=!1,m=B.pointerId,f=B.clientY,p=((A=s.value)==null?void 0:A.offsetHeight)??0;try{(M=(x=l.value)==null?void 0:x.setPointerCapture)==null||M.call(x,B.pointerId)}catch{}s.value&&(s.value.style.transition="none")}},R=B=>{if(!c||B.pointerId!==m)return;const A=B.clientY-f,x=p-A,M=v("collapsed"),w=v("full"),F=Math.max(M,Math.min(w,x));s.value&&(s.value.style.height=`${F}px`),Math.abs(A)>4&&(u=!0),B.preventDefault()},N=B=>{var x,M,w;if(!c)return;c=!1;try{(M=(x=l.value)==null?void 0:x.releasePointerCapture)==null||M.call(x,B.pointerId)}catch{}m=null;const A=((w=s.value)==null?void 0:w.offsetHeight)??0;E(y(A))},T=(B,A={})=>{n.includes(B)&&E(B,{animate:A.animate!==!1})},S=B=>{h=Math.max(0,Number(B)||0),E(d.value,{animate:!1})};return e.watch(()=>i.containerHeight,B=>{B>0&&S(B)}),e.onMounted(()=>{i.containerHeight>0&&(h=i.containerHeight),E(d.value,{animate:!1})}),e.onBeforeUnmount(()=>{c=!1,m=null}),a({snapTo:T,updateContainerHeight:S,snap:d}),(B,A)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"rootEl",ref:s,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:l,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:g,onPointerdown:b,onPointermove:R,onPointerup:N,onPointercancel:N},[...A[0]||(A[0]=[e.createElementVNode("span",{class:"drawer-handle-grip","aria-hidden":"true"},null,-1)])],40,dB),e.createElementVNode("div",cB,[e.renderSlot(B.$slots,"header",{},void 0,!0)]),e.createElementVNode("div",uB,[e.renderSlot(B.$slots,"default",{},void 0,!0)])],8,lB))}}),pB=Fe(mB,[["__scopeId","data-v-4ebedbf7"]]),fB=new Set(["INPUT","TEXTAREA","SELECT"]);function hB(o){return o instanceof HTMLElement?!!(fB.has(o.tagName)||o.isContentEditable):!1}function vB(o,a={}){const t=n=>{var l,d,c,u,m,f,p,h,v,E,y,k,g,b,R,N,T;if(a.enabled&&a.enabled()===!1||hB(n.target))return;const i=n.ctrlKey||n.metaKey,r=n.shiftKey,s=n.key;if(i&&(s==="z"||s==="Z")){r?(l=o.redo)==null||l.call(o):(d=o.undo)==null||d.call(o),n.preventDefault();return}if(i&&(s==="s"||s==="S")){(c=o.save)==null||c.call(o),n.preventDefault();return}if(i&&(s==="e"||s==="E")){(u=o.exportNow)==null||u.call(o),n.preventDefault();return}switch(s){case" ":case"Spacebar":(m=o.playPause)==null||m.call(o),n.preventDefault();return;case"ArrowLeft":r?(f=o.secondBackward)==null||f.call(o):(p=o.frameBackward)==null||p.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":(E=o.skipToStart)==null||E.call(o),n.preventDefault();return;case"End":(y=o.skipToEnd)==null||y.call(o),n.preventDefault();return;case"[":(k=o.prevClip)==null||k.call(o),n.preventDefault();return;case"]":(g=o.nextClip)==null||g.call(o),n.preventDefault();return;case"s":case"S":i||((b=o.splitAtPlayhead)==null||b.call(o),n.preventDefault());return;case"Delete":case"Backspace":r?(R=o.rippleDeleteSelected)==null||R.call(o):(N=o.deleteSelected)==null||N.call(o),n.preventDefault();return;case"?":(T=o.showShortcutsOverlay)==null||T.call(o),n.preventDefault();return}};e.onMounted(()=>{window.addEventListener("keydown",t)}),e.onBeforeUnmount(()=>{window.removeEventListener("keydown",t)})}const Qp=["video/mp4","video/webm","video/quicktime"],ef=["image/png","image/jpeg","image/jpg","image/webp"],gB=["audio/mpeg","audio/mp3","audio/aac","audio/wav","audio/x-wav","audio/wave"],bB=new Set([...Qp,...ef,...gB]),yB=2*1024*1024*1024,wB=60*60;function yu(o,a){const t=o.type.toLowerCase();return bB.has(t)?o.size>yB?{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>wB?{ok:!1,reason:"duration_exceeded",message:`Clip is too long (${Math.round(a)}s). Limit is 1 hour.`}:{ok:!0,kind:Qp.includes(t)?"video":ef.includes(t)?"image":"audio"}:{ok:!1,reason:"unsupported_mime",message:`Unsupported file type: ${t||"unknown"}.`}}const kB="mediables-asset-blobs",Ka="blobs",_B=1;class EB{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(kB,_B);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Ka)||i.createObjectStore(Ka)},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(Ka,"readwrite").objectStore(Ka).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 l=t.transaction(Ka,"readonly").objectStore(Ka).get(a);l.onsuccess=()=>{const d=l.result;d==null?n(null):d instanceof Blob?n(d):n(null)},l.onerror=()=>{i(l.error??new Error("Failed to read blob."))}})}async delete(a){const t=await this.openDb();await new Promise((n,i)=>{const l=t.transaction(Ka,"readwrite").objectStore(Ka).delete(a);l.onsuccess=()=>{n()},l.onerror=()=>{i(l.error??new Error("Failed to delete blob."))}})}async clear(){const a=await this.openDb();await new Promise((t,n)=>{const s=a.transaction(Ka,"readwrite").objectStore(Ka).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error??new Error("Failed to clear cache."))}})}}let tl=null;function SB(){return tl===null&&(tl=new EB),tl}class CB{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 xB(){return`asset-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function VB(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 NB(o){const a=e.reactive(new Map),t=o.blobCache??TB();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,f){var p,h,v;try{m.status="uploading",m.uploadProgress=0,a.set(m.assetId,m);const E=await o.uploader.upload({file:u},({assetId:y,progress:k,status:g})=>{if(y!==m.assetId)return;const b=a.get(y);b&&(b.uploadProgress=k,b.status=g,a.set(y,b))});return a.set(m.assetId,E),E.status==="ready"?(i(m.assetId),(p=o.onReady)==null||p.call(o,E)):E.status==="failed"&&((h=o.onFailure)==null||h.call(o,E)),{ok:!0,record:E}}catch(E){const y=E instanceof Error?E.message:"Upload failed.",k={...m,status:"failed",failureMessage:y};return a.set(m.assetId,k),(v=o.onFailure)==null||v.call(o,k),{ok:!1,reason:"upload",message:y}}}const s=o.probeTimeoutMs??1500;async function l(u){const m=await VB(u,s),f=yu(u,m.durationSeconds);if(!f.ok)return{ok:!1,reason:"preflight",message:f.message};const p=xB(),h={assetId:p,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(p,h),await n(p,u),r(u,h)}async function d(u){const m=a.get(u);if(!m)return{ok:!1,reason:"unknown",message:"Unknown asset."};const f=await t.get(u);if(!f)return{ok:!1,reason:"unknown",message:"Original file is no longer cached."};const p=f instanceof File?f:new File([f],m.filename,{type:m.mime}),h=yu(p,m.durationSeconds);return h.ok?r(p,m):{ok:!1,reason:"preflight",message:h.message}}async function c(u){a.delete(u),await i(u)}return{records:e.readonly(a),importFile:l,retry:d,remove:c}}function TB(){return typeof indexedDB<"u"?SB():new CB}const BB={class:"v2-toolbar-group"},MB=["aria-label"],IB=["disabled"],$B={class:"v2-toolbar-group"},FB={class:"v2-toolbar-fit"},DB=["disabled"],RB=["aria-label","title","disabled"],AB={class:"v2-assets"},LB={key:0,class:"v2-asset-rail-status","data-testid":"v2-asset-rail-status",role:"status"},PB={class:"v2-preview-host"},UB={class:"v2-timeline-topbar"},OB={class:"v2-timeline-heading"},zB={class:"v2-timeline-meta","data-testid":"v2-timeline-meta"},jB={class:"v2-timeline-zoom"},WB=["value"],HB={class:"v2-timeline-zoom-readout"},ZB={key:0,class:"v2-timeline-track-actions"},GB={key:0,class:"v2-timeline-track-target"},XB=["value"],KB=["value"],JB=["aria-pressed"],qB={key:0,class:"v2-editor-status","data-testid":"v2-editor-status",role:"status","aria-live":"polite"},YB={key:1,class:"v2-timeline-empty","data-testid":"v2-timeline-empty"},QB={key:1,class:"v2-empty-state"},e4={key:0,"data-testid":"v2-export-status-completed",class:"v2-export-status"},t4={key:1,class:"v2-export-status","data-testid":"v2-export-status-message"},a4={key:1,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-look"},n4={class:"v2-mobile-panel-section"},o4={class:"v2-mobile-panel-section v2-mobile-panel-section--compact"},i4={key:1,class:"v2-empty-state"},r4={key:2,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-trim"},s4={key:3,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-text"},l4={key:4,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-audio"},d4={key:5,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-export"},c4={key:0,class:"v2-export-status"},u4={key:1,class:"v2-export-status"},m4={key:6,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-more"},p4={class:"v2-mobile-secondary-controls"},f4={class:"v2-mobile-secondary-field"},h4=["aria-pressed"],v4=["disabled"],g4=["disabled"],b4={key:0,class:"v2-mobile-secondary-details","data-testid":"v2-mobile-transitions"},y4={class:"v2-mobile-secondary-details","data-testid":"v2-mobile-keyframes"},w4={class:"v2-shortcuts-overlay__panel"},k4={class:"v2-shortcuts-overlay__header"},_4=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 Qi,er,tr,ar;const n=o,i=t,r=e.computed(()=>{var Y;const _=typeof n.mediaUuid=="string"?n.mediaUuid.trim():"";if(_!=="")return _;const $=(Y=n.media)==null?void 0:Y.uuid;return typeof $=="string"&&$.trim()!==""?$.trim():`temp-${Date.now()}`}),s=kp(r.value,n.initialRecipe,n.media),l=Sp(),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}),f=e.computed(()=>{const _=n.featureFlags??{},$=["filters","adjustments","text","transitions","audio","export"],Y={filters:"Filters",adjustments:"Adjust",text:"Text",transitions:"Transitions",audio:"Audio",export:"Export"};return $.map(we=>({id:we,label:Y[we],enabled:typeof _[we]=="boolean"?_[we]:m.value[we]}))}),p=_=>f.value.some($=>$.id===_&&$.enabled),h={look:"filters",text:"text",audio:"audio",export:"export"},v=e.computed(()=>{var _;return((_=n.featureFlags)==null?void 0:_.transitions)===!0});e.watch(c,_=>{var $,Y;if(_!=="trim"&&_!=="more"){const we=h[_];p(we)&&(d.value=we)}(Y=($=u.value)==null?void 0:$.snapTo)==null||Y.call($,"full"),e.nextTick(()=>{var Ue;if(typeof document>"u")return;const we=document.querySelector(`[data-testid="v2-mobile-panel-${_}"]`);if(!we||!(we instanceof HTMLElement))return;const Pe=typeof window<"u"&&((Ue=window.matchMedia)==null?void 0:Ue.call(window,"(prefers-reduced-motion: reduce)").matches);we.scrollIntoView({block:"start",behavior:Pe?"auto":"smooth"})})});const E=e.ref(!1),y=e.computed(()=>d.value),k=e.computed(()=>y.value==="filters"||E.value),g=e.computed(()=>y.value!=="filters"&&!E.value),b=e.ref(null),R=e.computed(()=>b.value),N=["contain","cover","none"],T=_=>typeof _=="string"&&N.includes(_),S=_=>{var Y;const $=(Y=_==null?void 0:_.metadata)==null?void 0:Y.fit_mode;return T($)?$:null},B=e.ref(S(n.initialRecipe)??"contain"),A=e.ref("");e.watch(()=>{var _,$;return{file:(_=n.media)==null?void 0:_.file,url:($=n.media)==null?void 0:$.url}},(_,$,Y)=>{var Pe,Ue;const we=A.value;Y(()=>{we&&we.startsWith("blob:")&&URL.revokeObjectURL(we)}),(Pe=n.media)!=null&&Pe.file?A.value=URL.createObjectURL(n.media.file):(Ue=n.media)!=null&&Ue.url?A.value=n.media.url:A.value=""},{immediate:!0});const x=e.computed(()=>A.value),M=e.computed(()=>l.activeFilters.value),w=e.computed(()=>s.playheadPosition.value),F=Xm({forcePixiPreview:E,getPreviewRef:()=>R.value,getSourceUrl:()=>A.value,setPlaying:s.setPlaying}),P=e.computed(()=>{if(!n.media)return null;const{file:_,...$}=n.media;return{...$,url:A.value}}),D=e.computed(()=>{var $;const _=($=n.media)==null?void 0:$.url;return!!(_&&/^https?:/i.test(_))}),O=e.ref(0),I=e.computed(()=>{var $;if(s.totalDuration.value>0)return s.totalDuration.value;if(O.value>0)return O.value;const _=Number(($=n.media)==null?void 0:$.duration);return Number.isFinite(_)&&_>0?_:0}),Z=_=>{!Number.isFinite(_)||_<=0||(O.value=_,s.updateSourceDuration(_))},z=_=>{_&&typeof _.time=="number"&&Number.isFinite(_.time)&&s.seekTo(_.time)},K=_=>{Number.isFinite(_)&&s.seekTo(_)},se=_=>{s.setPlaying(_)},Be=e.computed(()=>l.videoCompatibleFilters.value.map($=>{var we;const Y=[];if($.controls&&$.controls.length>0)for(const Pe of $.controls){const Ue=Pe.type;if(Ue==="button"||Ue==="text"||Ue==="range")continue;const dt={id:Pe.property||Pe.id,label:Pe.label||Pe.id,type:Ue,default:Pe.default??(Ue==="toggle"?!1:Ue==="color"?"#ffffff":0)};Ue==="slider"&&(dt.min=Pe.min??0,dt.max=Pe.max??1,dt.step=Pe.step??.01),Ue==="select"&&Pe.options&&(dt.options=Pe.options),Y.push(dt)}else if($.paramRanges){const Pe=Object.entries($.paramRanges);for(const[Ue,dt]of Pe){const Nt=Ue.replace(/[-_]/g," ").replace(/\b\w/g,_o=>_o.toUpperCase()),Zt=(we=$.defaultParams)==null?void 0:we[Ue],ma=(dt.min+dt.max)/2;Y.push({id:Ue,label:Nt,min:dt.min,max:dt.max,step:dt.step??.01,default:typeof Zt=="number"?Zt:ma})}}return{id:$.id,name:$.name,category:$.category,params:Y}})),ce=e.computed(()=>{const _=new Map;return l.activeFilters.value.forEach($=>_.set($.filterId,$)),_}),ie=e.computed(()=>{if(s.currentFrame.value)return s.currentFrame.value;const _=n.media;return(_==null?void 0:_.thumbnail_url)??(_==null?void 0:_.url)}),W=e.shallowRef(null),C=e.ref(null),U=e.ref(null),j=e.ref(null),ne=e.ref(!1),de=new Map,Ke=(_,$)=>{const Y={id:_.id??`text-overlay-recipe-${$}`,text:_.content};return _.fontFamily!==void 0&&(Y.fontFamily=_.fontFamily),_.fontSize!==void 0&&(Y.fontSize=_.fontSize),_.fontWeight!==void 0&&(Y.fontWeight=_.fontWeight),_.color!==void 0&&(Y.color=_.color),_.position!==void 0&&(Y.position=_.position),_.startTime!==void 0&&(Y.startTime=_.startTime),_.duration!==void 0&&(Y.duration=_.duration),_.animation!==void 0&&(Y.animation=_.animation),_.textAlign!==void 0&&(Y.textAlign=_.textAlign),_.textBaseline!==void 0&&(Y.textBaseline=_.textBaseline),Y},be=_=>{const $={id:_.id,content:_.text};return _.fontFamily!==void 0&&($.fontFamily=_.fontFamily),_.fontSize!==void 0&&($.fontSize=_.fontSize),_.fontWeight!==void 0&&($.fontWeight=_.fontWeight),_.color!==void 0&&($.color=_.color),_.position!==void 0&&($.position=_.position),_.startTime!==void 0&&($.startTime=_.startTime),_.duration!==void 0&&($.duration=_.duration),_.animation!==void 0&&($.animation=_.animation),_.textAlign!==void 0&&($.textAlign=_.textAlign),_.textBaseline!==void 0&&($.textBaseline=_.textBaseline),$},_e=(_,$)=>{const Y={id:_.id??`audio-track-recipe-${$}`,source:_.source};return _.volume!==void 0&&(Y.volume=_.volume),_.startTime!==void 0&&(Y.startTime=_.startTime),_.duration!==void 0&&(Y.duration=_.duration),_.fadeIn!==void 0&&(Y.fadeIn=_.fadeIn),_.fadeOut!==void 0&&(Y.fadeOut=_.fadeOut),_.loop!==void 0&&(Y.loop=_.loop),_.name!==void 0&&(Y.name=_.name),Y},ve=_=>{if(typeof _.source!="string")return null;const $={id:_.id,source:_.source};return _.volume!==void 0&&($.volume=_.volume),_.startTime!==void 0&&($.startTime=_.startTime),_.duration!==void 0&&($.duration=_.duration),_.fadeIn!==void 0&&($.fadeIn=_.fadeIn),_.fadeOut!==void 0&&($.fadeOut=_.fadeOut),_.loop!==void 0&&($.loop=_.loop),_.name!==void 0&&($.name=_.name),$},xe=_=>{const $={id:_.id,source:typeof _.source=="string"?_.source:""};return _.volume!==void 0&&($.volume=_.volume),_.startTime!==void 0&&($.startTime=_.startTime),_.duration!==void 0&&($.duration=_.duration),_.fadeIn!==void 0&&($.fadeIn=_.fadeIn),_.fadeOut!==void 0&&($.fadeOut=_.fadeOut),_.loop!==void 0&&($.loop=_.loop),_.name!==void 0&&($.name=_.name),_.muted!==void 0&&($.muted=_.muted),_.solo!==void 0&&($.solo=_.solo),_.pan!==void 0&&($.pan=_.pan),_.faderDb!==void 0&&($.faderDb=_.faderDb),$},Se=_=>({..._,segments:_.segments.map($=>{const Y={...$};return $.words&&(Y.words=$.words.map(we=>({...we}))),Y})}),Ae=e.ref((((Qi=n.initialRecipe)==null?void 0:Qi.textOverlays)??[]).map(Ke)),re=_=>{switch(_){case"crossfade":return"cross-fade";case"zoom":return"zoom-in";case"cut":return"fade";default:return _}},ge=_=>{switch(_){case"ease-in":return"easeIn";case"ease-out":return"easeOut";case"ease-in-out":return"easeInOut";case"linear":return"linear"}},Ge=_=>{switch(_){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 _}},Ve=_=>{switch(_){case"easeIn":return"ease-in";case"easeOut":return"ease-out";case"easeInOut":return"ease-in-out";case"linear":default:return"linear"}},at=_=>({id:_.id,type:re(_.type),duration:_.duration,easing:ge(_.easing),name:_.type,fromClipId:_.fromClipId,toClipId:_.toClipId,cutTime:_.cutTime??0}),rt=_=>({id:_.id,type:Ge(_.type),fromClipId:_.fromClipId,toClipId:_.toClipId,duration:_.duration,easing:Ve(_.easing),cutTime:_.cutTime}),gt=e.ref((((er=n.initialRecipe)==null?void 0:er.transitions)??[]).map(at)),lt=e.ref((((tr=n.initialRecipe)==null?void 0:tr.audioTracks)??[]).map(_e)),Et=e.ref(1),Ee=e.ref(!1),Ce=e.ref((((ar=n.initialRecipe)==null?void 0:ar.captionTracks)??[]).map(Se)),Re=e.ref([]),et=e.ref(null),qe=e.computed(()=>r.value),Ze=e.computed(()=>Re.value),bt=e.computed(()=>Ce.value[0]??null),ct=e.computed(()=>{const _=s.selectedClip.value??s.timelineClips.value[0];return _?Math.max(0,_.timelineEnd-_.timelineStart):I.value}),At=e.computed(()=>hE(lt.value.map(xe),{master:{volume:Et.value,muted:Ee.value}})),$t=e.computed(()=>{const _=[...s.timelineClips.value].sort((dt,Nt)=>dt.timelineStart-Nt.timelineStart),$=s.selectedClip.value??_[0];if(!$)return[];const Y=_.findIndex(dt=>dt.id===$.id);if(Y===-1)return[];const we=dt=>(dt.trackId??null)===($.trackId??null),Pe=_.slice(Y+1).find(we);if(Pe)return[$,Pe];const Ue=[..._.slice(0,Y)].reverse().find(we);return Ue?[Ue,$]:[]}),Pt=_=>{W.value=_,_!=null&&_.composition&&(U.value=new Cp(_.composition),j.value=new xp(_.composition));try{de.size&&W.value&&(de.forEach(($,Y)=>{W.value.setClipFilters(Y,$)}),de.clear(),W.value.composition.computeFrame())}catch{}},Ut=_=>{W.value?W.value.setClipFilters(_,l.activeFilters.value):de.set(_,[...l.activeFilters.value])},ea=_=>{var Y,we;const $=((Y=s.selectedClip.value)==null?void 0:Y.id)??((we=s.timelineClips.value[0])==null?void 0:we.id);$&&(ne.value=!0,typeof _=="object"&&_!==null&&"id"in _?l.applyFilter(_.id):typeof _=="string"&&l.applyFilter(_),s.setFilters(l.activeFilters.value),Ut($),s.handleClipSelect($),ne.value=!1,He())},Jt=_=>{var we,Pe;const $=l.activeFilters.value.find(Ue=>Ue.filterId===_);$&&l.removeFilter($.id),s.setFilters(l.activeFilters.value);const Y=((we=s.selectedClip.value)==null?void 0:we.id)??((Pe=s.timelineClips.value[0])==null?void 0:Pe.id);Y&&Ut(Y),He()},ta=(_,$,Y)=>{var Ue,dt;const we=l.activeFilters.value.find(Nt=>Nt.filterId===_);if(we){we.params={...we.params??{},[$]:Y},s.setFilters(l.activeFilters.value);const Nt=((Ue=s.selectedClip.value)==null?void 0:Ue.id)??((dt=s.timelineClips.value[0])==null?void 0:dt.id);Nt&&Ut(Nt),He();return}const Pe=l.previewFilter.value;Pe&&Pe.filterId===_&&(Pe.params={...Pe.params??{},[$]:Y})},fa=_=>{_&&typeof _.id=="string"&&_.id!==""&&l.previewFilterEffect(_.id)},Q=_=>{l.updateFilterParams(_),s.setFilters(l.activeFilters.value),He()},he=async _=>{if(!U.value)return;const $=await U.value.addTextOverlay(_);Ae.value.push({id:$,..._})},ue=async(_,$)=>{if(!U.value)return;await U.value.updateTextOverlay(_,$);const Y=Ae.value.findIndex(we=>we.id===_);Y!==-1&&(Ae.value[Y]={...Ae.value[Y],...$})},le=async _=>{U.value&&(await U.value.removeTextOverlay(_),Ae.value=Ae.value.filter($=>$.id!==_))},Te=async _=>{const[$,Y]=$t.value;if(!$||!Y)return;const we={id:`transition-${$.id}-${Y.id}-${Date.now()}`,..._,name:_.type,fromClipId:$.id,toClipId:Y.id,cutTime:$.timelineEnd};gt.value.push(we),s.setTransitions(gt.value.map(rt)),He()},ze=_=>{gt.value[_]&&(gt.value.splice(_,1),s.setTransitions(gt.value.map(rt)),He())},ot=_=>{},St=async _=>{if(!j.value)return;const $=await j.value.addAudioTrack(_);lt.value.push({id:$,..._});const Y=typeof _.source=="string"?_.source:_.source instanceof File?URL.createObjectURL(_.source):null;if(!Y)return;const we={id:`audio-source-${$}`,type:"url",url:Y,duration:typeof _.duration=="number"&&_.duration>0?_.duration:0,width:0,height:0};typeof _.name=="string"&&(we.filename=_.name),s.registerMediaSource(we);const Pe=s.appendAudioSourceToTimeline(we.id);if(!Pe.ok){tt.value=Pe.message;return}tt.value=`Audio added to ${Pe.value.trackId??"timeline"}.`,He()},Ft=async(_,$)=>{if(!j.value)return;await j.value.updateAudioTrack(_,$);const Y=lt.value.findIndex(we=>we.id===_);Y!==-1&&(lt.value[Y]={...lt.value[Y],...$})},Vt=async _=>{j.value&&(await j.value.removeAudioTrack(_),lt.value=lt.value.filter($=>$.id!==_))},Ct=async(_,$)=>{if(!j.value)return;await j.value.updateVolume(_,$);const Y=lt.value.find(we=>we.id===_);Y&&(Y.volume=$)},Ht=async(_,$)=>{if(!j.value)return;await j.value.muteTrack(_,$);const Y=lt.value.find(we=>we.id===_);Y&&(Y.muted=$)},X=_=>{j.value&&(j.value.setMasterVolume(_),Et.value=_)},ye=(_,$)=>{const Y=lt.value.findIndex(Pe=>Pe.id===_);if(Y===-1)return null;const we={...lt.value[Y],...$};return lt.value[Y]=we,we},te=_=>{switch(_.type){case"track-fader-db":{const $=Pl(_.valueDb);ye(_.trackId,{faderDb:_.valueDb,volume:$}),j.value&&j.value.updateVolume(_.trackId,$);break}case"track-mute":ye(_.trackId,{muted:_.muted}),j.value&&j.value.muteTrack(_.trackId,_.muted);break;case"track-solo":ye(_.trackId,{solo:_.solo});break;case"track-pan":ye(_.trackId,{pan:_.pan});break;case"master-fader-db":{Et.value=Pl(_.valueDb),j.value&&j.value.setMasterVolume(Ee.value?0:Et.value);break}case"master-mute":Ee.value=_.muted,j.value&&j.value.setMasterVolume(Ee.value?0:Et.value);break}},De=_=>{Ce.value=[Se(_.track)],s.setCaptionTracks(Ce.value),He()},Tt=_=>{Ce.value=[Se(_)],s.setCaptionTracks(Ce.value),He()},Dt=()=>{Ce.value=[],s.setCaptionTracks([]),He()},Bt=_=>{const $=s.selectedClip.value??s.timelineClips.value[0];if(!$)return;const we=[...($.keyframes??[]).filter(Pe=>Pe.target!==_.target),..._.keyframes].sort((Pe,Ue)=>{const dt=Pe.time-Ue.time;return dt===0?Pe.id.localeCompare(Ue.id):dt});s.setClipKeyframes($.id,we),He()},pt=_=>{var $;return _.metadata||(_.metadata={created_at:new Date().toISOString(),editor_version:"2.0.0"}),_.metadata.fit_mode=B.value,($=n.media)!=null&&$.url&&/^https?:/i.test(n.media.url)?_.metadata.source_url=n.media.url:delete _.metadata.source_url,_.captionTracks=Ce.value.map(Se),_},ft=(_,$)=>$?{..._,output:{..._.output,format:$.format,quality:$.quality,codec:$.codec??_.output.codec,fps:$.fps??_.output.fps,...typeof $.bitrate=="number"?{bitrate:$.bitrate}:{}}}:_,qt=_=>_.map($=>({...$,params:$.params&&typeof $.params=="object"?{...$.params}:$.params})),wt=_=>_.timeline.some($=>Array.isArray($.filters)&&$.filters.length>0),Ot=_=>{const $=qt(l.activeFilters.value);if(!wt(_)&&$.length>0&&_.timeline.length>0){const we=_.timeline[0];we&&(_.timeline=[{...we,filters:$},..._.timeline.slice(1)])}return _},_a=()=>{const _=Ot(pt(s.saveDraft()));try{localStorage.setItem(`video-draft-${r.value}`,JSON.stringify(_))}catch{}return me(_,"manual",!0),_},G=()=>typeof localStorage>"u"?null:{getItem:_=>localStorage.getItem(_),setItem:(_,$)=>{localStorage.setItem(_,$)},removeItem:_=>{localStorage.removeItem(_)},listKeys:_=>{const $=[];for(let Y=0;Y<localStorage.length;Y+=1){const we=localStorage.key(Y);we!=null&&we.startsWith(_)&&$.push(we)}return $}},J=async()=>{const _=G();if(_===null){Re.value=[];return}Re.value=await jc(_)},me=async(_,$,Y)=>{var ma,_o;const we=G();if(we===null)return;const Pe=new Date().toISOString(),Ue={projectId:qe.value,sourceMediaUuid:r.value,durationSeconds:I.value,editorVersion:((ma=_.metadata)==null?void 0:ma.editor_version)??"2.0.0",saveReason:$,now:Pe};((_o=_.metadata)==null?void 0:_o.title)!==void 0&&(Ue.title=_.metadata.title);const dt=j2(Km(_),Ue);await q2(we,dt);const Nt=await jc(we),Zt=G2(Nt,{maxCount:5,projectId:qe.value,now:Pe});await Wc(we,Zt.removed),Re.value=[...Zt.retained],Y&&(et.value=Pe)},pe=_=>_.snapshot.metadata.payloadKind==="project"?L2(_.snapshot.payload):_.snapshot.payload,Ne=_=>{const $=pe(_);s.loadRecipe($),Ae.value=($.textOverlays??[]).map(Ke),lt.value=($.audioTracks??[]).map(_e),Ce.value=($.captionTracks??[]).map(Se),gt.value=($.transitions??[]).map(at);const Y=S($);Y!==null&&(B.value=Y),st()},We=_=>{const $=G();Re.value=Re.value.filter(Y=>!_.some(we=>we.key===Y.key)),$!==null&&Wc($,_)},st=()=>{C.value=pt(s.generateRecipe())};let Ye=null;const He=()=>{Ye&&clearTimeout(Ye),Ye=setTimeout(()=>{st(),Ye=null},200)};if(e.watch(()=>s.timelineClips.value,He,{deep:!0}),e.watch(()=>s.selectedClip.value,_=>{if(ne.value||!_)return;const $=(_==null?void 0:_.filters)??[];l.setActiveFilters($)},{immediate:!0}),e.watch(()=>l.activeFilters.value,_=>{s.setFilters(_),He()},{deep:!0}),e.watch(()=>Ae.value,_=>{s.setTextOverlays(_.map(be)),He()},{deep:!0}),e.watch(()=>lt.value,_=>{const $=_.map(ve).filter(Y=>Y!==null);s.setAudioTracks($),He()},{deep:!0}),e.watch(()=>Ce.value,_=>{s.setCaptionTracks(_.map(Se)),He()},{deep:!0}),Ae.value.length>0&&s.setTextOverlays(Ae.value.map(be)),lt.value.length>0){const _=lt.value.map(ve).filter($=>$!==null);s.setAudioTracks(_)}Ce.value.length>0&&s.setCaptionTracks(Ce.value.map(Se)),e.watch(()=>s.playheadPosition.value,He),st();const ut=e.ref(!0),ht=e.ref(null),tt=e.ref(null);let Yt=null;e.watch(tt,_=>{Yt!==null&&(clearTimeout(Yt),Yt=null),!(_===null||_==="")&&(Yt=setTimeout(()=>{tt.value=null},4e3))});const It=e.ref(null),Pa=e.computed(()=>s.tracks.value),Fa=e.computed(()=>s.mediaSources.value),co=e.computed(()=>{var _,$;return((_=s.selectedClip.value)==null?void 0:_.sourceRefId)??(($=Fa.value[0])==null?void 0:$.id)}),Da=e.computed(()=>Pa.value.filter(_=>_.locked!==!0&&_.type==="video")),on=e.computed(()=>It.value?Pa.value.find(_=>_.id===It.value)??null:null),Ua=e.computed(()=>!!s.selectedClip.value&&s.playheadPosition.value>0),ha=e.computed(()=>!!s.selectedClip.value),Mn=e.computed(()=>s.timelineClips.value.length>0&&s.hasChanges.value),uo=e.computed(()=>s.selectedClip.value??s.timelineClips.value[0]??null),In=_=>{const $=Number.isFinite(_)&&_>0?Math.round(_):0,Y=Math.floor($/60),we=$%60;return`${Y}:${we.toString().padStart(2,"0")}`},mo=e.computed(()=>{const _=s.timelineClips.value.length,$=Pa.value.length,Y=_===1?"1 clip":`${_} clips`,we=$===1?"1 track":`${$} tracks`;return`${Y} / ${we} / ${In(I.value)}`});e.watch(()=>Pa.value.map(_=>`${_.id}:${_.locked===!0?"locked":"open"}`).join("|"),()=>{var _;It.value&&Da.value.some($=>$.id===It.value)||(It.value=((_=Da.value[0])==null?void 0:_.id)??null)},{immediate:!0}),e.watch(()=>{var _;return(_=s.selectedClip.value)==null?void 0:_.trackId},_=>{_&&Da.value.some($=>$.id===_)&&(It.value=_)},{immediate:!0});const hn=_=>{const $=Fa.value.find(Y=>Y.id===_);return $?$.filename??$.mediaUuid??$.url??$.id:"Asset"},Oa=n.assetUploader?NB({uploader:n.assetUploader,onReady:_=>{if(!_.mediaUrl&&!_.mediaUuid)return;const $={id:`imported-${_.assetId}`,type:_.mediaUuid?"media":"url",filename:_.filename,mimeType:_.mime,duration:_.durationSeconds??0,width:_.width??0,height:_.height??0};_.mediaUuid!==void 0&&($.mediaUuid=_.mediaUuid),_.mediaUrl!==void 0&&($.url=_.mediaUrl),s.registerMediaSource($),tt.value=`${_.filename} ready.`},onFailure:_=>{tt.value=_.failureMessage??`Upload of ${_.filename} failed.`}}):null,Ts=async _=>{if(!Oa){tt.value="Asset import is not configured for this editor host.";return}for(const $ of _){const Y=await Oa.importFile($);Y.ok||(tt.value=Y.message)}},Wo=_=>{var Pe;const $=s.appendMediaSourceToTimeline(_,It.value);if(!$.ok){ht.value=$.message;return}const Y=$.value;Y.trackId&&(It.value=Y.trackId),s.handleClipSelect(Y.id);const we=((Pe=on.value)==null?void 0:Pe.name)??"timeline";ht.value=`${hn(_)} added to ${we}.`,He()},Bs=_=>{if(!s.replaceSelectedClipSource(_)){ht.value="Select a clip before replacing its source.";return}ht.value=`${hn(_)} replaced the selected clip.`,He()},Ms=_=>{const $=hn(_);if(!s.removeMediaSource(_)){ht.value="Remove timeline clips before deleting this asset.";return}ht.value=`${$} removed.`,He()},$n=(_="video")=>{const $=s.addTimelineTrack(_);It.value=$.id,ht.value=`${$.name} added. New assets will be placed on that track.`,He()},va=_=>{const $=_.target;$&&(It.value=$.value||null)},vn=_=>{var Y;s.handleClipSelect(_);const $=(Y=s.selectedClip.value)==null?void 0:Y.trackId;$&&Da.value.some(we=>we.id===$)&&(It.value=$)},Ho=(_,$,Y)=>{const we=s.moveClip(_,$,Y);if(!we.ok){tt.value=we.message;return}He()},Zo=_=>{const $=s.deleteClip(_);if(!$.ok){tt.value=$.message;return}tt.value="Clip deleted.",He()},gn=(_,$)=>{$(_)&&He()},po=(_,$)=>{const Y=s.renameTimelineTrack(_,$);if(!Y.ok){tt.value=Y.message;return}tt.value=`Track renamed to "${$}".`,He()},rn=_=>{const $=s.deleteTimelineTrack(_);if(!$.ok){tt.value=$.message;return}It.value===_&&(It.value=null),tt.value="Track deleted.",He()},ra=(_,$)=>{const Y=s.reorderTimelineTrack(_,$);if(!Y.ok){tt.value=Y.message;return}tt.value=`Track moved ${$}.`,He()},Ta=_=>{ut.value=_},sn=()=>{ut.value=!ut.value},Xi=_=>{const $=_.target;if(!$)return;const Y=Number($.value);Number.isFinite(Y)&&s.setZoomLevel(Y)},oa=e.ref(!1),bn=e.ref(0),za=e.ref(!1),Lt=e.ref(null),ln=e.ref(null),fo=e.ref("preparing");let Fn=null,ja=!1;const Go={preparing:"Preparing export...",rendering:"Rendering frames...","encoding-video":"Encoding video...","encoding-audio":"Encoding audio...",muxing:"Muxing output...",storing:"Storing export...",complete:"Export complete"},ho=_=>typeof _=="string"&&_ in Go,Wa=(_,$)=>{fo.value=_,Lt.value=typeof $=="string"&&$.trim()!==""?$.trim():Go[_]},Ea=(_,$,Y)=>{const we=Number.isFinite(_)?Math.max(0,Math.min(100,_)):0;bn.value=we,$&&Wa($,Y)},Xo=_=>{if(ho(_.phase))return _.phase;switch(_.status){case"pending":return"preparing";case"processing":return"rendering";case"completed":return"complete";default:return fo.value}},Ki=_=>typeof _.progress_message=="string"&&_.progress_message.trim()!==""?_.progress_message.trim():void 0,Dn=(_,$,Y={allowClient:!0})=>{if(!Number.isFinite($)||$<=0||_.timeline.length===0)return{route:"unsupported",exportDuration:$,message:"Export unavailable: the recipe has no renderable duration."};if(n.maxDuration>0&&$>n.maxDuration)return{route:"unsupported",exportDuration:$,message:`Export unavailable: duration exceeds the ${n.maxDuration}s limit.`};if(Y.allowClient&&n.clientExportThreshold>0&&$<=n.clientExportThreshold)return{route:"client",exportDuration:$};const Pe=!!n.serverRenderEndpoint,Ue=r.value.startsWith("temp-");return Pe&&!Ue?{route:"server-render",exportDuration:$}:{route:"recipe-download",exportDuration:$,message:Ue?"Local media — downloaded recipe.json. Client-side PIXI export is unavailable on this device.":"No server render endpoint configured — downloaded recipe.json."}},vo=()=>new Ss(n.serverRenderEndpoint??"/api/v1"),Ha=()=>{Fn!==null&&(clearInterval(Fn),Fn=null)},Ji=_=>{Ha();const $=vo();Fn=setInterval(async()=>{if(ja){Ha();return}try{const Y=await $.getJob(_),we=Number(Y.progress??0);if(Ea(we,Xo(Y),Ki(Y)),i("server-render-progress",bn.value),Y.status==="completed"||Y.status==="failed"||Y.status==="cancelled")if(Ha(),oa.value=!1,ln.value=null,Y.status==="completed"){Ea(100,"complete"),za.value=!0,Lt.value=null;const Pe=typeof Y.output_media_id=="string"?Y.output_media_id:void 0,Ue={id:_};Pe!==void 0&&(Ue.output_media_id=Pe),i("server-render-completed",Ue)}else{const Pe=Y.status==="cancelled"||typeof Y.error_message=="string"&&/cancel/i.test(Y.error_message),Ue=Pe?"Export canceled.":typeof Y.error_message=="string"&&Y.error_message.trim()!==""?Y.error_message:"Export failed";Lt.value=Ue,Pe||i("server-render-failed",Ue)}}catch(Y){Ha(),oa.value=!1,ln.value=null;const we=Y instanceof Error?Y.message:"Failed to check export progress";Lt.value=we,i("server-render-failed",we)}},2e3)},go=_=>{const $=new Blob([JSON.stringify(_,null,2)],{type:"application/json"}),Y=URL.createObjectURL($),we=document.createElement("a");we.href=Y,we.download=`video-recipe-${Date.now()}.json`,we.click(),setTimeout(()=>URL.revokeObjectURL(Y),100)},bo=()=>{Ha(),ja=!1,F.resetClientExport(),ln.value=null,Lt.value=null,za.value=!1,bn.value=0,fo.value="preparing"},yn=async _=>{Ea(0,"preparing");const Y=await vo().createRenderJob({source_media_uuid:r.value,recipe:_}),we=typeof Y.id=="string"?Y.id:null;if(!we)throw new Error("Export failed: missing job id");ln.value=we,i("export-started",we),i("server-render-started",we),Ea(1,"rendering"),Ji(we)},Ko=async(_,$)=>{if(!await F.canExportClientSide())return null;const Y=await F.renderRecipeWithPixi(_,$,we=>{ja||Ea(we,"rendering")});return ja?(Lt.value="Export canceled.",Ea(0),i("video-exported",null),null):(s.clearHasChanges(),i("recipe-generated",_),i("video-exported",Y),Ea(100,"complete"),za.value=!0,Y)},Rn=async _=>{bo(),oa.value=!0,Wa("preparing");try{const $=pt(Ot(ft(s.generateRecipe(),_)));me($,"before-export",!1),i("recipe-generated",$);const Y=zc($,I.value),we=Dn($,Y);if(we.route==="unsupported"){oa.value=!1,Lt.value=we.message??"Export unavailable.",i("server-render-failed",Lt.value);return}if(we.route==="client"){const Ue=await Ko($,_);if(Ue!==null){const dt=URL.createObjectURL(Ue.file),Nt=document.createElement("a");Nt.href=dt,Nt.download=`edited-video-${Date.now()}.mp4`,Nt.click(),setTimeout(()=>URL.revokeObjectURL(dt),100),oa.value=!1;return}}const Pe=we.route==="client"?Dn($,Y,{allowClient:!1}):we;if(Pe.route==="unsupported"){oa.value=!1,Lt.value=Pe.message??"Export unavailable.",i("server-render-failed",Lt.value);return}if(Pe.route==="recipe-download"){go($),oa.value=!1,Ea(100,"complete"),za.value=!0,Lt.value=Pe.message??"Downloaded recipe.json.";return}await yn($)}catch($){const Y=pt(s.generateRecipe());go(Y);const we=$ instanceof Error?$.message:"Export failed";oa.value=!1,Ea(0),ln.value=null,Lt.value=we,i("server-render-failed",we)}},yo=async()=>{ja=!0,E.value=!1,F.cancelClientExport();const _=ln.value;if(Ha(),oa.value=!1,Ea(0),Lt.value="Export canceled.",ln.value=null,_&&n.serverRenderEndpoint)try{await vo().cancelJob(_)}catch{}},An=()=>{s.togglePlayback()},wo=()=>{s.resetChanges()},wn=()=>{const _=_a();i("draft-saved",_)},qi=()=>{Rn()},Jo=()=>{i("close")};a({saveDraft:async()=>{const _=_a();return i("draft-saved",_),_},exportForUpload:async _=>{bo();const $=pt(_??s.generateRecipe()),Y=Ot($),we=Array.isArray(Y.filters)&&Y.filters.length>0,Pe=wt(Y);if(!(s.hasChanges.value||we||Pe))return s.clearHasChanges(),i("video-exported",null),null;const dt=zc(Y,I.value),Nt=Dn(Y,dt);if(Nt.route==="unsupported"){const Zt=Nt.message??"Export unavailable.";throw Lt.value=Zt,new Error(`Video export failed: ${Zt}`)}if(Nt.route==="server-render")return oa.value=!0,await yn(Y),null;oa.value=!0;try{if(Nt.route==="client"){const ma=await Ko(Y);if(ma!==null)return ma}const Zt=Nt.route==="client"?Dn(Y,dt,{allowClient:!1}):Nt;if(Zt.route==="server-render")return await yn(Y),null;if(Zt.route==="unsupported"){const ma=Zt.message??"Export unavailable.";throw Lt.value=ma,new Error(`Video export failed: ${ma}`)}return Lt.value=Zt.message??"Export unavailable for upload.",i("video-exported",null),null}catch(Zt){if(ja)return Lt.value="Export canceled.",Ea(0),i("video-exported",null),null;const ma=Zt instanceof Error?Zt.message:"Local WebGL export failed.";throw Lt.value=ma,new Error(`Video export failed: ${ma}`)}finally{oa.value=!1}}});const ko=e.ref(!1),qo=_=>{var Ue,dt;const $=[...s.timelineClips.value].sort((Nt,Zt)=>Nt.timelineStart-Zt.timelineStart);if($.length===0)return;const Y=s.selectedClip.value;if(!Y){s.handleClipSelect(((Ue=$[0])==null?void 0:Ue.id)??null);return}const we=$.findIndex(Nt=>Nt.id===Y.id);if(we===-1){s.handleClipSelect(((dt=$[0])==null?void 0:dt.id)??null);return}const Pe=_==="next"?$[Math.min(we+1,$.length-1)]:$[Math.max(we-1,0)];Pe&&s.handleClipSelect(Pe.id)},Yo=()=>{s.seekTo(Math.min(s.totalDuration.value,s.playheadPosition.value+1))},Yi=()=>{s.seekTo(Math.max(0,s.playheadPosition.value-1))};return vB({playPause:An,frameForward:s.frameForward,frameBackward:s.frameBackward,secondForward:Yo,secondBackward:Yi,skipToStart:s.skipToStart,skipToEnd:s.skipToEnd,prevClip:()=>qo("prev"),nextClip:()=>qo("next"),splitAtPlayhead:s.splitAtPlayhead,deleteSelected:()=>{const _=s.deleteSelectedClip();_.ok?tt.value="Clip deleted.":tt.value=_.message},rippleDeleteSelected:()=>{s.rippleDeleteSelectedClip()?tt.value="Clip removed and gap closed.":tt.value="Nothing to ripple-delete."},undo:s.undo,redo:s.redo,save:wn,exportNow:()=>{if(s.timelineClips.value.length===0){tt.value="Add media to export.";return}qi()},showShortcutsOverlay:()=>{ko.value=!0}}),e.onMounted(()=>{document.documentElement.setAttribute("data-video-editor-version","v2"),J()}),e.onBeforeUnmount(()=>{document.documentElement.getAttribute("data-video-editor-version")==="v2"&&document.documentElement.removeAttribute("data-video-editor-version")}),e.onUnmounted(()=>{Ha(),ja=!0,F.cancelClientExport(),Ye&&(clearTimeout(Ye),Ye=null),W.value&&(W.value.destroy(),W.value=null),U.value=null,j.value=null}),(_,$)=>(e.openBlock(),e.createElementBlock(e.Fragment,null,[e.createVNode(AV,{"data-testid":"video-editor-v2"},{toolbar:e.withCtx(()=>[e.createElementVNode("div",BB,[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["v2-toolbar-btn",{"is-active":e.unref(s).isPlaying.value}]),"data-testid":"v2-btn-play","aria-label":e.unref(s).isPlaying.value?"Pause":"Play",onClick:An},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(s).isPlaying.value?e.unref(ed):e.unref(td),"aria-hidden":"true"},null,8,["icon"])],10,MB),e.createElementVNode("button",{type:"button",class:"v2-toolbar-btn","data-testid":"v2-btn-reset","aria-label":"Reset all changes",disabled:!e.unref(s).hasChanges.value,onClick:wo},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(io),"aria-hidden":"true"},null,8,["icon"])],8,IB)]),$[20]||($[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",$B,[e.createElementVNode("label",FB,[$[18]||($[18]=e.createElementVNode("span",{class:"sr-only"},"Fit mode",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":$[0]||($[0]=Y=>B.value=Y),"aria-label":"Fit mode","data-testid":"v2-select-fit-mode"},[...$[17]||($[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(s).hasChanges.value,onClick:wn},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Qr),"aria-hidden":"true"},null,8,["icon"]),$[19]||($[19]=e.createElementVNode("span",{class:"v2-toolbar-btn-label"},"Save",-1))],8,DB),e.createElementVNode("button",{type:"button",class:"v2-toolbar-btn","data-testid":"v2-btn-export","aria-label":e.unref(s).timelineClips.value.length===0?"Export disabled — add media first":"Export",title:e.unref(s).timelineClips.value.length===0?"Add media to export":void 0,disabled:oa.value||e.unref(s).timelineClips.value.length===0,onClick:qi},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref($o),"aria-hidden":"true"},null,8,["icon"])],8,RB),e.createElementVNode("button",{type:"button",class:"v2-toolbar-btn","data-testid":"v2-btn-close","aria-label":"Close editor",onClick:Jo},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Yn),"aria-hidden":"true"},null,8,["icon"])])])]),assets:e.withCtx(()=>[e.createElementVNode("div",AB,[e.createVNode(JV,{sources:Fa.value,"selected-source-id":co.value,"uploads-enabled":!!_.assetUploader,onAdd:Wo,onReplaceSelected:Bs,onRemove:Ms,onImportFiles:Ts},null,8,["sources","selected-source-id","uploads-enabled"]),ht.value?(e.openBlock(),e.createElementBlock("p",LB,e.toDisplayString(ht.value),1)):e.createCommentVNode("",!0)])]),canvas:e.withCtx(()=>[e.createElementVNode("div",PB,[e.withDirectives(e.createVNode(ul,{ref_key:"pixiPreviewRef",ref:b,class:"v2-preview-child","aria-hidden":!k.value,source:x.value,"fallback-duration":I.value,filters:M.value,playhead:w.value,"is-playing":e.unref(s).isPlaying.value,"fit-mode":B.value,active:k.value,onPlayPause:An,onFrameUpdate:z,onDurationChange:Z},null,8,["aria-hidden","source","fallback-duration","filters","playhead","is-playing","fit-mode","active"]),[[e.vShow,k.value]]),e.withDirectives(e.createVNode(Vl,{class:"v2-preview-child","aria-hidden":!g.value,"media-uuid":r.value,recipe:C.value,media:P.value,"enable-engine":g.value&&D.value,"fit-mode":B.value,onTimeUpdate:K,onPlayStateChange:se,onDurationChange:Z,onEngineReady:Pt},null,8,["aria-hidden","media-uuid","recipe","media","enable-engine","fit-mode"]),[[e.vShow,g.value]])])]),timeline:e.withCtx(({isMobile:Y})=>{var we,Pe;return[e.createElementVNode("div",{class:e.normalizeClass(["v2-timeline",{"is-mobile":!!Y}])},[e.createElementVNode("div",UB,[e.createElementVNode("div",OB,[$[21]||($[21]=e.createElementVNode("span",{class:"v2-timeline-title","data-testid":"v2-timeline-title"},"Timeline",-1)),e.createElementVNode("span",zB,e.toDisplayString(mo.value),1)]),e.createElementVNode("label",jB,[$[22]||($[22]=e.createElementVNode("span",null,"Zoom",-1)),e.createElementVNode("input",{type:"range",min:"10",max:"600",value:e.unref(s).zoomLevel.value,"aria-label":"Timeline zoom","data-testid":"v2-timeline-zoom",onInput:Xi},null,40,WB),e.createElementVNode("span",HB,e.toDisplayString(Math.round(e.unref(s).zoomLevel.value))+" px/s",1)]),Y?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",ZB,[e.createElementVNode("button",{type:"button",class:"v2-toolbar-btn v2-toolbar-btn--ghost","data-testid":"v2-btn-add-track",onClick:$[1]||($[1]=Ue=>$n("video"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(wr)},null,8,["icon"]),$[23]||($[23]=e.createTextVNode(" Add Track ",-1))]),Da.value.length>0?(e.openBlock(),e.createElementBlock("label",GB,[$[24]||($[24]=e.createElementVNode("span",null,"Place clips in",-1)),e.createElementVNode("select",{value:It.value??"","data-testid":"v2-select-target-track","aria-label":"Target track for added assets",onChange:va},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Da.value,Ue=>(e.openBlock(),e.createElementBlock("option",{key:Ue.id,value:Ue.id},e.toDisplayString(Ue.name),9,KB))),128))],40,XB)])):e.createCommentVNode("",!0)])),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["v2-toolbar-btn v2-toolbar-btn--ghost",{"is-active":ut.value}]),"data-testid":"v2-btn-snap-toggle","aria-pressed":ut.value?"true":"false",onClick:sn},e.toDisplayString(ut.value?"Snap On":"Snap Off"),11,JB)]),tt.value?(e.openBlock(),e.createElementBlock("p",qB,e.toDisplayString(tt.value),1)):e.createCommentVNode("",!0),e.unref(s).timelineClips.value.length===0?(e.openBlock(),e.createElementBlock("div",YB,[...$[25]||($[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(Nl,{key:2,playhead:e.unref(s).playheadPosition.value,clips:e.unref(s).timelineClips.value,tracks:Pa.value,"selected-clip-id":((we=e.unref(s).selectedClip.value)==null?void 0:we.id)??((Pe=e.unref(s).timelineClips.value[0])==null?void 0:Pe.id)??null,duration:I.value,fps:e.unref(s).fps.value,"is-mobile":!!Y,"zoom-level":e.unref(s).zoomLevel.value,"snap-enabled":ut.value,sensitivity:.25,"onUpdate:playhead":$[2]||($[2]=Ue=>e.unref(s).seekTo(Ue)),onTrim:$[3]||($[3]=(Ue,dt,Nt)=>e.unref(s).handleTrim(Ue,dt,Nt)),onSplit:$[4]||($[4]=Ue=>e.unref(s).handleSplit(Ue)),onClipSelect:vn,onClipDelete:Zo,onClipMove:Ho,onSnapStateChange:Ta,onToggleLock:$[5]||($[5]=Ue=>gn(Ue,e.unref(s).toggleTrackLock)),onToggleHidden:$[6]||($[6]=Ue=>gn(Ue,e.unref(s).toggleTrackHidden)),onToggleMuted:$[7]||($[7]=Ue=>gn(Ue,e.unref(s).toggleTrackMuted)),onToggleSolo:$[8]||($[8]=Ue=>gn(Ue,e.unref(s).toggleTrackSolo)),onRenameTrack:po,onDeleteTrack:rn,onReorderTrack:ra},null,8,["playhead","clips","tracks","selected-clip-id","duration","fps","is-mobile","zoom-level","snap-enabled"])),e.createVNode(Tl,{"selected-clip":e.unref(s).selectedClip.value,"can-split":Ua.value,"can-delete":ha.value,"can-undo":e.unref(s).canUndo.value,"can-redo":e.unref(s).canRedo.value,"is-playing":e.unref(s).isPlaying.value,"zoom-level":e.unref(s).zoomLevel.value,"playback-speed":e.unref(s).playbackSpeed.value,"is-mobile":!!Y,"show-add-track":!!Y,onSplit:e.unref(s).splitAtPlayhead,onDelete:e.unref(s).deleteSelectedClip,onAddTrack:$[9]||($[9]=Ue=>$n("video")),onDuplicate:e.unref(s).duplicateSelectedClip,onUndo:e.unref(s).undo,onRedo:e.unref(s).redo,onZoomIn:e.unref(s).zoomIn,onZoomOut:e.unref(s).zoomOut,onZoomChange:e.unref(s).setZoomLevel,onFitToWindow:e.unref(s).fitToWindow,onPlayPause:An,onFrameForward:e.unref(s).frameForward,onFrameBackward:e.unref(s).frameBackward,onSkipToStart:e.unref(s).skipToStart,onSkipToEnd:e.unref(s).skipToEnd,onSpeedChange:e.unref(s).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(()=>[Ze.value.length>0?(e.openBlock(),e.createBlock(gu,{key:0,class:"v2-draft-recovery",records:Ze.value,surface:"desktop","project-id":qe.value,"saved-at":et.value,onRestore:Ne,onDismiss:We},null,8,["records","project-id","saved-at"])):e.createCommentVNode("",!0),e.createVNode(MT,{"active-tab":d.value,"onUpdate:activeTab":$[10]||($[10]=Y=>d.value=Y),tabs:f.value},{filters:e.withCtx(()=>[e.createVNode(Bl,{filters:Be.value,"active-filters":ce.value,"thumbnail-url":ie.value,onApplyFilter:ea,onRemoveFilter:Jt,onUpdateParam:ta,onPreviewFilter:fa},null,8,["filters","active-filters","thumbnail-url"])]),adjustments:e.withCtx(()=>[e.unref(l).selectedFilter.value?(e.openBlock(),e.createBlock(Ml,{key:0,filter:e.unref(l).selectedFilter.value,"current-frame":e.unref(s).currentFrame.value,onUpdateParams:Q},null,8,["filter","current-frame"])):(e.openBlock(),e.createElementBlock("div",QB,[...$[26]||($[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:ct.value,target:"all","device-class":"desktop",onApplyPreset:Bt},null,8,["duration"])]),text:e.withCtx(()=>[e.createVNode($l,{overlays:Ae.value,onAddOverlay:he,onUpdateOverlay:ue,onRemoveOverlay:le},null,8,["overlays"]),e.createVNode(vu,{class:"v2-caption-panel","caption-track":bt.value,layout:"desktop",onImport:De,"onUpdate:captionTrack":Tt,onClear:Dt},null,8,["caption-track"])]),transitions:e.withCtx(()=>[e.createVNode(Fl,{"selected-clips":$t.value,"applied-transitions":gt.value,onApplyTransition:Te,onRemoveTransition:ze,onPreviewTransition:ot},null,8,["selected-clips","applied-transitions"])]),audio:e.withCtx(()=>[e.createVNode(Dl,{"audio-layers":lt.value,"master-volume":Et.value,onAddTrack:St,onUpdateTrack:Ft,onRemoveTrack:Vt,onUpdateVolume:Ct,onToggleMute:Ht,onUpdateMasterVolume:X},null,8,["audio-layers","master-volume"]),e.createVNode(hu,{class:"v2-audio-mixer",state:At.value,"device-class":"desktop",onUpdate:te},null,8,["state"])]),export:e.withCtx(()=>[e.createVNode(Il,{"can-export":Mn.value,"is-exporting":oa.value,"export-progress":bn.value,onExport:Rn,onCancelExport:yo,onSaveDraft:wn,onReset:wo},null,8,["can-export","is-exporting","export-progress"]),za.value?(e.openBlock(),e.createElementBlock("div",e4," Export complete ")):e.createCommentVNode("",!0),Lt.value&&!za.value?(e.openBlock(),e.createElementBlock("div",t4,e.toDisplayString(Lt.value),1)):e.createCommentVNode("",!0)]),_:1},8,["active-tab","tabs"])]),drawer:e.withCtx(()=>[e.createVNode(pB,{ref_key:"mobileDrawerRef",ref:u,"initial-snap":"half","aria-label":"Video editor controls"},{default:e.withCtx(()=>[Ze.value.length>0?(e.openBlock(),e.createBlock(gu,{key:0,class:"v2-draft-recovery",records:Ze.value,surface:"mobile","project-id":qe.value,"saved-at":et.value,onRestore:Ne,onDismiss:We},null,8,["records","project-id","saved-at"])):e.createCommentVNode("",!0),e.createVNode(aB,{"selected-clip":uo.value,onOpenActions:$[11]||($[11]=Y=>c.value="trim")},null,8,["selected-clip"]),e.createVNode(sB,{modelValue:c.value,"onUpdate:modelValue":$[12]||($[12]=Y=>c.value=Y)},null,8,["modelValue"]),c.value==="look"?(e.openBlock(),e.createElementBlock("section",a4,[e.createElementVNode("div",n4,[e.createVNode(Bl,{filters:Be.value,"active-filters":ce.value,"thumbnail-url":ie.value,onApplyFilter:ea,onRemoveFilter:Jt,onUpdateParam:ta,onPreviewFilter:fa},null,8,["filters","active-filters","thumbnail-url"])]),e.createElementVNode("div",o4,[e.unref(l).selectedFilter.value?(e.openBlock(),e.createBlock(Ml,{key:0,filter:e.unref(l).selectedFilter.value,"current-frame":e.unref(s).currentFrame.value,onUpdateParams:Q},null,8,["filter","current-frame"])):(e.openBlock(),e.createElementBlock("div",i4,[...$[27]||($[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",r4,[e.createVNode(Tl,{"selected-clip":e.unref(s).selectedClip.value,"can-split":Ua.value,"can-delete":ha.value,"can-undo":e.unref(s).canUndo.value,"can-redo":e.unref(s).canRedo.value,"is-playing":e.unref(s).isPlaying.value,"zoom-level":e.unref(s).zoomLevel.value,"playback-speed":e.unref(s).playbackSpeed.value,"is-mobile":"","show-add-track":"",onSplit:e.unref(s).splitAtPlayhead,onDelete:e.unref(s).deleteSelectedClip,onAddTrack:$[13]||($[13]=Y=>$n("video")),onDuplicate:e.unref(s).duplicateSelectedClip,onUndo:e.unref(s).undo,onRedo:e.unref(s).redo,onZoomIn:e.unref(s).zoomIn,onZoomOut:e.unref(s).zoomOut,onZoomChange:e.unref(s).setZoomLevel,onFitToWindow:e.unref(s).fitToWindow,onPlayPause:An,onFrameForward:e.unref(s).frameForward,onFrameBackward:e.unref(s).frameBackward,onSkipToStart:e.unref(s).skipToStart,onSkipToEnd:e.unref(s).skipToEnd,onSpeedChange:e.unref(s).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",s4,[e.createVNode($l,{overlays:Ae.value,onAddOverlay:he,onUpdateOverlay:ue,onRemoveOverlay:le},null,8,["overlays"]),e.createVNode(vu,{"caption-track":bt.value,layout:"mobile",onImport:De,"onUpdate:captionTrack":Tt,onClear:Dt},null,8,["caption-track"])])):c.value==="audio"?(e.openBlock(),e.createElementBlock("section",l4,[e.createVNode(Dl,{"audio-layers":lt.value,"master-volume":Et.value,onAddTrack:St,onUpdateTrack:Ft,onRemoveTrack:Vt,onUpdateVolume:Ct,onToggleMute:Ht,onUpdateMasterVolume:X},null,8,["audio-layers","master-volume"]),e.createVNode(hu,{state:At.value,"device-class":"mobile",onUpdate:te},null,8,["state"])])):c.value==="export"?(e.openBlock(),e.createElementBlock("section",d4,[e.createVNode(Il,{"can-export":Mn.value,"is-exporting":oa.value,"export-progress":bn.value,"is-mobile":"",onExport:Rn,onCancelExport:yo,onSaveDraft:wn,onReset:wo},null,8,["can-export","is-exporting","export-progress"]),za.value?(e.openBlock(),e.createElementBlock("div",c4,"Export complete")):e.createCommentVNode("",!0),Lt.value&&!za.value?(e.openBlock(),e.createElementBlock("div",u4,e.toDisplayString(Lt.value),1)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("section",m4,[e.createElementVNode("div",p4,[e.createElementVNode("label",f4,[$[29]||($[29]=e.createElementVNode("span",null,"Fit",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":$[14]||($[14]=Y=>B.value=Y),"aria-label":"Mobile fit mode"},[...$[28]||($[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":ut.value}]),"aria-pressed":ut.value?"true":"false","data-testid":"v2-mobile-btn-snap-toggle",onClick:sn},e.toDisplayString(ut.value?"Snap On":"Snap Off"),11,h4),e.createElementVNode("button",{type:"button",class:"v2-mobile-secondary-button","data-testid":"v2-mobile-btn-reset",disabled:!e.unref(s).hasChanges.value,onClick:wo}," Reset ",8,v4),e.createElementVNode("button",{type:"button",class:"v2-mobile-secondary-button","data-testid":"v2-mobile-btn-save",disabled:!e.unref(s).hasChanges.value,onClick:wn}," Save ",8,g4)]),v.value?(e.openBlock(),e.createElementBlock("details",b4,[$[30]||($[30]=e.createElementVNode("summary",null,"Transitions",-1)),e.createVNode(Fl,{"selected-clips":$t.value,"applied-transitions":gt.value,onApplyTransition:Te,onRemoveTransition:ze,onPreviewTransition:ot},null,8,["selected-clips","applied-transitions"])])):e.createCommentVNode("",!0),e.createElementVNode("details",y4,[$[31]||($[31]=e.createElementVNode("summary",null,"Keyframe presets",-1)),e.createVNode(bu,{duration:ct.value,target:"all","device-class":"mobile",onApplyPreset:Bt},null,8,["duration"])])]))]),_:1},512)]),_:1}),ko.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:$[16]||($[16]=e.withModifiers(Y=>ko.value=!1,["self"]))},[e.createElementVNode("div",w4,[e.createElementVNode("div",k4,[$[32]||($[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:$[15]||($[15]=Y=>ko.value=!1)},"×")]),$[33]||($[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))}}),E4=Fe(_4,[["__scopeId","data-v-aa4426a6"]]),Aa=o=>o===null||typeof o!="object"||Array.isArray(o)?null:o,kt=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},S4=(o,a)=>{if(a===null)return;const t=Aa(o.source)??{},n=kt(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=Aa(r[0]);if(d!==null){const c=kt(d.sourceIn)??0,u=kt(d.sourceOut)??kt(d.end)??kt(d.timelineEnd);if(c===0&&u!==null&&u>0&&u<=1){d.sourceOut=a;const f=kt(d.end);f!==null&&f>0&&f<=1&&(d.end=a);const p=kt(d.timelineEnd);p!==null&&p>0&&p<=1&&(d.timelineEnd=a)}}}const s=kt(o.trimEnd)??kt(o.trim_end);s!==null&&s>0&&s<=1&&(o.trimEnd=a);const l=Aa(o.trim);if(l!==null){const d=kt(l.end);d!==null&&d>0&&d<=1&&(l.end=a,o.trim=l)}},C4=(o,a)=>{if(!o)return!1;const t=Aa(o);if(t===null)return!1;const n=Aa(t.trim),i=Aa(t.source),s=kt(i==null?void 0:i.duration)??a,l=Array.isArray(o.filters)&&o.filters.length>0;let d=!1;if(Array.isArray(o.timeline)&&o.timeline.length===1){const p=o.timeline[0];p&&Array.isArray(p.filters)&&p.filters.length>0&&(d=!0)}let c=!1;const u=kt(t.trimStart)??kt(t.trim_start)??kt(n==null?void 0:n.start),m=kt(t.trimEnd)??kt(t.trim_end)??kt(n==null?void 0:n.end);if(u!==null&&u>0&&(c=!0),m!==null&&s!==void 0&&m<s&&(c=!0),!c&&Array.isArray(o.timeline)&&o.timeline.length===1){const p=o.timeline[0];if(p){const h=kt(p.sourceIn),v=kt(p.sourceOut);h!==null&&h>0&&(c=!0),v!==null&&s!==void 0&&v<s&&(c=!0)}}let f=!1;if(Array.isArray(o.timeline)&&o.timeline.length===1){const p=o.timeline[0];if(p){const h=kt(p.speed);f=h!==null&&h!==1}}return l||d||c||f},tf=o=>{if(!o)return!1;const a=Aa(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)},x4=(o,a={})=>{var f,p;const t=JSON.parse(JSON.stringify(o)),n=Array.isArray(t.timeline)?t.timeline:[],i=n.length>0?Aa(n[0]):null,r=Array.isArray(i==null?void 0:i.filters)?i.filters:[],s=Array.isArray(t.filters)?t.filters:[];if(s.length>0?t.filters=s:t.filters=r,n.length===1&&i!==null){const h=kt(i.sourceIn),v=kt(i.sourceOut);h!==null&&t.trimStart===void 0&&(t.trimStart=h),v!==null&&t.trimEnd===void 0&&(t.trimEnd=v)}const l=Aa(t.trim);if(t.trimStart===void 0){const h=kt(l==null?void 0:l.start);h!==null&&(t.trimStart=h)}if(t.trimEnd===void 0){const h=kt(l==null?void 0:l.end);h!==null&&(t.trimEnd=h)}const d=Aa(t.source),c=kt(t.width)??kt(d==null?void 0:d.original_width)??kt((f=a.exportMeta)==null?void 0:f.width);c!==null&&(t.width=c);const u=kt(t.height)??kt(d==null?void 0:d.original_height)??kt((p=a.exportMeta)==null?void 0:p.height);u!==null&&(t.height=u);const m=Aa(t.output);return t.fps=kt(t.fps)??kt(m==null?void 0:m.fps)??30,S4(t,a.mediaDuration??null),t},V4={key:0},N4=["data-testid"],T4={class:"ve-mobile-header"},B4=["data-testid"],M4={class:"ve-mobile-title"},I4=["data-testid","disabled"],$4={key:1,class:"ve-mobile-spacer","aria-hidden":"true"},F4={class:"ve-body"},D4=["data-testid"],R4=["aria-label"],A4={class:"ve-header"},L4={class:"ve-title"},P4=["data-testid"],U4={class:"ve-body"},O4={class:"ve-footer"},z4=["data-testid"],j4=["data-testid","disabled"],W4=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),s=e.computed(()=>n.open),l=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),f=e.ref(!1),p=e.ref(null),h=`temp-${Date.now()}`,v=e.computed(()=>{var I;const O=(I=n.featureFlags)==null?void 0:I.export;return typeof O=="boolean"?O:n.workflowMode==="full"}),E=e.computed(()=>{if(n.editorVersion==="v1"||n.editorVersion==="v2")return n.editorVersion;if(typeof window>"u")return"v2";try{const O=new URLSearchParams(window.location.search),I=O.get("editor")??O.get("video-editor");if(I==="v1")return"v1";if(I==="v2")return"v2"}catch{}return"v2"}),y=e.computed(()=>E.value==="v2"?E4:Yp),k=e.computed(()=>typeof n.mediaUuid=="string"&&n.mediaUuid.trim()!==""?n.mediaUuid.trim():n.media&&n.media.uuid.trim()!==""?n.media.uuid.trim():h),g=e.computed(()=>{const O={showThumbnailPicker:n.showThumbnailPicker,workflowMode:n.workflowMode,clientExportThreshold:n.clientExportThreshold,maxDuration:n.maxDuration,serverRenderEndpoint:n.serverRenderEndpoint};return n.featureFlags!==void 0&&(O.featureFlags=n.featureFlags),n.initialRecipe!==void 0&&(O.initialRecipe=n.initialRecipe),n.media!==void 0&&(O.media=n.media),O}),b=()=>{u.value=window.innerWidth<768};e.onMounted(()=>{window.addEventListener("resize",b)}),e.onUnmounted(()=>{window.removeEventListener("resize",b)}),e.onErrorCaptured(()=>(f.value=!0,!1));const R=O=>{const I=Array.isArray(O.timeline)?O.timeline:[];if(I.length===0)return 0;let Z=0;for(const z of I){const K=Number(z.sourceIn),se=Number(z.sourceOut),Be=Number(z.speed??1),ce=Number.isFinite(Be)&&Be>0?Be:1;if(Number.isFinite(K)&&Number.isFinite(se)&&se>K){Z+=(se-K)/ce;continue}const ie=Number(z.timelineStart),W=Number(z.timelineEnd);Number.isFinite(ie)&&Number.isFinite(W)&&W>ie&&(Z+=W-ie)}return Z},N=(O,I,Z)=>{let z=null;const K=new Promise((se,Be)=>{z=setTimeout(()=>Be(new Error(`${Z} timed out after ${I}ms`)),I)});return Promise.race([O,K]).finally(()=>{z!==null&&clearTimeout(z)})},T=()=>{var K;const Z=(K=n.media)==null?void 0:K.duration;if(typeof Z!="number"||!Number.isFinite(Z)||Z<=0)return 12e3;const z=Math.round(Z*1e3);return Math.min(45e3,Math.max(12e3,z))},S=()=>{i("close"),i("update:open",!1)},B=()=>{m.value=!1,S()},A=O=>{i("recipe-generated",O)},x=O=>{i("export-started",O),i("save-started",O)},M=O=>{i("video-exported",O)},w=O=>{i("thumbnail-selected",O)},F=(O,I,Z)=>{i("save-recipe",O);const z={recipe:O,exportPayload:I};Z!==void 0&&(z.toastDescription=Z),i("save-complete",z),S()},P=O=>{m.value||(i("draft-saved",O),F(O,null))},D=async()=>{var O;if(!m.value){if(f.value||p.value===null){i("save-error",{code:"save-failed",message:"Unable to save video edits. Please try again."}),S();return}m.value=!0;try{const I=await N(p.value.saveDraft(),T(),"saveDraft");let Z=null,z=!1,K;const se=R(I),Be=se>0?se:((O=n.media)==null?void 0:O.duration)??0;if(v.value&&Be>0&&Be<=n.clientExportThreshold&&typeof p.value.exportForUpload=="function"){z=!0;const ie=Math.min(9e4,Math.max(15e3,n.clientExportThreshold*2e3));try{Z=await N(p.value.exportForUpload(I),ie,"exportForUpload")}catch{Z=null}}if(tf(I)&&Z===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}z&&Z===null&&(K="Video edits saved. Final render will happen when you share."),F(I,Z,K)}catch{i("save-error",{code:"save-failed",message:"Unable to save video edits. Please try again."}),S()}finally{m.value=!1}}};return a({saveDraft:D}),(O,I)=>(e.openBlock(),e.createBlock(e.Teleport,{to:"body"},[s.value?(e.openBlock(),e.createElementBlock("div",V4,[u.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"ve-fullscreen","data-testid":r.value},[e.createElementVNode("header",T4,[e.createElementVNode("button",{class:"ve-mobile-action",type:"button","data-testid":`${r.value}-close-button`,onClick:B},e.toDisplayString(d.value),9,B4),e.createElementVNode("h2",M4,e.toDisplayString(O.title),1),l.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:D},e.toDisplayString(c.value),9,I4)):(e.openBlock(),e.createElementBlock("span",$4))]),e.createElementVNode("section",F4,[(e.openBlock(),e.createBlock(e.resolveDynamicComponent(y.value),e.mergeProps({ref_key:"videoEditorRef",ref:p,"media-uuid":k.value,"data-editor-version":E.value},g.value,{onClose:B,onDraftSaved:P,onExportStarted:x,onRecipeGenerated:A,onThumbnailSelected:w,onVideoExported:M}),null,16,["media-uuid","data-editor-version"]))])],8,N4)):(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":O.title,"aria-modal":"true"},[e.createElementVNode("header",A4,[e.createElementVNode("h2",L4,e.toDisplayString(O.title),1),e.createElementVNode("button",{class:"ve-close",type:"button","data-testid":`${r.value}-close-button`,"aria-label":"Close",onClick:B}," ✕ ",8,P4)]),e.createElementVNode("section",U4,[(e.openBlock(),e.createBlock(e.resolveDynamicComponent(y.value),e.mergeProps({ref_key:"videoEditorRef",ref:p,"media-uuid":k.value,"data-editor-version":E.value},g.value,{onClose:B,onDraftSaved:P,onExportStarted:x,onRecipeGenerated:A,onThumbnailSelected:w,onVideoExported:M}),null,16,["media-uuid","data-editor-version"]))]),e.createElementVNode("footer",O4,[e.renderSlot(O.$slots,"footer",{close:B,isSaving:m.value,save:D},()=>[e.createElementVNode("button",{class:"ve-btn",type:"button","data-testid":`${r.value}-cancel-button`,onClick:B},e.toDisplayString(d.value),9,z4),l.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:D},e.toDisplayString(c.value),9,j4)):e.createCommentVNode("",!0)],!0)])],8,R4)],8,D4))])):e.createCommentVNode("",!0)]))}}),H4=Fe(W4,[["__scopeId","data-v-3cc6e078"]]),Z4={class:"video-editor-modal"},G4={class:"video-preview-container"},X4=["src"],K4={class:"video-overlay-controls"},J4=["aria-label"],q4={class:"time-display"},Y4={class:"timeline-container"},Q4={class:"clip-name"},eM={class:"timeline-time-labels"},tM={class:"tool-tabs"},aM=["onClick"],nM={class:"tool-panel"},oM={key:0,class:"trim-panel"},iM={class:"trim-controls"},rM={key:1,class:"filters-panel"},sM={class:"filter-grid"},lM=["onClick"],dM={key:2,class:"text-panel"},cM={key:3,class:"transitions-panel"},uM={class:"transition-grid"},mM=["onClick"],pM={class:"action-buttons"},fM=e.defineComponent({__name:"VideoEditorSimple",props:{media:{}},emits:["save","cancel"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(),r=e.ref(""),s=e.ref(!1),l=e.ref(0),d=e.ref(0),c=e.ref("video-1"),u=e.ref(0),m=e.ref(0),f=e.ref(null),p=e.ref("trim"),h=e.ref(null),v=e.ref(""),E=[{id:"trim",label:"Trim",icon:$r},{id:"filters",label:"Filters",icon:iv},{id:"text",label:"Text",icon:lm},{id:"transitions",label:"Transitions",icon:pv}],y=[{id:"none",name:"None"},{id:"grayscale",name:"Grayscale"},{id:"sepia",name:"Sepia"},{id:"blur",name:"Blur"},{id:"brightness",name:"Brightness"},{id:"contrast",name:"Contrast"}],k=[{id:"fade",name:"Fade"},{id:"slide",name:"Slide"},{id:"zoom",name:"Zoom"},{id:"wipe",name:"Wipe"}],g=e.ref();e.onMounted(()=>{var I,Z;(I=t.media)!=null&&I.url?r.value=t.media.url:(Z=t.media)!=null&&Z.file&&(r.value=URL.createObjectURL(t.media.file))}),e.onUnmounted(()=>{var I;(I=t.media)!=null&&I.file&&r.value&&URL.revokeObjectURL(r.value)});function b(){i.value&&(d.value=i.value.duration,m.value=d.value)}function R(){i.value&&(l.value=i.value.currentTime)}function N(){s.value=!1}function T(){i.value&&(s.value?(i.value.pause(),s.value=!1):(i.value.play(),s.value=!0))}function S(I){if(!I||isNaN(I))return"00:00";const Z=Math.floor(I/60),z=Math.floor(I%60);return`${Z.toString().padStart(2,"0")}:${z.toString().padStart(2,"0")}`}function B(I){if(!i.value||!g.value)return;const Z=g.value.getBoundingClientRect(),se=(I.clientX-Z.left)/Z.width*d.value;i.value.currentTime=Math.max(0,Math.min(se,d.value))}function A(){u.value=l.value}function x(){m.value=l.value}function M(){u.value=0,m.value=d.value}function w(I){f.value=I;const Z=K=>{if(!f.value||!g.value)return;const se=g.value.getBoundingClientRect(),ie=(K.clientX-se.left)/se.width*d.value;f.value==="start"?u.value=Math.max(0,Math.min(ie,m.value-1)):m.value=Math.max(u.value+1,Math.min(ie,d.value))},z=()=>{f.value=null,document.removeEventListener("mousemove",Z),document.removeEventListener("mouseup",z)};document.addEventListener("mousemove",Z),document.addEventListener("mouseup",z)}function F(I){if(h.value=I,!i.value)return;const Z={none:"none",grayscale:"grayscale(100%)",sepia:"sepia(100%)",blur:"blur(5px)",brightness:"brightness(150%)",contrast:"contrast(150%)"};i.value.style.filter=Z[I]||"none"}function P(){}function D(I){}function O(){const I={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",I)}return(I,Z)=>(e.openBlock(),e.createElementBlock("div",Z4,[e.createElementVNode("div",G4,[e.createElementVNode("video",{ref_key:"videoElement",ref:i,class:"video-preview",src:r.value,onLoadedmetadata:b,onTimeupdate:R,onEnded:N,controls:""},null,40,X4),e.createElementVNode("div",K4,[e.createElementVNode("button",{class:"play-pause-btn",onClick:T,"aria-label":s.value?"Pause":"Play"},[e.createVNode(e.unref(H.IonIcon),{icon:s.value?e.unref(gv):e.unref(kv)},null,8,["icon"])],8,J4),e.createElementVNode("div",q4,e.toDisplayString(S(l.value))+" / "+e.toDisplayString(S(d.value)),1)])]),e.createElementVNode("div",Y4,[e.createElementVNode("div",{class:"timeline-track",onClick:B,ref_key:"timelineTrack",ref:g},[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",Q4,e.toDisplayString(c.value),1)],4),e.createElementVNode("div",{class:"timeline-playhead",style:e.normalizeStyle({left:`${l.value/d.value*100}%`})},null,4),p.value==="trim"?(e.openBlock(),e.createElementBlock("div",{key:0,class:"trim-handle trim-start",style:e.normalizeStyle({left:`${u.value/d.value*100}%`}),onMousedown:Z[0]||(Z[0]=z=>w("start"))},null,36)):e.createCommentVNode("",!0),p.value==="trim"?(e.openBlock(),e.createElementBlock("div",{key:1,class:"trim-handle trim-end",style:e.normalizeStyle({left:`${m.value/d.value*100}%`}),onMousedown:Z[1]||(Z[1]=z=>w("end"))},null,36)):e.createCommentVNode("",!0)],512),e.createElementVNode("div",eM,[e.createElementVNode("span",null,e.toDisplayString(S(0)),1),e.createElementVNode("span",null,e.toDisplayString(S(d.value)),1)])]),e.createElementVNode("div",tM,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(E,z=>e.createElementVNode("button",{key:z.id,class:e.normalizeClass(["tool-tab",{active:p.value===z.id}]),onClick:K=>p.value=z.id},[e.createVNode(e.unref(H.IonIcon),{icon:z.icon},null,8,["icon"]),e.createTextVNode(" "+e.toDisplayString(z.label),1)],10,aM)),64))]),e.createElementVNode("div",nM,[p.value==="trim"?(e.openBlock(),e.createElementBlock("div",oM,[Z[7]||(Z[7]=e.createElementVNode("h3",null,"Trim Video",-1)),Z[8]||(Z[8]=e.createElementVNode("p",null,"Click and drag on the timeline to set trim points",-1)),e.createElementVNode("div",iM,[e.createElementVNode("button",{class:"btn-trim",onClick:A},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(uc)},null,8,["icon"]),Z[4]||(Z[4]=e.createTextVNode(" Set Start ",-1))]),e.createElementVNode("button",{class:"btn-trim",onClick:x},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(uc)},null,8,["icon"]),Z[5]||(Z[5]=e.createTextVNode(" Set End ",-1))]),e.createElementVNode("button",{class:"btn-trim",onClick:M},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Yn)},null,8,["icon"]),Z[6]||(Z[6]=e.createTextVNode(" Clear ",-1))])])])):p.value==="filters"?(e.openBlock(),e.createElementBlock("div",rM,[Z[9]||(Z[9]=e.createElementVNode("h3",null,"Filters",-1)),e.createElementVNode("div",sM,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(y,z=>e.createElementVNode("button",{key:z.id,class:e.normalizeClass(["filter-option",{active:h.value===z.id}]),onClick:K=>F(z.id)},e.toDisplayString(z.name),11,lM)),64))])])):p.value==="text"?(e.openBlock(),e.createElementBlock("div",dM,[Z[10]||(Z[10]=e.createElementVNode("h3",null,"Text Overlay",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":Z[2]||(Z[2]=z=>v.value=z),type:"text",placeholder:"Enter text...",class:"text-input"},null,512),[[e.vModelText,v.value]]),e.createElementVNode("button",{class:"btn-add-text",onClick:P},"Add Text")])):p.value==="transitions"?(e.openBlock(),e.createElementBlock("div",cM,[Z[11]||(Z[11]=e.createElementVNode("h3",null,"Transitions",-1)),e.createElementVNode("div",uM,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(k,z=>e.createElementVNode("button",{key:z.id,class:"transition-option",onClick:K=>(z.id,void 0)},e.toDisplayString(z.name),9,mM)),64))])])):e.createCommentVNode("",!0)]),e.createElementVNode("div",pM,[e.createElementVNode("button",{class:"btn-cancel",onClick:Z[3]||(Z[3]=z=>I.$emit("cancel"))},"CANCEL"),e.createElementVNode("button",{class:"btn-save",onClick:O},"SAVE")])]))}}),hM=Fe(fM,[["__scopeId","data-v-b933f33b"]]),vM={class:"time-label"},gM=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 s=[],l=i(a.duration,a.zoom);for(let d=0;d<=a.duration;d+=l){const c=`${d/a.duration*100}%`,u=r(d),m=d%(l*5)===0;s.push({time:d,position:c,label:u,major:m})}return s});function i(s,l){const d=s/(10*l);return d<=1?1:d<=5?5:d<=10?10:d<=30?30:d<=60?60:Math.ceil(d/60)*60}function r(s){const l=Math.floor(s/60),d=Math.floor(s%60);return l===0?`${d}s`:d===0?`${l}m`:`${l}:${d.toString().padStart(2,"0")}`}return(s,l)=>(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",vM,e.toDisplayString(d.label),1),e.createElementVNode("div",{class:e.normalizeClass(["time-tick",{major:d.major}])},null,2)],4))),128))],4))}}),bM=Fe(gM,[["__scopeId","data-v-0ef9c910"]]),yM=["data-track-index"],wM={class:"track-header"},kM={class:"track-label"},_M={class:"track-controls"},EM=["data-testid","aria-label"],SM=["data-testid","onMousedown","onClick"],CM={class:"clip-content"},xM={class:"clip-name"},VM={key:0,class:"clip-thumbnail"},NM=["src","alt"],TM=["onMousedown","aria-label"],BM=["onMousedown","aria-label"],MM=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),s=e.ref(!1),l=e.ref(null),d=e.computed(()=>({width:`${t.duration*t.zoom*100}px`}));function c(E){const y=E.timelineEnd-E.timelineStart,k=E.timelineStart/t.duration*100,g=y/t.duration*100;return{left:`${k}%`,width:`${g}%`,backgroundColor:u(E)}}function u(E){const y=["#4A90E2","#7ED321","#F5A623","#BD10E0","#9013FE","#50E3C2","#B8E986","#F8E71C"],k=parseInt(E.id.replace(/\D/g,""))%y.length;return y[k]}function m(E){return E.label?E.label:E.url?(E.url.split("/").pop()||"Clip").split(".")[0]:`Clip ${E.id.slice(-4)}`}function f(E){i.value=E.id,n("clip-select",E.id)}function p(){r.value=!r.value}function h(E,y){if(l.value)return;s.value=!0;const k=y.clientX,g=E.timelineStart,b=N=>{if(!s.value)return;const T=N.clientX-k,S=parseFloat(d.value.width),B=T/(t.zoom*100)*(t.duration/S),A=Math.max(0,g+B);n("clip-move",E.id,A)},R=()=>{s.value=!1,document.removeEventListener("mousemove",b),document.removeEventListener("mouseup",R)};document.addEventListener("mousemove",b),document.addEventListener("mouseup",R)}function v(E,y,k){l.value=y;const g=k.clientX,b=E.sourceIn,R=E.sourceOut,N=S=>{if(!l.value)return;const B=S.clientX-g,A=parseFloat(d.value.width),x=B/(t.zoom*100)*(t.duration/A);if(l.value==="start"){const M=Math.max(0,b+x);n("clip-trim",E.id,M,R)}else{const M=Math.max(b+1,R+x);n("clip-trim",E.id,b,M)}},T=()=>{l.value=null,document.removeEventListener("mousemove",N),document.removeEventListener("mouseup",T)};document.addEventListener("mousemove",N),document.addEventListener("mouseup",T)}return(E,y)=>(e.openBlock(),e.createElementBlock("div",{class:"video-track","data-track-index":E.trackIndex},[e.createElementVNode("div",wM,[e.createElementVNode("span",kM,"Track "+e.toDisplayString(E.trackIndex+1),1),e.createElementVNode("div",_M,[E.clips.length>0?(e.openBlock(),e.createElementBlock("button",{key:0,class:"track-btn","data-testid":`btn-mute-track-${E.trackIndex}`,"aria-label":`${r.value?"Unmute":"Mute"} track ${E.trackIndex+1}`,onClick:p},[e.createVNode(e.unref(H.IonIcon),{icon:r.value?e.unref(Dv):e.unref($v)},null,8,["icon"])],8,EM)):e.createCommentVNode("",!0)])]),e.createElementVNode("div",{class:"track-timeline",style:e.normalizeStyle(d.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(E.clips,k=>(e.openBlock(),e.createElementBlock("div",{key:k.id,class:e.normalizeClass(["timeline-clip",{selected:k.id===i.value}]),style:e.normalizeStyle(c(k)),"data-testid":`clip-${k.id}`,onMousedown:g=>h(k,g),onClick:g=>f(k)},[e.createElementVNode("div",CM,[e.createElementVNode("span",xM,e.toDisplayString(m(k)),1),k.thumbnail?(e.openBlock(),e.createElementBlock("div",VM,[e.createElementVNode("img",{src:k.thumbnail,alt:m(k)},null,8,NM)])):e.createCommentVNode("",!0)]),e.createElementVNode("div",{class:"trim-handle trim-start",onMousedown:e.withModifiers(g=>v(k,"start",g),["stop"]),"aria-label":`Trim start of ${m(k)}`},null,40,TM),e.createElementVNode("div",{class:"trim-handle trim-end",onMousedown:e.withModifiers(g=>v(k,"end",g),["stop"]),"aria-label":`Trim end of ${m(k)}`},null,40,BM)],46,SM))),128))],4)],8,yM))}}),IM=Fe(MM,[["__scopeId","data-v-48e480d2"]]),$M={class:"video-timeline"},FM={class:"timeline-tracks"},DM=["aria-label","aria-valuenow","aria-valuemax"],RM={class:"timeline-controls"},AM={class:"zoom-level"},LM=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),s=e.ref(!1),l=e.ref(),d=e.computed(()=>{const g=Math.max(0,...t.clips.map(b=>b.track||0));return Array(g+1).fill(null)}),c=e.computed(()=>`${t.currentTime/t.duration*100}%`);function u(g){return t.clips.filter(b=>(b.track||0)===g)}function m(g){const b=Math.floor(g/60),R=Math.floor(g%60);return`${b}:${R.toString().padStart(2,"0")}`}function f(g,b){n("clip-move",g,b)}function p(g,b,R){n("clip-trim",g,b,R)}function h(g){r.value=g}function v(){i.value=Math.min(i.value*1.2,5)}function E(){i.value=Math.max(i.value/1.2,.5)}function y(){s.value=!0;const g=R=>{if(!s.value||!l.value)return;const N=l.value.getBoundingClientRect(),B=Math.max(0,Math.min(R.clientX-N.left,N.width))/N.width*t.duration;n("seek",B)},b=()=>{s.value=!1,document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",b)};document.addEventListener("mousemove",g),document.addEventListener("mouseup",b)}function k(g){let b=t.currentTime;switch(g.key){case"ArrowLeft":b=Math.max(0,t.currentTime-1);break;case"ArrowRight":b=Math.min(t.duration,t.currentTime+1);break;case"Home":b=0;break;case"End":b=t.duration;break;default:return}g.preventDefault(),n("seek",b)}return e.onMounted(()=>{l.value=document.querySelector(".video-timeline")}),e.onUnmounted(()=>{}),(g,b)=>(e.openBlock(),e.createElementBlock("div",$M,[e.createVNode(bM,{duration:g.duration,zoom:i.value},null,8,["duration","zoom"]),e.createElementVNode("div",FM,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(d.value,(R,N)=>(e.openBlock(),e.createBlock(IM,{key:`track-${N}`,"data-testid":`track-${N}`,clips:u(N),"track-index":N,zoom:i.value,duration:g.duration,onClipMove:f,onClipTrim:p,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:y,"data-testid":"playhead","aria-label":`Playhead at ${m(g.currentTime)}`,role:"slider","aria-valuenow":g.currentTime,"aria-valuemax":g.duration,tabindex:"0",onKeydown:k},null,44,DM),e.createElementVNode("div",RM,[e.createElementVNode("button",{"data-testid":"btn-zoom-in","aria-label":"Zoom in",onClick:v},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Yl)},null,8,["icon"])]),e.createElementVNode("span",AM,e.toDisplayString(Math.round(i.value*100))+"%",1),e.createElementVNode("button",{"data-testid":"btn-zoom-out","aria-label":"Zoom out",onClick:E},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Vv)},null,8,["icon"])])])]))}}),PM=Fe(LM,[["__scopeId","data-v-001df415"]]),UM={class:"video-filters-panel"},OM={class:"filter-controls"},zM=["for"],jM={class:"filter-slider-group"},WM=["id","onUpdate:modelValue","min","max","step","data-testid","aria-label","aria-valuenow","aria-valuemin","aria-valuemax","onInput"],HM={class:"filter-value"},ZM={class:"filter-actions"},GM={key:0,class:"filter-presets"},XM={class:"preset-list"},KM=["data-testid","aria-label","onClick"],JM=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((f,p)=>(f[p.type]=p.default,f),{})),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 s(f,p){switch(f){case"brightness":case"contrast":case"saturation":case"sepia":case"grayscale":return`${p}%`;case"hue":return`${p}°`;case"blur":case"sharpen":return p.toFixed(1);default:return p.toString()}}function l(f){return["brightness","contrast","saturation","hue","blur","sharpen","sepia","grayscale"].includes(f)}function d(f){if(!l(f))return;const p={id:`filter-${f}`,filterId:f,params:{value:i[f]},intensity:1};t("filter-change",p)}function c(){n.forEach(f=>{i[f.type]=f.default,d(f.type)})}function u(){const f=prompt("Enter preset name:");if(!f)return;const p={id:`custom-${Date.now()}`,name:f,values:{...i}};r.value.push(p)}function m(f){Object.entries(f.values).forEach(([p,h])=>{i[p]=h,d(p)})}return(f,p)=>(e.openBlock(),e.createElementBlock("div",UM,[p[3]||(p[3]=e.createElementVNode("h3",null,"Video Filters",-1)),e.createElementVNode("div",OM,[(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,zM),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,WM),[[e.vModelText,i[h.type],void 0,{number:!0}]]),e.createElementVNode("span",HM,e.toDisplayString(s(h.type,i[h.type])),1)])])),64))]),e.createElementVNode("div",ZM,[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(H.IonIcon),{icon:e.unref(io)},null,8,["icon"]),p[0]||(p[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(H.IonIcon),{icon:e.unref(Qr)},null,8,["icon"]),p[1]||(p[1]=e.createTextVNode(" Save as Preset ",-1))])]),r.value.length>0?(e.openBlock(),e.createElementBlock("div",GM,[p[2]||(p[2]=e.createElementVNode("h4",null,"Presets",-1)),e.createElementVNode("div",XM,[(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,KM))),128))])])):e.createCommentVNode("",!0)]))}}),qM=Fe(JM,[["__scopeId","data-v-5ad2ac63"]]),YM={class:"video-text-panel"},QM={class:"text-input-group"},eI={class:"text-options"},tI={class:"option-row"},aI={class:"option-row"},nI={class:"option-row"},oI={class:"option-row"},iI={class:"checkbox-label"},rI={class:"option-row"},sI={class:"text-overlay-list"},lI={key:0,class:"empty-state"},dI=["data-testid"],cI={class:"overlay-preview"},uI={class:"overlay-controls"},mI=["data-testid","aria-label","onClick"],pI=["data-testid","aria-label","onClick"],fI=["data-testid","aria-label","onClick"],hI=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 s(c){const u=n.value.findIndex(m=>m.id===c);u!==-1&&(n.value.splice(u,1),t("text-remove",c))}function l(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",s(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",YM,[u[17]||(u[17]=e.createElementVNode("h3",null,"Text Overlays",-1)),e.createElementVNode("div",QM,[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(H.IonIcon),{icon:e.unref(Yl)},null,8,["icon"]),u[7]||(u[7]=e.createTextVNode(" Add ",-1))])]),e.createElementVNode("div",eI,[e.createElementVNode("div",tI,[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",aI,[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",nI,[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",oI,[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",iI,[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",rI,[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",sI,[u[16]||(u[16]=e.createElementVNode("h4",null,"Active Overlays",-1)),n.value.length===0?(e.openBlock(),e.createElementBlock("div",lI," No text overlays added yet ")):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.value,(m,f)=>(e.openBlock(),e.createElementBlock("div",{key:m.id,class:"text-overlay-item","data-testid":`overlay-${f}`},[e.createElementVNode("div",cI,[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",uI,[e.createElementVNode("button",{class:"edit-btn","data-testid":`btn-edit-${f}`,"aria-label":`Edit overlay: ${m.text}`,onClick:p=>l(m)},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(sv)},null,8,["icon"])],8,mI),e.createElementVNode("button",{class:"duplicate-btn","data-testid":`btn-duplicate-${f}`,"aria-label":`Duplicate overlay: ${m.text}`,onClick:p=>d(m)},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(cl)},null,8,["icon"])],8,pI),e.createElementVNode("button",{class:"remove-btn","data-testid":`btn-remove-${f}`,"aria-label":`Remove overlay: ${m.text}`,onClick:p=>s(m.id)},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Fr)},null,8,["icon"])],8,fI)])],8,dI))),128))])]))}}),vI=Fe(hI,[["__scopeId","data-v-4d240e1e"]]),gI={class:"video-tools-panel"},bI={class:"tool-tabs"},yI=["data-testid","aria-label","aria-selected","onClick"],wI={class:"tool-content"},kI={key:0,class:"trim-panel",role:"tabpanel","aria-label":"Trim controls"},_I={class:"trim-actions"},EI={key:3,class:"transitions-panel",role:"tabpanel","aria-label":"Transition controls"},SI={class:"transition-types"},CI=["data-testid","aria-label","onClick"],xI={class:"transition-preview"},VI=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:$r},{id:"filters",name:"Filters",icon:Cn},{id:"text",name:"Text",icon:lm},{id:"transitions",name:"Transitions",icon:fc}],t=[{id:"fade",name:"Fade",icon:zs},{id:"slide-left",name:"Slide Left",icon:ev},{id:"slide-right",name:"Slide Right",icon:tv},{id:"dissolve",name:"Dissolve",icon:zs},{id:"wipe",name:"Wipe",icon:fc},{id:"zoom",name:"Zoom",icon:zs}];return(n,i)=>(e.openBlock(),e.createElementBlock("div",gI,[e.createElementVNode("div",bI,[(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:s=>n.$emit("tool-change",r.id)},[e.createVNode(e.unref(H.IonIcon),{icon:r.icon},null,8,["icon"]),e.createTextVNode(" "+e.toDisplayString(r.name),1)],10,yI)),64))]),e.createElementVNode("div",wI,[n.activeTool==="trim"?(e.openBlock(),e.createElementBlock("div",kI,[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",_I,[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(H.IonIcon),{icon:e.unref(mc)},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(H.IonIcon),{icon:e.unref(mc)},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(H.IonIcon),{icon:e.unref(Yn)},null,8,["icon"]),i[7]||(i[7]=e.createTextVNode(" Clear ",-1))])])])):e.createCommentVNode("",!0),n.activeTool==="filters"?(e.openBlock(),e.createBlock(qM,{key:1,onFilterChange:i[3]||(i[3]=r=>n.$emit("filter-change",r))})):e.createCommentVNode("",!0),n.activeTool==="text"?(e.openBlock(),e.createBlock(vI,{key:2,onTextAdd:i[4]||(i[4]=r=>n.$emit("text-add",r))})):e.createCommentVNode("",!0),n.activeTool==="transitions"?(e.openBlock(),e.createElementBlock("div",EI,[i[10]||(i[10]=e.createElementVNode("h3",null,"Transitions",-1)),e.createElementVNode("div",SI,[(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:s=>n.$emit("transition-add",r.id)},[e.createElementVNode("div",xI,[e.createVNode(e.unref(H.IonIcon),{icon:r.icon},null,8,["icon"])]),e.createElementVNode("span",null,e.toDisplayString(r.name),1)],8,CI)),64))])])):e.createCommentVNode("",!0)])]))}}),NI=Fe(VI,[["__scopeId","data-v-fc135306"]]),TI={class:"video-export-panel"},BI={class:"export-presets"},MI=["value"],II={key:0,class:"preset-details"},$I={class:"detail-row"},FI={class:"detail-row"},DI={class:"detail-row"},RI={class:"advanced-options"},AI={class:"options-content"},LI={class:"option-group"},PI={class:"option-group"},UI={class:"option-group"},OI=["disabled"],zI={key:1,class:"export-progress"},jI={class:"progress-message"},WI={class:"progress-bar"},HI=["aria-valuenow"],ZI={class:"progress-percentage"},GI=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}),s=e.computed(()=>t.presets.find(c=>c.id===i.value)),l=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(){s.value&&n("export",{...s.value,options:{...r}})}return(c,u)=>(e.openBlock(),e.createElementBlock("div",TI,[u[14]||(u[14]=e.createElementVNode("h3",null,"Export Video",-1)),e.createElementVNode("div",BI,[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,MI))),128))],512),[[e.vModelSelect,i.value]])]),s.value?(e.openBlock(),e.createElementBlock("div",II,[e.createElementVNode("div",$I,[u[5]||(u[5]=e.createElementVNode("span",null,"Resolution:",-1)),e.createElementVNode("span",null,e.toDisplayString(s.value.width)+"x"+e.toDisplayString(s.value.height),1)]),e.createElementVNode("div",FI,[u[6]||(u[6]=e.createElementVNode("span",null,"Frame Rate:",-1)),e.createElementVNode("span",null,e.toDisplayString(s.value.fps)+" fps",1)]),e.createElementVNode("div",DI,[u[7]||(u[7]=e.createElementVNode("span",null,"Format:",-1)),e.createElementVNode("span",null,e.toDisplayString(s.value.format.toUpperCase()),1)])])):e.createCommentVNode("",!0),e.createElementVNode("details",RI,[u[12]||(u[12]=e.createElementVNode("summary",null,"Advanced Options",-1)),e.createElementVNode("div",AI,[e.createElementVNode("div",LI,[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",PI,[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",UI,[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||!s.value,"data-testid":"btn-start-export","aria-label":"Start video export",onClick:d},[c.isExporting?(e.openBlock(),e.createBlock(e.unref(H.IonSpinner),{key:0,name:"crescent"})):(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref($o)},null,8,["icon"]),u[13]||(u[13]=e.createTextVNode(" Export Video ",-1))],64))],8,OI),c.isExporting?(e.openBlock(),e.createElementBlock("div",zI,[e.createElementVNode("div",jI,e.toDisplayString(l.value),1),e.createElementVNode("div",WI,[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,HI)]),e.createElementVNode("div",ZI,e.toDisplayString(c.exportProgress)+"% ",1)])):e.createCommentVNode("",!0)]))}}),XI=Fe(GI,[["__scopeId","data-v-5caf8fe6"]]),KI=["data-testid"],JI={class:"progress-header"},qI={class:"file-info"},YI={class:"file-details"},QI={class:"file-name"},e3={class:"file-meta"},t3={class:"file-size"},a3={key:0,class:"separator"},n3={key:1,class:"upload-speed"},o3={key:2,class:"separator"},i3={key:3,class:"time-remaining"},r3={class:"progress-actions"},s3={key:0,class:"status-icon completed","data-testid":"video-upload-status-completed"},l3={key:1,class:"status-icon error","data-testid":"video-upload-status-error"},d3={key:2,class:"status-icon processing","data-testid":"video-upload-status-processing",role:"status","aria-label":"Processing video"},c3=["aria-valuenow","aria-label"],u3={class:"progress-bar"},m3={class:"progress-percent"},p3={key:1,class:"error-message","data-testid":"video-upload-error"},f3={key:2,class:"thumbnail-preview","data-testid":"video-upload-thumbnail"},h3=["src","alt"],v3={key:0,class:"video-duration"},g3=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(()=>dm),i=e.computed(()=>["uploading","processing"].includes(a.upload.status)),r=e.computed(()=>(a.upload.status==="processing",a.upload.progress||0)),s=e.computed(()=>{if(!a.upload.timeRemaining||a.upload.status!=="uploading")return null;const f=a.upload.timeRemaining;if(f<60)return`${Math.round(f)}s`;const p=Math.floor(f/60);return p<60?`${p}m ${Math.round(f%60)}s`:`${Math.floor(p/60)}h ${p%60}m`}),l=e.computed(()=>{var f;return a.upload.status==="completed"&&((f=a.upload.media)!=null&&f.thumbnail_url)?a.upload.media.thumbnail_url:null}),d=e.computed(()=>{var f;return(f=a.upload.media)==null?void 0:f.duration});function c(f){if(f===0)return"0 B";const p=["B","KB","MB","GB","TB"],h=1024,v=Math.floor(Math.log(f)/Math.log(h));return`${(f/Math.pow(h,v)).toFixed(1)} ${p[v]}`}function u(f){if(f===0)return"0 B/s";const p=["B/s","KB/s","MB/s","GB/s"],h=1024,v=Math.floor(Math.log(f)/Math.log(h));return`${(f/Math.pow(h,v)).toFixed(1)} ${p[v]}`}function m(f){const p=Math.floor(f/3600),h=Math.floor(f%3600/60),v=Math.floor(f%60);return p>0?`${p}:${h.toString().padStart(2,"0")}:${v.toString().padStart(2,"0")}`:`${h}:${v.toString().padStart(2,"0")}`}return(f,p)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["upload-progress-item",t.value]),"data-testid":`video-upload-progress-${f.upload.id}`},[e.createElementVNode("div",JI,[e.createElementVNode("div",qI,[e.createVNode(e.unref(H.IonIcon),{icon:n.value,class:"file-icon","aria-hidden":"true"},null,8,["icon"]),e.createElementVNode("div",YI,[e.createElementVNode("h4",QI,e.toDisplayString(f.upload.filename),1),e.createElementVNode("p",e3,[e.createElementVNode("span",t3,e.toDisplayString(c(f.upload.bytesTotal||0)),1),f.upload.status==="uploading"?(e.openBlock(),e.createElementBlock("span",a3,"•")):e.createCommentVNode("",!0),f.upload.status==="uploading"?(e.openBlock(),e.createElementBlock("span",n3,e.toDisplayString(u(f.upload.uploadSpeed||0)),1)):e.createCommentVNode("",!0),s.value?(e.openBlock(),e.createElementBlock("span",o3,"•")):e.createCommentVNode("",!0),s.value?(e.openBlock(),e.createElementBlock("span",i3,e.toDisplayString(s.value)+" remaining ",1)):e.createCommentVNode("",!0)])])]),e.createElementVNode("div",r3,[f.upload.status==="completed"?(e.openBlock(),e.createElementBlock("div",s3,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(om)},null,8,["icon"])])):f.upload.status==="error"?(e.openBlock(),e.createElementBlock("div",l3,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Qh),"aria-hidden":"true"},null,8,["icon"])])):f.upload.status==="processing"?(e.openBlock(),e.createElementBlock("div",d3,[e.createVNode(e.unref(H.IonSpinner),{name:"crescent"})])):e.createCommentVNode("",!0),f.upload.status==="uploading"?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:3,fill:"clear",size:"small",onClick:p[0]||(p[0]=h=>f.$emit("cancel")),"data-testid":"btn-cancel-video-upload","aria-label":"Cancel upload"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Yn),slot:"icon-only"},null,8,["icon"])]),_:1})):f.upload.status==="error"?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:4,fill:"clear",size:"small",onClick:p[1]||(p[1]=h=>f.$emit("retry")),"data-testid":"btn-retry-video-upload","aria-label":"Retry upload"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(io),slot:"icon-only"},null,8,["icon"])]),_:1})):f.upload.status==="completed"?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:5,fill:"clear",size:"small",onClick:p[2]||(p[2]=h=>f.$emit("remove")),"data-testid":"btn-remove-video-upload","aria-label":"Remove from list"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Yn),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":f.upload.status==="processing"?"Processing progress":"Upload progress"},[e.createElementVNode("div",u3,[e.createElementVNode("div",{class:e.normalizeClass(["progress-fill",{indeterminate:f.upload.status==="processing"}]),style:e.normalizeStyle({width:r.value+"%"})},null,6)]),e.createElementVNode("span",m3,e.toDisplayString(Math.round(r.value))+"%",1)],8,c3)):e.createCommentVNode("",!0),f.upload.error?(e.openBlock(),e.createElementBlock("div",p3,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Rv)},null,8,["icon"]),e.createElementVNode("span",null,e.toDisplayString(f.upload.error),1)])):e.createCommentVNode("",!0),l.value?(e.openBlock(),e.createElementBlock("div",f3,[e.createElementVNode("img",{src:l.value,alt:f.upload.filename},null,8,h3),d.value?(e.openBlock(),e.createElementBlock("div",v3,e.toDisplayString(m(d.value)),1)):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)],10,KI))}}),b3=Fe(g3,[["__scopeId","data-v-9eacbf91"]]),al=4,y3=500,w3=new Set([408,425,429,500,502,503,504,520,521,522,523,524,525]);function Cs(o){return typeof o=="object"&&o!==null}function wu(o){return Cs(o)?typeof o.upload_url=="string"&&typeof o.upload_id=="string"&&typeof o.media_uuid=="string"&&typeof o.expires_at=="string":!1}function k3(o){if(wu(o))return o;if(Cs(o)&&wu(o.data))return o.data;throw new Error("Invalid upload response from backend")}function ku(o){return Cs(o)?typeof o.uuid=="string"&&typeof o.processing_status=="string":!1}function _3(o){if(ku(o))return o;if(Cs(o)&&ku(o.data))return o.data;throw new Error("Invalid media response from backend")}function pr(o){return o?{...o}:{}}function _u(o,a="PUT"){return typeof o.method=="string"&&o.method.trim()!==""?o.method.trim().toUpperCase():a}function E3(o){return o.resumable===!0?!0:/tusupload/i.test(o.upload_url)}function S3(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 C3(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} ${S3(i)}`).join(",")}function fr(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 x3(o,a){return o instanceof Error?o:new Error(a)}function V3(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 Eu(o){const a=Math.max(0,o-1),t=y3*Math.pow(2,a);return Math.min(5e3,t)}function Su(o){return new Promise(a=>{window.setTimeout(a,o)})}async function Cu(o,a){for(let t=1;t<=al;t+=1)try{const n=await a();if(n.ok||!w3.has(n.status)||t>=al)return n;await Su(Eu(t))}catch(n){if(!V3(n)||t>=al)throw n;await Su(Eu(t))}throw new Error(`${o} failed after retry attempts`)}function N3(o={}){const a=e.ref(new Map),t=e.ref(new Set),n=e.ref(null),i=new Map,r=new Map,s=e.computed(()=>t.value.size>0),l=e.computed(()=>Array.from(a.value.values())),d=e.computed(()=>{const x=Array.from(a.value.values());return x.length===0?0:x.reduce((w,F)=>w+F.progress,0)/x.length});function c(x){n.value=x}function u(){}async function m(x){var w;const M=x.filter(F=>f(F));if(M.length!==0&&((w=o.onFilesSelected)==null||w.call(o,M),o.autoUpload!==!1))for(const F of M)await p(F)}function f(x){return!(o.maxFileSize&&x.size>o.maxFileSize||o.allowedFormats&&o.allowedFormats.length>0&&!o.allowedFormats.includes(x.type))}async function p(x){var F,P,D;const M=A(x);if(a.value.has(M)){const O=a.value.get(M);if((O==null?void 0:O.status)==="uploading")return}const w={id:M,file:x,filename:x.name,progress:0,status:"pending",startedAt:new Date,bytesTotal:x.size,bytesUploaded:0};a.value.set(w.id,w),t.value.add(w.id);try{w.status="uploading",(F=o.onUploadStart)==null||F.call(o,w);const O=await h(x);o.resumable===!0||O.resumable===!0?await E(w,O):await v(w,O),w.status="processing",w.progress=100;const Z=await R(O.media_uuid);w.status="completed",w.media=Z,(P=o.onUploadComplete)==null||P.call(o,Z)}catch(O){if(w.status!=="cancelled"){const I=x3(O,"Upload failed");w.status="error",w.error=I.message,(D=o.onUploadError)==null||D.call(o,I,w)}}finally{t.value.delete(w.id),i.delete(w.id),r.delete(w.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}:{}},w=await n.value.post("/api/v1/video/upload",M);return k3(w)}async function v(x,M){const w=new XMLHttpRequest,F=_u(M),P=pr(M.headers);return new Promise((D,O)=>{w.upload.addEventListener("progress",I=>{var Z;I.lengthComputable&&(fr(x,I.loaded),(Z=o.onUploadProgress)==null||Z.call(o,x))}),w.addEventListener("load",()=>{i.delete(x.id),w.status>=200&&w.status<300?D():O(new Error(`Upload failed with status ${w.status}`))}),w.addEventListener("error",()=>{i.delete(x.id),O(new Error("Upload failed"))}),w.addEventListener("abort",()=>{i.delete(x.id),O(new Error("Upload cancelled"))}),w.open(F,M.upload_url),Object.entries(P).forEach(([I,Z])=>{w.setRequestHeader(I,Z)}),!Object.keys(P).some(I=>I.toLowerCase()==="content-type")&&x.file.type&&w.setRequestHeader("Content-Type",x.file.type),i.set(x.id,w),w.send(x.file)})}async function E(x,M){var O;if(E3(M)){await y(x,M);return}const w=o.chunkSize||5*1024*1024,F=k(x.file,w),P=new AbortController;r.set(x.id,P);const D=await b(M.upload_id);D&&(F.forEach(I=>{I.end<=D.bytesUploaded&&(I.uploaded=!0)}),fr(x,D.bytesUploaded));for(const I of F)I.uploaded||(await g(x,M,I,P),fr(x,I.end),(O=o.onUploadProgress)==null||O.call(o,x))}async function y(x,M){var z;const w=new AbortController;r.set(x.id,w);const F={...pr(M.headers),"Tus-Resumable":"1.0.0","Upload-Length":String(x.file.size),"Upload-Metadata":C3(x,M)},P=await Cu("Resumable upload initialization",()=>fetch(M.upload_url,{method:"POST",headers:F,signal:w.signal}));if(!P.ok)throw new Error(`Failed to initialize resumable upload: ${P.status}`);const D=P.headers.get("Location");if(!D)throw new Error("Resumable upload endpoint did not return upload location");const O=new URL(D,M.upload_url).toString(),I=o.chunkSize||5*1024*1024;let Z=0;for(;Z<x.file.size;){const K=Math.min(Z+I,x.file.size),se=x.file.slice(Z,K),Be={...pr(M.headers),"Tus-Resumable":"1.0.0","Upload-Offset":String(Z),"Content-Type":"application/offset+octet-stream"},ce=await Cu("Resumable chunk upload",()=>fetch(O,{method:"PATCH",headers:Be,body:se,signal:w.signal}));if(ce.status===409){const W=Number(ce.headers.get("Upload-Offset")??"-1");if(Number.isFinite(W)&&W>=0){Z=W;continue}}if(!ce.ok)throw new Error(`Resumable chunk upload failed: ${ce.status}`);const ie=Number(ce.headers.get("Upload-Offset")??String(K));Z=Number.isFinite(ie)&&ie>Z?ie:K,fr(x,Z),(z=o.onUploadProgress)==null||z.call(o,x)}}function k(x,M){const w=[];let F=0,P=0;for(;F<x.size;){const D=Math.min(F+M,x.size);w.push({start:F,end:D,blob:x.slice(F,D),index:P,uploaded:!1}),F=D,P++}return w}async function g(x,M,w,F){const P={...pr(M.headers),"Content-Range":`bytes ${w.start}-${w.end-1}/${x.file.size}`,"Content-Type":x.file.type||"application/octet-stream"},D=await fetch(M.upload_url,{method:_u(M),headers:P,body:w.blob,signal:F.signal});if(!D.ok)throw new Error(`Chunk upload failed: ${D.status}`);w.uploaded=!0}async function b(x){return null}async function R(x){if(!n.value)throw new Error("API client not configured");const M=60;let w=0;for(;w<M;){const F=await n.value.get(`/api/v1/video/${x}`),P=_3(F),D=String(P.processing_status);if(D==="ready")return P;if(D==="failed"||D==="error")throw new Error("Video processing failed");await new Promise(O=>{window.setTimeout(O,5e3)}),w++}throw new Error("Video processing timeout")}function N(x){const M=a.value.get(x);if(!M)return;const w=i.get(x);w&&(w.abort(),i.delete(x));const F=r.get(x);F&&(F.abort(),r.delete(x)),M.status="cancelled",M.error="Upload cancelled",t.value.delete(x)}async function T(x){const M=a.value.get(x);M&&(M.status="pending",M.error="",M.progress=0,M.bytesUploaded=0,await p(M.file))}function S(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 A(x){return`${x.name}-${x.size}-${Date.now()}`}return{uploads:l,isUploading:s,totalProgress:d,openFilePicker:u,handleFileSelect:m,validateFile:f,startUpload:p,cancelUpload:N,retryUpload:T,removeUpload:S,clearCompleted:B,setApiClient:c}}const T3=["accept","multiple"],B3={key:0,class:"upload-trigger","data-testid":"video-uploader-trigger"},M3=["onKeydown"],I3={key:1,class:"upload-list","data-testid":"video-upload-list"},$3={class:"drag-content"},F3=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:s,isUploading:l,handleFileSelect:d,cancelUpload:c,retryUpload:u,removeUpload:m,setApiClient:f}=N3({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:b=>n("upload-start",b),onUploadProgress:b=>n("upload-progress",b),onUploadComplete:b=>n("upload-complete",b),onUploadError:(b,R)=>n("upload-error",b,R),onFilesSelected:b=>n("files-selected",b)});t.apiClient&&f(t.apiClient);const p=e.computed(()=>t.allowedFormats.join(",")),h=e.computed(()=>t.multiple||s.value.length===0);function v(){i.value&&i.value.click()}function E(b){const R=b.target,N=Array.from(R.files||[]);N.length>0&&(d(N),R.value="")}function y(b){var T;b.preventDefault(),r.value=!1;const N=Array.from(((T=b.dataTransfer)==null?void 0:T.files)||[]).filter(S=>S.type.startsWith("video/"));N.length>0&&d(N)}function k(b){var R;b.preventDefault(),(R=b.dataTransfer)!=null&&R.types.includes("Files")&&(r.value=!0)}function g(b){b.target.closest(".video-uploader")||(r.value=!1)}return e.onMounted(()=>{document.addEventListener("dragover",k),document.addEventListener("dragleave",g),document.addEventListener("drop",b=>b.preventDefault())}),e.onUnmounted(()=>{document.removeEventListener("dragover",k),document.removeEventListener("dragleave",g),document.removeEventListener("drop",b=>b.preventDefault())}),(b,R)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-uploader",{"is-uploading":e.unref(l)}]),"data-testid":"video-uploader"},[e.createElementVNode("input",{ref_key:"fileInputEl",ref:i,type:"file",accept:p.value,multiple:b.multiple,onChange:E,"data-testid":"video-uploader-input","aria-label":"Select video files to upload",hidden:""},null,40,T3),!e.unref(l)||h.value?(e.openBlock(),e.createElementBlock("div",B3,[e.renderSlot(b.$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(H.IonIcon),{icon:e.unref(dm),class:"upload-icon","aria-hidden":"true"},null,8,["icon"]),e.createElementVNode("h3",null,e.toDisplayString(b.label),1),e.createElementVNode("p",null,e.toDisplayString(b.description),1),e.createVNode(e.unref(H.IonButton),{size:"small","data-testid":"btn-select-video","aria-label":"Select video file"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Yl),slot:"start","aria-hidden":"true"},null,8,["icon"]),R[2]||(R[2]=e.createTextVNode(" Select Video ",-1))]),_:1})],40,M3)],!0)])):e.createCommentVNode("",!0),e.unref(s).length>0?(e.openBlock(),e.createElementBlock("div",I3,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(s),N=>(e.openBlock(),e.createBlock(b3,{key:N.id,upload:N,onCancel:T=>e.unref(c)(N.id),onRetry:T=>e.unref(u)(N.id),onRemove:T=>e.unref(m)(N.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:y,onDragover:R[0]||(R[0]=e.withModifiers(()=>{},["prevent"])),onDragleave:R[1]||(R[1]=N=>r.value=!1)},[e.createElementVNode("div",$3,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref($o),"aria-hidden":"true"},null,8,["icon"]),R[3]||(R[3]=e.createElementVNode("p",null,"Drop video files here",-1))])],32)):e.createCommentVNode("",!0)],2))}}),D3=Fe(F3,[["__scopeId","data-v-ea7587f7"]]),R3=["aria-valuenow","aria-valuemax","aria-label"],A3={class:"progress-bar"},L3={class:"time-display","data-testid":"video-time-display"},P3={class:"current-time"},U3={class:"duration"},O3={class:"control-buttons"},z3={class:"controls-left"},j3=["aria-label"],W3={class:"controls-center"},H3={key:0,class:"volume-controls"},Z3=["aria-label"],G3=["value"],X3={class:"controls-right"},K3={key:0,class:"quality-selector"},J3=["aria-expanded"],q3={class:"quality-label"},Y3={key:0,class:"quality-menu","data-testid":"video-quality-menu",role:"menu"},Q3=["data-testid","aria-label","onClick"],e$=["aria-label"],t$=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),s=e.ref(),l=H.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 b=0;b<t.buffered.length;b++){const R=t.buffered.start(b),N=t.buffered.end(b);if(t.currentTime>=R&&t.currentTime<=N)return{width:`${N/t.duration*100}%`}}return t.buffered.length>0?{width:`${t.buffered.end(0)/t.duration*100}%`}:{width:"0%"}}),f=e.computed(()=>t.muted||t.volume===0?Fv:t.volume<33?Mv:t.volume<66?Iv:Bv);let p=null;function h(){i.value=!0,v()}function v(){p&&clearTimeout(p),t.playing&&!l&&(p=setTimeout(()=>{i.value=!1},3e3))}function E(b){if(!s.value||t.isLive)return;const R=s.value.getBoundingClientRect(),T=(b.clientX-R.left)/R.width*t.duration;n("seek",Math.max(0,Math.min(T,t.duration)))}function y(b){const R=b.target;n("setVolume",parseInt(R.value))}function k(b){n("selectQuality",b),r.value=!1}function g(b){if(!isFinite(b))return"0:00";const R=Math.floor(b/3600),N=Math.floor(b%3600/60),T=Math.floor(b%60);return R>0?`${R}:${N.toString().padStart(2,"0")}:${T.toString().padStart(2,"0")}`:`${N}:${T.toString().padStart(2,"0")}`}return e.onMounted(()=>{document.addEventListener("mousemove",h),v()}),e.onUnmounted(()=>{document.removeEventListener("mousemove",h),p&&clearTimeout(p)}),(b,R)=>(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(b.currentTime),"aria-valuemin":"0","aria-valuemax":Math.round(b.duration),"aria-label":b.isLive?"Live stream":"Video progress",tabindex:"0",onClick:E},[e.createElementVNode("div",A3,[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",L3,[e.createElementVNode("span",P3,e.toDisplayString(g(b.currentTime)),1),R[7]||(R[7]=e.createElementVNode("span",{class:"separator"},"/",-1)),e.createElementVNode("span",U3,e.toDisplayString(b.isLive?"LIVE":g(b.duration)),1)])],8,R3),e.createElementVNode("div",O3,[e.createElementVNode("div",z3,[e.createElementVNode("button",{class:"control-btn play-pause","data-testid":"btn-video-play-pause",onClick:R[0]||(R[0]=N=>b.$emit("play-pause")),"aria-label":b.playing?"Pause":"Play"},[e.createVNode(e.unref(H.IonIcon),{icon:b.playing?e.unref(vv):e.unref(bv),"aria-hidden":"true"},null,8,["icon"])],8,j3),b.isLive?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("button",{key:0,class:"control-btn skip-backward","data-testid":"btn-video-skip-backward",onClick:R[1]||(R[1]=N=>b.$emit("skip-backward")),"aria-label":"Skip backward 10 seconds"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(yv),"aria-hidden":"true"},null,8,["icon"]),R[8]||(R[8]=e.createElementVNode("span",{class:"skip-label"},"10",-1))])),b.isLive?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("button",{key:1,class:"control-btn skip-forward","data-testid":"btn-video-skip-forward",onClick:R[2]||(R[2]=N=>b.$emit("skip-forward")),"aria-label":"Skip forward 10 seconds"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(_v),"aria-hidden":"true"},null,8,["icon"]),R[9]||(R[9]=e.createElementVNode("span",{class:"skip-label"},"10",-1))]))]),e.createElementVNode("div",W3,[e.unref(l)?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",H3,[e.createElementVNode("button",{class:"control-btn mute-btn","data-testid":"btn-video-mute",onClick:R[3]||(R[3]=N=>b.$emit("toggleMute")),"aria-label":b.muted?"Unmute":"Mute"},[e.createVNode(e.unref(H.IonIcon),{icon:f.value,"aria-hidden":"true"},null,8,["icon"])],8,Z3),e.createElementVNode("input",{type:"range",class:"volume-slider","data-testid":"slider-video-volume",min:"0",max:"100",value:b.muted?0:b.volume,onInput:y,"aria-label":"Volume"},null,40,G3)]))]),e.createElementVNode("div",X3,[b.qualityLevels.length>1?(e.openBlock(),e.createElementBlock("div",K3,[e.createElementVNode("button",{class:"control-btn quality-btn","data-testid":"btn-video-quality",onClick:R[4]||(R[4]=N=>r.value=!r.value),"aria-label":"Quality settings","aria-expanded":r.value},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Nv),"aria-hidden":"true"},null,8,["icon"]),e.createElementVNode("span",q3,e.toDisplayString(b.currentQuality),1)],8,J3),r.value?(e.openBlock(),e.createElementBlock("div",Y3,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(b.qualityLevels,N=>(e.openBlock(),e.createElementBlock("button",{key:N.label,class:e.normalizeClass(["quality-option",{active:N.label===b.currentQuality}]),"data-testid":`btn-video-quality-${N.label}`,"aria-label":`Set quality to ${N.label}`,role:"menuitem",onClick:T=>k(N)},e.toDisplayString(N.label),11,Q3))),128))])):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0),!e.unref(l)&&d?(e.openBlock(),e.createElementBlock("button",{key:1,class:"control-btn pip-btn","data-testid":"btn-video-pip",onClick:R[5]||(R[5]=N=>b.$emit("togglePiP")),"aria-label":"Picture in Picture"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Tv),"aria-hidden":"true"},null,8,["icon"])])):e.createCommentVNode("",!0),e.createElementVNode("button",{class:"control-btn fullscreen-btn","data-testid":"btn-video-fullscreen",onClick:R[6]||(R[6]=N=>b.$emit("toggleFullscreen")),"aria-label":b.fullscreen?"Exit fullscreen":"Enter fullscreen"},[e.createVNode(e.unref(H.IonIcon),{icon:b.fullscreen?e.unref(rv):e.unref(dv),"aria-hidden":"true"},null,8,["icon"])],8,e$)])])],2))}}),a$=Fe(t$,[["__scopeId","data-v-2ae77c13"]]);function n$(o={}){var se,Be,ce;const a=e.ref(),t=e.ref(),n=e.ref(!1),i=e.ref(0),r=e.ref(0),s=e.ref(100),l=e.ref(o.muted||!1),d=e.ref(!1),c=e.ref(),u=e.ref(1),m=e.ref(!1),f=e.ref(null),p=e.ref("idle"),h=e.ref(o.playbackUrl||((se=o.media)==null?void 0:se.playback_url)||((Be=o.media)==null?void 0:Be.url)||""),v=e.ref(null),E=e.ref(o.isLive||!1),y=e.ref(null),k=e.ref(null);function g(ie){k.value=ie}if((ce=o.media)!=null&&ce.token_expires_at){const ie=new Date(o.media.token_expires_at);v.value=Number.isNaN(ie.getTime())?null:ie}async function b(){var W;const ie=E.value?t.value:a.value;if(ie)try{await ie.play(),n.value=!0,p.value=E.value?"live":"playing",(W=o.onPlay)==null||W.call(o)}catch{f.value="Failed to play video",p.value="error"}}function R(){var W;const ie=E.value?t.value:a.value;ie&&(ie.pause(),n.value=!1,p.value="paused",(W=o.onPause)==null||W.call(o))}function N(){n.value?R():b()}function T(ie){const W=E.value?t.value:a.value;if(!W||E.value)return;const C=Number.isFinite(W.duration)?W.duration:ie;W.currentTime=Math.max(0,Math.min(ie,C)),i.value=W.currentTime}function S(ie=10){const W=a.value;!W||E.value||T(W.currentTime+ie)}function B(ie=10){const W=a.value;!W||E.value||T(W.currentTime-ie)}function A(){const ie=E.value?t.value:a.value;ie&&(ie.muted=!ie.muted,l.value=ie.muted)}function x(ie){const W=E.value?t.value:a.value;if(!W)return;const C=Math.max(0,Math.min(100,ie));W.volume=C/100,s.value=C,C>0&&W.muted&&(W.muted=!1,l.value=!1)}function M(ie){const W=a.value;!W||E.value||(W.playbackRate=ie,u.value=ie)}async function w(){const ie=document.querySelector(".video-player-container");if(ie)try{document.fullscreenElement?(await document.exitFullscreen(),d.value=!1):(await ie.requestFullscreen(),d.value=!0)}catch{}}async function F(){const ie=E.value?t.value:a.value;if(ie)try{document.pictureInPictureElement?await document.exitPictureInPicture():document.pictureInPictureEnabled&&await ie.requestPictureInPicture()}catch{}}async function P(){var W;f.value=null,p.value="loading",(W=o.media)!=null&&W.provider&&o.media.provider!=="local"&&await D();const ie=E.value?t.value:a.value;ie&&(ie.load(),await b())}async function D(){if(!(!k.value||!o.media))try{m.value=!0;const ie=await k.value.get(`/api/v1/video/${o.media.uuid}/playback`);h.value=ie.playback_url,v.value=new Date(ie.token_expires_at);const W=E.value?t.value:a.value;if(W&&W.src!==h.value){const C=!W.paused,U=W.currentTime;W.src=h.value,E.value||(W.currentTime=U),C&&await b()}}catch{f.value="Failed to refresh playback token",p.value="error"}finally{m.value=!1}}async function O(ie){if(t.value){if(t.value.canPlayType("application/vnd.apple.mpegurl")){t.value.src=ie;return}try{t.value.src=ie}catch{f.value="Live streaming not supported in this browser",p.value="error"}}}function I(){y.value&&(y.value.destroy(),y.value=null)}function Z(){var W;const ie=E.value?t.value:a.value;ie&&(i.value=ie.currentTime,r.value=ie.duration,(W=o.onTimeUpdate)==null||W.call(o,ie.currentTime))}const z=e.computed(()=>{if(!c.value||c.value.length===0||!r.value)return 0;for(let ie=0;ie<c.value.length;ie++){const W=c.value.start(ie),C=c.value.end(ie);if(i.value>=W&&i.value<=C)return C/r.value*100}return 0});function K(){if(!v.value)return!1;const ie=new Date;return v.value.getTime()-ie.getTime()<5*60*1e3}return e.watch([a,t],([ie,W])=>{const C=E.value?W:ie;C&&(C.addEventListener("timeupdate",Z),C.addEventListener("loadedmetadata",()=>{r.value=C.duration,p.value="ready"}),C.addEventListener("progress",()=>{c.value=C.buffered}),C.addEventListener("ended",()=>{var U;n.value=!1,p.value="ended",(U=o.onEnded)==null||U.call(o)}),C.addEventListener("error",U=>{var j;p.value="error",(j=o.onError)==null||j.call(o,"Video playback error")}),C.volume=s.value/100,C.muted=l.value)}),e.onUnmounted(()=>{I();const ie=E.value?t.value:a.value;ie&&ie.removeEventListener("timeupdate",Z)}),{videoEl:a,liveVideoEl:t,playing:n,currentTime:i,duration:r,volume:s,muted:l,isFullscreen:d,bufferedRanges:c,bufferedPercent:z,playbackRate:u,isLoading:m,error:f,status:p,currentPlaybackUrl:h,tokenExpiresAt:v,play:b,pause:R,togglePlayPause:N,seek:T,skipForward:S,skipBackward:B,toggleMute:A,setVolume:x,setPlaybackRate:M,toggleFullscreen:w,togglePiP:F,retry:P,refreshToken:D,setupLiveStream:O,setApiClient:g,shouldRefreshToken:K}}const o$=["src","poster","controls","autoplay","muted","loop","preload"],i$={key:1,ref:"livePlayerEl",class:"live-player"},r$=["controls","muted"],s$={key:0,class:"live-indicator","data-testid":"video-live-indicator","aria-label":"Live stream"},l$={key:2,class:"video-loading","data-testid":"video-loading",role:"status","aria-label":"Loading video"},d$={key:3,class:"video-error","data-testid":"video-error",role:"alert"},c$={key:5,class:"gesture-zones","data-testid":"video-gesture-zones"},u$=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:s,currentTime:l,duration:d,volume:c,muted:u,isFullscreen:m,bufferedRanges:f,isLoading:p,error:h,status:v,currentPlaybackUrl:E,tokenExpiresAt:y,play:k,pause:g,seek:b,toggleMute:R,setVolume:N,toggleFullscreen:T,togglePlayPause:S,skipForward:B,skipBackward:A,retry:x,refreshToken:M,setApiClient:w,shouldRefreshToken:F,setupLiveStream:P}=n$({...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 D(){await M()}const O=e.computed(()=>{const j=["video-player-container"];return t.className&&j.push(t.className),m.value&&j.push("fullscreen"),t.isLive&&j.push("is-live"),s.value&&j.push("is-playing"),p.value&&j.push("is-loading"),j}),I=e.computed(()=>{var j,ne;if(t.poster)return t.poster;if((j=t.media)!=null&&j.poster_url)return t.media.poster_url;if((ne=t.media)!=null&&ne.thumbnail_url)return t.media.thumbnail_url});function Z(j){const ne=j.target;n("loadedmetadata",{duration:ne.duration,width:ne.videoWidth,height:ne.videoHeight})}function z(j){const ne=j.target;l.value=ne.currentTime,n("timeupdate",ne.currentTime)}function K(){s.value=!0,n("play")}function se(){s.value=!1,n("pause")}function Be(){s.value=!1,n("ended")}function ce(j){const ne=j.target;let de="Failed to load video";if(ne.error)switch(ne.error.code){case ne.error.MEDIA_ERR_ABORTED:de="Video playback aborted";break;case ne.error.MEDIA_ERR_NETWORK:de="Network error while loading video";break;case ne.error.MEDIA_ERR_DECODE:de="Video decoding error";break;case ne.error.MEDIA_ERR_SRC_NOT_SUPPORTED:de="Video format not supported";break}h.value=de,n("error",de)}function ie(j){const ne=j.target;f.value=ne.buffered,n("progress",ne.buffered)}function W(){p.value=!0}function C(){p.value=!1}e.watch(()=>t.apiClient,j=>{j&&w(j)},{immediate:!0}),e.watch(()=>t.playbackUrl,j=>{typeof j=="string"&&j.length>0&&(E.value=j)},{immediate:!0}),e.watch(()=>{var j;return(j=t.media)==null?void 0:j.token_expires_at},j=>{if(!j){y.value=null;return}const ne=new Date(j);y.value=Number.isNaN(ne.getTime())?null:ne},{immediate:!0}),e.watch(()=>{var j;return(j=t.media)==null?void 0:j.playback_url},async(j,ne)=>{if(t.playbackUrl||!j||j===ne)return;const de=i.value;if(!de||t.isLive){E.value=j;return}const Ke=!de.paused,be=de.currentTime;E.value=j,await e.nextTick();try{de.currentTime=be}catch{}Ke&&await k()},{immediate:!0});let U=null;return e.watch(()=>t.isLive,async j=>{var de;if(!j)return;const ne=t.playbackUrl||((de=t.media)==null?void 0:de.playback_url)||"";ne&&await P(ne)},{immediate:!0}),e.onMounted(()=>{var j;(j=t.media)!=null&&j.provider&&t.media.provider!=="local"&&(U=setInterval(()=>{F()&&D()},3e4)),H.isPlatform("mobile")&&t.showCustomControls}),e.onUnmounted(()=>{U&&clearInterval(U)}),(j,ne)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-player-container",O.value]),"data-testid":"video-player"},[j.isLive?(e.openBlock(),e.createElementBlock("div",i$,[e.createElementVNode("video",{ref_key:"liveVideoEl",ref:r,controls:j.controls&&!j.showCustomControls,autoplay:!0,muted:e.unref(u),onPlay:K,onPause:se,onError:ce,playsinline:"",class:"video-element","data-testid":"video-element"},null,40,r$),e.unref(v)==="live"?(e.openBlock(),e.createElementBlock("div",s$,[...ne[3]||(ne[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(E),poster:I.value,controls:j.controls&&!j.showCustomControls,autoplay:j.autoplay,muted:e.unref(u),loop:j.loop,preload:j.preload,onLoadedmetadata:Z,onTimeupdate:z,onPlay:K,onPause:se,onEnded:Be,onError:ce,onProgress:ie,onWaiting:W,onCanplay:C,playsinline:"",class:"video-element","data-testid":"video-element"},null,40,o$)),e.unref(p)?(e.openBlock(),e.createElementBlock("div",l$,[e.createVNode(e.unref(H.IonSpinner),{name:"crescent"})])):e.createCommentVNode("",!0),e.unref(h)?(e.openBlock(),e.createElementBlock("div",d$,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Ql),"aria-hidden":"true"},null,8,["icon"]),e.createElementVNode("p",null,e.toDisplayString(e.unref(h)),1),e.createVNode(e.unref(H.IonButton),{size:"small",onClick:e.unref(x),"data-testid":"btn-video-retry","aria-label":"Retry loading video"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(io),slot:"start","aria-hidden":"true"},null,8,["icon"]),ne[4]||(ne[4]=e.createTextVNode(" Retry ",-1))]),_:1},8,["onClick"])])):e.createCommentVNode("",!0),j.showCustomControls&&!e.unref(h)?(e.openBlock(),e.createBlock(a$,{key:4,playing:e.unref(s),currentTime:e.unref(l),duration:e.unref(d),buffered:e.unref(f),volume:e.unref(c),muted:e.unref(u),fullscreen:e.unref(m),isLive:j.isLive,onPlay:e.unref(k),onPause:e.unref(g),onSeek:e.unref(b),onToggleMute:e.unref(R),onSetVolume:e.unref(N),onToggleFullscreen:e.unref(T),class:"custom-controls"},null,8,["playing","currentTime","duration","buffered","volume","muted","fullscreen","isLive","onPlay","onPause","onSeek","onToggleMute","onSetVolume","onToggleFullscreen"])):e.createCommentVNode("",!0),j.enableGestures&&!e.unref(h)?(e.openBlock(),e.createElementBlock("div",c$,[e.createElementVNode("div",{class:"gesture-left","data-testid":"video-gesture-skip-back","aria-label":"Double tap to skip backward",onDblclick:ne[0]||(ne[0]=(...de)=>e.unref(A)&&e.unref(A)(...de))},null,32),e.createElementVNode("div",{class:"gesture-center","data-testid":"video-gesture-play-pause","aria-label":"Tap to play or pause",onClick:ne[1]||(ne[1]=(...de)=>e.unref(S)&&e.unref(S)(...de))}),e.createElementVNode("div",{class:"gesture-right","data-testid":"video-gesture-skip-forward","aria-label":"Double tap to skip forward",onDblclick:ne[2]||(ne[2]=(...de)=>e.unref(B)&&e.unref(B)(...de))},null,32)])):e.createCommentVNode("",!0)],2))}}),af=Fe(u$,[["__scopeId","data-v-b8db4951"]]),m$=Yr.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())),s=e.computed(()=>Array.from(a.value.values())),l=e.computed(()=>s.value.filter(P=>P.status==="live")),d=e.computed(()=>r.value.filter(P=>P.processing_status==="processing"));function c(P){o.value.set(P.uuid,P)}function u(P,D){const O=o.value.get(P);O&&o.value.set(P,{...O,...D})}function m(P){o.value.delete(P)}function f(P){return o.value.get(P)}function p(P){a.value.set(P.id,P)}function h(P,D){const O=a.value.get(P);O&&a.value.set(P,{...O,...D})}function v(P,D){const O=a.value.get(P);O&&a.value.set(P,{...O,status:D.status,viewer_count:D.viewer_count,peak_viewers:D.peak_viewers})}function E(P){a.value.delete(P)}function y(P){return a.value.get(P)}function k(P){return s.value.find(D=>D.media_uuid===P)}function g(P){t.value.set(P.id,P)}function b(P,D){const O=t.value.get(P);O&&t.value.set(P,{...O,...D})}function R(P){t.value.delete(P)}function N(P){return t.value.get(P)}function T(P){return Array.from(t.value.values()).filter(D=>D.media_uuid===P)}function S(P){n.value=P}function B(P){n.value&&(n.value={...n.value,...P})}function A(){n.value=null}function x(P){i.value=P}function M(){o.value.clear(),a.value.clear(),t.value.clear(),n.value=null,i.value=!1}function w(P){o.value.clear(),P.forEach(D=>{o.value.set(D.uuid,D)})}function F(P){a.value.clear(),P.forEach(D=>{a.value.set(D.id,D)})}return{videos:o,liveStreams:a,exportJobs:t,currentEditorState:n,isProcessing:i,allVideos:r,allLiveStreams:s,activeLiveStreams:l,processingVideos:d,setVideo:c,updateVideo:u,removeVideo:m,getVideo:f,setLiveStream:p,updateLiveStream:h,updateLiveStreamStats:v,removeLiveStream:E,getLiveStream:y,getLiveStreamByMedia:k,addExportJob:g,updateExportJob:b,removeExportJob:R,getExportJob:N,getExportJobsByMedia:T,setEditorState:S,updateEditorState:B,clearEditorState:A,setProcessing:x,clearAll:M,loadVideos:w,loadLiveStreams:F}});let Hn=null;function p$(o){Hn=o}const hr={post:async(o,a)=>{if(!Hn)throw new Error("HTTP client not configured");return await Hn(`/api/v1/video${o}`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json"}})},get:async o=>{if(!Hn)throw new Error("HTTP client not configured");return await Hn(`/api/v1/video${o}`)},delete:async o=>{if(!Hn)throw new Error("HTTP client not configured");return await Hn(`/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 s=o.ended_at??(a==null?void 0:a.ended_at);return s!==void 0&&(n.ended_at=s),(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 nl(o,a){return o instanceof Error&&o.message?o.message:a}function f$(o){const a=m$(),t=e.ref(null),n=e.ref(!1),i=e.ref(!0),r=e.ref(""),s=e.ref(!1),l=e.ref(!1),d=e.ref(null),c=e.ref(null),u=e.ref(0),m=e.ref(0);let f;const p=e.computed(()=>c.value?Math.floor((new Date().getTime()-c.value.getTime())/1e3):0),h=e.computed(()=>{var A;if(!((A=t.value)!=null&&A.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"}),E=e.computed(()=>{var B;return((B=t.value)==null?void 0:B.status)==="idle"}),y=e.computed(()=>{var B;return((B=t.value)==null?void 0:B.status)==="ended"});async function k(B={}){s.value=!0,d.value=null;try{const A=await hr.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(A);return t.value=x,a.setLiveStream(x),N(),x}catch(A){throw d.value=nl(A,"Failed to create stream"),A instanceof Error?A:new Error(d.value)}finally{s.value=!1}}async function g(){if(!t.value)throw new Error("No active stream");l.value=!0,d.value=null;try{const B=await hr.post(`/live/${t.value.id}/end`),A=vr(B,t.value);return t.value=A,a.setLiveStream(A),T(),A}catch(B){throw d.value=nl(B,"Failed to end stream"),B instanceof Error?B:new Error(d.value)}finally{l.value=!1}}async function b(){if(t.value)try{const B=await hr.get(`/live/${t.value.id}`),A=vr(B,t.value);u.value=A.viewer_count,m.value=A.peak_viewers,t.value=A;const x={status:A.status,viewer_count:A.viewer_count,peak_viewers:A.peak_viewers};A.started_at&&(x.started_at=A.started_at),A.ended_at&&(x.ended_at=A.ended_at),a.updateLiveStreamStats(A.id,x),A.status==="live"&&!c.value&&A.started_at&&(c.value=new Date(A.started_at)),A.status==="ended"&&T()}catch{}}async function R(B){try{const A=await hr.get(`/live/${B}`),x=vr(A,t.value);return{rtmp_url:x.rtmp_url,stream_key:x.stream_key,playback_url:x.playback_url||""}}catch(A){throw d.value=nl(A,"Failed to get stream credentials"),A instanceof Error?A:new Error(d.value)}}function N(B=5e3){T(),f=window.setInterval(()=>{b()},B)}function T(){f!==void 0&&(clearInterval(f),f=void 0)}async function S(){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"&&(N(),B.started_at&&(c.value=new Date(B.started_at))))}return o&&S(),e.onUnmounted(()=>{T()}),{stream:t,lowLatency:n,autoRecord:i,streamTitle:r,isCreating:s,isEnding:l,error:d,streamDuration:p,viewerCount:u,peakViewers:m,playbackUrl:h,isLive:v,isIdle:E,hasEnded:y,createStream:k,endStream:g,refreshStreamStatus:b,getStreamCredentials:R,startStatusPolling:N,stopStatusPolling:T}}const h$={class:"stream-status"},v$={class:"flex items-center justify-between"},g$={class:"flex items-center gap-3"},b$={key:0,class:"flex items-center"},y$={key:2,class:"text-sm text-gray-600"},w$={key:0,class:"flex items-center gap-2"},k$={class:"text-sm font-medium text-gray-700"},_$={key:0,class:"text-xs text-gray-500"},E$=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",s={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} ${s[a.status]||s.idle}`}),i=e.computed(()=>{if(!a.duration)return null;const r=Math.floor(a.duration/3600),s=Math.floor(a.duration%3600/60),l=a.duration%60;return r>0?`${r}:${s.toString().padStart(2,"0")}:${l.toString().padStart(2,"0")}`:`${s}:${l.toString().padStart(2,"0")}`});return(r,s)=>(e.openBlock(),e.createElementBlock("div",h$,[e.createElementVNode("div",v$,[e.createElementVNode("div",g$,[r.status==="live"?(e.openBlock(),e.createElementBlock("div",b$,[...s[0]||(s[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",y$,e.toDisplayString(i.value),1)):e.createCommentVNode("",!0)]),r.viewers!==void 0?(e.openBlock(),e.createElementBlock("div",w$,[s[1]||(s[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",k$,e.toDisplayString(r.viewers)+" "+e.toDisplayString(r.viewers===1?"viewer":"viewers"),1),r.peakViewers>r.viewers?(e.openBlock(),e.createElementBlock("span",_$," (Peak: "+e.toDisplayString(r.peakViewers)+") ",1)):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)])]))}}),S$=Fe(E$,[["__scopeId","data-v-1d09c19f"]]),C$={class:"stream-credentials"},x$={class:"space-y-3"},V$={class:"credential-field"},N$={class:"flex gap-2"},T$=["value"],B$={class:"credential-field"},M$={class:"flex gap-2"},I$=["value","type"],$$=["aria-label"],F$={key:0,class:"w-4 h-4 text-gray-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},D$={key:1,class:"w-4 h-4 text-gray-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},R$={key:0,class:"mt-2 text-sm text-green-600"},A$=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(""),s=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 l(){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",C$,[u[8]||(u[8]=e.createElementVNode("h4",{class:"text-sm font-medium text-gray-700 mb-3"},"Stream Settings",-1)),e.createElementVNode("div",x$,[e.createElementVNode("div",V$,[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",N$,[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,T$),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",B$,[u[7]||(u[7]=e.createElementVNode("label",{class:"block text-xs font-medium text-gray-500 mb-1"},"Stream Key",-1)),e.createElementVNode("div",M$,[e.createElementVNode("input",{value:s.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,I$),e.createElementVNode("button",{onClick:l,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",D$,[...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",F$,[...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,$$),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",R$,e.toDisplayString(r.value)+" copied to clipboard! ",1)):e.createCommentVNode("",!0)]),_:1})]))}}),L$=Fe(A$,[["__scopeId","data-v-306d92f6"]]),P$={class:"live-stream-manager","data-testid":"live-stream-manager"},U$={key:0,class:"stream-setup"},O$={class:"space-y-4"},z$={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"},W$=["disabled"],H$={key:0},Z$={key:1,class:"flex items-center justify-center"},G$={key:1,class:"stream-active space-y-6"},X$={key:1,class:"video-preview"},K$={key:2,class:"analytics-panel"},J$={class:"grid grid-cols-2 gap-4"},q$={class:"bg-gray-50 p-3 rounded"},Y$={class:"text-2xl font-bold text-gray-900"},Q$={class:"bg-gray-50 p-3 rounded"},e5={class:"text-2xl font-bold text-gray-900"},t5={class:"stream-controls flex gap-3"},a5=["disabled"],n5={key:0},o5={key:1},i5={key:2,class:"mt-4 p-4 bg-red-50 border border-red-200 rounded-lg"},r5={class:"text-red-600 text-sm"},s5=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&&p$(t.httpClient);const{stream:i,lowLatency:r,autoRecord:s,streamTitle:l,isCreating:d,isEnding:c,error:u,createStream:m,endStream:f,streamDuration:p,playbackUrl:h,refreshStreamStatus:v}=f$(t.mediaUuid),E=e.ref(!1);async function y(){var N;try{const T=await m({title:l.value,low_latency:r.value,auto_record:s.value});n("stream-created",T),(N=t.onStreamCreated)==null||N.call(t,T)}catch(T){n("error",T)}}async function k(){var N;try{const T=await f();n("stream-ended",T),(N=t.onStreamEnded)==null||N.call(t,T)}catch(T){n("error",T)}}function g(){i.value=null,l.value="",E.value=!1,u.value=null}async function b(N,T){try{await navigator.clipboard.writeText(N)}catch{}}let R;return e.onMounted(()=>{var N;((N=i.value)==null?void 0:N.status)==="live"&&(R=window.setInterval(()=>{v()},5e3))}),e.onUnmounted(()=>{R&&clearInterval(R)}),(N,T)=>(e.openBlock(),e.createElementBlock("div",P$,[e.unref(i)?(e.openBlock(),e.createElementBlock("div",G$,[e.createVNode(S$,{status:e.unref(i).status,viewers:e.unref(i).viewer_count,duration:e.unref(p),"peak-viewers":e.unref(i).peak_viewers},null,8,["status","viewers","duration","peak-viewers"]),e.unref(i).status==="idle"?(e.openBlock(),e.createBlock(L$,{key:0,"rtmp-url":e.unref(i).rtmp_url,"stream-key":e.unref(i).stream_key,onCopy:b},null,8,["rtmp-url","stream-key"])):e.createCommentVNode("",!0),e.unref(h)?(e.openBlock(),e.createElementBlock("div",X$,[T[9]||(T[9]=e.createElementVNode("h4",{class:"text-sm font-medium text-gray-700 mb-2"},"Live Preview",-1)),e.createVNode(af,{"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",K$,[T[12]||(T[12]=e.createElementVNode("h4",{class:"text-sm font-medium text-gray-700 mb-3"},"Live Analytics",-1)),e.createElementVNode("div",J$,[e.createElementVNode("div",q$,[e.createElementVNode("div",Y$,e.toDisplayString(e.unref(i).viewer_count),1),T[10]||(T[10]=e.createElementVNode("div",{class:"text-xs text-gray-500"},"Current Viewers",-1))]),e.createElementVNode("div",Q$,[e.createElementVNode("div",e5,e.toDisplayString(e.unref(i).peak_viewers),1),T[11]||(T[11]=e.createElementVNode("div",{class:"text-xs text-gray-500"},"Peak Viewers",-1))])])])):e.createCommentVNode("",!0),e.createElementVNode("div",t5,[e.unref(i).status==="idle"?(e.openBlock(),e.createElementBlock("button",{key:0,onClick:T[3]||(T[3]=S=>E.value=!E.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(E.value?"Hide":"Show")+" Credentials ",1)):e.createCommentVNode("",!0),e.unref(i).status==="live"?(e.openBlock(),e.createElementBlock("button",{key:1,onClick:k,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",o5,"Ending...")):(e.openBlock(),e.createElementBlock("span",n5,"End Stream"))],8,a5)):e.createCommentVNode("",!0),e.unref(i).status==="ended"?(e.openBlock(),e.createElementBlock("button",{key:2,onClick:g,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",U$,[T[8]||(T[8]=e.createElementVNode("h3",{class:"text-lg font-semibold mb-4"},"Start Live Stream",-1)),e.createElementVNode("div",O$,[e.createElementVNode("div",z$,[T[4]||(T[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":T[0]||(T[0]=S=>e.isRef(r)?r.value=S: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$,[T[5]||(T[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":T[1]||(T[1]=S=>e.isRef(s)?s.value=S: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(s)]])]),e.createElementVNode("div",null,[T[6]||(T[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":T[2]||(T[2]=S=>e.isRef(l)?l.value=S: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(l)]])]),e.createElementVNode("button",{onClick:y,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",Z$,[...T[7]||(T[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",H$,"Create Stream"))],8,W$)])])),e.unref(u)?(e.openBlock(),e.createElementBlock("div",i5,[e.createElementVNode("p",r5,e.toDisplayString(e.unref(u)),1)])):e.createCommentVNode("",!0)]))}}),l5=Fe(s5,[["__scopeId","data-v-26291f6f"]]),d5={class:"album-tree-node"},c5=["data-album-id","draggable","aria-selected","aria-expanded"],u5={key:1,class:"album-node__chevron-placeholder"},m5={key:2,"data-testid":"media-count",class:"album-node__count"},p5={key:0,class:"album-tree-node__children",role:"group"},f5=16,h5=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),s=e.computed(()=>t.focusedId===t.album.id),l=e.computed(()=>t.album.children_count>0),d=e.computed(()=>`${t.depth*f5}px`),c=e.computed(()=>{var g;return((g=t.dragState)==null?void 0:g.draggedAlbumId)===t.album.id}),u=e.computed(()=>{var g;return((g=t.dragState)==null?void 0:g.dropTargetId)===t.album.id}),m=e.computed(()=>{var g;return(g=t.dragState)!=null&&g.draggedAlbumId?t.dragState.draggedAlbumId===t.album.id:!1}),f=e.computed(()=>{const g=["album-node"];return r.value&&g.push("album-node--selected"),s.value&&g.push("album-node--focused"),t.compact&&g.push("album-node--compact"),c.value&&g.push("album-node--dragging"),u.value&&g.push("album-node--drop-target"),m.value&&g.push("album-node--invalid-drop"),g});function p(){n("select",t.album)}function h(g){g.stopPropagation(),n("toggle-expand",t.album.id)}function v(g){t.draggable&&(g.dataTransfer&&(g.dataTransfer.setData("text/plain",t.album.id),g.dataTransfer.effectAllowed="move"),n("drag-start",t.album.id))}function E(g){t.draggable&&(g.preventDefault(),g.dataTransfer&&(g.dataTransfer.dropEffect="move"),n("drag-over",t.album.id))}function y(){n("drag-leave",t.album.id)}function k(g){t.draggable&&(g.preventDefault(),n("drop",t.album.id))}return(g,b)=>{var N;const R=e.resolveComponent("AlbumTreeNode",!0);return e.openBlock(),e.createElementBlock("div",d5,[e.createElementVNode("div",{"data-testid":"album-node","data-album-id":g.album.id,class:e.normalizeClass(f.value),style:e.normalizeStyle({paddingLeft:d.value}),draggable:g.draggable,role:"treeitem","aria-selected":r.value,"aria-expanded":l.value?i.value:void 0,onDragstart:v,onDragover:E,onDragleave:y,onDrop:k},[l.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(H.IonIcon),{icon:i.value?e.unref(nv):e.unref(ov)},null,8,["icon"])])):(e.openBlock(),e.createElementBlock("span",u5)),e.createVNode(e.unref(H.IonIcon),{icon:e.unref(mv),class:"album-node__icon"},null,8,["icon"]),e.createElementVNode("span",{"data-testid":"album-name",class:"album-node__name",onClick:p},e.toDisplayString(g.album.name),1),g.showMediaCount?(e.openBlock(),e.createElementBlock("span",m5,e.toDisplayString(g.album.media_count),1)):e.createCommentVNode("",!0)],46,c5),i.value&&((N=g.album.children)!=null&&N.length)?(e.openBlock(),e.createElementBlock("div",p5,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(g.album.children,T=>(e.openBlock(),e.createBlock(R,{key:T.id,album:T,depth:g.depth+1,"selected-id":g.selectedId,"expanded-ids":g.expandedIds,"focused-id":g.focusedId,draggable:g.draggable,"show-media-count":g.showMediaCount,compact:g.compact,onSelect:b[0]||(b[0]=S=>n("select",S)),onToggleExpand:b[1]||(b[1]=S=>n("toggle-expand",S))},null,8,["album","depth","selected-id","expanded-ids","focused-id","draggable","show-media-count","compact"]))),128))])):e.createCommentVNode("",!0)])}}}),v5=Fe(h5,[["__scopeId","data-v-76be65a6"]]);let ao={apiBaseUrl:"/api/v1"};function nf(o){ao={...ao,...o}}function g5(){return{...ao}}function b5(o){ao={...o}}function xu(o,a){const t=(o??a).trim().replace(/\/+$/,"");return t===""?a:/^https?:\/\//i.test(t)||t.startsWith("/")?t:`/${t}`}function y5(){const o=xu(ao.apiBaseUrl,"/api/v1");return xu(ao.albumBaseUrl,`${o}/albums`)}function dn(o){return encodeURIComponent(o)}function w5(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 Ja(o="",a={}){return w5(`${y5()}${o}`,a)}async function k5(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)throw new Error(`Album request failed with status ${r.status}.`);return r.status===204?{}:await r.json()}async function qa(o,a){return await(ao.httpClient??k5)(o,a)}function ii(o){if(typeof o=="object"&&o!==null&&"data"in o&&typeof o.data=="object"&&o.data!==null)return o.data;throw new Error("Album response was invalid")}function _5(o){return typeof o=="object"&&o!==null&&"data"in o&&Array.isArray(o.data)?o.data:[]}const xs=Yr.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 S=new Map;return o.value.forEach(B=>S.set(B.id,B)),S}),s=e.computed(()=>o.value.filter(S=>S.parent_id===null));function l(S){const B=o.value.findIndex(A=>A.id===S.id);B>=0?o.value[B]=S:o.value.push(S)}function d(S,B){Array.isArray(B.media)&&a.value.set(S,B.media)}async function c(S){t.value=!0,n.value=null;try{const B=(S==null?void 0:S.parent_id)??null,A=await qa(Ja("",{parent_id:B})),x=_5(A);for(const M of x)l(M);B!==null&&i.value.add(B)}catch(B){n.value=B instanceof Error?B.message:"Unknown error"}finally{t.value=!1}}async function u(S){t.value=!0,n.value=null;try{const B=await qa(Ja(`/${dn(S)}`)),A=ii(B);return l(A),A}catch(B){throw n.value=B instanceof Error?B.message:"Unknown error",B}finally{t.value=!1}}async function m(S){t.value=!0,n.value=null;try{const B=await qa(Ja(`/${dn(S)}`,{include_media:!0})),A=ii(B);l(A);const x=Array.isArray(A.media)?A.media:[];return a.value.set(S,x),x}catch(B){throw n.value=B instanceof Error?B.message:"Unknown error",B}finally{t.value=!1}}async function f(S,B,A){t.value=!0,n.value=null;try{const x={media_uuids:B};A!==void 0&&(x.order_column=A);const M=await qa(Ja(`/${dn(S)}/media`),{method:"POST",body:x}),w=ii(M);return l(w),d(S,w),w}catch(x){throw n.value=x instanceof Error?x.message:"Unknown error",x}finally{t.value=!1}}async function p(S,B){t.value=!0,n.value=null;try{await qa(Ja(`/${dn(S)}/media/${dn(B)}`),{method:"DELETE"});const A=a.value.get(S)||[];a.value.set(S,A.filter(x=>x.uuid!==B))}catch(A){throw n.value=A instanceof Error?A.message:"Unknown error",A}finally{t.value=!1}}async function h(S,B){t.value=!0,n.value=null;try{const A=await qa(Ja(`/${dn(S)}/media/reorder`),{method:"POST",body:{ordered_media_uuids:B}});if(A.data!==void 0){l(A.data),d(S,A.data);return}const x=a.value.get(S)||[],M=B.map(w=>x.find(F=>F.uuid===w)).filter(w=>w!==void 0);a.value.set(S,M)}catch(A){throw n.value=A instanceof Error?A.message:"Unknown error",A}finally{t.value=!1}}async function v(S){t.value=!0,n.value=null;try{const B=await qa(Ja(),{method:"POST",body:S}),A=ii(B);return l(A),A}catch(B){throw n.value=B instanceof Error?B.message:"Unknown error",B}finally{t.value=!1}}async function E(S,B){t.value=!0,n.value=null;try{const A=await qa(Ja(`/${dn(S)}`),{method:"PATCH",body:B}),x=ii(A);return l(x),x}catch(A){throw n.value=A instanceof Error?A.message:"Unknown error",A}finally{t.value=!1}}async function y(S){t.value=!0,n.value=null;try{await qa(Ja(`/${dn(S)}`),{method:"DELETE"});const B=o.value.findIndex(A=>A.id===S);B>=0&&o.value.splice(B,1),a.value.delete(S)}catch(B){throw n.value=B instanceof Error?B.message:"Unknown error",B}finally{t.value=!1}}function k(S){return o.value.filter(B=>B.parent_id===S)}function g(S){return i.value.has(S)}function b(S){return a.value.get(S)||[]}async function R(S,B){const A=o.value.findIndex(M=>M.id===S);if(A<0)return;const x=o.value[A];o.value[A]={...x,parent_id:B};try{const M=await qa(Ja(`/${dn(S)}/move`),{method:"POST",body:{parent_id:B}});M.data!==void 0&&l(M.data)}catch(M){throw o.value[A]=x,n.value=M instanceof Error?M.message:"Unknown error",M instanceof Error?M:new Error("Failed to move album")}}function N(S){o.value=S}function T(){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:s,fetchAlbums:c,fetchAlbum:u,fetchAlbumMedia:m,attachMedia:f,detachMedia:p,reorderAlbumMedia:h,createAlbum:v,updateAlbum:E,deleteAlbum:y,getChildrenOf:k,childrenLoaded:g,getAlbumMedia:b,moveAlbum:R,setAlbums:N,reset:T}});function Td(){const o=xs(),{albums:a,albumsById:t,rootAlbums:n,loading:i,error:r}=Yr.storeToRefs(o);async function s(k){await o.fetchAlbums(k)}async function l(k){return await o.fetchAlbum(k)}async function d(k){return await o.fetchAlbumMedia(k)}async function c(k,g,b){return await o.attachMedia(k,g,b)}async function u(k,g){await o.detachMedia(k,g)}async function m(k,g){await o.reorderAlbumMedia(k,g)}async function f(k){return await o.createAlbum(k)}async function p(k,g){return await o.updateAlbum(k,g)}async function h(k){await o.deleteAlbum(k)}function v(k){return o.getChildrenOf(k)}function E(k){return o.childrenLoaded(k)}async function y(k,g){await o.moveAlbum(k,g)}return{albums:a,albumsById:t,rootAlbums:n,loading:i,error:r,fetchAlbums:s,fetchAlbum:l,fetchAlbumMedia:d,attachMedia:c,detachMedia:u,reorderAlbumMedia:m,createAlbum:f,updateAlbum:p,deleteAlbum:h,getChildrenOf:v,childrenLoaded:E,moveAlbum:y}}function of(o){const{childrenByParentId:a,onMove:t}=o,n=e.ref({isDragging:!1,draggedAlbumId:null,dropTargetId:null,dropPosition:null});function i(m,f){if(m===f)return!0;const p=new Set,h=[m];for(;h.length>0;){const v=h.shift();if(!v||p.has(v))continue;p.add(v);const E=a.get(v)||[];for(const y of E){if(y===f)return!0;h.push(y)}}return!1}function r(m,f){return m===f?!1:f===null?!0:!i(m,f)}function s(m){n.value={isDragging:!0,draggedAlbumId:m,dropTargetId:null,dropPosition:null}}function l(){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:f}=n.value;if(!m){l();return}if(!r(m,f)){l();return}try{await t(m,f)}finally{l()}}return{dragState:n,isDescendant:i,canDropOn:r,startDrag:s,endDrag:l,setDropTarget:d,clearDropTarget:c,executeDrop:u}}const E5={key:0,"data-testid":"loading-spinner",class:"album-tree__loading"},S5={key:1,"data-testid":"error-state",class:"album-tree__error"},C5={key:2,"data-testid":"empty-state",class:"album-tree__empty"},x5={key:3,class:"album-tree__content",role:"group"},V5=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),s=e.computed(()=>n.showMediaCount===!0),l=e.computed(()=>n.compact===!0),d=e.computed(()=>({"album-tree--rail":n.mode==="rail"})),{albums:c,rootAlbums:u,loading:m,error:f,fetchAlbums:p,getChildrenOf:h,childrenLoaded:v,moveAlbum:E}=Td(),y=e.shallowRef(new Set(n.expandedIds)),k=e.ref(n.modelValue??null),g=e.ref(null),b=new Map,R=new Map;function N(C){b.clear(),R.clear();for(const U of C){b.set(U.id,U);const j=U.parent_id??null,ne=R.get(j)??[];ne.push(U.id),R.set(j,ne)}}e.watch(c,C=>{N(C)},{immediate:!0});const{dragState:T,canDropOn:S,startDrag:B,endDrag:A,setDropTarget:x,clearDropTarget:M,executeDrop:w}=of({childrenByParentId:R,onMove:async(C,U)=>{await E(C,U),i("album-moved",{albumId:C,newParentId:U})}});e.watch(()=>n.modelValue,C=>{k.value=C??null}),e.watch(()=>n.expandedIds,C=>{y.value=new Set(C)}),e.onMounted(async()=>{await p({parent_id:null})});const F=e.computed(()=>u.value.map(C=>P(C)));function P(C){if(!y.value.has(C.id))return C;const U=h(C.id);return{...C,children:U.map(j=>P(j))}}const D=e.computed(()=>{const C=[];function U(j){var ne;for(const de of j)C.push(de),y.value.has(de.id)&&((ne=de.children)!=null&&ne.length)&&U(de.children)}return U(F.value),C});function O(C){var ne;if(!D.value.length)return;const U=g.value?D.value.findIndex(de=>de.id===g.value):-1,j=U>=0?D.value[U]:null;switch(C.key){case"ArrowDown":C.preventDefault(),U<D.value.length-1?g.value=D.value[U+1].id:U===-1&&D.value.length>0&&(g.value=D.value[0].id);break;case"ArrowUp":C.preventDefault(),U>0&&(g.value=D.value[U-1].id);break;case"ArrowRight":C.preventDefault(),j&&(j.children_count>0&&!y.value.has(j.id)?I(j.id):y.value.has(j.id)&&((ne=j.children)!=null&&ne.length)&&(g.value=j.children[0].id));break;case"ArrowLeft":C.preventDefault(),j&&(y.value.has(j.id)&&j.children_count>0?I(j.id):j.parent_id&&(g.value=j.parent_id));break;case"Enter":case" ":C.preventDefault(),j&&Z(j);break;case"Home":C.preventDefault(),D.value.length>0&&(g.value=D.value[0].id);break;case"End":C.preventDefault(),D.value.length>0&&(g.value=D.value[D.value.length-1].id);break}}async function I(C){y.value.has(C)?(y.value.delete(C),i("album-collapsed",C)):(v(C)||await p({parent_id:C}),y.value.add(C),i("album-expanded",C))}function Z(C){k.value=C.id,i("update:modelValue",C.id),i("album-selected",C)}function z(C){n.draggable&&B(C)}function K(C){var j;if(!n.draggable)return;const U=(j=T.value)==null?void 0:j.draggedAlbumId;U&&(x(C),S(U,C))}function se(){n.draggable&&M()}async function Be(C){n.draggable&&(x(C),await w())}function ce(C){n.draggable&&(C.preventDefault(),x(null))}async function ie(C){n.draggable&&(C.preventDefault(),x(null),await w())}function W(){A()}return a({focusedId:g}),(C,U)=>(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:O,onDragover:ce,onDrop:ie,onDragend:W},[e.unref(m)?(e.openBlock(),e.createElementBlock("div",E5,[e.createVNode(e.unref(H.IonSpinner),{name:"crescent"})])):e.unref(f)?(e.openBlock(),e.createElementBlock("div",S5,[e.createElementVNode("p",null,e.toDisplayString(e.unref(f)),1)])):e.unref(u).length?(e.openBlock(),e.createElementBlock("div",x5,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(F.value,j=>(e.openBlock(),e.createBlock(v5,{key:j.id,album:j,depth:0,"selected-id":k.value,"expanded-ids":y.value,"focused-id":g.value,draggable:r.value,"drag-state":r.value?e.unref(T):null,"show-media-count":s.value,compact:l.value,onSelect:Z,onToggleExpand:I,onDragStart:z,onDragOver:K,onDragLeave:se,onDrop:Be},null,8,["album","selected-id","expanded-ids","focused-id","draggable","drag-state","show-media-count","compact"]))),128))])):(e.openBlock(),e.createElementBlock("div",C5,[U[0]||(U[0]=e.createElementVNode("p",null,"No albums yet",-1)),e.renderSlot(C.$slots,"empty-action",{},void 0,!0)]))],34))}}),Vs=Fe(V5,[["__scopeId","data-v-ee405f62"]]),N5=300,T5=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),s=e.ref(0),l=e.ref(null);e.watch(()=>t.selectedAlbumId,p=>{i.value=p??null});const d=e.computed(()=>r.value!==null);function c(p){const h=Date.now();if(l.value===p.id&&h-s.value<N5){n("confirm",p);return}s.value=h,l.value=p.id,i.value=p.id,r.value=p}function u(){r.value&&n("confirm",r.value)}function m(){n("close")}function f(){n("close")}return(p,h)=>(e.openBlock(),e.createBlock(e.unref(H.IonModal),{"is-open":p.isOpen,class:"album-browser-modal",onDidDismiss:f},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonHeader),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonToolbar),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonTitle),null,{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(p.title),1)]),_:1}),e.createVNode(e.unref(H.IonButtons),{slot:"end"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.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(H.IonContent),{class:"album-browser-content"},{default:e.withCtx(()=>[e.createVNode(Vs,{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(H.IonFooter),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonToolbar),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButtons),{slot:"end"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButton),{fill:"clear",onClick:m},{default:e.withCtx(()=>[...h[2]||(h[2]=[e.createTextVNode(" Cancel ",-1)])]),_:1}),e.createVNode(e.unref(H.IonButton),{"data-testid":"confirm-button",fill:"solid",color:"primary",disabled:!d.value,onClick:u},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(p.confirmText),1)]),_:1},8,["disabled"])]),_:1})]),_:1})]),_:1})]),_:1},8,["is-open"]))}}),rf=Fe(T5,[["__scopeId","data-v-21676ec1"]]),B5={class:"ion-padding-start text-sm"},M5={class:"ion-padding-start text-sm"},I5={key:1},$5={key:1,class:"album-manager-inline rounded-lg border border-gray-200 bg-white p-4"},F5={class:"flex items-center justify-between gap-3 pb-3"},D5={class:"text-base font-semibold text-gray-900"},R5={class:"ion-padding-start text-sm"},A5={class:"ion-padding-start text-sm"},L5={class:"flex justify-between pt-2"},P5={key:1},ri=255,si=1e3,U5=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=xs(),r=e.computed(()=>t.albumId!==null&&t.albumId!==void 0),s=e.computed(()=>r.value?"Edit Album":"Create Album"),l=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),f=e.ref(null),p=e.ref(!1),h=e.ref(!1),v=e.computed(()=>c.value.name?d.value.name.trim()?d.value.name.length>ri?`Name must be ${ri} characters or less`:null:"Name is required":null),E=e.computed(()=>c.value.description&&d.value.description.length>si?`Description must be ${si} characters or less`:null),y=e.computed(()=>{const D=d.value.name.trim().length>0,O=d.value.name.length<=ri,I=d.value.description.length<=si;return D&&O&&I&&!p.value}),k=e.computed(()=>{var D;return((D=u.value)==null?void 0:D.name)??"None (Root)"}),g=e.computed(()=>f.value?f.value.children_count===0&&f.value.media_count===0:!1),b=e.computed(()=>f.value?f.value.children_count>0?"Cannot delete album with child albums. Move or delete children first.":f.value.media_count>0?"Cannot delete album with media. Remove media first.":`Are you sure you want to delete "${f.value.name}"? This action cannot be undone.`:"");e.onMounted(async()=>{t.albumId&&await R()});async function R(){if(t.albumId)try{const D=await i.fetchAlbum(t.albumId);f.value=D,d.value={name:D.name,description:D.description??"",parent_id:D.parent_id},D.parent_id&&(u.value={id:D.parent_id,name:"Parent Album"})}catch(D){n("error",D)}}function N(){c.value.name=!0}function T(){c.value.description=!0}function S(){m.value=!0}function B(D){u.value={id:D.id,name:D.name},d.value.parent_id=D.id,m.value=!1}function A(){m.value=!1}function x(){n("close")}function M(){n("close")}async function w(){if(c.value.name=!0,c.value.description=!0,!(!y.value||p.value)){p.value=!0;try{const D={name:d.value.name.trim(),description:d.value.description.trim(),parent_id:d.value.parent_id};if(r.value&&t.albumId){const O=await i.updateAlbum(t.albumId,D);n("updated",O)}else{const O=await i.createAlbum(D);n("created",O)}n("close")}catch(D){n("error",D)}finally{p.value=!1}}}function F(){g.value&&(h.value=!0)}async function P(D){var I;if((((I=D.detail)==null?void 0:I.role)??"")!=="confirm"){h.value=!1;return}if(t.albumId){p.value=!0;try{await i.deleteAlbum(t.albumId),n("deleted",t.albumId),n("close")}catch(Z){n("error",Z)}finally{p.value=!1,h.value=!1}}}return(D,O)=>(e.openBlock(),e.createElementBlock(e.Fragment,null,[D.mode==="modal"?(e.openBlock(),e.createBlock(e.unref(H.IonModal),{key:0,"is-open":D.isOpen,class:"album-manager-modal",onDidDismiss:M},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonHeader),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonToolbar),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonTitle),null,{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(s.value),1)]),_:1}),e.createVNode(e.unref(H.IonButtons),{slot:"end"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButton),{"data-testid":"cancel-btn",fill:"clear",onClick:x},{default:e.withCtx(()=>[...O[4]||(O[4]=[e.createTextVNode(" Cancel ",-1)])]),_:1})]),_:1})]),_:1})]),_:1}),e.createVNode(e.unref(H.IonContent),{class:"album-manager-content"},{default:e.withCtx(()=>[e.createElementVNode("form",{"data-testid":"album-form",class:"p-4 space-y-3",onSubmit:e.withModifiers(w,["prevent"])},[e.createVNode(e.unref(H.IonItem),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),{position:"stacked"},{default:e.withCtx(()=>[...O[5]||(O[5]=[e.createTextVNode("Name *",-1)])]),_:1}),e.createVNode(e.unref(H.IonInput),{modelValue:d.value.name,"onUpdate:modelValue":O[0]||(O[0]=I=>d.value.name=I),"data-testid":"name-input",maxlength:ri,onIonBlur:N},null,8,["modelValue"])]),_:1}),v.value?(e.openBlock(),e.createBlock(e.unref(H.IonText),{key:0,color:"danger","data-testid":"name-error"},{default:e.withCtx(()=>[e.createElementVNode("p",B5,e.toDisplayString(v.value),1)]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(H.IonItem),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),{position:"stacked"},{default:e.withCtx(()=>[...O[6]||(O[6]=[e.createTextVNode("Description",-1)])]),_:1}),e.createVNode(e.unref(H.IonTextarea),{modelValue:d.value.description,"onUpdate:modelValue":O[1]||(O[1]=I=>d.value.description=I),"data-testid":"description-input",maxlength:si,onIonBlur:T},null,8,["modelValue"])]),_:1}),E.value?(e.openBlock(),e.createBlock(e.unref(H.IonText),{key:1,color:"danger","data-testid":"description-error"},{default:e.withCtx(()=>[e.createElementVNode("p",M5,e.toDisplayString(E.value),1)]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(H.IonItem),{button:"","data-testid":"parent-selector",onClick:S},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...O[7]||(O[7]=[e.createTextVNode("Parent Album",-1)])]),_:1}),e.createVNode(e.unref(H.IonNote),{slot:"end","data-testid":"parent-name"},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(k.value),1)]),_:1})]),_:1})],32)]),_:1}),e.createVNode(e.unref(H.IonFooter),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonToolbar),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButtons),{slot:"start"},{default:e.withCtx(()=>[r.value?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:0,"data-testid":"delete-btn",color:"danger",disabled:!g.value,title:g.value?void 0:b.value,onClick:F},{default:e.withCtx(()=>[...O[8]||(O[8]=[e.createTextVNode(" Delete ",-1)])]),_:1},8,["disabled","title"])):e.createCommentVNode("",!0)]),_:1}),e.createVNode(e.unref(H.IonButtons),{slot:"end"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButton),{"data-testid":"submit-btn",type:"submit",color:"primary",disabled:!y.value,onClick:w},{default:e.withCtx(()=>[p.value?(e.openBlock(),e.createBlock(e.unref(H.IonSpinner),{key:0,"data-testid":"loading-spinner",name:"crescent"})):(e.openBlock(),e.createElementBlock("span",I5,e.toDisplayString(l.value),1))]),_:1},8,["disabled"])]),_:1})]),_:1})]),_:1})]),_:1},8,["is-open"])):(e.openBlock(),e.createElementBlock("div",$5,[e.createElementVNode("div",F5,[e.createElementVNode("h2",D5,e.toDisplayString(s.value),1),e.createVNode(e.unref(H.IonButton),{"data-testid":"cancel-btn",fill:"clear",onClick:x},{default:e.withCtx(()=>[...O[9]||(O[9]=[e.createTextVNode(" Cancel ",-1)])]),_:1})]),e.createElementVNode("form",{"data-testid":"album-form",class:"space-y-3",onSubmit:e.withModifiers(w,["prevent"])},[e.createVNode(e.unref(H.IonItem),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),{position:"stacked"},{default:e.withCtx(()=>[...O[10]||(O[10]=[e.createTextVNode("Name *",-1)])]),_:1}),e.createVNode(e.unref(H.IonInput),{modelValue:d.value.name,"onUpdate:modelValue":O[2]||(O[2]=I=>d.value.name=I),"data-testid":"name-input",maxlength:ri,onIonBlur:N},null,8,["modelValue"])]),_:1}),v.value?(e.openBlock(),e.createBlock(e.unref(H.IonText),{key:0,color:"danger","data-testid":"name-error"},{default:e.withCtx(()=>[e.createElementVNode("p",R5,e.toDisplayString(v.value),1)]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(H.IonItem),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),{position:"stacked"},{default:e.withCtx(()=>[...O[11]||(O[11]=[e.createTextVNode("Description",-1)])]),_:1}),e.createVNode(e.unref(H.IonTextarea),{modelValue:d.value.description,"onUpdate:modelValue":O[3]||(O[3]=I=>d.value.description=I),"data-testid":"description-input",maxlength:si,onIonBlur:T},null,8,["modelValue"])]),_:1}),E.value?(e.openBlock(),e.createBlock(e.unref(H.IonText),{key:1,color:"danger","data-testid":"description-error"},{default:e.withCtx(()=>[e.createElementVNode("p",A5,e.toDisplayString(E.value),1)]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(H.IonItem),{button:"","data-testid":"parent-selector",onClick:S},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...O[12]||(O[12]=[e.createTextVNode("Parent Album",-1)])]),_:1}),e.createVNode(e.unref(H.IonNote),{slot:"end","data-testid":"parent-name"},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(k.value),1)]),_:1})]),_:1}),e.createElementVNode("div",L5,[e.createElementVNode("div",null,[r.value?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:0,"data-testid":"delete-btn",color:"danger",fill:"outline",disabled:!g.value,title:g.value?void 0:b.value,onClick:F},{default:e.withCtx(()=>[...O[13]||(O[13]=[e.createTextVNode(" Delete ",-1)])]),_:1},8,["disabled","title"])):e.createCommentVNode("",!0)]),e.createVNode(e.unref(H.IonButton),{"data-testid":"submit-btn",type:"submit",color:"primary",disabled:!y.value,onClick:w},{default:e.withCtx(()=>[p.value?(e.openBlock(),e.createBlock(e.unref(H.IonSpinner),{key:0,"data-testid":"loading-spinner",name:"crescent"})):(e.openBlock(),e.createElementBlock("span",P5,e.toDisplayString(l.value),1))]),_:1},8,["disabled"])])],32)])),e.createVNode(rf,{"is-open":m.value,"selected-album-id":d.value.parent_id,title:"Select Parent Album",onClose:A,onConfirm:B},null,8,["is-open","selected-album-id"]),e.createVNode(e.unref(H.IonAlert),{"is-open":h.value,header:"Delete Album?",message:b.value,buttons:[{text:"Cancel",role:"cancel"},{text:"Delete",role:"confirm",cssClass:"alert-button-danger"}],onDidDismiss:P},null,8,["is-open","message"])],64))}}),O5=Fe(U5,[["__scopeId","data-v-22083f3a"]]),z5={class:"album-media-grid"},j5={class:"aspect-square"},W5={key:1,"data-testid":"empty-state",class:"flex flex-col items-center justify-center py-12 gap-4"},H5={class:"text-gray-500"},Z5=["data-media-id","draggable","onDragstart","onDragover","onDrop","onMouseenter"],G5={key:0,"data-testid":"drop-indicator",class:"absolute inset-0 border-2 border-primary rounded-lg pointer-events-none z-30"},X5={key:1,class:"absolute top-2 right-2 z-20 opacity-0 group-hover:opacity-100 transition-opacity cursor-grab"},K5={class:"aspect-square relative"},J5=["src","alt"],q5={key:0,class:"absolute inset-0 bg-black/50 flex items-center justify-center gap-2 transition-opacity"},Y5=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=xs(),r=e.ref([]),s=e.ref(!1),l=e.ref(null),d=e.ref(null),c=e.ref(null),u=e.computed(()=>t.isLoading||s.value),m=e.computed(()=>!u.value&&r.value.length===0),f=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}`]}),p=e.computed(()=>(t.columns.md??4)*2);e.onMounted(async()=>{await h()}),e.watch(()=>t.albumId,async()=>{await h()});async function h(){s.value=!0;try{const M=await i.fetchAlbumMedia(t.albumId);r.value=M}catch{r.value=[]}finally{s.value=!1}}function v(M){return t.selectedItems.includes(M)}function E(M){n("toggle-select",M);const w=v(M.uuid)?t.selectedItems.filter(F=>F!==M.uuid):[...t.selectedItems,M.uuid];n("selection-change",w)}function y(M){if(M.conversions&&typeof M.conversions=="object"){const w=M.conversions.thumb;if(typeof w=="string")return w}return M.original_url}function k(M){l.value=M}function g(){l.value=null}function b(M){n("preview",M)}function R(M){n("edit",M)}function N(M){n("detach",M.uuid)}function T(){n("add")}function S(M,w){t.reorderable&&(d.value=w,M.dataTransfer&&(M.dataTransfer.effectAllowed="move",M.dataTransfer.setData("text/plain",String(w))))}function B(M,w){!t.reorderable||d.value===null||(M.preventDefault(),c.value=w)}function A(M,w){if(!t.reorderable||d.value===null)return;M.preventDefault();const F=d.value;if(F!==w){const P=[...r.value],[D]=P.splice(F,1);P.splice(w,0,D),r.value=P;const O=P.map(I=>I.uuid);n("reorder",O),i.reorderAlbumMedia(t.albumId,O).catch(()=>{h()})}d.value=null,c.value=null}function x(){d.value=null,c.value=null}return(M,w)=>(e.openBlock(),e.createElementBlock("div",z5,[u.value?(e.openBlock(),e.createElementBlock("div",{key:0,"data-testid":"loading-grid",class:e.normalizeClass(f.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(p.value,F=>(e.openBlock(),e.createBlock(e.unref(H.IonCard),{key:F,class:"m-0"},{default:e.withCtx(()=>[e.createElementVNode("div",j5,[e.createVNode(e.unref(H.IonSkeletonText),{animated:"",class:"w-full h-full skeleton"})])]),_:1}))),128))],2)):m.value?(e.openBlock(),e.createElementBlock("div",W5,[e.createVNode(e.unref(H.IonIcon),{name:"images-outline",class:"text-6xl text-gray-400"}),e.createElementVNode("p",H5,e.toDisplayString(M.emptyText),1),e.createVNode(e.unref(H.IonButton),{"data-testid":"add-media-btn",onClick:T},{default:e.withCtx(()=>[...w[0]||(w[0]=[e.createTextVNode(" Add Media ",-1)])]),_:1})])):(e.openBlock(),e.createElementBlock("div",{key:2,"data-testid":"media-grid",class:e.normalizeClass(f.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.value,(F,P)=>(e.openBlock(),e.createElementBlock("div",{key:F.uuid,"data-media-id":F.uuid,class:e.normalizeClass(["media-item relative group",{"opacity-50":d.value===P,"ring-2 ring-primary":c.value===P&&d.value!==P}]),draggable:M.reorderable,onDragstart:D=>S(D,P),onDragover:D=>B(D,P),onDrop:D=>A(D,P),onDragend:x,onMouseenter:D=>k(F.uuid),onMouseleave:g},[c.value===P&&d.value!==P&&M.reorderable?(e.openBlock(),e.createElementBlock("div",G5)):e.createCommentVNode("",!0),M.reorderable?(e.openBlock(),e.createElementBlock("div",X5,[e.createVNode(e.unref(H.IonIcon),{name:"reorder-three-outline",class:"text-white drop-shadow-md"})])):e.createCommentVNode("",!0),M.selectionMode?(e.openBlock(),e.createBlock(e.unref(H.IonCheckbox),{key:2,"data-testid":"media-checkbox",checked:v(F.uuid),class:"absolute top-2 left-2 z-20",onIonChange:D=>E(F)},null,8,["checked","onIonChange"])):e.createCommentVNode("",!0),e.createVNode(e.unref(H.IonCard),{class:"m-0 overflow-hidden"},{default:e.withCtx(()=>[e.createElementVNode("div",K5,[e.createElementVNode("img",{src:y(F),alt:F.file_name,class:"w-full h-full object-cover"},null,8,J5),M.showActions&&l.value===F.uuid?(e.openBlock(),e.createElementBlock("div",q5,[e.createVNode(e.unref(H.IonButton),{"data-testid":"action-preview",fill:"clear",size:"small",color:"light",onClick:D=>b(F)},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{slot:"icon-only",name:"eye-outline"})]),_:1},8,["onClick"]),e.createVNode(e.unref(H.IonButton),{"data-testid":"action-edit",fill:"clear",size:"small",color:"light",onClick:D=>R(F)},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{slot:"icon-only",name:"create-outline"})]),_:1},8,["onClick"]),e.createVNode(e.unref(H.IonButton),{"data-testid":"action-detach",fill:"clear",size:"small",color:"danger",onClick:D=>N(F)},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{slot:"icon-only",name:"close-circle-outline"})]),_:1},8,["onClick"])])):e.createCommentVNode("",!0)])]),_:2},1024)],42,Z5))),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:T},[e.createVNode(e.unref(H.IonIcon),{name:"add-circle-outline",class:"text-4xl text-gray-400"}),w[1]||(w[1]=e.createElementVNode("span",{class:"text-sm text-gray-500"},"Add Media",-1))])],2))]))}}),Q5=Fe(Y5,[["__scopeId","data-v-d84b796a"]]),eF={key:0,class:"media-album-inline-create","data-testid":"media-album-inline-create"},tF={class:"media-album-inline-create__field"},aF={class:"media-album-inline-create__field"},nF=["value"],oF={key:1,class:"media-album-inline-create__autocomplete"},iF={class:"media-album-inline-create__autocomplete-input-wrap"},rF={key:0,class:"media-album-inline-create__autocomplete-list"},sF=["onMousedown"],lF={key:1,class:"media-album-inline-create__autocomplete-empty"},dF={class:"media-album-inline-create__actions"},cF=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(""),s=e.ref(""),l=e.ref(!1),d=e.computed(()=>t.albums.length>5),c=e.computed(()=>{if(s.value.trim()==="")return t.albums;const E=s.value.toLowerCase();return t.albums.filter(y=>y.name.toLowerCase().includes(E))}),u=e.computed(()=>{if(r.value==="")return"";const E=t.albums.find(y=>y.id===r.value);return(E==null?void 0:E.name)??""}),m=E=>{r.value=E.id,s.value=E.name,l.value=!1},f=()=>{r.value="",s.value="",l.value=!1},p=()=>{l.value=!0,r.value!==""&&(s.value=u.value)},h=()=>{setTimeout(()=>{l.value=!1,r.value!==""?s.value=u.value:s.value=""},150)},v=()=>{i.value.trim()!==""&&(n("create",i.value.trim(),r.value!==""?r.value:void 0),i.value="",r.value="",s.value="")};return(E,y)=>E.open?(e.openBlock(),e.createElementBlock("section",eF,[y[7]||(y[7]=e.createElementVNode("h4",{class:"media-album-inline-create__heading"}," New album ",-1)),e.createElementVNode("label",tF,[e.createElementVNode("span",null,e.toDisplayString(E.nameLabel),1),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":y[0]||(y[0]=k=>i.value=k),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",aF,[y[6]||(y[6]=e.createElementVNode("span",null,"Parent album (optional)",-1)),d.value?(e.openBlock(),e.createElementBlock("div",oF,[e.createElementVNode("div",iF,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":y[2]||(y[2]=k=>s.value=k),type:"text",class:"media-album-inline-create__input",placeholder:"Search albums...","data-testid":"input-media-album-parent-search",onFocus:p,onBlur:h},null,544),[[e.vModelText,s.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(f,["prevent"])},[...y[5]||(y[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)]),l.value?(e.openBlock(),e.createElementBlock("ul",rF,[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(f,["prevent"])}," None ",32)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.value,k=>(e.openBlock(),e.createElementBlock("li",{key:k.id,class:e.normalizeClass(["media-album-inline-create__autocomplete-option",{"is-selected":k.id===r.value}]),onMousedown:e.withModifiers(g=>m(k),["prevent"])},e.toDisplayString(k.name),43,sF))),128)),c.value.length===0?(e.openBlock(),e.createElementBlock("li",lF," No albums match ")):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)])):e.withDirectives((e.openBlock(),e.createElementBlock("select",{key:0,"onUpdate:modelValue":y[1]||(y[1]=k=>r.value=k),class:"media-album-inline-create__input","data-testid":"select-media-album-parent"},[y[4]||(y[4]=e.createElementVNode("option",{value:""}," None ",-1)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(E.albums,k=>(e.openBlock(),e.createElementBlock("option",{key:k.id,value:k.id},e.toDisplayString(k.name),9,nF))),128))],512)),[[e.vModelSelect,r.value]])]),e.createElementVNode("div",dF,[e.createElementVNode("button",{type:"button",class:"media-album-inline-create__button","data-testid":"btn-media-album-cancel",onClick:y[3]||(y[3]=k=>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)}}),Bd=Fe(cF,[["__scopeId","data-v-a85162fe"]]),uF={class:"media-album-unavailable-state","data-testid":"media-album-unavailable-state"},mF=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",uF,[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)]))}}),sf=Fe(mF,[["__scopeId","data-v-04620e64"]]);/*!
|
|
350
|
+
* tabbable 6.2.0
|
|
351
|
+
* @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE
|
|
352
|
+
*/var lf=["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])"],Gr=lf.join(","),df=typeof Element>"u",no=df?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,Xr=!df&&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},Kr=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",s=r||t&&a&&o(a.parentNode);return s},pF=function(a){var t,n=a==null||(t=a.getAttribute)===null||t===void 0?void 0:t.call(a,"contenteditable");return n===""||n==="true"},cf=function(a,t,n){if(Kr(a))return[];var i=Array.prototype.slice.apply(a.querySelectorAll(Gr));return t&&no.call(a,Gr)&&i.unshift(a),i=i.filter(n),i},uf=function o(a,t,n){for(var i=[],r=Array.from(a);r.length;){var s=r.shift();if(!Kr(s,!1))if(s.tagName==="SLOT"){var l=s.assignedElements(),d=l.length?l:s.children,c=o(d,!0,n);n.flatten?i.push.apply(i,c):i.push({scopeParent:s,candidates:c})}else{var u=no.call(s,Gr);u&&n.filter(s)&&(t||!a.includes(s))&&i.push(s);var m=s.shadowRoot||typeof n.getShadowRoot=="function"&&n.getShadowRoot(s),f=!Kr(m,!1)&&(!n.shadowRootFilter||n.shadowRootFilter(s));if(m&&f){var p=o(m===!0?s.children:m.children,!0,n);n.flatten?i.push.apply(i,p):i.push({scopeParent:s,candidates:p})}else r.unshift.apply(r,s.children)}}return i},mf=function(a){return!isNaN(parseInt(a.getAttribute("tabindex"),10))},Gn=function(a){if(!a)throw new Error("No node provided");return a.tabIndex<0&&(/^(AUDIO|VIDEO|DETAILS)$/.test(a.tagName)||pF(a))&&!mf(a)?0:a.tabIndex},fF=function(a,t){var n=Gn(a);return n<0&&t&&!mf(a)?0:n},hF=function(a,t){return a.tabIndex===t.tabIndex?a.documentOrder-t.documentOrder:a.tabIndex-t.tabIndex},pf=function(a){return a.tagName==="INPUT"},vF=function(a){return pf(a)&&a.type==="hidden"},gF=function(a){var t=a.tagName==="DETAILS"&&Array.prototype.slice.apply(a.children).some(function(n){return n.tagName==="SUMMARY"});return t},bF=function(a,t){for(var n=0;n<a.length;n++)if(a[n].checked&&a[n].form===t)return a[n]},yF=function(a){if(!a.name)return!0;var t=a.form||Xr(a),n=function(l){return t.querySelectorAll('input[type="radio"][name="'+l+'"]')},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=bF(i,a.form);return!r||r===a},wF=function(a){return pf(a)&&a.type==="radio"},kF=function(a){return wF(a)&&!yF(a)},_F=function(a){var t,n=a&&Xr(a),i=(t=n)===null||t===void 0?void 0:t.host,r=!1;if(n&&n!==a){var s,l,d;for(r=!!((s=i)!==null&&s!==void 0&&(l=s.ownerDocument)!==null&&l!==void 0&&l.contains(i)||a!=null&&(d=a.ownerDocument)!==null&&d!==void 0&&d.contains(a));!r&&i;){var c,u,m;n=Xr(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},Vu=function(a){var t=a.getBoundingClientRect(),n=t.width,i=t.height;return n===0&&i===0},EF=function(a,t){var n=t.displayCheck,i=t.getShadowRoot;if(getComputedStyle(a).visibility==="hidden")return!0;var r=no.call(a,"details>summary:first-of-type"),s=r?a.parentElement:a;if(no.call(s,"details:not([open]) *"))return!0;if(!n||n==="full"||n==="legacy-full"){if(typeof i=="function"){for(var l=a;a;){var d=a.parentElement,c=Xr(a);if(d&&!d.shadowRoot&&i(d)===!0)return Vu(a);a.assignedSlot?a=a.assignedSlot:!d&&c!==a.ownerDocument?a=c.host:a=d}a=l}if(_F(a))return!a.getClientRects().length;if(n!=="legacy-full")return!0}else if(n==="non-zero-area")return Vu(a);return!1},SF=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 no.call(t,"fieldset[disabled] *")?!0:!i.contains(a)}return!0}t=t.parentElement}return!1},Jr=function(a,t){return!(t.disabled||Kr(t)||vF(t)||EF(t,a)||gF(t)||SF(t))},Xl=function(a,t){return!(kF(t)||Gn(t)<0||!Jr(a,t))},CF=function(a){var t=parseInt(a.getAttribute("tabindex"),10);return!!(isNaN(t)||t>=0)},xF=function o(a){var t=[],n=[];return a.forEach(function(i,r){var s=!!i.scopeParent,l=s?i.scopeParent:i,d=fF(l,s),c=s?o(i.candidates):l;d===0?s?t.push.apply(t,c):t.push(l):n.push({documentOrder:r,tabIndex:d,item:i,isScope:s,content:c})}),n.sort(hF).reduce(function(i,r){return r.isScope?i.push.apply(i,r.content):i.push(r.content),i},[]).concat(t)},VF=function(a,t){t=t||{};var n;return t.getShadowRoot?n=uf([a],t.includeContainer,{filter:Xl.bind(null,t),flatten:!1,getShadowRoot:t.getShadowRoot,shadowRootFilter:CF}):n=cf(a,t.includeContainer,Xl.bind(null,t)),xF(n)},NF=function(a,t){t=t||{};var n;return t.getShadowRoot?n=uf([a],t.includeContainer,{filter:Jr.bind(null,t),flatten:!0,getShadowRoot:t.getShadowRoot}):n=cf(a,t.includeContainer,Jr.bind(null,t)),n},Co=function(a,t){if(t=t||{},!a)throw new Error("No node provided");return no.call(a,Gr)===!1?!1:Xl(t,a)},TF=lf.concat("iframe").join(","),ol=function(a,t){if(t=t||{},!a)throw new Error("No node provided");return no.call(a,TF)===!1?!1:Jr(t,a)};/*!
|
|
353
|
+
* focus-trap 7.6.5
|
|
354
|
+
* @license MIT, https://github.com/focus-trap/focus-trap/blob/master/LICENSE
|
|
355
|
+
*/function Kl(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 BF(o){if(Array.isArray(o))return Kl(o)}function MF(o,a,t){return(a=RF(a))in o?Object.defineProperty(o,a,{value:t,enumerable:!0,configurable:!0,writable:!0}):o[a]=t,o}function IF(o){if(typeof Symbol<"u"&&o[Symbol.iterator]!=null||o["@@iterator"]!=null)return Array.from(o)}function $F(){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 Nu(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 Tu(o){for(var a=1;a<arguments.length;a++){var t=arguments[a]!=null?arguments[a]:{};a%2?Nu(Object(t),!0).forEach(function(n){MF(o,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(t)):Nu(Object(t)).forEach(function(n){Object.defineProperty(o,n,Object.getOwnPropertyDescriptor(t,n))})}return o}function FF(o){return BF(o)||IF(o)||AF(o)||$F()}function DF(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 RF(o){var a=DF(o,"string");return typeof a=="symbol"?a:a+""}function AF(o,a){if(o){if(typeof o=="string")return Kl(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)?Kl(o,a):void 0}}var Bu={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)}},LF=function(a){return a.tagName&&a.tagName.toLowerCase()==="input"&&typeof a.select=="function"},PF=function(a){return(a==null?void 0:a.key)==="Escape"||(a==null?void 0:a.key)==="Esc"||(a==null?void 0:a.keyCode)===27},xi=function(a){return(a==null?void 0:a.key)==="Tab"||(a==null?void 0:a.keyCode)===9},UF=function(a){return xi(a)&&!a.shiftKey},OF=function(a){return xi(a)&&a.shiftKey},Mu=function(a){return setTimeout(a,0)},li=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},gr=function(a){return a.target.shadowRoot&&typeof a.composedPath=="function"?a.composedPath()[0]:a.target},zF=[],jF=function(a,t){var n=(t==null?void 0:t.document)||document,i=(t==null?void 0:t.trapStack)||zF,r=Tu({returnFocusOnDeactivate:!0,escapeDeactivates:!0,delayInitialFocus:!0,isKeyForward:UF,isKeyBackward:OF},t),s={containers:[],containerGroups:[],tabbableGroups:[],nodeFocusedBeforeActivation:null,mostRecentlyFocusedNode:null,active:!1,paused:!1,manuallyPaused:!1,delayInitialFocusTimer:void 0,recentNavEvent:void 0},l,d=function(w,F,P){return w&&w[F]!==void 0?w[F]:r[P||F]},c=function(w,F){var P=typeof(F==null?void 0:F.composedPath)=="function"?F.composedPath():void 0;return s.containerGroups.findIndex(function(D){var O=D.container,I=D.tabbableNodes;return O.contains(w)||(P==null?void 0:P.includes(O))||I.find(function(Z){return Z===w})})},u=function(w){var F=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},P=F.hasFallback,D=P===void 0?!1:P,O=F.params,I=O===void 0?[]:O,Z=r[w];if(typeof Z=="function"&&(Z=Z.apply(void 0,FF(I))),Z===!0&&(Z=void 0),!Z){if(Z===void 0||Z===!1)return Z;throw new Error("`".concat(w,"` was specified but was not a node, or did not return a node"))}var z=Z;if(typeof Z=="string"){try{z=n.querySelector(Z)}catch(K){throw new Error("`".concat(w,'` appears to be an invalid selector; error="').concat(K.message,'"'))}if(!z&&!D)throw new Error("`".concat(w,"` as selector refers to no known node"))}return z},m=function(){var w=u("initialFocus",{hasFallback:!0});if(w===!1)return!1;if(w===void 0||w&&!ol(w,r.tabbableOptions))if(c(n.activeElement)>=0)w=n.activeElement;else{var F=s.tabbableGroups[0],P=F&&F.firstTabbableNode;w=P||u("fallbackFocus")}else w===null&&(w=u("fallbackFocus"));if(!w)throw new Error("Your focus-trap needs to have at least one focusable element");return w},f=function(){if(s.containerGroups=s.containers.map(function(w){var F=VF(w,r.tabbableOptions),P=NF(w,r.tabbableOptions),D=F.length>0?F[0]:void 0,O=F.length>0?F[F.length-1]:void 0,I=P.find(function(K){return Co(K)}),Z=P.slice().reverse().find(function(K){return Co(K)}),z=!!F.find(function(K){return Gn(K)>0});return{container:w,tabbableNodes:F,focusableNodes:P,posTabIndexesFound:z,firstTabbableNode:D,lastTabbableNode:O,firstDomTabbableNode:I,lastDomTabbableNode:Z,nextTabbableNode:function(se){var Be=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,ce=F.indexOf(se);return ce<0?Be?P.slice(P.indexOf(se)+1).find(function(ie){return Co(ie)}):P.slice(0,P.indexOf(se)).reverse().find(function(ie){return Co(ie)}):F[ce+(Be?1:-1)]}}}),s.tabbableGroups=s.containerGroups.filter(function(w){return w.tabbableNodes.length>0}),s.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(s.containerGroups.find(function(w){return w.posTabIndexesFound})&&s.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.")},p=function(w){var F=w.activeElement;if(F)return F.shadowRoot&&F.shadowRoot.activeElement!==null?p(F.shadowRoot):F},h=function(w){if(w!==!1&&w!==p(document)){if(!w||!w.focus){h(m());return}w.focus({preventScroll:!!r.preventScroll}),s.mostRecentlyFocusedNode=w,LF(w)&&w.select()}},v=function(w){var F=u("setReturnFocus",{params:[w]});return F||(F===!1?!1:w)},E=function(w){var F=w.target,P=w.event,D=w.isBackward,O=D===void 0?!1:D;F=F||gr(P),f();var I=null;if(s.tabbableGroups.length>0){var Z=c(F,P),z=Z>=0?s.containerGroups[Z]:void 0;if(Z<0)O?I=s.tabbableGroups[s.tabbableGroups.length-1].lastTabbableNode:I=s.tabbableGroups[0].firstTabbableNode;else if(O){var K=s.tabbableGroups.findIndex(function(C){var U=C.firstTabbableNode;return F===U});if(K<0&&(z.container===F||ol(F,r.tabbableOptions)&&!Co(F,r.tabbableOptions)&&!z.nextTabbableNode(F,!1))&&(K=Z),K>=0){var se=K===0?s.tabbableGroups.length-1:K-1,Be=s.tabbableGroups[se];I=Gn(F)>=0?Be.lastTabbableNode:Be.lastDomTabbableNode}else xi(P)||(I=z.nextTabbableNode(F,!1))}else{var ce=s.tabbableGroups.findIndex(function(C){var U=C.lastTabbableNode;return F===U});if(ce<0&&(z.container===F||ol(F,r.tabbableOptions)&&!Co(F,r.tabbableOptions)&&!z.nextTabbableNode(F))&&(ce=Z),ce>=0){var ie=ce===s.tabbableGroups.length-1?0:ce+1,W=s.tabbableGroups[ie];I=Gn(F)>=0?W.firstTabbableNode:W.firstDomTabbableNode}else xi(P)||(I=z.nextTabbableNode(F))}}else I=u("fallbackFocus");return I},y=function(w){var F=gr(w);if(!(c(F,w)>=0)){if(li(r.clickOutsideDeactivates,w)){l.deactivate({returnFocus:r.returnFocusOnDeactivate});return}li(r.allowOutsideClick,w)||w.preventDefault()}},k=function(w){var F=gr(w),P=c(F,w)>=0;if(P||F instanceof Document)P&&(s.mostRecentlyFocusedNode=F);else{w.stopImmediatePropagation();var D,O=!0;if(s.mostRecentlyFocusedNode)if(Gn(s.mostRecentlyFocusedNode)>0){var I=c(s.mostRecentlyFocusedNode),Z=s.containerGroups[I].tabbableNodes;if(Z.length>0){var z=Z.findIndex(function(K){return K===s.mostRecentlyFocusedNode});z>=0&&(r.isKeyForward(s.recentNavEvent)?z+1<Z.length&&(D=Z[z+1],O=!1):z-1>=0&&(D=Z[z-1],O=!1))}}else s.containerGroups.some(function(K){return K.tabbableNodes.some(function(se){return Gn(se)>0})})||(O=!1);else O=!1;O&&(D=E({target:s.mostRecentlyFocusedNode,isBackward:r.isKeyBackward(s.recentNavEvent)})),h(D||s.mostRecentlyFocusedNode||m())}s.recentNavEvent=void 0},g=function(w){var F=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;s.recentNavEvent=w;var P=E({event:w,isBackward:F});P&&(xi(w)&&w.preventDefault(),h(P))},b=function(w){(r.isKeyForward(w)||r.isKeyBackward(w))&&g(w,r.isKeyBackward(w))},R=function(w){PF(w)&&li(r.escapeDeactivates,w)!==!1&&(w.preventDefault(),l.deactivate())},N=function(w){var F=gr(w);c(F,w)>=0||li(r.clickOutsideDeactivates,w)||li(r.allowOutsideClick,w)||(w.preventDefault(),w.stopImmediatePropagation())},T=function(){if(s.active)return Bu.activateTrap(i,l),s.delayInitialFocusTimer=r.delayInitialFocus?Mu(function(){h(m())}):h(m()),n.addEventListener("focusin",k,!0),n.addEventListener("mousedown",y,{capture:!0,passive:!1}),n.addEventListener("touchstart",y,{capture:!0,passive:!1}),n.addEventListener("click",N,{capture:!0,passive:!1}),n.addEventListener("keydown",b,{capture:!0,passive:!1}),n.addEventListener("keydown",R),l},S=function(){if(s.active)return n.removeEventListener("focusin",k,!0),n.removeEventListener("mousedown",y,!0),n.removeEventListener("touchstart",y,!0),n.removeEventListener("click",N,!0),n.removeEventListener("keydown",b,!0),n.removeEventListener("keydown",R),l},B=function(w){var F=w.some(function(P){var D=Array.from(P.removedNodes);return D.some(function(O){return O===s.mostRecentlyFocusedNode})});F&&h(m())},A=typeof window<"u"&&"MutationObserver"in window?new MutationObserver(B):void 0,x=function(){A&&(A.disconnect(),s.active&&!s.paused&&s.containers.map(function(w){A.observe(w,{subtree:!0,childList:!0})}))};return l={get active(){return s.active},get paused(){return s.paused},activate:function(w){if(s.active)return this;var F=d(w,"onActivate"),P=d(w,"onPostActivate"),D=d(w,"checkCanFocusTrap");D||f(),s.active=!0,s.paused=!1,s.nodeFocusedBeforeActivation=p(n),F==null||F();var O=function(){D&&f(),T(),x(),P==null||P()};return D?(D(s.containers.concat()).then(O,O),this):(O(),this)},deactivate:function(w){if(!s.active)return this;var F=Tu({onDeactivate:r.onDeactivate,onPostDeactivate:r.onPostDeactivate,checkCanReturnFocus:r.checkCanReturnFocus},w);clearTimeout(s.delayInitialFocusTimer),s.delayInitialFocusTimer=void 0,S(),s.active=!1,s.paused=!1,x(),Bu.deactivateTrap(i,l);var P=d(F,"onDeactivate"),D=d(F,"onPostDeactivate"),O=d(F,"checkCanReturnFocus"),I=d(F,"returnFocus","returnFocusOnDeactivate");P==null||P();var Z=function(){Mu(function(){I&&h(v(s.nodeFocusedBeforeActivation)),D==null||D()})};return I&&O?(O(v(s.nodeFocusedBeforeActivation)).then(Z,Z),this):(Z(),this)},pause:function(w){return s.active?(s.manuallyPaused=!0,this._setPausedState(!0,w)):this},unpause:function(w){return s.active?(s.manuallyPaused=!1,i[i.length-1]!==this?this:this._setPausedState(!1,w)):this},updateContainerElements:function(w){var F=[].concat(w).filter(Boolean);return s.containers=F.map(function(P){return typeof P=="string"?n.querySelector(P):P}),s.active&&f(),x(),this}},Object.defineProperties(l,{_isManuallyPaused:{value:function(){return s.manuallyPaused}},_setPausedState:{value:function(w,F){if(s.paused===w)return this;if(s.paused=w,w){var P=d(F,"onPause"),D=d(F,"onPostPause");P==null||P(),S(),x(),D==null||D()}else{var O=d(F,"onUnpause"),I=d(F,"onPostUnpause");O==null||O(),f(),T(),x(),I==null||I()}return this}}}),l.updateContainerElements(a),l};const WF=["aria-labelledby"],HF={class:"media-preview-sheet__header"},ZF=["id"],GF=["aria-label"],XF=["src","alt"],KF=["src"],JF={class:"media-preview-sheet__actions"},qF=["disabled","aria-label"],YF=["aria-label","aria-pressed"],QF=["disabled","aria-label"],e8=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),s=e.ref(null);let l=null,d=null;const c=e.computed(()=>{var A;return((A=t.media)==null?void 0:A.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,f=e.computed(()=>t.media?t.media.preview_url??t.media.original_url:"");function p(A){const x=A.replace(/\.[^.]+$/,""),w=x.replace(u,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return w!==""?w:x||A}function h(A){var F,P;const x=(F=A.name)==null?void 0:F.trim(),M=A.file_name.replace(/\.[^.]+$/,"");if(x!==void 0&&x!==""&&x!==A.file_name&&x!==M&&!m.test(x))return x;const w=(P=A.alt_text)==null?void 0:P.trim();return w!==void 0&&w!==""?w:p(x||A.file_name)}const v=e.computed(()=>t.media?h(t.media):"media"),E=e.computed(()=>t.media?`Preview ${v.value}`:"Media preview"),y=e.computed(()=>t.media?`Close preview of ${v.value}`:"Close preview"),k=e.computed(()=>t.canGoPrevious?"Previous media":"No previous media"),g=e.computed(()=>t.canGoNext?"Next media":"No next media"),b=e.computed(()=>{const A=t.selected?t.deselectLabel:t.selectLabel;return t.media?t.selected?`${t.deselectLabel} ${v.value}`:`${t.selectLabel} ${v.value}`:A}),R=e.computed(()=>t.selected?t.deselectLabel:t.selectLabel),N=()=>{t.media&&n("toggleSelect",t.media)},T=A=>{if(A.key==="Escape"){A.preventDefault(),n("close");return}if(A.key==="ArrowLeft"&&t.canGoPrevious){A.preventDefault(),n("previous");return}A.key==="ArrowRight"&&t.canGoNext&&(A.preventDefault(),n("next"))},S=()=>{if(l){try{l.deactivate({returnFocus:!1})}catch{}l=null}},B=()=>{const A=d;d=null,A&&typeof A.focus=="function"&&e.nextTick(()=>{A.focus()})};return e.watch(()=>t.open&&t.media!==null,async A=>{var x;if(A){d=document.activeElement instanceof HTMLElement?document.activeElement:null,await e.nextTick();const M=r.value;if(M)try{l=jF(M,{initialFocus:()=>s.value??M,escapeDeactivates:!1,clickOutsideDeactivates:!1,returnFocusOnDeactivate:!1,allowOutsideClick:!0}),l.activate()}catch{(x=s.value)==null||x.focus()}}else S(),B()},{immediate:!0}),e.onBeforeUnmount(()=>{S()}),(A,x)=>(e.openBlock(),e.createBlock(e.Teleport,{to:"body"},[A.open&&A.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:T},[e.createElementVNode("header",HF,[e.createElementVNode("strong",{id:e.unref(i),"data-testid":"media-preview-sheet-title"},e.toDisplayString(E.value),9,ZF),e.createElementVNode("button",{ref_key:"closeButtonRef",ref:s,type:"button",class:"media-preview-sheet__close","aria-label":y.value,"data-testid":"btn-media-preview-close",onClick:x[0]||(x[0]=M=>n("close"))},e.toDisplayString(A.closeLabel),9,GF)]),c.value?(e.openBlock(),e.createElementBlock("img",{key:0,class:"media-preview-sheet__image",src:f.value,alt:A.media.alt_text||v.value},null,8,XF)):(e.openBlock(),e.createElementBlock("video",{key:1,class:"media-preview-sheet__video",src:f.value,controls:""},null,8,KF)),e.createElementVNode("div",JF,[e.createElementVNode("button",{type:"button",class:"media-preview-sheet__nav",disabled:!A.canGoPrevious,"aria-label":k.value,"data-testid":"btn-media-preview-previous",onClick:x[1]||(x[1]=M=>n("previous"))},e.toDisplayString(A.previousLabel),9,qF),e.createElementVNode("button",{type:"button",class:"media-preview-sheet__select","aria-label":b.value,"aria-pressed":A.selected,"data-testid":"btn-media-preview-select",onClick:N},e.toDisplayString(R.value),9,YF),e.createElementVNode("button",{type:"button",class:"media-preview-sheet__nav",disabled:!A.canGoNext,"aria-label":g.value,"data-testid":"btn-media-preview-next",onClick:x[2]||(x[2]=M=>n("next"))},e.toDisplayString(A.nextLabel),9,QF)])],40,WF)):e.createCommentVNode("",!0)]))}}),Md=Fe(e8,[["__scopeId","data-v-fa05530d"]]),t8={key:0,class:"media-album-grid","data-testid":"media-source-sheet"},a8={class:"media-album-grid__items"},n8={class:"media-album-grid__card-name"},o8={class:"media-album-grid__card-name"},i8=["data-testid","onClick"],r8={class:"media-album-grid__card-name"},s8={key:0,class:"media-album-grid__card-meta"},l8={key:0,class:"media-album-grid__empty"},d8=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",t8,[e.createElementVNode("div",a8,[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",n8,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",o8,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:s=>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",r8,e.toDisplayString(r.name),1),r.mediaCount!==void 0?(e.openBlock(),e.createElementBlock("span",s8,e.toDisplayString(r.mediaCount)+" item"+e.toDisplayString(r.mediaCount===1?"":"s"),1)):e.createCommentVNode("",!0)],10,i8))),128))]),n.albums.length===0?(e.openBlock(),e.createElementBlock("p",l8," No albums yet. ")):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)}}),ff=Fe(d8,[["__scopeId","data-v-129f67b1"]]),c8={key:0,class:"media-upload-sheet","data-testid":"media-upload-sheet"},u8={class:"media-upload-sheet__dropzone-text"},m8={key:0,class:"media-upload-sheet__dropzone-helper","data-testid":"text-media-upload-sheet-helper"},p8={class:"media-upload-sheet__sr-only"},f8=["accept","aria-label"],h8=["aria-label"],v8={class:"media-upload-sheet__queue-row"},g8={key:0,class:"media-upload-sheet__preview"},b8=["src","alt","data-testid"],y8={class:"media-upload-sheet__queue-body"},w8={class:"media-upload-sheet__queue-info"},k8={class:"media-upload-sheet__queue-status"},_8=["aria-valuenow","aria-label","data-testid"],E8=["aria-label"],S8=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=f=>{var h;return t.progressAriaLabel!==void 0?t.progressAriaLabel(f):`Uploading ${((h=f.file)==null?void 0:h.name)??"file"}`},s=f=>{const p=Number.isFinite(f.progress)?f.progress:0;return p<0?0:p>100?100:Math.round(p)},l=e.computed(()=>t.queue.length===0?"":`${t.queue.length} upload${t.queue.length===1?"":"s"} in progress`),d=f=>{const p=f.target;!(p instanceof HTMLInputElement)||p.files===null||(n("filesSelected",Array.from(p.files)),p.value="")},c=f=>{f.preventDefault(),i.value=!0},u=()=>{i.value=!1},m=f=>{var p;f.preventDefault(),i.value=!1,(p=f.dataTransfer)!=null&&p.files&&f.dataTransfer.files.length>0&&n("filesSelected",Array.from(f.dataTransfer.files))};return(f,p)=>f.open?(e.openBlock(),e.createElementBlock("section",c8,[e.createElementVNode("label",{class:e.normalizeClass(["media-upload-sheet__dropzone",{"is-drag-over":i.value}]),onDragover:c,onDragleave:u,onDrop:m},[p[1]||(p[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",u8,e.toDisplayString(f.dropzoneLabel),1),f.dropzoneHelperText?(e.openBlock(),e.createElementBlock("span",m8,e.toDisplayString(f.dropzoneHelperText),1)):e.createCommentVNode("",!0),e.createElementVNode("span",p8,e.toDisplayString(f.fileInputLabel),1),e.createElementVNode("input",{type:"file",accept:f.accept,multiple:"",class:"media-upload-sheet__file-input","data-testid":"input-media-upload-sheet","aria-label":f.fileInputLabel,onChange:d},null,40,f8)],34),f.queue.length>0?(e.openBlock(),e.createElementBlock("ul",{key:0,class:"media-upload-sheet__queue","aria-live":"polite","aria-label":l.value,"data-testid":"list-media-upload-sheet-queue"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(f.queue,h=>(e.openBlock(),e.createElementBlock("li",{key:h.id,class:"media-upload-sheet__queue-item"},[e.createElementVNode("div",v8,[h.previewUrl?(e.openBlock(),e.createElementBlock("div",g8,[e.createElementVNode("img",{src:h.previewUrl,alt:`Preview of ${h.file.name}`,"data-testid":`img-media-upload-sheet-preview-${h.id}`},null,8,b8)])):e.createCommentVNode("",!0),e.createElementVNode("div",y8,[e.createElementVNode("div",w8,[e.createElementVNode("strong",null,e.toDisplayString(h.file.name),1),e.createElementVNode("span",k8,e.toDisplayString(h.status),1)]),e.createElementVNode("div",{class:"media-upload-sheet__progress-bar",role:"progressbar","aria-valuemin":"0","aria-valuemax":"100","aria-valuenow":s(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:`${s(h)}%`})},null,4)],8,_8)])])]))),128))],8,h8)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",class:"media-upload-sheet__close-btn","aria-label":f.closeButtonAriaLabel,"data-testid":"btn-close-upload-sheet",onClick:p[0]||(p[0]=h=>n("close"))},e.toDisplayString(f.closeButtonLabel),9,E8)])):e.createCommentVNode("",!0)}}),hf=Fe(S8,[["__scopeId","data-v-df614629"]]),C8=["aria-label","aria-pressed","data-testid"],x8=["src","alt"],V8={key:1,class:"media-thumbnail-cell__video"},N8={class:"media-thumbnail-cell__video-name"},T8={key:2,class:"media-thumbnail-cell__selected-badge"},B8={key:3,class:"media-thumbnail-cell__status-badge"},M8=["aria-label"],I8=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/")),s=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}}),l=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":s.value!==null}])},[e.createElementVNode("button",{type:"button",class:"media-thumbnail-cell__button","aria-label":l.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,x8)):(e.openBlock(),e.createElementBlock("div",V8,[m[0]||(m[0]=e.createElementVNode("span",{class:"media-thumbnail-cell__video-label"},"Video",-1)),e.createElementVNode("span",N8,e.toDisplayString(u.media.file_name),1)])),u.selected?(e.openBlock(),e.createElementBlock("span",T8," Selected ")):e.createCommentVNode("",!0),s.value!==null?(e.openBlock(),e.createElementBlock("span",B8,e.toDisplayString(s.value),1)):e.createCommentVNode("",!0)],8,C8),e.createElementVNode("button",{type:"button",class:"media-thumbnail-cell__preview-button","aria-label":`Preview ${u.media.file_name}`,onClick:c}," Preview ",8,M8)],2))}}),vf=Fe(I8,[["__scopeId","data-v-edd4f0ad"]]),$8={class:"virtual-media-grid"},F8={key:0,class:"virtual-media-grid__state","data-testid":"media-grid-loading"},D8={key:1,class:"virtual-media-grid__state","data-testid":"media-grid-empty"},R8={key:2,class:"virtual-media-grid__items"},A8=["disabled"],L8=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(s=>s.id===r)}return(r,s)=>(e.openBlock(),e.createElementBlock("div",$8,[r.loading&&r.items.length===0?(e.openBlock(),e.createElementBlock("div",F8,e.toDisplayString(r.loadingMessage),1)):r.items.length===0?(e.openBlock(),e.createElementBlock("div",D8,e.toDisplayString(r.emptyMessage),1)):(e.openBlock(),e.createElementBlock("div",R8,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.items,l=>{var d,c;return e.openBlock(),e.createBlock(vf,{key:l.uuid,media:l,selected:((d=i(l.uuid))==null?void 0:d.status)==="ready",status:(c=i(l.uuid))==null?void 0:c.status,"test-id":`${r.testIdPrefix}-${l.uuid}`,onToggle:s[0]||(s[0]=u=>n("toggle",u)),onPreview:s[1]||(s[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:s[2]||(s[2]=l=>n("loadMore"))},e.toDisplayString(r.loadingMore?r.loadingMoreLabel:r.loadMoreLabel),9,A8)):e.createCommentVNode("",!0)]))}}),gf=Fe(L8,[["__scopeId","data-v-34667f65"]]);function qr(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 bf(o){var t;const a=o.split(".");return a.length>1?`.${(t=a.pop())==null?void 0:t.toLowerCase()}`:""}function Id(o){return o.type.startsWith("image/")}async function yf(o){return Id(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 wf(o,a){const t=[];if(a.maxFileSize&&o.size>a.maxFileSize&&t.push({field:"size",message:`File exceeds maximum size of ${qr(a.maxFileSize)}`,code:"MAX_FILE_SIZE"}),a.minFileSize&&o.size<a.minFileSize&&t.push({field:"size",message:`File is smaller than minimum size of ${qr(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=bf(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(Id(o)&&(a.maxDimensions||a.minDimensions)){const n=await yf(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 $d(o={}){const a=e.ref(o.rules||{});function t(d){a.value=d}async function n(d){return wf(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 s=e.computed(()=>{const d=[];return a.value.acceptedMimeTypes&&d.push(...a.value.acceptedMimeTypes),a.value.acceptedExtensions&&d.push(...a.value.acceptedExtensions),d.join(",")});function l(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:s,isMimeTypeAllowed:l}}function P8(){return`upload-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function U8(o){if(o.type.startsWith("image/"))return URL.createObjectURL(o)}function Fd(o){const{adapter:a,maxConcurrent:t=3,rules:n,collection:i,onUploadStart:r,onUploadProgress:s,onUploadComplete:l,onUploadError:d,onQueueComplete:c,postUpload:u}=o,m=e.ref(new Map),f=e.ref(new Set),p=n?{rules:n}:{},{validateFile:h}=$d(p);async function v(){if(f.value.size>=t)return;const M=Array.from(m.value.entries()).find(([P,D])=>D.status==="pending"&&!f.value.has(P));if(!M){Array.from(m.value.values()).every(D=>D.status==="completed"||D.status==="error")&&m.value.size>0&&(c==null||c());return}const[w,F]=M;await E(w,F)}async function E(M,w){f.value.add(M),w.status="uploading",w.abortController=new AbortController,m.value.set(M,{...w}),r==null||r(w);try{const F={onProgress:D=>{w.progress=D,m.value.set(M,{...w}),s==null||s(w)},signal:w.abortController.signal};i&&(F.collection=i);const P=await a.upload(w.file,F);u&&(w.status="attaching",m.value.set(M,{...w}),s==null||s(w),await u(w,P.media,a)),w.status="completed",w.progress=100,w.media=P.media,m.value.set(M,{...w}),l==null||l(w,P.media)}catch(F){F.name==="AbortError"?m.value.delete(M):(w.status="error",w.error=F.message,m.value.set(M,{...w}),d==null||d(w,F))}finally{f.value.delete(M),delete w.abortController,v()}}async function y(M){var P;const w=Array.from(M),F=[];for(const D of w){const O=await h(D),I=P8(),Z=U8(D),z={id:I,file:D,progress:0,status:O.valid?"pending":"error"};!O.valid&&((P=O.errors[0])!=null&&P.message)&&(z.error=O.errors[0].message),Z&&(z.previewUrl=Z),m.value.set(I,z);const K={media:null,clientId:I,name:D.name,order:0,upload:z,errors:O.errors};F.push(K)}for(let D=0;D<t;D++)v();return F}function k(M){const w=m.value.get(M);w&&(w.abortController&&w.abortController.abort(),w.previewUrl&&URL.revokeObjectURL(w.previewUrl),m.value.delete(M),f.value.delete(M),v())}async function g(M){const w=m.value.get(M);!w||w.status!=="error"||(w.status="pending",w.progress=0,delete w.error,m.value.set(M,{...w}),v())}function b(){for(const[M,w]of m.value.entries())(w.status==="completed"||w.status==="error")&&(w.previewUrl&&URL.revokeObjectURL(w.previewUrl),m.value.delete(M))}function R(){for(const M of m.value.values())M.abortController&&M.abortController.abort(),M.previewUrl&&URL.revokeObjectURL(M.previewUrl);m.value.clear(),f.value.clear()}function N(M){return m.value.get(M)}const T=e.computed(()=>f.value.size>0),S=e.computed(()=>f.value.size),B=e.computed(()=>Array.from(m.value.values()).filter(M=>M.status==="pending").length),A=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:T,activeCount:S,pendingCount:B,isComplete:A,addFiles:y,cancelUpload:k,retryUpload:g,clearCompleted:b,clearAll:R,getUpload:N,uploadsArray:x}}function oo(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Fi(o){return typeof o=="string"?o:null}function di(o){return typeof o=="number"?o:null}function O8(o){return typeof o=="boolean"?o:null}function kf(o){return oo(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 z8(o){return!oo(o)||typeof o.id!="string"||typeof o.status!="string"?null:o.status==="ready"?kf(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 j8(o){return oo(o)?{next_cursor:Fi(o.next_cursor),previous_cursor:Fi(o.previous_cursor),has_more:O8(o.has_more)??!1,per_page:di(o.per_page),count:di(o.count),total:di(o.total),current_page:di(o.current_page),last_page:di(o.last_page)}:null}function Iu(o){const a=oo(o)?o:{},t=Array.isArray(a.data)?a.data.filter(kf):[],n=oo(a.meta)?a.meta:{},i=j8(n.pagination),r=(i==null?void 0:i.next_cursor)??Fi(n.next_cursor)??Fi(n.cursor),s=(i==null?void 0:i.has_more)??n.has_more===!0,l=Array.isArray(a.hydrated)?a.hydrated.map(z8).filter(c=>c!==null):[],d={cursor:r,has_more:s};return i!==null&&(d.pagination=i),{data:t,meta:d,hydrated:l}}function $u(o,a,t,n,i,r){const s={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()!==""&&(s.query=a.query.trim()),a.kinds&&a.kinds.length>0&&(s.kinds=a.kinds),a.created_after&&a.created_after.trim()!==""&&(s.created_after=a.created_after.trim()),a.created_before&&a.created_before.trim()!==""&&(s.created_before=a.created_before.trim()),(a.usage_status==="used"||a.usage_status==="not_used")&&(s.usage_status=a.usage_status),(a.unfiled_only===!0||o.scope==="unfiled")&&(s.unfiled_only=1),a.selected_uuids&&a.selected_uuids.length>0&&(s.selected_uuids=[...a.selected_uuids]),r!=null?(s.page=r,s.include_total=1):n!==null&&(s.cursor=n),i&&i.length>0&&(s.hydrate_ids=i),s}function Fu(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 W8(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 H8(o){var a;return o instanceof Error?((a=o.response)==null?void 0:a.data)??null:null}function Z8(o){if(!oo(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 G8(o){var r;const a=H8(o),t=oo(a)?a:null,n=((r=Fi(t==null?void 0:t.message))==null?void 0:r.trim())??null,i=Z8(t==null?void 0:t.errors);return n!==null&&i.length>0?n==="Validation failed"?i.join(" "):i.every(l=>n.includes(l))?n:`${n} ${i.join(" ")}`:n!==null?n:i.length>0?i.join(" "):o instanceof Error?o.message:"Failed to load media."}function Du(o,a){const t=G8(a),n=W8(a);return{code:n===403?"permission_denied":o,message:t,retriable:n!==403,cause:a}}function Dd(o){const a=()=>{const N=o.perPage!==void 0?e.toValue(o.perPage):40;return N>0?N:40},t=()=>{const N=o.page!==void 0?e.toValue(o.page):null;return N==null?null:N>0?N:1},n=e.ref([]),i=e.ref([]),r=e.ref(null),s=e.ref(!1),l=e.ref(!1),d=e.ref(!1),c=e.ref(!1),u=e.ref(null),m=e.ref(null),f=e.ref(null),p=e.ref(null);let h=null,v=0;const E=async(N,T)=>{v+=1;const S=v;h==null||h.abort();const B=new AbortController;h=B,N?d.value=!0:l.value=!0,u.value=null,c.value=!1;const A=T??t(),x=A!==null;try{const M=await o.httpClient.get("/v1/media/library",{params:$u(o.view.value,o.filters.value,a(),x?null:N?r.value:null,void 0,A),signal:B.signal});if(S!==v)return;const w=Iu(M);n.value=N&&!x?Fu([...n.value,...w.data]):w.data,i.value=w.hydrated,r.value=w.meta.cursor,s.value=w.meta.has_more;const F=w.meta.pagination;m.value=(F==null?void 0:F.total)??null,f.value=(F==null?void 0:F.current_page)??(x&&A!==null?A:null);const P=(F==null?void 0:F.per_page)??a();p.value=(F==null?void 0:F.last_page)??(m.value!==null&&P>0?Math.max(1,Math.ceil(m.value/P)):null)}catch(M){if(B.signal.aborted||S!==v)return;const w=Du(N?"load_more_failed":"query_failed",M);u.value=w,c.value=w.code==="permission_denied",N||(n.value=[],r.value=null,s.value=!1)}finally{S===v&&(l.value=!1,d.value=!1)}},y=async N=>{if(N.length===0)return i.value=[],[];try{const T=await o.httpClient.get("/v1/media/library",{params:$u(o.view.value,o.filters.value,1,null,N)}),S=Iu(T);return i.value=S.hydrated,S.hydrated}catch(T){return u.value=Du("hydration_failed",T),[]}},k=N=>{n.value=Fu([N,...n.value])},g=async()=>{!s.value||d.value||t()===null&&await E(!0)};return{items:n,hydrated:i,cursor:r,hasMore:s,loading:l,loadingMore:d,permissionDenied:c,error:u,total:m,currentPage:f,totalPages:p,loadInitial:async()=>{r.value=null,await E(!1)},loadMore:g,loadAll:async N=>{const T=(N==null?void 0:N.maxItems)??5e3;if(!(l.value||d.value))for(;s.value&&n.value.length<T;){const S=n.value.length;if(await g(),u.value!==null||n.value.length===S)return}},goToPage:async N=>{!Number.isFinite(N)||N<1||l.value||d.value||await E(!1,N)},refresh:async()=>{r.value=null,await E(!1)},hydrateSelection:y,prepend:k}}const X8="mediables.media-library.";function K8(o){return!o||o.key.trim()===""?null:`${X8}${o.key}`}function il(){return typeof window>"u"||typeof window.sessionStorage>"u"?null:window.sessionStorage}function J8(o,a){const t=Date.parse(o);return Number.isFinite(t)?Date.now()-t>a*60*1e3:!0}function _f(o){const a=K8(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 l=il();if(l===null)return null;const d=l.getItem(a);if(d===null)return null;let c;try{c=JSON.parse(d)}catch{return l.removeItem(a),null}if(typeof c!="object"||c===null||Array.isArray(c))return l.removeItem(a),null;const u=c;if(u.version!==1||typeof u.savedAt!="string"||J8(u.savedAt,t))return l.removeItem(a),null;const m={selectedIds:Array.isArray(u.selectedIds)?u.selectedIds.filter(f=>typeof f=="string"&&f.trim()!==""):[]};return((o==null?void 0:o.restoreView)??!0)&&u.view&&(m.view=u.view),u.filters&&(m.filters=u.filters),m},save:l=>{if(a===null)return;const d=il();if(d===null)return;const c={version:1,savedAt:new Date().toISOString(),selectedIds:[...l.selectedIds]};((o==null?void 0:o.restoreView)??!0)&&l.view&&(c.view=l.view),l.filters&&(c.filters=l.filters),d.setItem(a,JSON.stringify(c))},clear:()=>{if(a===null)return;const l=il();l==null||l.removeItem(a)},sessionId:n}}function Ef(o){const a=e.ref(o);return{state:a,transition:n=>{a.value=n}}}function Sf(o){return{emitMetric:(t,n)=>{const i={name:t,timestamp:new Date().toISOString()};n!==void 0&&(i.payload=n),o==null||o(i)}}}function Mo(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function q8(o){const a=Mo(o)?o:{};return(Array.isArray(a.data)?a.data:Mo(a.data)&&Array.isArray(a.data.data)?a.data.data:Array.isArray(o)?o:[]).map(n=>{if(!Mo(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 Y8(o){const a=Mo(o)?o:{},t=Mo(a.data)?a.data:Mo(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 Q8(o){return o==="ready"||o==="uploading"||o==="failed"}function Un(o,a="ready"){return{id:o.uuid,media:o,status:a,countsTowardMax:Q8(a)}}function e6(o,a){return o.scope==="library"?!0:o.scope!=="album"?!1:a.type==="album"&&a.albumId===o.albumId}function t6(o,a){return o.scope==="library"?a.type==="library"||a.type==="album":o.scope!=="album"?!1:a.type==="album"&&a.albumId===o.albumId}function rl(o){return{code:"configuration_error",message:o,retriable:!1}}const Cf="/v1/albums";function a6(o){var a;return((a=o.deps.albumEndpoints)==null?void 0:a.list)??Cf}function n6(o){var a,t;return((a=o.deps.albumEndpoints)==null?void 0:a.create)??((t=o.deps.albumEndpoints)==null?void 0:t.list)??Cf}function o6(o){return typeof o!="string"||o.length===0?"document":o.startsWith("image/")?"image":o.startsWith("video/")?"video":o.startsWith("audio/")?"audio":"document"}function i6(o,a){return a.length===0||o===null?!0:a.includes(o6(o.mime_type))}function Ru(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 xf(o){var W,C;const a=o.selectionMode??"multiple",t=o.maxSelection,n=o.uploadBehavior??"adapter",i=e.ref(o.initialView??{scope:"library"}),r=((W=o.initialFilters)==null?void 0:W.kinds)??(o.allowedMediaKinds&&o.allowedMediaKinds.length>0?[...o.allowedMediaKinds]:void 0),s=e.ref({...Ru(o.initialFilters),sort:((C=o.initialFilters)==null?void 0:C.sort)??"newest",...r?{kinds:r}:{}}),l=o.allowedMediaKinds?[...o.allowedMediaKinds]:[],d=e.ref([]),c=e.ref([]),u=e.ref(null),m=e.ref(null),f=_f(o.sessionPolicy),{emitMetric:p}=Sf(o.telemetry),h=Ef("idle"),v=Dd({httpClient:o.deps.httpClient,view:i,filters:s}),E=e.computed(()=>c.value.map(U=>U.id)),y=e.computed(()=>{const U=u.value;return U===null?null:v.items.value[U]??null}),k=e.computed(()=>o.uploadTarget??{type:"library"}),g=Fd({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:U=>U.original_url,getThumbnailUrl:U=>U.thumbnail_url??U.preview_url??U.original_url},postUpload:async(U,j,ne)=>{const de=k.value;de.type!=="album"||!de.albumId||await ne.attach(j.uuid,{modelType:"album",modelId:de.albumId})},onUploadComplete:(U,j)=>{const ne=k.value;e6(i.value,ne)&&v.prepend(j),o.autoSelectUploaded&&t6(i.value,ne)&&A(j),p("upload-complete",{mediaId:j.uuid,targetType:ne.type,targetAlbumId:ne.albumId})},onUploadError:(U,j)=>{m.value={code:"upload_failed",message:j.message,retriable:!0,cause:j}}}),b=e.computed(()=>g.isUploading.value),R=()=>{f.save({selectedIds:[...E.value],view:i.value,filters:s.value})},N=async U=>{const j=await v.hydrateSelection(U);c.value=j.map(ne=>ne.status==="ready"&&ne.media?Un(ne.media):{id:ne.id,media:null,status:ne.status,countsTowardMax:!1})},T=e.computed(()=>c.value.filter(U=>U.countsTowardMax).length),S=()=>a==="single"||t===void 0?!0:T.value<t,B=U=>{if(c.value.findIndex(ne=>ne.id===U.uuid)>=0){a==="multiple"?c.value=c.value.filter(ne=>ne.id!==U.uuid):c.value=[Un(U)],R();return}if(!S()){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=[Un(U)]:c.value=[...c.value,Un(U)],m.value=null,R()},A=U=>{const j=c.value.findIndex(ne=>ne.id===U.uuid);if(j>=0){c.value=c.value.map((ne,de)=>de===j?Un(U):ne),m.value=null,R();return}if(!S()){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=[Un(U)]:c.value=[...c.value,Un(U)],m.value=null,R()},x=async()=>{var j;h.transition("restoring");const U=f.restore();if(U===null){h.transition("ready");return}U.view&&(i.value=U.view),U.filters&&(s.value={...Ru(U.filters),sort:U.filters.sort??"newest"}),await v.loadInitial(),(((j=o.sessionPolicy)==null?void 0:j.restoreSelection)??!0)&&await N(U.selectedIds),h.transition("ready")};e.watch(()=>v.error.value,U=>{U!==null&&(m.value=U,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 U=o.defaultSelectedIds??[];c.value.length===0&&U.length>0&&await N(U),h.transition("ready")},w=async(U,j="user")=>{const ne=i.value;i.value=U,j==="user"&&o.preserveSelectionOnViewChange===!1&&(c.value=[]),p("view-change",{from:ne.scope,to:U.scope,reason:j}),await v.loadInitial(),R()},F=async()=>{const U=await o.deps.httpClient.get(a6(o));d.value=q8(U)},P=async(U,j)=>{try{const ne={name:U,visibility:"private"};j&&j.trim()!==""&&(ne.parent_id=j);const de=await o.deps.httpClient.post(n6(o),ne),Ke=Y8(de);return Ke===null?rl("Album creation response was invalid."):(d.value=[Ke,...d.value.filter(be=>be.id!==Ke.id)],await w({scope:"album",albumId:Ke.id,albumName:Ke.name},"inline-album-created"),Ke)}catch(ne){const de={code:"album_create_failed",message:ne instanceof Error?ne.message:"Album creation failed.",retriable:!0,cause:ne};return m.value=de,de}},D=async U=>{if(!o.enableUpload){m.value=rl("Uploads are not enabled for this picker.");return}if(n!=="delegate"){if(!o.deps.uploadAdapter){m.value=rl("Uploads require a configured upload adapter.");return}await g.addFiles(U)}},O=()=>{var ne;if(l.length>0&&c.value.find(Ke=>Ke.media!==null&&!i6(Ke.media,l))){const be={code:"selection_invalid",message:`Selected media is not allowed here. Choose one of: ${l.join(", ")}.`,retriable:!0};return m.value=be,be}const U=((ne=o.validateSelection)==null?void 0:ne.call(o,c.value))??null;if(U!==null){const de={code:"selection_invalid",message:U,retriable:!0};return m.value=de,de}if(c.value.filter(de=>de.status==="ready"&&de.media!==null).length===0){const de={code:"selection_invalid",message:"Select at least one available media item.",retriable:!0};return m.value=de,de}return{orderedIds:E.value,items:[...c.value],view:i.value,filters:s.value,dirty:!0,sessionId:f.sessionId}},I=U=>{const j=v.items.value.findIndex(ne=>ne.uuid===U.uuid);u.value=j>=0?j:null},Z=()=>{u.value=null},z=()=>{u.value===null||u.value<=0||(u.value-=1)},K=()=>{u.value===null||u.value>=v.items.value.length-1||(u.value+=1)},se=U=>{c.value=c.value.filter(j=>j.id!==U),R()},Be=async()=>{await v.refresh()},ce=async U=>{s.value={...s.value,...U&&U.trim()!==""?{query:U.trim()}:{}},(!U||U.trim()==="")&&delete s.value.query,await v.loadInitial(),R()},ie=async()=>{await w({scope:"library"},"permission-unavailable")};return{view:i,filters:s,albums:d,selectedItems:c,orderedIds:E,queryItems:v.items,cursor:v.cursor,hasMore:v.hasMore,loading:v.loading,loadingMore:v.loadingMore,permissionDenied:v.permissionDenied,error:m,uploadQueue:g.uploadsArray,isUploading:b,previewIndex:u,previewItem:y,initialize:M,refresh:Be,loadMore:v.loadMore,setQuery:ce,setView:w,toggleSelection:B,removeSelected:se,confirmSelection:O,openPreview:I,closePreview:Z,showPreviousPreview:z,showNextPreview:K,loadAlbums:F,createAlbum:P,addUploadFiles:D,goToLibrary:ie,sessionId:f.sessionId}}const r6=["data-testid"],s6={class:"mlp-location-bar"},l6={class:"mlp-location-bar__left"},d6={class:"mlp-location-bar__label"},c6={class:"mlp-tabs","data-testid":"media-picker-tabs"},u6={key:0,class:"mlp-search-row"},m6=["placeholder"],p6={key:2,class:"mlp-overlay-panel"},f6={key:0,class:"mlp-error","data-testid":"media-picker-error"},h6={key:5,class:"mlp-bottom-bar"},v6={key:0,class:"mlp-bottom-bar__selection"},g6={class:"mlp-bottom-bar__count"},b6={class:"mlp-bottom-bar__thumbs"},y6=["src","alt"],w6={key:1,class:"mlp-bottom-bar__thumb-placeholder"},k6=["aria-label","onClick"],_6={class:"mlp-bottom-bar__actions"},E6=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 C,U,j,ne,de,Ke,be,_e,ve,xe,Se,Ae,re,ge,Ge,Ve,at,rt,gt,lt,Et,Ee,Ce,Re,et,qe,Ze,bt,ct,At,$t,Pt,Ut,ea,Jt,ta,fa,Q,he;return{title:((C=n.labels)==null?void 0:C.title)??"Media library",searchPlaceholder:((U=n.labels)==null?void 0:U.searchPlaceholder)??"Search your media",viewLibrary:((j=n.labels)==null?void 0:j.viewLibrary)??"Library",browseAlbums:((ne=n.labels)==null?void 0:ne.browseAlbums)??"Albums",createAlbum:((de=n.labels)==null?void 0:de.createAlbum)??"Create album",createAlbumNameLabel:((Ke=n.labels)==null?void 0:Ke.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:((ve=n.labels)==null?void 0:ve.networkError)??"Unable to load media right now.",retry:((xe=n.labels)==null?void 0:xe.retry)??"Retry",selectedCount:((Se=n.labels)==null?void 0:Se.selectedCount)??(ue=>`${ue} selected`),confirmAction:((Ae=n.labels)==null?void 0:Ae.confirmAction)??"Attach selected",cancel:((re=n.labels)==null?void 0:re.cancel)??"Cancel",dismiss:((ge=n.labels)==null?void 0:ge.dismiss)??"Remove",uploadLabel:((Ge=n.labels)==null?void 0:Ge.uploadLabel)??"Upload",albumUnavailableTitle:((Ve=n.labels)==null?void 0:Ve.albumUnavailableTitle)??"Album unavailable",albumUnavailableBody:((at=n.labels)==null?void 0:at.albumUnavailableBody)??"You no longer have access to this album.",goToLibrary:((rt=n.labels)==null?void 0:rt.goToLibrary)??"Go to library",allMediaTab:((gt=n.labels)==null?void 0:gt.allMediaTab)??"All Media",loadingMedia:((lt=n.labels)==null?void 0:lt.loadingMedia)??"Loading media…",loadMore:((Et=n.labels)==null?void 0:Et.loadMore)??"Load more",loadingMore:((Ee=n.labels)==null?void 0:Ee.loadingMore)??"Loading…",uploadDropzone:((Ce=n.labels)==null?void 0:Ce.uploadDropzone)??"Drop files here or browse",uploadDropzoneHelper:((Re=n.labels)==null?void 0:Re.uploadDropzoneHelper)??"",uploadDone:((et=n.labels)==null?void 0:et.uploadDone)??"Done",uploadDoneAria:((qe=n.labels)==null?void 0:qe.uploadDoneAria)??"Close upload panel",uploadFileInputLabel:((Ze=n.labels)==null?void 0:Ze.uploadFileInputLabel)??"Choose media files",previewClose:((bt=n.labels)==null?void 0:bt.previewClose)??"Close preview",previewPrevious:((ct=n.labels)==null?void 0:ct.previewPrevious)??"Previous media",previewNext:((At=n.labels)==null?void 0:At.previewNext)??"Next media",previewSelect:(($t=n.labels)==null?void 0:$t.previewSelect)??"Select media",previewDeselect:((Pt=n.labels)==null?void 0:Pt.previewDeselect)??"Deselect media",selectAction:((Ut=n.labels)==null?void 0:Ut.selectAction)??"Select",allMedia:((ea=n.labels)==null?void 0:ea.allMedia)??((Jt=n.labels)==null?void 0:Jt.allMediaTab)??"All media",unfiled:((ta=n.labels)==null?void 0:ta.unfiled)??"Unfiled",pageTitle:((fa=n.labels)==null?void 0:fa.pageTitle)??((Q=n.labels)==null?void 0:Q.title)??"Media library",albumLabel:((he=n.labels)==null?void 0:he.albumLabel)??"Album"}}),s=e.computed(()=>n.mode),l=e.computed(()=>s.value==="picker-single"?"single":n.selectionMode),d=e.computed(()=>n.showFooter===!0&&s.value!=="picker-single"),c=e.computed(()=>n.enablePreview===!0&&s.value!=="picker-single"),u={deps:n.deps,selectionMode:l.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:C=>{var U;(U=n.telemetry)==null||U.call(n,C),i("metric",C)}},m=xf(u),f=e.ref(n.initialFilters.query??""),p=e.ref(n.enableUpload?"upload":"media"),h=e.ref(!1),v=JSON.stringify(n.modelValue.length>0?n.modelValue:n.defaultSelectedIds);let E=null;const y=e.computed(()=>JSON.stringify(m.orderedIds.value)!==v),k=e.computed(()=>m.view.value.scope==="album"?r.value.emptyAlbum:r.value.emptyLibrary),g=e.computed(()=>r.value.selectedCount(m.selectedItems.value.length));function b(C){return typeof C=="boolean"?{allowed:C}:typeof C=="string"?{allowed:!1,reason:C}:C}function R(C){return n.itemFilter?b(n.itemFilter(C)):{allowed:!0}}const N=e.computed(()=>n.itemFilter?m.queryItems.value.filter(C=>R(C).allowed):m.queryItems.value),T=e.computed(()=>m.view.value.scope==="album"?m.view.value.albumName??"Album":r.value.viewLibrary),S=e.computed(()=>m.view.value.scope==="album"),B=()=>{E!==null&&(window.clearTimeout(E),E=null)},A=()=>{i("update:modelValue",[...m.orderedIds.value]),i("selection-change",{orderedIds:[...m.orderedIds.value],items:[...m.selectedItems.value],dirty:y.value})},x=C=>{C!==null&&i("error",C)},M=C=>typeof C.code=="string",w=C=>typeof C=="object"&&C!==null&&"code"in C&&typeof C.code=="string",F=()=>{const C=m.confirmSelection();if(M(C)){x(C);return}i("confirm",{...C,dirty:y.value})},P=C=>{const U=R(C);if(!U.allowed){x({code:"selection_invalid",message:U.reason??"This media item is not available for this picker.",retriable:!0});return}m.toggleSelection(C),s.value==="picker-single"&&i("select",C)},D=(C="user")=>{i("cancel",{dirty:y.value,reason:C,sessionId:m.sessionId})},O=async()=>{p.value="albums",await m.loadAlbums()},I=async()=>{await m.goToLibrary(),p.value="albums",await m.loadAlbums()},Z=C=>{m.setView({scope:"album",albumId:C.id,albumName:C.name}),p.value="media"},z=async(C,U)=>{const j=m.view.value,ne=await m.createAlbum(C,U);if(w(ne)){x(ne);return}h.value=!1,p.value="media",i("view-change",{from:j,to:{scope:"album",albumId:ne.id,albumName:ne.name},reason:"inline-album-created",restoredFromSession:!1})},K=async C=>{if(n.uploadBehavior==="delegate"){i("request-upload-files",{files:[...C],view:m.view.value,filters:m.filters.value,sessionId:m.sessionId});return}await m.addUploadFiles(C)};function se(C){var U;return C?C.thumbnail_url??((U=C.conversion_urls)==null?void 0:U.thumb)??C.preview_url??C.original_url??C.url??null:null}function Be(C){return C!=null&&C.mime_type?C.mime_type.startsWith("image/"):!1}e.watch(()=>f.value,C=>{B(),E=window.setTimeout(()=>{m.setQuery(C)},250)}),e.watch(()=>m.selectedItems.value,()=>{A()},{deep:!0}),e.watch(()=>m.error.value,C=>{x(C)}),e.watch(()=>n.enableUpload,C=>{!C&&p.value==="upload"&&(p.value="media")}),e.onMounted(()=>{m.initialize()}),e.onBeforeUnmount(()=>{B()}),a({refresh:m.refresh});function ce(C){if(C==="albums"){O();return}if(C==="upload"&&!n.enableUpload){p.value="media";return}p.value=C}const ie=e.computed(()=>({activeTab:p.value,setActiveTab:ce,enableUpload:n.enableUpload,labels:{uploadLabel:r.value.uploadLabel,allMediaTab:r.value.allMediaTab,browseAlbums:r.value.browseAlbums}})),W=e.computed(()=>({query:f.value,setQuery:C=>{f.value=C},placeholder:r.value.searchPlaceholder}));return(C,U)=>(e.openBlock(),e.createElementBlock("section",{class:"media-library-picker","data-testid":C.testIdPrefix},[e.createElementVNode("header",s6,[e.createElementVNode("div",l6,[S.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:I},[...U[8]||(U[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",d6,e.toDisplayString(T.value),1)])]),e.renderSlot(C.$slots,"tabs",e.normalizeProps(e.guardReactiveProps(ie.value)),()=>[e.createElementVNode("nav",c6,[C.enableUpload?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:e.normalizeClass(["mlp-tabs__tab",{"is-active":p.value==="upload"}]),"data-testid":"tab-media-picker-upload",onClick:U[0]||(U[0]=j=>p.value="upload")},e.toDisplayString(r.value.uploadLabel),3)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["mlp-tabs__tab",{"is-active":p.value==="media"}]),"data-testid":"tab-media-picker-all",onClick:U[1]||(U[1]=j=>p.value="media")},e.toDisplayString(r.value.allMediaTab),3),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["mlp-tabs__tab",{"is-active":p.value==="albums"}]),"data-testid":"tab-media-picker-albums",onClick:O},e.toDisplayString(r.value.browseAlbums),3)])],!0),p.value==="media"||p.value==="albums"?(e.openBlock(),e.createElementBlock("div",u6,[e.renderSlot(C.$slots,"search",e.normalizeProps(e.guardReactiveProps(W.value)),()=>[U[9]||(U[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":U[2]||(U[2]=j=>f.value=j),class:"mlp-search-row__input",type:"search",placeholder:r.value.searchPlaceholder,"data-testid":"input-media-picker-search"},null,8,m6),[[e.vModelText,f.value]])],!0)])):e.createCommentVNode("",!0),C.enableUpload&&p.value==="upload"?(e.openBlock(),e.createBlock(hf,{key:1,open:!0,queue:e.unref(m).uploadQueue.value,accept:C.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:U[3]||(U[3]=j=>p.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",p6,[e.createVNode(Bd,{open:h.value,"name-label":r.value.createAlbumNameLabel,albums:e.unref(m).albums.value,onCancel:U[4]||(U[4]=j=>h.value=!1),onCreate:z},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(sf,{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",f6,[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:U[5]||(U[5]=(...j)=>e.unref(m).refresh&&e.unref(m).refresh(...j))},e.toDisplayString(r.value.retry),1)])):e.createCommentVNode("",!0),p.value==="media"?(e.openBlock(),e.createBlock(gf,{key:1,items:N.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":k.value,"loading-message":r.value.loadingMedia,"load-more-label":r.value.loadMore,"loading-more-label":r.value.loadingMore,"test-id-prefix":`${C.testIdPrefix}-item`,onToggle:P,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"])):p.value==="albums"?(e.openBlock(),e.createBlock(ff,{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":C.enableAlbumCreation,onSelectLibrary:I,onSelectAlbum:Z,onCreateAlbum:U[6]||(U[6]=j=>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",h6,[e.unref(m).selectedItems.value.length>0?(e.openBlock(),e.createElementBlock("div",v6,[e.createElementVNode("span",g6,e.toDisplayString(g.value),1),e.createElementVNode("div",b6,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(m).selectedItems.value,j=>{var ne,de,Ke;return e.openBlock(),e.createElementBlock("div",{key:j.id,class:"mlp-bottom-bar__thumb-item"},[Be(j.media)&&se(j.media)?(e.openBlock(),e.createElementBlock("img",{key:0,src:se(j.media),alt:((ne=j.media)==null?void 0:ne.alt_text)??((de=j.media)==null?void 0:de.file_name)??"Selected",class:"mlp-bottom-bar__thumb-img"},null,8,y6)):(e.openBlock(),e.createElementBlock("div",w6,[...U[10]||(U[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} ${((Ke=j.media)==null?void 0:Ke.file_name)??j.id}`,"data-testid":"btn-media-picker-remove-selected",onClick:be=>e.unref(m).removeSelected(j.id)},[...U[11]||(U[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,k6)])}),128))])])):e.createCommentVNode("",!0),e.createElementVNode("div",_6,[e.createElementVNode("button",{type:"button",class:"mlp-bottom-bar__cancel","data-testid":"btn-media-picker-cancel",onClick:U[7]||(U[7]=j=>D())},e.toDisplayString(r.value.cancel),1),e.createElementVNode("button",{type:"button",class:"mlp-bottom-bar__confirm","data-testid":"btn-media-picker-confirm",onClick:F},e.toDisplayString(r.value.confirmAction),1)])])):e.createCommentVNode("",!0),c.value?(e.openBlock(),e.createBlock(Md,{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,r6))}}),Vf=Fe(E6,[["__scopeId","data-v-307fef12"]]),S6={key:0,class:"media-library-picker-modal","data-testid":"media-library-picker-modal"},C6={class:"media-library-picker-modal__panel"},x6=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,s)=>r.isOpen?(e.openBlock(),e.createElementBlock("div",S6,[e.createElementVNode("button",{type:"button",class:"media-library-picker-modal__backdrop","aria-label":"Close media picker",onClick:i}),e.createElementVNode("div",C6,[e.createVNode(Vf,e.mergeProps(t,{"onUpdate:modelValue":s[0]||(s[0]=l=>n("update:modelValue",l)),onConfirm:s[1]||(s[1]=l=>n("confirm",l)),onCancel:s[2]||(s[2]=l=>n("cancel",l))}),null,16)])])):e.createCommentVNode("",!0)}}),V6=Fe(x6,[["__scopeId","data-v-a92e8703"]]),N6=["aria-label"],T6={class:"media-album-picker-modal__panel"},B6={class:"media-album-picker-modal__header"},M6={key:0,class:"media-album-picker-modal__selection","data-testid":"media-album-picker-selection"},I6={class:"media-album-picker-modal__actions"},$6=["disabled"],F6=e.defineComponent({__name:"MediaAlbumPickerModal",props:{open:{type:Boolean},selectedCount:{},labels:{default:()=>({})}},emits:["cancel","confirm"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(null),r=e.computed(()=>{var d,c,u,m,f;return{title:((d=t.labels)==null?void 0:d.title)??"Add to album",body:((c=t.labels)==null?void 0:c.body)??`Choose an album for ${t.selectedCount} selected item${t.selectedCount===1?"":"s"}.`,confirm:((u=t.labels)==null?void 0:u.confirm)??"Add",cancel:((m=t.labels)==null?void 0:m.cancel)??"Cancel",selectedAlbum:((f=t.labels)==null?void 0:f.selectedAlbum)??(p=>`Selected: ${p}`)}});e.watch(()=>t.open,d=>{d||(i.value=null)});function s(d){i.value=d}function l(){i.value!==null&&n("confirm",i.value.id)}return(d,c)=>{var u;return t.open?(e.openBlock(),e.createElementBlock("div",{key:0,class:"media-album-picker-modal","data-testid":"media-album-picker-modal",role:"dialog","aria-modal":"true","aria-label":r.value.title},[e.createElementVNode("div",T6,[e.createElementVNode("header",B6,[e.createElementVNode("h2",null,e.toDisplayString(r.value.title),1),e.createElementVNode("p",null,e.toDisplayString(r.value.body),1)]),e.createVNode(Vs,{class:"media-album-picker-modal__tree","model-value":((u=i.value)==null?void 0:u.id)??null,draggable:!1,compact:!0,"data-testid":"media-album-picker-tree",onAlbumSelected:s},null,8,["model-value"]),i.value!==null?(e.openBlock(),e.createElementBlock("p",M6,e.toDisplayString(r.value.selectedAlbum(i.value.name)),1)):e.createCommentVNode("",!0),e.createElementVNode("footer",I6,[e.createElementVNode("button",{type:"button","data-testid":"btn-media-album-picker-cancel",onClick:c[0]||(c[0]=m=>n("cancel"))},e.toDisplayString(r.value.cancel),1),e.createElementVNode("button",{type:"button","data-testid":"btn-media-album-picker-confirm",disabled:i.value===null,onClick:l},e.toDisplayString(r.value.confirm),9,$6)])])],8,N6)):e.createCommentVNode("",!0)}}}),Nf=Fe(F6,[["__scopeId","data-v-cb9c9581"]]),D6={class:"album-nav-rail__search"},R6={class:"album-nav-rail__sr-only"},A6=["placeholder"],L6={class:"album-nav-rail__primary","aria-label":"Media scopes"},P6={class:"album-nav-rail__count"},U6={class:"album-nav-rail__count"},O6={key:0,class:"album-nav-rail__recent","data-testid":"album-rail-recent","aria-label":"Recent albums"},z6={class:"album-nav-rail__section-label"},j6=["data-testid","onClick"],W6={class:"album-nav-rail__tree"},H6={class:"album-nav-rail__utility"},Z6={class:"album-nav-rail__count"},G6=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(""),s=e.ref([]),l=e.ref(null),d=e.computed(()=>{var y,k,g,b,R,N;return{allMedia:((y=t.labels)==null?void 0:y.allMedia)??"All media",unfiled:((k=t.labels)==null?void 0:k.unfiled)??"Unfiled",newAlbum:((g=t.labels)==null?void 0:g.newAlbum)??"New album",findAlbum:((b=t.labels)==null?void 0:b.findAlbum)??"Find album...",trash:((R=t.labels)==null?void 0:R.trash)??"Trash",recentSection:((N=t.labels)==null?void 0:N.recentSection)??"Recent"}});function c(y){return typeof y=="number"&&Number.isFinite(y)?String(y):""}function u(y){n("change-album",y.id)}function m(y,k){i.value=!1,n("create-album",k?{name:y,parentId:k}:{name:y})}function f(y){var g;const k=((g=y.dataTransfer)==null?void 0:g.getData("application/x-mediables-media-ids"))??"";if(k.trim()==="")return s.value;try{const b=JSON.parse(k);return Array.isArray(b)?b.filter(R=>typeof R=="string"&&R.trim()!==""):[]}catch{return k.split(",").map(b=>b.trim()).filter(b=>b!=="")}}function p(y,k){t.allowDragDropTarget&&(y.preventDefault(),l.value=k)}function h(){l.value=null}function v(y,k){if(!t.allowDragDropTarget)return;y.preventDefault();const g=f(y);l.value=null,g.length!==0&&n("drop-media",{albumId:k==="all"||k==="unfiled"?null:k,mediaIds:g})}const E=e.computed(()=>({"is-collapsed":t.collapsed}));return(y,k)=>(e.openBlock(),e.createElementBlock("aside",{class:e.normalizeClass(["album-nav-rail",E.value]),"data-testid":"album-rail"},[e.createElementVNode("label",D6,[e.createElementVNode("span",R6,e.toDisplayString(d.value.findAlbum),1),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":k[0]||(k[0]=g=>r.value=g),type:"search",placeholder:d.value.findAlbum,"data-testid":"input-album-rail-search"},null,8,A6),[[e.vModelText,r.value]])]),e.createElementVNode("nav",L6,[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["album-nav-rail__row",{"is-active":t.activeAlbumId===null,"is-drop-target":l.value==="all"}]),"data-testid":"album-rail-row-all",onClick:k[1]||(k[1]=g=>n("change-album",null)),onDragover:k[2]||(k[2]=g=>p(g,"all")),onDragleave:h,onDrop:k[3]||(k[3]=g=>v(g,"all"))},[e.createElementVNode("span",null,e.toDisplayString(d.value.allMedia),1),e.createElementVNode("span",P6,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":l.value==="unfiled"}]),"data-testid":"album-rail-row-unfiled",onClick:k[4]||(k[4]=g=>n("change-album","unfiled")),onDragover:k[5]||(k[5]=g=>p(g,"unfiled")),onDragleave:h,onDrop:k[6]||(k[6]=g=>v(g,"unfiled"))},[e.createElementVNode("span",null,e.toDisplayString(d.value.unfiled),1),e.createElementVNode("span",U6,e.toDisplayString(c(t.mediaCounts.unfiled)),1)],34)]),t.recentAlbums.length>0?(e.openBlock(),e.createElementBlock("section",O6,[e.createElementVNode("p",z6,e.toDisplayString(d.value.recentSection),1),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.recentAlbums,g=>(e.openBlock(),e.createElementBlock("button",{key:`recent-${g.id}`,type:"button",class:e.normalizeClass(["album-nav-rail__row album-nav-rail__row--recent",{"is-active":t.activeAlbumId===g.id}]),"data-testid":`album-rail-recent-${g.id}`,onClick:b=>n("change-album",g.id)},[e.createElementVNode("span",null,e.toDisplayString(g.name),1)],10,j6))),128))])):e.createCommentVNode("",!0),e.createElementVNode("div",W6,[e.createVNode(Vs,{"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:k[7]||(k[7]=g=>i.value=!0)}," + "+e.toDisplayString(d.value.newAlbum),1),e.createVNode(Bd,{open:i.value,onCancel:k[8]||(k[8]=g=>i.value=!1),onCreate:m},null,8,["open"]),e.createElementVNode("div",H6,[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["album-nav-rail__row album-nav-rail__row--utility",{"is-drop-target":l.value==="trash"}]),"data-testid":"album-rail-row-trash",onClick:k[9]||(k[9]=g=>n("open-trash")),onDragover:k[10]||(k[10]=g=>p(g,"trash")),onDragleave:h,onDrop:k[11]||(k[11]=g=>v(g,"trash"))},[e.createElementVNode("span",null,e.toDisplayString(d.value.trash),1),e.createElementVNode("span",Z6,e.toDisplayString(c(t.mediaCounts.trash)),1)],34)])],2))}}),Tf=Fe(G6,[["__scopeId","data-v-0913c5b6"]]),X6={key:0,class:"media-bulk-action-bar","data-testid":"media-bulk-action-bar","aria-live":"polite"},K6={class:"media-bulk-action-bar__actions"},J6=["disabled"],q6=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 l,d,c,u,m,f,p,h,v,E,y,k,g,b;return{selectedCount:((l=t.labels)==null?void 0:l.selectedCount)??(R=>`${R} selected`),selectedAcrossPages:((d=t.labels)==null?void 0:d.selectedAcrossPages)??((R,N)=>`${R} selected, including ${N} not on this page`),cappedSelection:((c=t.labels)==null?void 0:c.cappedSelection)??((R,N)=>`Selected first ${R} of ${N??"many"} matching items`),addToAlbum:((u=t.labels)==null?void 0:u.addToAlbum)??"Add to album",moveBetweenAlbums:((m=t.labels)==null?void 0:m.moveBetweenAlbums)??(R=>`Move from ${R} to...`),removeFromCurrentAlbum:((f=t.labels)==null?void 0:f.removeFromCurrentAlbum)??"Remove from this album",moveToTrash:((p=t.labels)==null?void 0:p.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:((E=t.labels)==null?void 0:E.restore)??"Restore",purge:((y=t.labels)==null?void 0:y.purge)??"Delete forever",download:((k=t.labels)==null?void 0:k.download)??"Download",inspect:((g=t.labels)==null?void 0:g.inspect)??"Inspect",clear:((b=t.labels)==null?void 0:b.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)),s=e.computed(()=>t.sourceAlbum?i.value.moveBetweenAlbums(t.sourceAlbum.name):i.value.addToAlbum);return(l,d)=>(e.openBlock(),e.createBlock(e.Transition,{name:"media-bulk-action-bar"},{default:e.withCtx(()=>[t.selectedCount>0?(e.openBlock(),e.createElementBlock("aside",X6,[e.createElementVNode("button",{type:"button",class:"media-bulk-action-bar__count","data-testid":"media-bulk-action-count",onClick:d[0]||(d[0]=c=>n("inspect"))},e.toDisplayString(r.value),1),e.createElementVNode("div",K6,[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"?s.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,J6),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}))}}),Rd=Fe(q6,[["__scopeId","data-v-026a292d"]]),Y6={class:"media-library-toolbar","data-testid":"media-library-toolbar"},Q6={class:"media-library-toolbar__group"},eD=["aria-expanded"],tD={key:0,class:"media-library-toolbar__menu",role:"menu","data-testid":"media-library-toolbar-sort-menu"},aD={class:"media-library-toolbar__group"},nD=["aria-expanded"],oD={key:0,class:"media-library-toolbar__menu",role:"menu","data-testid":"media-library-toolbar-jump-menu"},iD={key:0,class:"media-library-toolbar__menu-status"},rD={key:1,class:"media-library-toolbar__menu-status"},sD=["data-testid","onClick"],lD={"aria-hidden":"true"},dD={class:"media-library-toolbar__group"},cD=["aria-expanded"],uD={key:0,class:"media-library-toolbar__menu",role:"menu","data-testid":"media-library-toolbar-density-menu"},mD=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 N,T,S,B,A,x,M,w,F,P,D,O;return{sort:((N=t.labels)==null?void 0:N.sort)??"Sort",sortNewest:((T=t.labels)==null?void 0:T.sortNewest)??"Newest",sortOldest:((S=t.labels)==null?void 0:S.sortOldest)??"Oldest",sortName:((B=t.labels)==null?void 0:B.sortName)??"Name A–Z",sortLargest:((A=t.labels)==null?void 0:A.sortLargest)??"Largest first",jumpTo:((x=t.labels)==null?void 0:x.jumpTo)??"Jump to",jumpToAll:((M=t.labels)==null?void 0:M.jumpToAll)??"All time",jumpToEmpty:((w=t.labels)==null?void 0:w.jumpToEmpty)??"No history yet",density:((F=t.labels)==null?void 0:F.density)??"Density",densityComfortable:((P=t.labels)==null?void 0:P.densityComfortable)??"Comfortable",densityCompact:((D=t.labels)==null?void 0:D.densityCompact)??"Compact",upload:((O=t.labels)==null?void 0:O.upload)??"Upload"}}),r=e.ref(null);function s(){var N;(N=r.value)==null||N.click()}function l(N){const T=N.target;!(T instanceof HTMLInputElement)||T.files===null||T.files.length===0||(n("upload-files",Array.from(T.files)),T.value="")}const d=e.ref(!1),c=e.ref(!1),u=e.ref(!1),m=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}}),f=e.computed(()=>t.density==="compact"?i.value.densityCompact:i.value.densityComfortable);function p(N){d.value=!1,n("update:sort",N)}function h(N){u.value=!1,n("update:density",N)}const v=e.ref([]),E=e.ref(!1),y=e.ref(!1);async function k(){if(!(E.value||y.value||t.httpClient===void 0)){y.value=!0;try{const N=await t.httpClient.get(t.timelineEndpoint),T=N.data,S=(T==null?void 0:T.buckets)??N.buckets??[];v.value=Array.isArray(S)?S:[],E.value=!0}finally{y.value=!1}}}async function g(){c.value=!c.value,c.value&&await k()}function b(N){c.value=!1,n("jump-to",N)}function R(){c.value=!1,n("jump-to-all")}return e.onMounted(()=>{}),(N,T)=>(e.openBlock(),e.createElementBlock("div",Y6,[e.createElementVNode("button",{type:"button",class:"media-library-toolbar__upload","data-testid":"btn-media-toolbar-upload",onClick:s}," ⤴ "+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:l},null,544),e.createElementVNode("div",Q6,[e.createElementVNode("button",{type:"button",class:"media-library-toolbar__trigger","data-testid":"btn-media-toolbar-sort","aria-expanded":d.value?"true":"false",onClick:T[0]||(T[0]=S=>d.value=!d.value)},e.toDisplayString(i.value.sort)+": "+e.toDisplayString(m.value),9,eD),d.value?(e.openBlock(),e.createElementBlock("div",tD,[e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-sort-newest",onClick:T[1]||(T[1]=S=>p("newest"))},e.toDisplayString(i.value.sortNewest),1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-sort-oldest",onClick:T[2]||(T[2]=S=>p("oldest"))},e.toDisplayString(i.value.sortOldest),1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-sort-name",onClick:T[3]||(T[3]=S=>p("name"))},e.toDisplayString(i.value.sortName),1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-sort-largest",onClick:T[4]||(T[4]=S=>p("largest"))},e.toDisplayString(i.value.sortLargest),1)])):e.createCommentVNode("",!0)]),e.createElementVNode("div",aD,[e.createElementVNode("button",{type:"button",class:"media-library-toolbar__trigger","data-testid":"btn-media-toolbar-jump-to","aria-expanded":c.value?"true":"false",onClick:T[5]||(T[5]=S=>void g())},e.toDisplayString(i.value.jumpTo),9,nD),c.value?(e.openBlock(),e.createElementBlock("div",oD,[e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-jump-all",onClick:R},e.toDisplayString(i.value.jumpToAll),1),y.value?(e.openBlock(),e.createElementBlock("p",iD,"Loading…")):E.value&&v.value.length===0?(e.openBlock(),e.createElementBlock("p",rD,e.toDisplayString(i.value.jumpToEmpty),1)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(v.value,S=>(e.openBlock(),e.createElementBlock("button",{key:S.starts_at,type:"button",role:"menuitem","data-testid":`opt-jump-${S.starts_at}`,onClick:B=>b(S)},[e.createTextVNode(e.toDisplayString(S.label)+" ",1),e.createElementVNode("span",lD,"("+e.toDisplayString(S.count)+")",1)],8,sD))),128))])):e.createCommentVNode("",!0)]),e.createElementVNode("div",dD,[e.createElementVNode("button",{type:"button",class:"media-library-toolbar__trigger","data-testid":"btn-media-toolbar-density","aria-expanded":u.value?"true":"false",onClick:T[6]||(T[6]=S=>u.value=!u.value)},e.toDisplayString(i.value.density)+": "+e.toDisplayString(f.value),9,cD),u.value?(e.openBlock(),e.createElementBlock("div",uD,[e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-density-comfortable",onClick:T[7]||(T[7]=S=>h("comfortable"))},e.toDisplayString(i.value.densityComfortable),1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-density-compact",onClick:T[8]||(T[8]=S=>h("compact"))},e.toDisplayString(i.value.densityCompact),1)])):e.createCommentVNode("",!0)])]))}}),Bf=Fe(mD,[["__scopeId","data-v-1634ed26"]]),pD={class:"media-shortcut-help__panel"},fD={class:"media-shortcut-help__header"},hD=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 s of t.shortcuts)r.set(s.group,[...r.get(s.group)??[],s]);return Array.from(r.entries()).map(([s,l])=>({group:s,shortcuts:l}))}return(r,s)=>t.open?(e.openBlock(),e.createElementBlock("div",{key:0,class:"media-shortcut-help",role:"dialog","aria-modal":"true","data-testid":"media-shortcut-help",onKeydown:s[1]||(s[1]=e.withKeys(l=>n("close"),["escape"]))},[e.createElementVNode("div",pD,[e.createElementVNode("header",fD,[e.createElementVNode("h3",null,e.toDisplayString(t.title),1),e.createElementVNode("button",{type:"button","data-testid":"btn-media-shortcut-close",onClick:s[0]||(s[0]=l=>n("close"))},e.toDisplayString(t.closeLabel),1)]),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i(),l=>(e.openBlock(),e.createElementBlock("section",{key:l.group,class:"media-shortcut-help__group"},[e.createElementVNode("h4",null,e.toDisplayString(l.group),1),e.createElementVNode("dl",null,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(l.shortcuts,d=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:`${l.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)}}),Mf=Fe(hD,[["__scopeId","data-v-abcdccb6"]]),vD="/v1/media/upload";function If(o){const a=o.endpoint??vD,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 s(u){t.value=t.value.filter(m=>m.cid!==u)}async function l(u){const m=i(),f=r(u),p={cid:m,fileName:u.name,size:u.size,status:"uploading",progress:0,...f!==void 0?{previewUrl:f}:{}};t.value=[p,...t.value];const h=new FormData;h.append("file",u);try{const v=await o.httpClient.post(a,h),E=v.data??v;return t.value=t.value.map(y=>y.cid===m?{...y,status:"success",progress:100}:y),typeof o.onMediaUploaded=="function"&&E&&typeof E.uuid=="string"&&await o.onMediaUploaded(E),setTimeout(()=>s(m),350),t.value.find(y=>y.cid===m)??p}catch(v){const E=v instanceof Error?v.message:"Upload failed";return t.value=t.value.map(y=>y.cid===m?{...y,status:"error",errorMessage:E}:y),t.value.find(y=>y.cid===m)??p}finally{if(f!==void 0&&typeof URL<"u")try{URL.revokeObjectURL(f)}catch{}}}async function d(u){const m=Array.from(u);return Promise.all(m.map(f=>l(f)))}function c(){t.value=[]}return{uploads:t,hasActiveUploads:n,uploadFile:l,uploadFiles:d,dismiss:s,clear:c}}const gD={class:"media-usage-list","data-testid":"media-usage-list"},bD={class:"media-usage-list__title"},yD={key:0,class:"media-usage-list__empty","data-testid":"media-usage-loading"},wD={key:1,class:"media-usage-list__empty","data-testid":"media-usage-empty"},kD={key:2,class:"media-usage-list__items"},_D=["data-testid"],ED=["href"],SD={key:1},CD={key:2,class:"media-usage-list__count"},xD=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(l){var m;if(typeof l!="object"||l===null||!("data"in l))return[];const d=l.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((f,p)=>({id:`${f.type??"usage"}-${p}`,label:f.context??f.type??"Usage"}))}async function s(){if(!a.httpClient||a.media===null){n.value=[];return}t.value=!0;try{const l=await a.httpClient.post("/v1/media/deletion/check",{uuids:[a.media.uuid]});n.value=r(l)}finally{t.value=!1}}return e.watch(()=>{var l;return(l=a.media)==null?void 0:l.uuid},()=>{s()}),e.onMounted(()=>{s()}),(l,d)=>(e.openBlock(),e.createElementBlock("section",gD,[e.createElementVNode("h4",bD,e.toDisplayString(a.title),1),t.value?(e.openBlock(),e.createElementBlock("p",yD," Loading... ")):i.value.length===0?(e.openBlock(),e.createElementBlock("p",wD,e.toDisplayString(a.emptyLabel),1)):(e.openBlock(),e.createElementBlock("ul",kD,[(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,ED)):(e.openBlock(),e.createElementBlock("span",SD,e.toDisplayString(c.label),1)),typeof c.count=="number"?(e.openBlock(),e.createElementBlock("span",CD,e.toDisplayString(c.count),1)):e.createCommentVNode("",!0)],8,_D))),128))]))]))}}),$f=Fe(xD,[["__scopeId","data-v-ef6f09cf"]]),VD={class:"media-variant-strip","data-testid":"media-variant-strip"},ND={class:"media-variant-strip__title"},TD={key:0,class:"media-variant-strip__empty"},BD={key:1,class:"media-variant-strip__empty"},MD={key:2,class:"media-variant-strip__list"},ID=["data-testid"],$D=["src","alt"],FD={key:1,class:"media-variant-strip__placeholder"},DD={class:"media-variant-strip__label"},RD=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 s(){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 l(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 f=Math.max(0,Math.round((Date.now()-m.getTime())/864e5));return f===0?"Edited today":f===1?"Edited 1 day ago":`Edited ${f} days ago`}return e.watch(()=>{var c;return(c=a.media)==null?void 0:c.uuid},()=>{s()}),e.onMounted(()=>{s()}),(c,u)=>(e.openBlock(),e.createElementBlock("section",VD,[e.createElementVNode("h4",ND,e.toDisplayString(a.title),1),t.value?(e.openBlock(),e.createElementBlock("p",TD,"Loading...")):i.value.length<=1?(e.openBlock(),e.createElementBlock("p",BD," No edits ")):(e.openBlock(),e.createElementBlock("ol",MD,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,(m,f)=>(e.openBlock(),e.createElementBlock("li",{key:m.uuid,class:"media-variant-strip__item","data-testid":`media-variant-${m.uuid}`},[l(m)?(e.openBlock(),e.createElementBlock("img",{key:0,src:l(m)??"",alt:m.alt_text??m.file_name},null,8,$D)):(e.openBlock(),e.createElementBlock("span",FD,e.toDisplayString(m.file_name),1)),e.createElementVNode("span",DD,e.toDisplayString(d(f,m)),1)],8,ID))),128))]))]))}}),Ff=Fe(RD,[["__scopeId","data-v-adb529cb"]]),AD=/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/ig,Au=/[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 Lu(o){const a=o.replace(/\.[^.]+$/,""),t=a.replace(AD,""),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 Pu(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 Df(o){const a=Pu(o,"display_name");if(a!==null&&!Au.test(a))return a;const t=Pu(o,"original_filename");return t!==null&&!Au.test(t)?Lu(t):Lu(o.file_name)}const LD=["role","aria-modal"],PD={class:"media-inspector-panel__header"},UD={key:0,class:"media-inspector-panel__raw-name"},OD={class:"media-inspector-panel__preview"},zD=["src","alt"],jD={class:"media-inspector-panel__meta"},WD={class:"media-inspector-panel__actions"},HD={class:"media-inspector-panel__actions"},ZD=["disabled"],GD={key:2,class:"media-inspector-panel__empty"},XD=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","bulk-add-to-album","bulk-create-album","bulk-move-to-trash","bulk-download","close"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(null),r=e.ref(null);e.watch(()=>t.target,(u,m)=>{const f=m==null,p=u==null;if(f&&!p){typeof document<"u"&&document.activeElement instanceof HTMLElement&&(r.value=document.activeElement),e.nextTick(()=>{var h;(h=i.value)==null||h.focus()});return}if(!f&&p){const h=r.value;r.value=null,h instanceof HTMLElement&&h.focus()}});function s(u){t.mode==="overlay"&&u.key==="Escape"&&(u.stopPropagation(),n("close"))}const l=e.computed(()=>t.mode==="overlay"?"dialog":"complementary"),d=e.computed(()=>{var u,m,f,p,h,v,E,y,k,g,b,R;return{title:((u=t.labels)==null?void 0:u.title)??"Inspector",emptyTitle:((m=t.labels)==null?void 0:m.emptyTitle)??"Select media to inspect",multiTitle:((f=t.labels)==null?void 0:f.multiTitle)??(N=>`${N} selected`),edit:((p=t.labels)==null?void 0:p.edit)??"Edit",replace:((h=t.labels)==null?void 0:h.replace)??"Replace",download:((v=t.labels)==null?void 0:v.download)??"Download",setVisibility:((E=t.labels)==null?void 0:E.setVisibility)??"Set visibility",moveToTrash:((y=t.labels)==null?void 0:y.moveToTrash)??"Move to trash",removeFromThisAlbum:((k=t.labels)==null?void 0:k.removeFromThisAlbum)??"Remove from this album",removeFromAlbums:((g=t.labels)==null?void 0:g.removeFromAlbums)??"Remove from album...",addToAlbum:((b=t.labels)==null?void 0:b.addToAlbum)??"Add to album",createAlbum:((R=t.labels)==null?void 0:R.createAlbum)??"Create album from selection"}}),c=e.computed(()=>{var u;return((u=t.target)==null?void 0:u.kind)==="single"?t.target.media:null});return(u,m)=>{var f;return e.openBlock(),e.createElementBlock("aside",{class:"media-inspector-panel","data-testid":"media-inspector-panel",role:l.value,"aria-modal":t.mode==="overlay"?"true":void 0,"aria-labelledby":"media-inspector-heading",onKeydown:s},[c.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("header",PD,[e.createElementVNode("h3",{id:"media-inspector-heading",ref_key:"headingRef",ref:i,tabindex:"-1"},e.toDisplayString(e.unref(Df)(c.value)),513),c.value.file_name?(e.openBlock(),e.createElementBlock("p",UD,e.toDisplayString(c.value.file_name),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",OD,[c.value.thumbnail_url??c.value.preview_url??c.value.original_url?(e.openBlock(),e.createElementBlock("img",{key:0,src:c.value.thumbnail_url??c.value.preview_url??c.value.original_url,alt:c.value.alt_text??c.value.file_name},null,8,zD)):e.createCommentVNode("",!0)]),e.createElementVNode("dl",jD,[e.createElementVNode("div",null,[m[11]||(m[11]=e.createElementVNode("dt",null,"Type",-1)),e.createElementVNode("dd",null,e.toDisplayString(c.value.mime_type),1)]),e.createElementVNode("div",null,[m[12]||(m[12]=e.createElementVNode("dt",null,"Size",-1)),e.createElementVNode("dd",null,e.toDisplayString(c.value.formatted_size??c.value.size),1)])]),e.createVNode($f,{media:c.value,"http-client":t.httpClient},null,8,["media","http-client"]),e.createVNode(Ff,{media:c.value,"http-client":t.httpClient},null,8,["media","http-client"]),e.createElementVNode("div",WD,[t.capabilities.allowImageEdit||t.capabilities.allowVideoEdit?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",onClick:m[0]||(m[0]=p=>n("edit",c.value))},e.toDisplayString(d.value.edit),1)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",onClick:m[1]||(m[1]=p=>n("replace",c.value))},e.toDisplayString(d.value.replace),1),e.createElementVNode("button",{type:"button",onClick:m[2]||(m[2]=p=>n("download",c.value))},e.toDisplayString(d.value.download),1),t.capabilities.allowVisibilityChange?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button",onClick:m[3]||(m[3]=p=>n("set-visibility",c.value))},e.toDisplayString(d.value.setVisibility),1)):e.createCommentVNode("",!0),t.inAlbumScope?(e.openBlock(),e.createElementBlock("button",{key:2,type:"button",onClick:m[4]||(m[4]=p=>n("remove-from-this-album",c.value))},e.toDisplayString(d.value.removeFromThisAlbum),1)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",onClick:m[5]||(m[5]=p=>n("remove-from-albums",c.value))},e.toDisplayString(d.value.removeFromAlbums),1),e.createElementVNode("button",{type:"button",onClick:m[6]||(m[6]=p=>n("move-to-trash",c.value))},e.toDisplayString(d.value.moveToTrash),1)])],64)):((f=t.target)==null?void 0:f.kind)==="multi"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[e.createElementVNode("h3",{id:"media-inspector-heading",ref_key:"headingRef",ref:i,tabindex:"-1"},e.toDisplayString(d.value.multiTitle(t.target.count)),513),e.createElementVNode("div",HD,[e.createElementVNode("button",{type:"button",onClick:m[7]||(m[7]=p=>n("bulk-add-to-album"))},e.toDisplayString(d.value.addToAlbum),1),e.createElementVNode("button",{type:"button",onClick:m[8]||(m[8]=p=>n("bulk-create-album"))},e.toDisplayString(d.value.createAlbum),1),e.createElementVNode("button",{type:"button",onClick:m[9]||(m[9]=p=>n("bulk-move-to-trash"))},e.toDisplayString(d.value.moveToTrash),1),e.createElementVNode("button",{type:"button",disabled:t.capabilities.allowDownloadZip!==!0,onClick:m[10]||(m[10]=p=>n("bulk-download"))},e.toDisplayString(d.value.download),9,ZD)])],64)):(e.openBlock(),e.createElementBlock("p",GD,e.toDisplayString(d.value.emptyTitle),1))],40,LD)}}}),Rf=Fe(XD,[["__scopeId","data-v-c39e7830"]]),KD={class:"media-filter-chips","data-testid":"media-filter-chips"},JD={class:"media-filter-chips__scroll"},qD={key:0,class:"media-filter-chips__chip media-filter-chips__chip--scope","data-testid":"media-filter-scope-chip"},YD=["data-testid","onClick"],QD={class:"media-filter-chips__add-wrap"},eR=["aria-expanded"],tR={key:0,class:"media-filter-chips__menu","data-testid":"media-filter-menu"},aR=e.defineComponent({__name:"MediaFilterChips",props:{filters:{},scopeLabel:{default:""},labels:{default:()=>({})}},emits:["update:filters","change","clear"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!1),r=e.computed(()=>{var k,g,b,R,N,T,S,B,A,x,M;return{addFilter:((k=t.labels)==null?void 0:k.addFilter)??"Filter",clearAll:((g=t.labels)==null?void 0:g.clearAll)??"Clear all filters",typeLabel:((b=t.labels)==null?void 0:b.typeLabel)??"Type",usageLabel:((R=t.labels)==null?void 0:R.usageLabel)??"Usage",imageLabel:((N=t.labels)==null?void 0:N.imageLabel)??"Image",videoLabel:((T=t.labels)==null?void 0:T.videoLabel)??"Video",usedLabel:((S=t.labels)==null?void 0:S.usedLabel)??"Used",notUsedLabel:((B=t.labels)==null?void 0:B.notUsedLabel)??"Not used",dateAfterLabel:((A=t.labels)==null?void 0:A.dateAfterLabel)??"After",dateBeforeLabel:((x=t.labels)==null?void 0:x.dateBeforeLabel)??"Before",searchLabel:((M=t.labels)==null?void 0:M.searchLabel)??"Search"}});function s(){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 l(k){n("update:filters",k),n("change",k)}function d(k){const g=s(),b=(g.kinds??[]).filter(R=>R!==k);b.length>0?g.kinds=b:delete g.kinds,l(g)}function c(k){const g=s(),b=new Set(g.kinds??[]);b.add(k),g.kinds=Array.from(b),l(g),i.value=!1}function u(){const k=s();delete k.usage_status,l(k)}function m(k){const g=s();g.usage_status=k,l(g),i.value=!1}function f(k){const g=new Date;return g.setHours(0,0,0,0),g.setDate(g.getDate()-k),g.toISOString()}function p(){const k=new Date;return new Date(k.getFullYear(),0,1).toISOString()}function h(k,g=null){const b=s();k===null?delete b.created_after:b.created_after=k,g===null?delete b.created_before:b.created_before=g,l(b),i.value=!1}function v(k){const g=s();delete g[k],l(g)}function E(){l({sort:t.filters.sort??"newest"}),n("clear")}const y=e.computed(()=>{const k=[];for(const g of t.filters.kinds??[]){const b=g==="image"?r.value.imageLabel:g==="video"?r.value.videoLabel:String(g);k.push({key:`kind-${g}`,label:`${r.value.typeLabel}: ${b}`,remove:()=>d(g)})}return(t.filters.usage_status==="used"||t.filters.usage_status==="not_used")&&k.push({key:"usage",label:`${r.value.usageLabel}: ${t.filters.usage_status==="used"?r.value.usedLabel:r.value.notUsedLabel}`,remove:u}),t.filters.created_after&&k.push({key:"created-after",label:`${r.value.dateAfterLabel}: ${t.filters.created_after}`,remove:()=>v("created_after")}),t.filters.created_before&&k.push({key:"created-before",label:`${r.value.dateBeforeLabel}: ${t.filters.created_before}`,remove:()=>v("created_before")}),t.filters.query&&t.filters.query.trim()!==""&&k.push({key:"query",label:`${r.value.searchLabel}: "${t.filters.query.trim()}"`,remove:()=>v("query")}),k});return(k,g)=>(e.openBlock(),e.createElementBlock("div",KD,[e.createElementVNode("div",JD,[t.scopeLabel!==""?(e.openBlock(),e.createElementBlock("span",qD,e.toDisplayString(t.scopeLabel),1)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(y.value,b=>(e.openBlock(),e.createElementBlock("button",{key:b.key,type:"button",class:"media-filter-chips__chip","data-testid":`media-filter-chip-${b.key}`,onClick:b.remove},[e.createElementVNode("span",null,e.toDisplayString(b.label),1),g[8]||(g[8]=e.createElementVNode("span",{"aria-hidden":"true"},"×",-1))],8,YD))),128)),y.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(r.value.clearAll),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",QD,[e.createElementVNode("button",{type:"button",class:"media-filter-chips__add","data-testid":"btn-media-filter-add","aria-expanded":i.value?"true":"false",onClick:g[0]||(g[0]=b=>i.value=!i.value)}," + "+e.toDisplayString(r.value.addFilter),9,eR),i.value?(e.openBlock(),e.createElementBlock("div",tR,[e.createElementVNode("button",{type:"button","data-testid":"opt-filter-image",onClick:g[1]||(g[1]=b=>c("image"))},e.toDisplayString(r.value.typeLabel)+": "+e.toDisplayString(r.value.imageLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-video",onClick:g[2]||(g[2]=b=>c("video"))},e.toDisplayString(r.value.typeLabel)+": "+e.toDisplayString(r.value.videoLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-used",onClick:g[3]||(g[3]=b=>m("used"))},e.toDisplayString(r.value.usageLabel)+": "+e.toDisplayString(r.value.usedLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-not-used",onClick:g[4]||(g[4]=b=>m("not_used"))},e.toDisplayString(r.value.usageLabel)+": "+e.toDisplayString(r.value.notUsedLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-date-7d",onClick:g[5]||(g[5]=b=>h(f(7)))},"Date: Last 7 days"),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-date-30d",onClick:g[6]||(g[6]=b=>h(f(30)))},"Date: Last 30 days"),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-date-year",onClick:g[7]||(g[7]=b=>h(p()))},"Date: This year")])):e.createCommentVNode("",!0)])]))}}),Af=Fe(aR,[["__scopeId","data-v-4861e8d7"]]);class Ad extends Error{constructor(a,t="Media deletion requires explicit confirmation."){super(t),this.name="RequiresConfirmationError",this.softBlocks=a}}const nR="/v1/media/deletion/check",oR="/v1/media/deletion/delete",br=100;function Uu(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 Lf(o){const a=o.checkEndpoint??nR,t=o.deleteEndpoint??oR,n=e.ref(!1),i=e.ref(!1),r=e.ref(null),s=e.ref(null),l=e.ref(null);async function d(p){l.value=null;const h=Uu(p);if(h.length===0)return r.value=[],[];if(h.length>br){const v=new Error(`Cannot check more than ${br} media items at once.`);throw l.value=v,v}n.value=!0;try{const v=await o.httpClient.post(a,{uuids:h}),E=((v==null?void 0:v.data)??[]).map(y=>{var k,g,b,R;return{uuid:y.uuid,canDelete:((k=y.report)==null?void 0:k.canDelete)??!1,blocks:Array.isArray((g=y.report)==null?void 0:g.blocks)?y.report.blocks:[],cascade:Array.isArray((b=y.report)==null?void 0:b.cascade)?y.report.cascade:[],variantCount:typeof((R=y.report)==null?void 0:R.variantCount)=="number"?y.report.variantCount:0}});return r.value=E,E}catch(v){throw l.value=v instanceof Error?v:new Error(String(v)),l.value}finally{n.value=!1}}async function c(p,h={}){l.value=null;const v=Uu(p);if(v.length===0){const E={results:[],summary:{}};return s.value=E,E}if(v.length>br){const E=new Error(`Cannot delete more than ${br} media items at once.`);throw l.value=E,E}i.value=!0;try{const E=await o.httpClient.post(t,{uuids:v,force:h.force===!0,confirmed:h.confirmed===!0}),y={results:Array.isArray(E==null?void 0:E.results)?E.results:[],summary:(E==null?void 0:E.summary)??{}};return s.value=y,y}catch(E){const y=u(E);if(y&&y.requires_confirmation===!0){const k=m(y.soft_blocks),g=new Ad(k);throw l.value=g,g}throw l.value=E instanceof Error?E:new Error(String(E)),l.value}finally{i.value=!1}}function u(p){if(typeof p!="object"||p===null)return null;const h=p;if(h.response&&typeof h.response=="object"&&h.response.data&&typeof h.response.data=="object")return h.response.data;const v=p;return"requires_confirmation"in v||"soft_blocks"in v?v:null}function m(p){if(typeof p!="object"||p===null)return{};const h={};for(const[v,E]of Object.entries(p)){if(!Array.isArray(E))continue;const y=[];for(const k of E){if(typeof k!="object"||k===null)continue;const g=k;typeof g.type=="string"&&typeof g.context=="string"&&y.push({type:g.type,context:g.context})}h[v]=y}return h}function f(){r.value=null,s.value=null,l.value=null}return{isChecking:n,isDeleting:i,lastReport:r,lastResponse:s,error:l,checkDependencies:d,deleteMany:c,reset:f}}const iR="/v1/user/media/trash";function rR(o){return`/v1/user/media/${encodeURIComponent(o)}/restore`}function sR(o){return`/v1/user/media/${encodeURIComponent(o)}/purge`}function Ld(o){const a=o.listEndpoint??iR,t=o.buildRestoreEndpoint??rR,n=o.buildPurgeEndpoint??sR,i=o.perPage??50,r=e.ref([]),s=e.ref(0),l=e.ref(1),d=e.ref(!1),c=e.ref(!1),u=e.ref(!1),m=e.ref(null);async function f(E=1){var y,k;m.value=null,d.value=!0;try{const g=await o.httpClient.get(a,{params:{page:E,per_page:i}});r.value=Array.isArray(g==null?void 0:g.data)?g.data:[],s.value=typeof((y=g==null?void 0:g.meta)==null?void 0:y.total)=="number"?g.meta.total:0,l.value=typeof((k=g==null?void 0:g.meta)==null?void 0:k.current_page)=="number"?g.meta.current_page:E}catch(g){throw m.value=g instanceof Error?g:new Error(String(g)),m.value}finally{d.value=!1}}async function p(E){m.value=null,c.value=!0;try{const y=await o.httpClient.post(t(E)),k={status:(y==null?void 0:y.status)??"failed",data:(y==null?void 0:y.data)??null,duplicate_uuid:(y==null?void 0:y.duplicate_uuid)??null};return typeof(y==null?void 0:y.message)=="string"&&(k.message=y.message),k.status==="restored"&&(r.value=r.value.filter(g=>g.uuid!==E),s.value=Math.max(0,s.value-1)),k}catch(y){const k=Ou(y);if(k&&typeof k.status=="string"){const g={status:k.status,duplicate_uuid:typeof k.duplicate_uuid=="string"?k.duplicate_uuid:null};return typeof k.message=="string"&&(g.message=k.message),g}throw m.value=y instanceof Error?y:new Error(String(y)),m.value}finally{c.value=!1}}async function h(E){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 y=await o.httpClient.delete(n(E)),k={status:(y==null?void 0:y.status)??"failed"};return typeof(y==null?void 0:y.message)=="string"&&(k.message=y.message),k.status==="purging"&&(r.value=r.value.filter(g=>g.uuid!==E),s.value=Math.max(0,s.value-1)),k}catch(y){const k=Ou(y);if(k&&typeof k.status=="string"){const g={status:k.status};return typeof k.message=="string"&&(g.message=k.message),g}throw m.value=y instanceof Error?y:new Error(String(y)),m.value}finally{u.value=!1}}function v(){r.value=[],s.value=0,l.value=1,m.value=null}return{items:r,total:s,currentPage:l,isLoading:d,isRestoring:c,isPurging:u,error:m,fetch:f,restore:p,purge:h,reset:v}}function Ou(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 lR={class:"media-management-view","data-testid":"media-management-view"},dR={key:0,class:"media-management-view__header"},cR={class:"media-management-view__title"},uR={class:"media-management-view__actions"},mR={key:0,class:"media-management-view__badge"},pR={key:1,class:"media-management-view__panel","data-testid":"panel-library"},fR={key:0,class:"media-management-view__view-mode",role:"radiogroup","aria-label":"Media library layout","data-testid":"media-management-layout-mode"},hR=["aria-checked"],vR=["aria-checked"],gR={key:1,class:"media-management-view__status","data-testid":"library-loading"},bR={key:2,class:"media-management-view__status media-management-view__status--error","data-testid":"library-error"},yR={key:3,class:"media-management-view__empty","data-testid":"library-empty"},wR={class:"media-management-view__empty-state"},kR={class:"media-management-view__empty-title","data-testid":"library-empty-title"},_R={class:"media-management-view__empty-description","data-testid":"library-empty-description"},ER={key:4,class:"media-management-view__table","data-testid":"library-table"},SR={scope:"col","data-testid":"table-header-select"},CR={class:"media-management-view__checkbox-label"},xR=["checked",".indeterminate","aria-label"],VR={class:"media-management-view__sr-only"},NR={scope:"col","data-testid":"table-header-thumbnail"},TR={scope:"col","data-testid":"table-header-name"},BR={scope:"col","data-testid":"table-header-type"},MR={scope:"col","data-testid":"table-header-created"},IR={scope:"col","data-testid":"table-header-size"},$R={scope:"col","data-testid":"table-header-status"},FR={scope:"col","data-testid":"table-header-actions"},DR=["data-testid"],RR={class:"media-management-view__checkbox-label"},AR=["checked","aria-label","data-testid","onChange"],LR=["data-testid","onClick"],PR=["src","alt","onError"],UR=["data-testid"],OR=["title","data-testid"],zR=["data-testid"],jR=["data-testid"],WR={class:"media-management-view__item-actions"},HR=["onKeydown"],ZR=["data-testid","aria-label","aria-expanded","onClick"],GR=["data-testid"],XR=["data-testid","onClick"],KR={key:5,class:"media-management-view__grid","data-testid":"library-grid"},JR=["data-testid"],qR=["data-testid","aria-pressed","onClick"],YR=["src","alt","onError"],QR=["data-testid"],eA={class:"media-management-view__selection-corner"},tA={class:"media-management-view__sr-only"},aA=["checked","data-testid","onChange"],nA={class:"media-management-view__item-meta"},oA=["title","data-testid"],iA=["data-testid"],rA=["data-testid"],sA={key:2,class:"media-management-view__item-badge","data-testid":"badge-orphaned"},lA=["data-testid"],dA={class:"media-management-view__item-actions media-management-view__item-actions--grid"},cA=["onKeydown"],uA=["data-testid","aria-label","aria-expanded","onClick"],mA=["data-testid"],pA=["data-testid","onClick"],fA={class:"media-management-view__bulk-bar","data-testid":"bulk-bar"},hA={"data-testid":"bulk-count"},vA=["disabled"],gA={key:7,class:"media-management-view__pagination","data-testid":"media-management-pagination"},bA={class:"media-management-view__pagination-count","data-testid":"media-management-pagination-count","aria-live":"polite"},yA={key:0,class:"media-management-view__page-size",role:"group","aria-label":"Items per page","data-testid":"media-management-page-size"},wA=["value","disabled"],kA=["value","data-testid"],_A=["disabled"],EA={key:2,class:"media-management-view__page-bar","aria-label":"Media library pagination","data-testid":"media-management-page-bar"},SA=["disabled"],CA=["data-testid","disabled","aria-current","aria-label","onClick"],xA=["disabled"],VA={key:2,class:"media-management-view__panel","data-testid":"panel-trash"},NA={key:0,class:"media-management-view__status","data-testid":"trash-loading"},TA={key:1,class:"media-management-view__empty","data-testid":"trash-empty"},BA={class:"media-management-view__empty-state"},MA={class:"media-management-view__empty-title","data-testid":"trash-empty-title"},IA={class:"media-management-view__empty-description","data-testid":"trash-empty-description"},$A={key:2,class:"media-management-view__grid","data-testid":"trash-grid"},FA=["data-testid"],DA={class:"media-management-view__item-thumb"},RA=["src","alt","onError"],AA=["data-testid"],LA={class:"media-management-view__item-meta"},PA={class:"media-management-view__item-name"},UA={key:0,class:"media-management-view__item-meta-line"},OA=["data-testid","disabled","onClick"],zA=["data-testid"],jA=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})),s=e.computed(()=>{var X,ye,te,De,Tt,Dt,Bt,pt,ft,qt,wt,Ot,_a,G,J,me,pe,Ne,We,st,Ye,He,ut,ht,tt,Yt,It,Pa,Fa,co,Da,on,Ua,ha,Mn,uo,In,mo,hn;return{title:((X=n.labels)==null?void 0:X.title)??"My Media",libraryTab:((ye=n.labels)==null?void 0:ye.libraryTab)??"Library",trashTab:((te=n.labels)==null?void 0:te.trashTab)??"Trash",loading:((De=n.labels)==null?void 0:De.loading)??"Loading…",emptyLibrary:((Tt=n.labels)==null?void 0:Tt.emptyLibrary)??"No media yet — upload your first creation.",emptyLibraryTitle:((Dt=n.labels)==null?void 0:Dt.emptyLibraryTitle)??"Your media library is ready",emptyLibraryDescription:((Bt=n.labels)==null?void 0:Bt.emptyLibraryDescription)??"Images and videos you upload for creations are saved here so you can reuse them later.",emptyTrash:((pt=n.labels)==null?void 0:pt.emptyTrash)??"Trash is empty.",emptyTrashTitle:((ft=n.labels)==null?void 0:ft.emptyTrashTitle)??"No media in trash",emptyTrashDescription:((qt=n.labels)==null?void 0:qt.emptyTrashDescription)??"Deleted files appear here for 30 days before permanent removal.",orphanedBadge:((wt=n.labels)==null?void 0:wt.orphanedBadge)??"Not in use",selectedCount:((Ot=n.labels)==null?void 0:Ot.selectedCount)??(Oa=>`${Oa} selected`),deleteButton:((_a=n.labels)==null?void 0:_a.deleteButton)??"Delete",createPostButton:((G=n.labels)==null?void 0:G.createPostButton)??"Create Post",createGalleryButton:((J=n.labels)==null?void 0:J.createGalleryButton)??"Create Gallery",addToAlbumButton:((me=n.labels)==null?void 0:me.addToAlbumButton)??"Add to Album",previewButton:((pe=n.labels)==null?void 0:pe.previewButton)??"Preview",previewCloseButton:((Ne=n.labels)==null?void 0:Ne.previewCloseButton)??"Close",previewPreviousButton:((We=n.labels)==null?void 0:We.previewPreviousButton)??"Previous",previewNextButton:((st=n.labels)==null?void 0:st.previewNextButton)??"Next",previewSelectButton:((Ye=n.labels)==null?void 0:Ye.previewSelectButton)??"Select",previewDeselectButton:((He=n.labels)==null?void 0:He.previewDeselectButton)??"Deselect",editButton:((ut=n.labels)==null?void 0:ut.editButton)??"Edit",loadMoreButton:((ht=n.labels)==null?void 0:ht.loadMoreButton)??"Load more",loadingMoreButton:((tt=n.labels)==null?void 0:tt.loadingMoreButton)??"Loading more...",restoreButton:((Yt=n.labels)==null?void 0:Yt.restoreButton)??"Restore",restoreUnavailable:((It=n.labels)==null?void 0:It.restoreUnavailable)??"Restore unavailable",gridView:((Pa=n.labels)==null?void 0:Pa.gridView)??"Grid",tableView:((Fa=n.labels)==null?void 0:Fa.tableView)??"Table",tableSelectHeader:((co=n.labels)==null?void 0:co.tableSelectHeader)??"Select",tableThumbnailHeader:((Da=n.labels)==null?void 0:Da.tableThumbnailHeader)??"Preview",tableNameHeader:((on=n.labels)==null?void 0:on.tableNameHeader)??"Name",tableTypeHeader:((Ua=n.labels)==null?void 0:Ua.tableTypeHeader)??"Type",tableCreatedHeader:((ha=n.labels)==null?void 0:ha.tableCreatedHeader)??"Uploaded",tableSizeHeader:((Mn=n.labels)==null?void 0:Mn.tableSizeHeader)??"Size",tableStatusHeader:((uo=n.labels)==null?void 0:uo.tableStatusHeader)??"Status",tableActionsHeader:((In=n.labels)==null?void 0:In.tableActionsHeader)??"Actions",purgeAfter:((mo=n.labels)==null?void 0:mo.purgeAfter)??(Oa=>`Purges ${Oa}`),ownerLabel:((hn=n.labels)==null?void 0:hn.ownerLabel)??(Oa=>`User ${Oa.user_id??""}`)}}),l=e.computed(()=>s.value.title),d=e.computed(()=>s.value.libraryTab),c=e.computed(()=>s.value.trashTab),u=e.computed(()=>s.value.loading),m=e.computed(()=>s.value.emptyLibraryTitle),f=e.computed(()=>s.value.emptyLibraryDescription),p=e.computed(()=>s.value.emptyTrashTitle),h=e.computed(()=>s.value.emptyTrashDescription),v=e.computed(()=>s.value.orphanedBadge),E=e.computed(()=>s.value.deleteButton),y=e.computed(()=>s.value.restoreButton),k=e.computed(()=>s.value.restoreUnavailable),g=e.computed(()=>s.value.gridView),b=e.computed(()=>s.value.tableView);function R(X){const ye=r.value.canRestore;return ye?ye(X):!0}const N=e.ref("library"),T=e.ref(n.layoutMode??n.initialLayoutMode??"grid"),S=e.ref(null),B=e.ref(null);function A(X){return{...X??{},...(X==null?void 0:X.kinds)!==void 0?{kinds:[...X.kinds]}:{}}}const x=e.ref(n.initialView??{scope:"library"}),M=e.ref(A(n.filters)),w=e.ref(n.perPage??50),F=e.ref(!1),P=e.ref(n.paginated?1:null),D=Dd({httpClient:n.httpClient,view:x,filters:M,perPage:w,page:P}),O=e.computed(()=>n.groupVariants!==!0?D.items.value:D.items.value.filter(X=>typeof X.parent_media_uuid!="string"||X.parent_media_uuid.trim()==="")),I=e.computed(()=>D.loading.value),Z=e.computed(()=>{var X;return((X=D.error.value)==null?void 0:X.message)??null}),z=e.computed(()=>r.value.allowBulkDelete!==!1||r.value.allowCreatePost===!0||r.value.allowCreateGallery===!0||r.value.allowAddToAlbum===!0),K=e.computed(()=>{const X=S.value;return X===null?null:O.value[X]??null}),se=es(O),Be=Lf({httpClient:n.httpClient}),ce=Ld({httpClient:n.httpClient});function ie(X){return s.value.selectedCount(X)}function W(X){return s.value.purgeAfter(X)}function C(X){return s.value.ownerLabel(X)}const U=e.computed(()=>{const X=O.value.length;return X===0?"":D.hasMore.value?X===1?"Showing 1 item":`Showing ${X} items`:X===1?"Showing all 1 item":`Showing all ${X} items`});function j(X){T.value!==X&&(Jt(),T.value=X,i("update:layoutMode",X))}function ne(X){return X.mime_type.startsWith("image/")}function de(X){return X.mime_type.startsWith("video/")}function Ke(X){return ne(X)?"image":de(X)?"video":null}function be(X){return ne(X)?r.value.allowImageEdit===!0:de(X)?r.value.allowVideoEdit===!0:!1}const _e=Df;function ve(X){return typeof X.variant_count=="number"&&Number.isFinite(X.variant_count)?Math.max(0,X.variant_count):0}function xe(X){return X===1?"1 edit":`${X} edits`}function Se(X){return ne(X)?"Image":de(X)?"Video":X.mime_type.startsWith("audio/")?"Audio":"File"}function Ae(X){if(typeof X.formatted_size=="string"&&X.formatted_size.trim()!=="")return X.formatted_size;if(!Number.isFinite(X.size)||X.size<=0)return"";const ye=["B","KB","MB","GB"];let te=X.size,De=0;for(;te>=1024&&De<ye.length-1;)te/=1024,De+=1;return`${te>=10||De===0?Math.round(te):te.toFixed(1)} ${ye[De]}`}function re(X){const ye=new Date(X.created_at);return Number.isNaN(ye.getTime())?X.created_at:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(ye)}function ge(X){return X.deletion_status==="active"||X.deletion_status===void 0||X.deletion_status===null?"Ready":X.deletion_status.replace(/_/g," ").replace(/\b\w/g,ye=>ye.toUpperCase())}function Ge(X){if(typeof X.thumbnail_url=="string"&&X.thumbnail_url.length>0)return X.thumbnail_url;const ye=typeof X.mime_type=="string"&&X.mime_type.startsWith("image/"),te=typeof X.mime_type=="string"&&X.mime_type.startsWith("video/");return ye?X.original_url||null:te&&typeof X.preview_url=="string"&&X.preview_url.length>0?X.preview_url:null}function Ve(X){return typeof X.mime_type=="string"&&X.mime_type.startsWith("video/")?`Video — ${X.file_name}`:X.file_name}const at=e.ref(new Set);function rt(X){if(at.value.has(X.uuid))return;const ye=new Set(at.value);ye.add(X.uuid),at.value=ye}function gt(X){if(r.value.allowPreview===!1)return;const ye=O.value.findIndex(te=>te.uuid===X.uuid);S.value=ye>=0?ye:null}function lt(){S.value=null}function Et(){S.value===null||S.value<=0||(S.value-=1)}function Ee(){S.value===null||S.value>=O.value.length-1||(S.value+=1)}async function Ce(){try{await D.loadMore()}catch(X){i("error",X instanceof Error?X:new Error(String(X)))}}const Re=e.computed(()=>{const X=D.totalPages.value??0,ye=D.currentPage.value??1;if(X<=1)return[];const te=Math.max(3,n.paginationWindow);if(X<=te)return Array.from({length:X},(ft,qt)=>({kind:"page",key:`p-${qt+1}`,value:qt+1}));const De=te-2,Tt=Math.floor(De/2);let Dt=Math.max(2,ye-Tt),Bt=Math.min(X-1,Dt+De-1);Bt===X-1&&(Dt=Math.max(2,Bt-De+1));const pt=[{kind:"page",key:"p-1",value:1}];Dt>2&&pt.push({kind:"ellipsis",key:"el-left"});for(let ft=Dt;ft<=Bt;ft++)pt.push({kind:"page",key:`p-${ft}`,value:ft});return Bt<X-1&&pt.push({kind:"ellipsis",key:"el-right"}),pt.push({kind:"page",key:`p-${X}`,value:X}),pt});async function et(X){if(!(X===D.currentPage.value||D.loading.value)){P.value=X;try{await D.goToPage(X)}catch(ye){i("error",ye instanceof Error?ye:new Error(String(ye)))}}}async function qe(X){const ye=D.currentPage.value??1,te=D.totalPages.value??1,De=Math.min(Math.max(1,ye+X),te);De!==ye&&await et(De)}const Ze=e.computed(()=>{const X=n.pageSizeOptions.map(ye=>({value:String(ye),label:String(ye)}));return X.length===0&&!n.showAllOption?[]:(n.showAllOption&&X.push({value:"all",label:"All"}),X)}),bt=e.computed(()=>F.value?"all":String(w.value));async function ct(X){const ye=X.target;if(!(ye instanceof HTMLSelectElement))return;const te=ye.value;try{if(te==="all"){const De=n.pageSizeOptions,Tt=De.length>0?Math.max(...De):w.value;P.value=null,w.value=Tt,F.value=!1,await D.refresh();const Dt=n.loadAllMaxItems!==void 0?{maxItems:n.loadAllMaxItems}:void 0;await D.loadAll(Dt),F.value=!D.hasMore.value}else{const De=Number.parseInt(te,10);Number.isFinite(De)&&De>0&&(w.value=De),F.value=!1,n.paginated&&(P.value=1),await D.refresh()}}catch(De){i("error",De instanceof Error?De:new Error(String(De)))}}function At(X,ye){i("create-post",{mediaIds:X.map(te=>te.uuid),items:X,source:ye})}function $t(X,ye){i("create-gallery",{mediaIds:X.map(te=>te.uuid),items:X,source:ye})}function Pt(X,ye){i("add-to-album",{mediaIds:X.map(te=>te.uuid),items:X,source:ye})}function Ut(X){const ye=Ke(X);ye===null||!be(X)||i("edit",{media:X,kind:ye})}function ea(X){B.value=B.value===X?null:X}function Jt(){B.value=null}function ta(X){X.run(),Jt()}function fa(X){const ye=[];return r.value.allowPreview!==!1&&ye.push({id:"preview",label:s.value.previewButton,testId:`btn-preview-${X.uuid}`,run:()=>gt(X)}),be(X)&&ye.push({id:"edit",label:s.value.editButton,testId:`btn-edit-${X.uuid}`,run:()=>Ut(X)}),r.value.allowCreatePost===!0&&ye.push({id:"create-post",label:s.value.createPostButton,testId:`btn-create-post-${X.uuid}`,run:()=>At([X],"item")}),r.value.allowCreateGallery===!0&&ye.push({id:"create-gallery",label:s.value.createGalleryButton,testId:`btn-create-gallery-${X.uuid}`,run:()=>$t([X],"item")}),r.value.allowAddToAlbum===!0&&ye.push({id:"add-to-album",label:s.value.addToAlbumButton,testId:`btn-add-to-album-${X.uuid}`,run:()=>Pt([X],"item")}),ye}async function Q(X){const ye=X.results.filter(te=>te.status==="trashed"||te.status==="already_trashed").map(te=>te.uuid);if(ye.length!==0){for(const te of ye)se.deselect(te);i("deleted",ye),await D.refresh(),r.value.showTrash!==!1&&await ce.fetch(ce.currentPage.value).catch(()=>{})}}function he(X){const ye=new Set;for(const Tt of X)for(const Dt of Tt.blocks)Dt.context&&ye.add(Dt.context);const te=Array.from(ye),De=te.length>0?`This media is still attached to: ${te.map(Tt=>`"${Tt}"`).join(", ")}. Remove from those and delete?`:"This media is still attached to other items. Remove from those and delete?";return window.confirm(De)}function ue(X){return Object.entries(X).map(([ye,te])=>({uuid:ye,blocks:te}))}async function le(){const X=se.selectedItems.value;if(X.length===0)return;const ye=r.value.canDelete?X.filter(De=>r.value.canDelete(De)):X;if(ye.length===0||n.confirmBulkDelete&&!await n.confirmBulkDelete(ye))return;const te=ye.map(De=>De.uuid);try{const De=await Be.deleteMany(te);await Q(De)}catch(De){if(De instanceof Ad){const Tt=ue(De.softBlocks);if(!(n.confirmDestructiveAction?await n.confirmDestructiveAction({items:ye,softBlocks:Tt}):he(Tt)))return;try{const Bt=await Be.deleteMany(te,{confirmed:!0});await Q(Bt)}catch(Bt){i("error",Bt instanceof Error?Bt:new Error(String(Bt)))}return}i("error",De instanceof Error?De:new Error(String(De)))}}async function Te(X){var te;const ye=ce.items.value.find(De=>De.uuid===X);if(!(ye&&!R(ye)))try{const De=await ce.restore(X);if(De.status==="restored"){i("restored",X),await D.refresh().catch(()=>{});return}if(De.status==="duplicate_conflict"){i("restore-conflict",{uuid:X,duplicateUuid:De.duplicate_uuid??null}),(te=n.onRestoreCollision)==null||te.call(n,X,De.duplicate_uuid??null);return}}catch(De){i("error",De instanceof Error?De:new Error(String(De)))}}async function ze(){N.value="trash",ce.items.value.length===0&&!ce.isLoading.value&&await ce.fetch().catch(X=>{i("error",X instanceof Error?X:new Error(String(X)))})}function ot(X){if(X==="trash"){ze();return}N.value=X}const St=e.computed(()=>({activeTab:N.value,setActiveTab:ot,trashCount:ce.total.value,showTrash:r.value.showTrash!==!1,labels:{libraryTab:s.value.libraryTab,trashTab:s.value.trashTab}})),Ft=e.computed(()=>({selectedCount:se.selectedCount.value,selectedItemIds:Array.from(se.selectedIds.value),selectedItems:se.selectedItems.value,crossPageCount:se.crossPageCount.value,isDeleting:Be.isDeleting.value,onBulkDelete:le,...r.value.allowCreatePost===!0?{onCreatePost:()=>At(se.selectedItems.value,"bulk")}:{},...r.value.allowCreateGallery===!0?{onCreateGallery:()=>$t(se.selectedItems.value,"bulk")}:{},...r.value.allowAddToAlbum===!0?{onAddToAlbum:()=>Pt(se.selectedItems.value,"bulk")}:{},clearSelection:se.clear,labels:{deleteButton:s.value.deleteButton,...r.value.allowCreatePost===!0?{createPostButton:s.value.createPostButton}:{},...r.value.allowCreateGallery===!0?{createGalleryButton:s.value.createGalleryButton}:{},...r.value.allowAddToAlbum===!0?{addToAlbumButton:s.value.addToAlbumButton}:{},selectedCount:s.value.selectedCount}})),Vt=e.computed(()=>({filters:M.value,view:x.value,total:D.total.value,shown:O.value.length,loading:D.loading.value}));function Ct(X){return{media:X,selected:se.isSelected(X.uuid),canEdit:be(X),onPreview:()=>gt(X),...be(X)?{onEdit:()=>Ut(X)}:{},...r.value.allowCreatePost===!0?{onCreatePost:()=>At([X],"item")}:{},...r.value.allowCreateGallery===!0?{onCreateGallery:()=>$t([X],"item")}:{},...r.value.allowAddToAlbum===!0?{onAddToAlbum:()=>Pt([X],"item")}:{},labels:{previewButton:s.value.previewButton,editButton:s.value.editButton,createPostButton:s.value.createPostButton,createGalleryButton:s.value.createGalleryButton,addToAlbumButton:s.value.addToAlbumButton}}}function Ht(X){return{media:X,canRestore:R(X),isRestoring:ce.isRestoring.value,onRestore:()=>Te(X.uuid),labels:{restoreButton:s.value.restoreButton,restoreUnavailable:s.value.restoreUnavailable}}}return e.watch(N,async X=>{X==="library"&&O.value.length===0&&!I.value&&await D.refresh().catch(()=>{})}),e.watch(()=>n.layoutMode,X=>{X!==void 0&&(T.value=X)}),e.watch(()=>n.filters,async X=>{M.value=A(X),se.clear(),lt(),await D.refresh().catch(ye=>{i("error",ye instanceof Error?ye:new Error(String(ye)))})},{deep:!0}),e.onMounted(async()=>{await D.refresh().catch(X=>{i("error",X instanceof Error?X:new Error(String(X)))}),r.value.showTrash!==!1&&ce.fetch().catch(()=>{})}),a({refresh:()=>D.refresh(),refreshTrash:()=>ce.fetch(),selection:se,deletion:Be,trash:ce}),(X,ye)=>(e.openBlock(),e.createElementBlock("div",lR,[r.value.showHeader!==!1?(e.openBlock(),e.createElementBlock("header",dR,[e.createElementVNode("h2",cR,e.toDisplayString(l.value),1),e.createElementVNode("div",uR,[e.renderSlot(X.$slots,"tabs",e.normalizeProps(e.guardReactiveProps(St.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":N.value==="library"}]),"data-testid":"tab-library",onClick:ye[0]||(ye[0]=te=>N.value="library")},e.toDisplayString(d.value),3),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["media-management-view__tab-button",{"is-active":N.value==="trash"}]),"data-testid":"tab-trash",onClick:ze},[e.createTextVNode(e.toDisplayString(c.value)+" ",1),e.unref(ce).total.value>0?(e.openBlock(),e.createElementBlock("span",mR,e.toDisplayString(e.unref(ce).total.value),1)):e.createCommentVNode("",!0)],2)],64)):e.createCommentVNode("",!0)],!0)])])):e.createCommentVNode("",!0),N.value==="library"?(e.openBlock(),e.createElementBlock("section",pR,[r.value.showLayoutSwitcher!==!1?(e.openBlock(),e.createElementBlock("div",fR,[e.createElementVNode("button",{type:"button",role:"radio",class:e.normalizeClass(["media-management-view__view-mode-button",{"is-active":T.value==="grid"}]),"aria-checked":T.value==="grid"?"true":"false","data-testid":"view-mode-grid",onClick:ye[1]||(ye[1]=te=>j("grid"))},e.toDisplayString(g.value),11,hR),e.createElementVNode("button",{type:"button",role:"radio",class:e.normalizeClass(["media-management-view__view-mode-button",{"is-active":T.value==="table"}]),"aria-checked":T.value==="table"?"true":"false","data-testid":"view-mode-table",onClick:ye[2]||(ye[2]=te=>j("table"))},e.toDisplayString(b.value),11,vR)])):e.createCommentVNode("",!0),e.renderSlot(X.$slots,"filter-bar",e.normalizeProps(e.guardReactiveProps(Vt.value)),void 0,!0),I.value?(e.openBlock(),e.createElementBlock("div",gR,e.toDisplayString(u.value),1)):Z.value?(e.openBlock(),e.createElementBlock("div",bR,e.toDisplayString(Z.value),1)):O.value.length===0?(e.openBlock(),e.createElementBlock("div",yR,[e.renderSlot(X.$slots,"empty-library",{},()=>[e.createElementVNode("div",wR,[e.createElementVNode("p",kR,e.toDisplayString(m.value),1),e.createElementVNode("p",_R,e.toDisplayString(f.value),1)])],!0)])):T.value==="table"?(e.openBlock(),e.createElementBlock("table",ER,[e.createElementVNode("thead",null,[e.createElementVNode("tr",null,[e.createElementVNode("th",SR,[e.createElementVNode("label",CR,[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":s.value.tableSelectHeader,"data-testid":"checkbox-select-all",onChange:ye[3]||(ye[3]=(...te)=>e.unref(se).toggleAll&&e.unref(se).toggleAll(...te))},null,40,xR),e.createElementVNode("span",VR,e.toDisplayString(s.value.tableSelectHeader),1)])]),e.createElementVNode("th",NR,e.toDisplayString(s.value.tableThumbnailHeader),1),e.createElementVNode("th",TR,e.toDisplayString(s.value.tableNameHeader),1),e.createElementVNode("th",BR,e.toDisplayString(s.value.tableTypeHeader),1),e.createElementVNode("th",MR,e.toDisplayString(s.value.tableCreatedHeader),1),e.createElementVNode("th",IR,e.toDisplayString(s.value.tableSizeHeader),1),e.createElementVNode("th",$R,e.toDisplayString(s.value.tableStatusHeader),1),e.createElementVNode("th",FR,e.toDisplayString(s.value.tableActionsHeader),1)])]),e.createElementVNode("tbody",null,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(O.value,te=>(e.openBlock(),e.createElementBlock("tr",{key:te.uuid,class:e.normalizeClass({"is-selected":e.unref(se).isSelected(te.uuid),"has-open-actions":B.value===te.uuid}),"data-testid":`media-row-${te.uuid}`},[e.createElementVNode("td",null,[e.createElementVNode("label",RR,[e.createElementVNode("input",{class:"media-management-view__checkbox",type:"checkbox",checked:e.unref(se).isSelected(te.uuid),"aria-label":`${s.value.tableSelectHeader} ${e.unref(_e)(te)}`,"data-testid":`checkbox-select-${te.uuid}`,onChange:De=>e.unref(se).toggle(te.uuid)},null,40,AR)])]),e.createElementVNode("td",null,[e.createElementVNode("button",{type:"button",class:"media-management-view__table-thumb","data-testid":`btn-preview-thumb-${te.uuid}`,onClick:De=>gt(te)},[Ge(te)&&!at.value.has(te.uuid)?(e.openBlock(),e.createElementBlock("img",{key:0,src:Ge(te)??"",alt:te.alt_text||te.file_name,loading:"lazy",onError:De=>rt(te)},null,40,PR)):(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__item-placeholder","data-testid":`placeholder-${te.uuid}`},e.toDisplayString(Ve(te)),9,UR))],8,LR)]),e.createElementVNode("td",null,[e.createElementVNode("span",{class:"media-management-view__display-name",title:te.file_name,"data-testid":`media-display-name-${te.uuid}`},e.toDisplayString(e.unref(_e)(te)),9,OR),ve(te)>0?(e.openBlock(),e.createElementBlock("span",{key:0,class:"media-management-view__variant-badge","data-testid":`media-variant-badge-${te.uuid}`},e.toDisplayString(xe(ve(te))),9,zR)):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-${te.uuid}`},e.toDisplayString(te.file_name),9,jR)):e.createCommentVNode("",!0)]),e.createElementVNode("td",null,e.toDisplayString(Se(te)),1),e.createElementVNode("td",null,e.toDisplayString(re(te)),1),e.createElementVNode("td",null,e.toDisplayString(Ae(te)),1),e.createElementVNode("td",null,e.toDisplayString(ge(te)),1),e.createElementVNode("td",null,[e.renderSlot(X.$slots,"item-actions",e.mergeProps({ref_for:!0},Ct(te)),()=>[e.createElementVNode("div",WR,[e.createElementVNode("div",{class:"media-management-view__action-menu",onKeydown:e.withKeys(e.withModifiers(Jt,["stop"]),["escape"])},[e.createElementVNode("button",{type:"button",class:"media-management-view__action-menu-trigger","data-testid":`btn-actions-menu-${te.uuid}`,"aria-label":`Actions for ${e.unref(_e)(te)}`,"aria-haspopup":"menu","aria-expanded":B.value===te.uuid?"true":"false",onClick:De=>ea(te.uuid)}," ... ",8,ZR),B.value===te.uuid?(e.openBlock(),e.createElementBlock("div",{key:0,class:"media-management-view__action-menu-panel",role:"menu","data-testid":`media-item-actions-menu-${te.uuid}`},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(fa(te),De=>(e.openBlock(),e.createElementBlock("button",{key:De.id,type:"button",class:"media-management-view__action-menu-item",role:"menuitem","data-testid":De.testId,onClick:Tt=>ta(De)},e.toDisplayString(De.label),9,XR))),128))],8,GR)):e.createCommentVNode("",!0)],40,HR)])],!0)])],10,DR))),128))])])):(e.openBlock(),e.createElementBlock("ul",KR,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(O.value,te=>(e.openBlock(),e.createElementBlock("li",{key:te.uuid,class:e.normalizeClass(["media-management-view__item",{"is-selected":e.unref(se).isSelected(te.uuid),"has-open-actions":B.value===te.uuid}]),"data-testid":`media-item-${te.uuid}`},[e.createElementVNode("button",{type:"button",class:"media-management-view__item-thumb","data-testid":`btn-select-${te.uuid}`,"aria-pressed":e.unref(se).isSelected(te.uuid),onClick:De=>e.unref(se).toggle(te.uuid)},[Ge(te)&&!at.value.has(te.uuid)?(e.openBlock(),e.createElementBlock("img",{key:0,src:Ge(te)??"",alt:te.alt_text||te.file_name,loading:"lazy",onError:De=>rt(te)},null,40,YR)):(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__item-placeholder","data-testid":`placeholder-${te.uuid}`},e.toDisplayString(Ve(te)),9,QR))],8,qR),e.createElementVNode("label",eA,[e.createElementVNode("span",tA,e.toDisplayString(s.value.tableSelectHeader)+" "+e.toDisplayString(e.unref(_e)(te)),1),e.createElementVNode("input",{class:"media-management-view__checkbox media-management-view__checkbox--overlay",type:"checkbox",checked:e.unref(se).isSelected(te.uuid),"data-testid":`checkbox-select-${te.uuid}`,onClick:ye[4]||(ye[4]=e.withModifiers(()=>{},["stop"])),onChange:De=>e.unref(se).toggle(te.uuid)},null,40,aA)]),e.createElementVNode("div",nA,[e.createElementVNode("span",{class:"media-management-view__item-name",title:te.file_name,"data-testid":`media-display-name-${te.uuid}`},e.toDisplayString(e.unref(_e)(te)),9,oA),r.value.showRawFileName===!0?(e.openBlock(),e.createElementBlock("span",{key:0,class:"media-management-view__raw-filename","data-testid":`media-raw-filename-${te.uuid}`},e.toDisplayString(te.file_name),9,iA)):e.createCommentVNode("",!0),r.value.showOwner&&te.user_id?(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__item-owner","data-testid":`owner-${te.uuid}`},e.toDisplayString(C(te)),9,rA)):e.createCommentVNode("",!0),te.is_orphaned?(e.openBlock(),e.createElementBlock("span",sA,e.toDisplayString(v.value),1)):e.createCommentVNode("",!0),ve(te)>0?(e.openBlock(),e.createElementBlock("span",{key:3,class:"media-management-view__variant-badge","data-testid":`media-variant-badge-${te.uuid}`},e.toDisplayString(xe(ve(te))),9,lA)):e.createCommentVNode("",!0)]),e.renderSlot(X.$slots,"item-actions",e.mergeProps({ref_for:!0},Ct(te)),()=>[e.createElementVNode("div",dA,[e.createElementVNode("div",{class:"media-management-view__action-menu",onKeydown:e.withKeys(e.withModifiers(Jt,["stop"]),["escape"])},[e.createElementVNode("button",{type:"button",class:"media-management-view__action-menu-trigger","data-testid":`btn-actions-menu-${te.uuid}`,"aria-label":`Actions for ${e.unref(_e)(te)}`,"aria-haspopup":"menu","aria-expanded":B.value===te.uuid?"true":"false",onClick:De=>ea(te.uuid)}," ... ",8,uA),B.value===te.uuid?(e.openBlock(),e.createElementBlock("div",{key:0,class:"media-management-view__action-menu-panel",role:"menu","data-testid":`media-item-actions-menu-${te.uuid}`},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(fa(te),De=>(e.openBlock(),e.createElementBlock("button",{key:De.id,type:"button",class:"media-management-view__action-menu-item",role:"menuitem","data-testid":De.testId,onClick:Tt=>ta(De)},e.toDisplayString(De.label),9,pA))),128))],8,mA)):e.createCommentVNode("",!0)],40,cA)])],!0)],10,JR))),128))])),e.unref(se).selectedCount.value>0&&z.value?e.renderSlot(X.$slots,"bulk-actions",e.normalizeProps(e.mergeProps({key:6},Ft.value)),()=>[e.createElementVNode("footer",fA,[e.createElementVNode("span",hA,e.toDisplayString(ie(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:ye[5]||(ye[5]=te=>At(e.unref(se).selectedItems.value,"bulk"))},e.toDisplayString(s.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:ye[6]||(ye[6]=te=>$t(e.unref(se).selectedItems.value,"bulk"))},e.toDisplayString(s.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:ye[7]||(ye[7]=te=>Pt(e.unref(se).selectedItems.value,"bulk"))},e.toDisplayString(s.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(Be).isDeleting.value,onClick:le},e.toDisplayString(E.value),9,vA)):e.createCommentVNode("",!0)])],!0):e.createCommentVNode("",!0),O.value.length>0?(e.openBlock(),e.createElementBlock("footer",gA,[e.createElementVNode("span",bA,e.toDisplayString(U.value),1),Ze.value.length>0?(e.openBlock(),e.createElementBlock("div",yA,[ye[11]||(ye[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:bt.value,disabled:e.unref(D).loading.value||e.unref(D).loadingMore.value,onChange:ct},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Ze.value,te=>(e.openBlock(),e.createElementBlock("option",{key:te.value,value:te.value,"data-testid":`option-page-size-${te.value}`},e.toDisplayString(te.label),9,kA))),128))],40,wA)])):e.createCommentVNode("",!0),!X.paginated&&e.unref(D).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(D).loadingMore.value,onClick:Ce},e.toDisplayString(e.unref(D).loadingMore.value?s.value.loadingMoreButton:s.value.loadMoreButton),9,_A)):e.createCommentVNode("",!0),X.paginated&&(e.unref(D).totalPages.value??0)>1?(e.openBlock(),e.createElementBlock("nav",EA,[e.createElementVNode("button",{type:"button",class:"media-management-view__page-bar-step","data-testid":"btn-media-management-page-prev",disabled:(e.unref(D).currentPage.value??1)<=1||e.unref(D).loading.value,"aria-label":"Previous page",onClick:ye[8]||(ye[8]=te=>qe(-1))}," ‹ ",8,SA),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Re.value,te=>(e.openBlock(),e.createElementBlock("button",{key:te.key,type:"button",class:e.normalizeClass(["media-management-view__page-bar-page",{"is-current":te.kind==="page"&&te.value===e.unref(D).currentPage.value}]),"data-testid":te.kind==="page"?`btn-media-management-page-${te.value}`:"media-management-page-ellipsis",disabled:te.kind!=="page"||e.unref(D).loading.value,"aria-current":te.kind==="page"&&te.value===e.unref(D).currentPage.value?"page":void 0,"aria-label":te.kind==="page"?`Page ${te.value}`:void 0,onClick:De=>te.kind==="page"?et(te.value):void 0},e.toDisplayString(te.kind==="page"?te.value:"…"),11,CA))),128)),e.createElementVNode("button",{type:"button",class:"media-management-view__page-bar-step","data-testid":"btn-media-management-page-next",disabled:(e.unref(D).currentPage.value??1)>=(e.unref(D).totalPages.value??1)||e.unref(D).loading.value,"aria-label":"Next page",onClick:ye[9]||(ye[9]=te=>qe(1))}," › ",8,xA)])):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)])):N.value==="trash"?(e.openBlock(),e.createElementBlock("section",VA,[e.unref(ce).isLoading.value?(e.openBlock(),e.createElementBlock("div",NA,e.toDisplayString(u.value),1)):e.unref(ce).items.value.length===0?(e.openBlock(),e.createElementBlock("div",TA,[e.renderSlot(X.$slots,"empty-trash",{},()=>[e.createElementVNode("div",BA,[e.createElementVNode("p",MA,e.toDisplayString(p.value),1),e.createElementVNode("p",IA,e.toDisplayString(h.value),1)])],!0)])):(e.openBlock(),e.createElementBlock("ul",$A,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(ce).items.value,te=>(e.openBlock(),e.createElementBlock("li",{key:te.uuid,class:"media-management-view__item is-trashed","data-testid":`trash-item-${te.uuid}`},[e.createElementVNode("div",DA,[Ge(te)&&!at.value.has(te.uuid)?(e.openBlock(),e.createElementBlock("img",{key:0,src:Ge(te)??"",alt:te.alt_text||te.file_name,loading:"lazy",onError:De=>rt(te)},null,40,RA)):(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__item-placeholder","data-testid":`placeholder-trash-${te.uuid}`},e.toDisplayString(Ve(te)),9,AA))]),e.createElementVNode("div",LA,[e.createElementVNode("span",PA,e.toDisplayString(te.file_name),1),te.purge_after?(e.openBlock(),e.createElementBlock("span",UA,e.toDisplayString(W(te.purge_after)),1)):e.createCommentVNode("",!0)]),e.renderSlot(X.$slots,"trash-action",e.mergeProps({ref_for:!0},Ht(te)),()=>[R(te)?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-management-view__btn-restore","data-testid":`btn-restore-${te.uuid}`,disabled:e.unref(ce).isRestoring.value,onClick:De=>Te(te.uuid)},e.toDisplayString(y.value),9,OA)):(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__btn-restore is-unavailable","data-testid":`btn-restore-${te.uuid}-unavailable`,"aria-disabled":!0},e.toDisplayString(k.value),9,zA))],!0)],8,FA))),128))]))])):e.createCommentVNode("",!0),r.value.allowPreview!==!1?(e.openBlock(),e.createBlock(Md,{key:3,open:K.value!==null,media:K.value,"can-go-previous":S.value!==null&&S.value>0,"can-go-next":S.value!==null&&S.value<O.value.length-1,selected:K.value!==null&&e.unref(se).isSelected(K.value.uuid),"close-label":s.value.previewCloseButton,"previous-label":s.value.previewPreviousButton,"next-label":s.value.previewNextButton,"select-label":s.value.previewSelectButton,"deselect-label":s.value.previewDeselectButton,onClose:lt,onPrevious:Et,onNext:Ee,onToggleSelect:ye[10]||(ye[10]=te=>e.unref(se).toggle(te.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)]))}}),Pf=Fe(jA,[["__scopeId","data-v-403d0484"]]),WA={class:"media-library-workspace","data-testid":"media-library-workspace"},HA=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(l){return{...l,...l.kinds!==void 0?{kinds:[...l.kinds]}:{},...l.selected_uuids!==void 0?{selected_uuids:[...l.selected_uuids]}:{}}}const r=e.ref(i(t.filters));e.watch(()=>t.filters,l=>{r.value=i(l)},{deep:!0});function s(l){r.value=i(l),n("filters-change",r.value)}return(l,d)=>(e.openBlock(),e.createElementBlock("section",WA,[e.createVNode(Pf,{"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(Af,{filters:r.value,"scope-label":t.labels.scopeLabel??"","onUpdate:filters":s},null,8,["filters","scope-label"])]),"bulk-actions":e.withCtx(c=>[e.renderSlot(l.$slots,"bulk-actions",e.normalizeProps(e.guardReactiveProps(c)),void 0,!0)]),"item-actions":e.withCtx(c=>[e.renderSlot(l.$slots,"item-actions",e.normalizeProps(e.guardReactiveProps(c)),void 0,!0)]),"empty-library":e.withCtx(()=>[e.renderSlot(l.$slots,"empty-library",{},void 0,!0)]),_:3},8,["http-client","filters","initial-view","group-variants","capabilities","labels"])]))}}),Uf=Fe(HA,[["__scopeId","data-v-d7753d2b"]]),ZA=["data-testid"],GA={class:"media-empty-state__illustration","aria-hidden":"true"},XA={class:"media-empty-state__copy"},KA={class:"media-empty-state__title"},JA={key:0,class:"media-empty-state__description"},qA={class:"media-empty-state__actions"},YA=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",GA,[e.renderSlot(i.$slots,"illustration",{},()=>[r[1]||(r[1]=e.createElementVNode("span",{class:"media-empty-state__icon"},"□",-1))],!0)]),e.createElementVNode("div",XA,[e.createElementVNode("h3",KA,e.toDisplayString(t.title),1),t.description!==""?(e.openBlock(),e.createElementBlock("p",JA,e.toDisplayString(t.description),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",qA,[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]=s=>n("action"))},e.toDisplayString(t.actionLabel),1)):e.createCommentVNode("",!0)],!0)])],8,ZA))}}),Of=Fe(YA,[["__scopeId","data-v-7b8e2619"]]),QA={class:"media-trash-workspace","data-testid":"media-trash-workspace"},eL={class:"media-trash-workspace__header"},tL={key:0,class:"media-trash-workspace__status"},aL={key:2,class:"media-trash-workspace__grid"},nL=["data-testid"],oL={class:"media-trash-workspace__select"},iL=["checked","data-testid","onChange"],rL=["src","alt"],sL={key:1,class:"media-trash-workspace__purge"},lL=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 f,p,h,v,E,y;return{title:((f=t.labels)==null?void 0:f.title)??"Trash",emptyTitle:((p=t.labels)==null?void 0:p.emptyTitle)??"Your trash is empty",emptyDescription:((h=t.labels)==null?void 0:h.emptyDescription)??"Deleted files appear here before permanent removal.",restore:((v=t.labels)==null?void 0:v.restore)??"Restore",purge:((E=t.labels)==null?void 0:E.purge)??"Delete forever",emptyTrash:((y=t.labels)==null?void 0:y.emptyTrash)??"Empty trash"}}),r=Ld({httpClient:t.httpClient}),s=es(r.items);function l(f){return f.thumbnail_url??f.preview_url??f.original_url??null}async function d(){const f=Array.from(s.selectedIds.value),p=[];try{for(const h of f)(await r.restore(h)).status==="restored"&&p.push(h);s.clear(),n("restored",p)}catch(h){n("error",h instanceof Error?h:new Error(String(h)))}}async function c(){const f=Array.from(s.selectedIds.value);await m(f)}async function u(){await m(r.items.value.map(f=>f.uuid))}async function m(f){const p=[];try{for(const h of f)(await r.purge(h)).status==="purging"&&p.push(h);s.clear(),n("purged",p)}catch(h){n("error",h instanceof Error?h:new Error(String(h)))}}return e.onMounted(()=>{r.fetch().catch(f=>{n("error",f instanceof Error?f:new Error(String(f)))})}),(f,p)=>(e.openBlock(),e.createElementBlock("section",QA,[e.createElementVNode("header",eL,[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",onClick:u},e.toDisplayString(i.value.emptyTrash),1)):e.createCommentVNode("",!0)]),e.unref(r).isLoading.value?(e.openBlock(),e.createElementBlock("p",tL,"Loading...")):e.unref(r).items.value.length===0?(e.openBlock(),e.createBlock(Of,{key:1,title:i.value.emptyTitle,description:i.value.emptyDescription,"test-id":"media-empty-trash"},null,8,["title","description"])):(e.openBlock(),e.createElementBlock("ul",aL,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(r).items.value,h=>(e.openBlock(),e.createElementBlock("li",{key:h.uuid,class:e.normalizeClass(["media-trash-workspace__item",{"is-selected":e.unref(s).isSelected(h.uuid)}]),"data-testid":`media-trash-item-${h.uuid}`},[e.createElementVNode("label",oL,[e.createElementVNode("input",{type:"checkbox",checked:e.unref(s).isSelected(h.uuid),"data-testid":`checkbox-trash-${h.uuid}`,onChange:v=>e.unref(s).toggle(h.uuid)},null,40,iL),e.createElementVNode("span",null,e.toDisplayString(h.file_name),1)]),l(h)?(e.openBlock(),e.createElementBlock("img",{key:0,src:l(h)??"",alt:h.alt_text??h.file_name},null,8,rL)):e.createCommentVNode("",!0),h.purge_after?(e.openBlock(),e.createElementBlock("span",sL,e.toDisplayString(h.purge_after),1)):e.createCommentVNode("",!0)],10,nL))),128))])),e.createVNode(Rd,{"selected-count":e.unref(s).selectedCount.value,"cross-page-count":e.unref(s).crossPageCount.value,scope:"trash",labels:{restore:i.value.restore,purge:i.value.purge},onBulkRestore:d,onBulkPurge:c,onClear:e.unref(s).clear},null,8,["selected-count","cross-page-count","labels","onClear"])]))}}),zf=Fe(lL,[["__scopeId","data-v-3b1b3c56"]]),dL=["data-density"],cL={class:"media-library-shell__toolbar"},uL={class:"media-library-shell__tabs","aria-label":"Media library sections"},mL={key:1,class:"media-library-shell__uploads","data-testid":"media-library-uploads","aria-live":"polite"},pL=["data-testid"],fL={class:"media-library-shell__upload-thumb"},hL=["src","alt"],vL={key:1,"aria-hidden":"true"},gL={class:"media-library-shell__upload-meta"},bL={class:"media-library-shell__upload-name"},yL={class:"media-library-shell__upload-status"},wL=["data-testid","onClick"],kL={class:"media-library-shell__body"},_L={class:"media-library-shell__workspace"},zu="media-library:density",ju="media-library:recent-albums",Wu=5,EL=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","error"],setup(o,{emit:a}){function t(){if(typeof window>"u")return"comfortable";try{return window.localStorage.getItem(zu)==="compact"?"compact":"comfortable"}catch{return"comfortable"}}function n(re){if(!(typeof window>"u"))try{window.localStorage.setItem(zu,re)}catch{}}function i(){if(typeof window>"u")return[];try{const re=window.localStorage.getItem(ju);if(typeof re!="string"||re==="")return[];const ge=JSON.parse(re);return Array.isArray(ge)?ge.filter(Ge=>typeof Ge=="string"):[]}catch{return[]}}function r(re){if(!(typeof window>"u"))try{window.localStorage.setItem(ju,JSON.stringify(re.slice(0,Wu)))}catch{}}const s=o,l=a,d=e.ref(s.initialTab),c=e.ref(s.initialAlbumId),u=e.ref({...s.initialFilters}),m=e.ref(null),f=e.ref(!1),p=e.ref(null),h=e.ref(!1),v=e.ref(null),E=e.ref(null),y=e.ref(t()),k=e.ref(i()),g=e.ref(!1);function b(){if(typeof document>"u")return!1;const re=document.activeElement;if(!(re instanceof HTMLElement))return!1;if(re.isContentEditable)return!0;const ge=re.tagName.toLowerCase();return ge==="input"||ge==="textarea"||ge==="select"}function R(re){re.key==="?"&&(re.metaKey||re.ctrlKey||re.altKey||b()||(re.preventDefault(),g.value=!0))}const N=e.computed(()=>k.value.map(re=>{const ge=B.albumsById.value.get(re);return ge?{id:re,name:ge.name}:null}).filter(re=>re!==null));function T(re){const ge=[re,...k.value.filter(Ge=>Ge!==re)].slice(0,Wu);k.value=ge,r(ge)}const S=e.computed(()=>u.value.sort??"newest"),B=Td(),A=If({httpClient:s.httpClient,onMediaUploaded:()=>{x.value+=1}}),x=e.ref(0);function M(re){re.length!==0&&A.uploadFiles(re).catch(ge=>{l("error",ge instanceof Error?ge:new Error(String(ge)))})}const w=e.computed(()=>{var re,ge,Ge,Ve,at,rt,gt,lt,Et,Ee,Ce,Re,et,qe,Ze,bt,ct;return{library:((re=s.labels)==null?void 0:re.library)??((ge=s.labels)==null?void 0:ge.libraryTab)??"Library",libraryTab:((Ge=s.labels)==null?void 0:Ge.libraryTab)??((Ve=s.labels)==null?void 0:Ve.library)??"Library",albums:((at=s.labels)==null?void 0:at.albums)??((rt=s.labels)==null?void 0:rt.albumsTab)??"Albums",albumsTab:((gt=s.labels)==null?void 0:gt.albumsTab)??((lt=s.labels)==null?void 0:lt.albums)??"Albums",trash:((Et=s.labels)==null?void 0:Et.trash)??((Ee=s.labels)==null?void 0:Ee.trashTab)??"Trash",trashTab:((Ce=s.labels)==null?void 0:Ce.trashTab)??((Re=s.labels)==null?void 0:Re.trash)??"Trash",allMedia:((et=s.labels)==null?void 0:et.allMedia)??"All media",unfiled:((qe=s.labels)==null?void 0:qe.unfiled)??"Unfiled",newAlbum:((Ze=s.labels)==null?void 0:Ze.newAlbum)??"New album",selectionScope:((bt=s.labels)==null?void 0:bt.selectionScope)??"Showing selected items",exitSelectionScope:((ct=s.labels)==null?void 0:ct.exitSelectionScope)??"Exit selection view"}}),F=e.computed(()=>v.value!==null?{scope:"library"}:c.value==="unfiled"?{scope:"unfiled"}:c.value!==null?{scope:"album",albumId:c.value}:{scope:"library"}),P=e.computed(()=>v.value!==null?{...u.value,selected_uuids:[...v.value],unfiled_only:!1}:u.value),D=e.computed(()=>{if(c.value===null||c.value==="unfiled")return null;const re=B.albumsById.value.get(c.value);return{uuid:c.value,name:(re==null?void 0:re.name)??"this album"}}),O=e.computed(()=>d.value==="trash"?"trash":v.value!==null?"selection":D.value!==null?"album":"all"),I=e.computed(()=>d.value==="trash"?w.value.trash:v.value!==null?w.value.selectionScope:c.value==="unfiled"?w.value.unfiled:D.value!==null?D.value.name:w.value.allMedia);function Z(re){var ge;d.value!==re&&(d.value=re,l("tab-change",re),(ge=s.routerPush)==null||ge.call(s,re==="trash"?"/media/trash":"/media"))}function z(re){var ge,Ge,Ve;Be(),c.value=re,d.value="library",typeof re=="string"&&re!=="unfiled"&&T(re),u.value={...u.value,...re==="unfiled"?{unfiled_only:!0}:{unfiled_only:!1}},l("album-change",re),re===null?(ge=s.routerPush)==null||ge.call(s,"/media"):re==="unfiled"?(Ge=s.routerPush)==null||Ge.call(s,"/media/unfiled"):(Ve=s.routerPush)==null||Ve.call(s,`/media/album/${encodeURIComponent(re)}`)}function K(){return d.value==="trash"?"/media/trash":c.value==="unfiled"?"/media/unfiled":c.value!==null?`/media/album/${encodeURIComponent(c.value)}`:"/media"}function se(re){var ge;re.length!==0&&(v.value===null&&(E.value=K()),v.value=[...re],(ge=s.routerPush)==null||ge.call(s,{path:"/media",query:{view:"selection"}}))}function Be(){v.value=null,E.value=null}function ce(){var ge;const re=E.value;Be(),re!==null&&((ge=s.routerPush)==null||ge.call(s,re))}function ie(re){var ge;u.value={...u.value,sort:re},l("filters-change",u.value),(ge=s.routerReplace)==null||ge.call(s,{query:u.value})}function W(re){y.value=re,n(re)}function C(re){var ge;u.value={...u.value,created_after:re.starts_at,created_before:re.ends_at},l("filters-change",u.value),(ge=s.routerReplace)==null||ge.call(s,{query:u.value})}function U(){var ge;const re={...u.value};delete re.created_after,delete re.created_before,u.value=re,l("filters-change",u.value),(ge=s.routerReplace)==null||ge.call(s,{query:u.value})}const j=e.computed(()=>u.value.created_after!==void 0||u.value.created_before!==void 0);function ne(re){var ge;u.value={...re,...re.kinds!==void 0?{kinds:[...re.kinds]}:{},...re.selected_uuids!==void 0?{selected_uuids:[...re.selected_uuids]}:{}},l("filters-change",u.value),(ge=s.routerReplace)==null||ge.call(s,{query:u.value})}function de(){nf({...s.albumHttpClient!==void 0?{httpClient:s.albumHttpClient}:{},...s.albumBaseUrl!==void 0?{albumBaseUrl:s.albumBaseUrl}:{}})}function Ke(re){re.mediaIds.length!==0&&(p.value=re,h.value=!0)}function be(){h.value=!1,p.value=null,ve.value=null}async function _e(re){const ge=p.value;if(ge===null)return;const Ge=ve.value;try{await B.attachMedia(re,ge.mediaIds),Ge!==null&&await Promise.all(ge.mediaIds.map(Ve=>B.detachMedia(Ge,Ve))),h.value=!1,p.value=null,ve.value=null,l("add-to-album",ge)}catch(Ve){l("error",Ve instanceof Error?Ve:new Error(String(Ve)))}}const ve=e.ref(null);function xe(re){re.mediaIds.length===0||D.value===null||(p.value=re,ve.value=D.value.uuid,h.value=!0)}async function Se(re){if(re.mediaIds.length===0||D.value===null)return;const ge=D.value.uuid;try{await Promise.all(re.mediaIds.map(Ge=>B.detachMedia(ge,Ge)))}catch(Ge){l("error",Ge instanceof Error?Ge:new Error(String(Ge)))}}e.watch(()=>s.initialAlbumId,re=>{c.value=re});function Ae(re){re===null||re==="unfiled"||B.albumsById.value.has(re)||B.fetchAlbum(re).catch(ge=>{l("error",ge instanceof Error?ge:new Error(String(ge)))})}return e.watch(()=>c.value,re=>Ae(re)),e.onMounted(()=>{de(),Ae(c.value),typeof window<"u"&&window.addEventListener("keydown",R)}),e.onUnmounted(()=>{typeof window<"u"&&window.removeEventListener("keydown",R)}),e.watch(()=>[s.albumHttpClient,s.albumBaseUrl],()=>de()),(re,ge)=>{var Ge;return e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["media-library-shell",{"is-density-compact":y.value==="compact"}]),"data-density":y.value,"data-testid":"media-library-shell"},[e.createElementVNode("header",cL,[e.createElementVNode("nav",uL,[e.createElementVNode("button",{type:"button",class:e.normalizeClass({"is-active":d.value==="library"}),"data-testid":"tab-media-library",onClick:ge[0]||(ge[0]=Ve=>Z("library"))},e.toDisplayString(w.value.library),3),e.createElementVNode("button",{type:"button",class:e.normalizeClass({"is-active":d.value==="albums"}),"data-testid":"tab-media-albums",onClick:ge[1]||(ge[1]=Ve=>Z("albums"))},e.toDisplayString(w.value.albums),3),e.createElementVNode("button",{type:"button",class:e.normalizeClass({"is-active":d.value==="trash"}),"data-testid":"tab-media-trash",onClick:ge[2]||(ge[2]=Ve=>Z("trash"))},e.toDisplayString(w.value.trash),3)]),e.createElementVNode("button",{type:"button",class:"media-library-shell__rail-toggle","data-testid":"btn-media-rail-toggle",onClick:ge[3]||(ge[3]=Ve=>f.value=!f.value)}," ☰ "),e.createElementVNode("button",{type:"button",class:"media-library-shell__shortcut-trigger","data-testid":"btn-media-shortcuts","aria-label":"Show keyboard shortcuts",onClick:ge[4]||(ge[4]=Ve=>g.value=!0)}," ? "),v.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:ce},e.toDisplayString(w.value.exitSelectionScope),1)):e.createCommentVNode("",!0)]),d.value!=="trash"?(e.openBlock(),e.createBlock(Bf,{key:0,class:"media-library-shell__toolbar-row",sort:S.value,density:y.value,"has-date-filter":j.value,"http-client":s.httpClient,"onUpdate:sort":ie,"onUpdate:density":W,onJumpTo:C,onJumpToAll:U,onUploadFiles:M},null,8,["sort","density","has-date-filter","http-client"])):e.createCommentVNode("",!0),e.unref(A).uploads.value.length>0&&d.value!=="trash"?(e.openBlock(),e.createElementBlock("div",mL,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(A).uploads.value,Ve=>(e.openBlock(),e.createElementBlock("article",{key:Ve.cid,class:e.normalizeClass(["media-library-shell__upload-tile",`is-status-${Ve.status}`]),"data-testid":`upload-tile-${Ve.cid}`},[e.createElementVNode("div",fL,[Ve.previewUrl?(e.openBlock(),e.createElementBlock("img",{key:0,src:Ve.previewUrl,alt:Ve.fileName},null,8,hL)):(e.openBlock(),e.createElementBlock("span",vL,"⤴"))]),e.createElementVNode("div",gL,[e.createElementVNode("span",bL,e.toDisplayString(Ve.fileName),1),e.createElementVNode("span",yL,[Ve.status==="uploading"||Ve.status==="queued"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createTextVNode("Uploading…")],64)):Ve.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(Ve.errorMessage??"Upload failed"),1)],64))])]),e.createElementVNode("button",{type:"button",class:"media-library-shell__upload-dismiss","data-testid":`btn-upload-dismiss-${Ve.cid}`,onClick:at=>e.unref(A).dismiss(Ve.cid)}," × ",8,wL)],10,pL))),128))])):e.createCommentVNode("",!0),e.createElementVNode("div",kL,[e.createVNode(Tf,{"active-album-id":c.value,collapsed:f.value,"recent-albums":N.value,labels:{allMedia:w.value.allMedia,unfiled:w.value.unfiled,newAlbum:w.value.newAlbum,trash:w.value.trash},onChangeAlbum:z,onOpenTrash:ge[5]||(ge[5]=Ve=>Z("trash"))},null,8,["active-album-id","collapsed","recent-albums","labels"]),e.createElementVNode("main",_L,[d.value==="trash"?(e.openBlock(),e.createBlock(zf,{key:0,"http-client":s.httpClient,onError:ge[6]||(ge[6]=Ve=>l("error",Ve))},null,8,["http-client"])):(e.openBlock(),e.createBlock(Uf,{key:`workspace-${x.value}`,"http-client":s.httpClient,filters:P.value,"initial-view":F.value,capabilities:s.capabilities,labels:{scopeLabel:I.value},onFiltersChange:ne,onCreatePost:ge[7]||(ge[7]=Ve=>l("create-post",Ve)),onCreateGallery:ge[8]||(ge[8]=Ve=>l("create-gallery",Ve)),onAddToAlbum:Ke,onEdit:ge[9]||(ge[9]=Ve=>l("edit",Ve)),onDeleted:ge[10]||(ge[10]=Ve=>l("deleted",Ve)),onRestored:ge[11]||(ge[11]=Ve=>l("restored",Ve)),onRestoreConflict:ge[12]||(ge[12]=Ve=>l("restore-conflict",Ve)),onError:ge[13]||(ge[13]=Ve=>l("error",Ve))},{"bulk-actions":e.withCtx(Ve=>[e.createVNode(Rd,{"selected-count":Ve.selectedCount,"cross-page-count":Ve.crossPageCount,scope:O.value,"source-album":D.value,capabilities:s.capabilities,onClear:Ve.clearSelection,onBulkMoveToTrash:Ve.onBulkDelete,onBulkAddToAlbum:at=>{var rt;return(rt=Ve.onAddToAlbum)==null?void 0:rt.call(Ve)},onBulkMoveBetweenAlbums:at=>xe({mediaIds:Ve.selectedItemIds,items:Ve.selectedItems,source:"bulk"}),onBulkRemoveFromCurrentAlbum:at=>void Se({mediaIds:Ve.selectedItemIds,items:Ve.selectedItems,source:"bulk"}),onBulkCreatePost:at=>{var rt;return(rt=Ve.onCreatePost)==null?void 0:rt.call(Ve)},onBulkCreateGallery:at=>{var rt;return(rt=Ve.onCreateGallery)==null?void 0:rt.call(Ve)},onInspect:at=>Ve.crossPageCount>0?se(Ve.selectedItemIds):m.value={kind:"multi",count:Ve.selectedCount,items:Ve.selectedItems}},null,8,["selected-count","cross-page-count","scope","source-album","capabilities","onClear","onBulkMoveToTrash","onBulkAddToAlbum","onBulkMoveBetweenAlbums","onBulkRemoveFromCurrentAlbum","onBulkCreatePost","onBulkCreateGallery","onInspect"])]),_:1},8,["http-client","filters","initial-view","capabilities","labels"]))]),e.createVNode(Nf,{open:h.value,"selected-count":((Ge=p.value)==null?void 0:Ge.mediaIds.length)??0,onCancel:be,onConfirm:_e},null,8,["open","selected-count"]),e.createVNode(Rf,{class:"media-library-shell__inspector",target:m.value,"http-client":s.httpClient,capabilities:s.capabilities,"in-album-scope":c.value!==null&&c.value!=="unfiled"},null,8,["target","http-client","capabilities","in-album-scope"])]),e.createVNode(Mf,{open:g.value,onClose:ge[14]||(ge[14]=Ve=>g.value=!1)},null,8,["open"])],10,dL)}}}),SL=Fe(EL,[["__scopeId","data-v-bbefc728"]]),CL={key:0,class:"media-selection-tray","data-testid":"media-selection-tray"},xL={class:"media-selection-tray__header"},VL={class:"media-selection-tray__title"},NL={class:"media-selection-tray__items"},TL={class:"media-selection-tray__item-preview"},BL=["src","alt"],ML={key:1,class:"media-selection-tray__file-icon"},IL={class:"media-selection-tray__item-copy"},$L=["aria-label","onClick"],FL=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 s;return r?r.thumbnail_url??((s=r.conversion_urls)==null?void 0:s.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,s)=>r.items.length>0?(e.openBlock(),e.createElementBlock("section",CL,[e.createElementVNode("header",xL,[e.createElementVNode("h3",VL,e.toDisplayString(r.selectedCountLabel),1)]),e.createElementVNode("div",NL,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.items,l=>{var d,c,u,m;return e.openBlock(),e.createElementBlock("article",{key:l.id,class:"media-selection-tray__item"},[e.createElementVNode("div",TL,[i(l.media)&&n(l.media)?(e.openBlock(),e.createElementBlock("img",{key:0,src:n(l.media),alt:((d=l.media)==null?void 0:d.alt_text)??((c=l.media)==null?void 0:c.file_name)??"Selected media",class:"media-selection-tray__thumb"},null,8,BL)):(e.openBlock(),e.createElementBlock("div",ML,[...s[0]||(s[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",IL,[e.createElementVNode("strong",null,e.toDisplayString(((u=l.media)==null?void 0:u.file_name)??l.id),1),e.createElementVNode("span",null,e.toDisplayString(l.status),1)]),e.createElementVNode("button",{type:"button",class:"media-selection-tray__remove","aria-label":`${r.dismissLabel} ${((m=l.media)==null?void 0:m.file_name)??l.id}`,onClick:f=>t("remove",l.id)},e.toDisplayString(r.dismissLabel),9,$L)])}),128))])])):e.createCommentVNode("",!0)}}),DL=Fe(FL,[["__scopeId","data-v-f2a3d69d"]]);function Pd(o={}){const a=e.ref(!1),t=e.ref(!1),n=e.ref(null),i=e.ref(null),r=e.ref(0),s=e.ref(0),l=e.ref(null),d=e.ref(null),c=e.computed(()=>d.value!==null),u=k=>{if(r.value++,d.value=null,i.value=null,t.value=!1,k!=null&&typeof k=="object"&&!(k instanceof Blob)&&("image"in k||"state"in k||"sessionKey"in k)){const g=k;n.value=g.image??null,l.value=g.state??null,s.value=g.sessionKey??r.value}else n.value=k??null,l.value=null,s.value=r.value;a.value=!0},m=()=>{a.value=!1,n.value=null,i.value=null,d.value=null,t.value=!1,l.value=null},f=async k=>{try{return t.value=!0,i.value=k,o.onSave&&await o.onSave(k),m(),k}catch(g){const b=g;throw d.value=b,o.onError&&o.onError(b),b}finally{t.value=!1}},p=()=>{o.onCancel&&o.onCancel(),m()},h=k=>{d.value=k,o.onError&&o.onError(k)},v=()=>{d.value=null},E=()=>i.value,y=e.computed(()=>a.value&&i.value!==null&&!t.value);return{isOpen:a,isProcessing:t,uploadedImage:n,editedImage:i,sessionKey:s,initialState:l,error:d,hasError:c,hasUnsavedChanges:y,open:u,close:m,handleSave:f,handleCancel:p,handleError:h,clearError:v,getEditedImage:E}}let sl=null;function RL(o){return sl||(sl=Pd(o)),sl}function AL(o){return a=>new Promise((t,n)=>{Pd({...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 Ud(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 Jl(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 Od(o){if(o){const t={};o.apiBaseUrl!==void 0&&(t.apiBaseUrl=o.apiBaseUrl),o.isAdmin!==void 0&&(t.isAdmin=o.isAdmin),Io(t)}return{name:"mediables",async upload(t,n){const r=await xa().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 xa().attachMedia(n.modelType,String(n.modelId),[t],n.collection||"images")},async attachMany(t,n){await xa().attachMedia(n.modelType,String(n.modelId),t,n.collection||"images")},async detach(t,n){await xa().detachMedia(n.modelType,String(n.modelId),t,n.collection||"images")},async reorder(t,n){await xa().reorderMedia(t.modelType,String(t.modelId),n,t.collection||"images")},async fetchModelMedia(t){return await xa().fetchModelMedia(t.modelType,String(t.modelId),t.collection||"images")},getUrl(t,n){return xa().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 xa().deleteMedia(t)},async update(t,n){const r=await xa().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),Io(n)}}}let Mr=null;function LL(){return Mr||(Mr=Od()),Mr}function PL(){Mr=null}const UL={apiBaseUrl:"/media-library-pro"};function yr(){var o;return typeof document>"u"?null:((o=document.querySelector('meta[name="csrf-token"]'))==null?void 0:o.getAttribute("content"))||null}function ll(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 zd(o){const a={...UL,...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 s={Accept:"application/json",...a.headers},l=a.csrfToken||yr();l&&(s["X-CSRF-TOKEN"]=l);const d={method:"POST",headers:s,body:r,credentials:"include"};i!=null&&i.signal&&(d.signal=i.signal);const c=await fetch(`${a.apiBaseUrl}/uploads`,d);if(!c.ok){const f=await c.json().catch(()=>({message:"Upload failed"}));throw new Error(f.message||`HTTP ${c.status}`)}const u=await c.json(),m=ll(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||yr();r&&(i["X-CSRF-TOKEN"]=r);const s=new URLSearchParams;s.append("model_type",n.modelType),s.append("model_id",String(n.modelId)),n.collection&&s.append("collection",n.collection);try{const l=await fetch(`${a.apiBaseUrl}/media?${s}`,{method:"GET",headers:i,credentials:"include"});if(!l.ok)throw new Error(`HTTP ${l.status}`);return(await l.json()).map(ll)}catch{return[]}},getUrl(n,i){var r;if(i){const s=(r=n.conversion_urls)==null?void 0:r[i];if(s)return s}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||yr();r&&(i["X-CSRF-TOKEN"]=r);const s=await fetch(`${a.apiBaseUrl}/uploads/${n}`,{method:"DELETE",headers:i,credentials:"include"});if(!s.ok){const l=await s.json().catch(()=>({message:"Delete failed"}));throw new Error(l.message||`HTTP ${s.status}`)}},async update(n,i){const r={Accept:"application/json","Content-Type":"application/json",...a.headers},s=a.csrfToken||yr();s&&(r["X-CSRF-TOKEN"]=s);const l=await fetch(`${a.apiBaseUrl}/uploads/${n}`,{method:"PATCH",headers:r,body:JSON.stringify(i),credentials:"include"});if(!l.ok){const c=await l.json().catch(()=>({message:"Update failed"}));throw new Error(c.message||`HTTP ${l.status}`)}const d=await l.json();return ll(d)},configure(n){Object.assign(a,n)}}}let Ir=null;function OL(){return Ir||(Ir=zd()),Ir}function zL(){Ir=null}function jf(o,a){switch(o){case"mediables":return Od(a);case"spatie":return zd(a);default:throw new Error(`Unknown adapter: ${o}`)}}function Wf(o={}){const{enabled:a=!0,onReorder:t,onDragStart:n,onDragEnd:i,draggingClass:r="is-dragging",dropTargetClass:s="is-drop-target"}=o,l=e.ref({isDragging:!1,dragIndex:null,dropIndex:null,draggedItem:null}),d=e.ref(!1);let c=null;function u(k,g,b){a&&("dataTransfer"in k&&k.dataTransfer&&(k.dataTransfer.effectAllowed="move",k.dataTransfer.setData("text/plain",String(b))),c=k.target,c&&c.classList.add(r),l.value={isDragging:!0,dragIndex:b,dropIndex:b,draggedItem:g},d.value=!0,n==null||n(g,b))}function m(k,g){var b;if(!(!a||!l.value.isDragging)&&(k.preventDefault(),l.value.dropIndex!==g)){const R=document.querySelector(`.${s}`);R==null||R.classList.remove(s);const N=(b=k.target)==null?void 0:b.closest("[data-index]");N==null||N.classList.add(s),l.value.dropIndex=g}}function f(){if(!l.value.isDragging)return;const{dragIndex:k,dropIndex:g,draggedItem:b}=l.value;c&&c.classList.remove(r);const R=document.querySelector(`.${s}`);R==null||R.classList.remove(s),k!==null&&g!==null&&k!==g&&b&&(t==null||t({fromIndex:k,toIndex:g,item:b})),h(),i==null||i()}function p(){c&&c.classList.remove(r);const k=document.querySelector(`.${s}`);k==null||k.classList.remove(s),h(),i==null||i()}function h(){l.value={isDragging:!1,dragIndex:null,dropIndex:null,draggedItem:null},d.value=!1,c=null}function v(k,g,b){const R=[...k],[N]=R.splice(g,1);return R.splice(b,0,N),R.map((T,S)=>({...T,order:S}))}function E(k,g){return{draggable:a,"data-index":g,onDragstart:b=>u(b,k,g),onDragover:b=>m(b,g),onDragend:()=>f(),onDrop:b=>{b.preventDefault(),f()}}}function y(k){k.key==="Escape"&&l.value.isDragging&&p()}return e.onMounted(()=>{document.addEventListener("keydown",y)}),e.onUnmounted(()=>{document.removeEventListener("keydown",y),p()}),{dragState:l,isDragging:d,startDrag:u,handleDragOver:m,endDrag:f,cancelDrag:p,reorderItems:v,getDragProps:E}}function Ns(o={}){const{initialItems:a=[],modelType:t,modelId:n,collection:i="images",maxItems:r,maxFileSize:s,acceptedMimeTypes:l,sortable:d=!0,disabled:c=!1,rules:u={},adapterType:m="mediables",adapter:f,maxConcurrentUploads:p=3,onChange:h,onUpload:v,onUploadComplete:E,onUploadError:y,onRemove:k,onReorder:g,onError:b,onReadyToSubmitChange:R}=o,N={maxItems:r,maxFileSize:s,acceptedMimeTypes:l,...u},T=f||jf(m),S=e.ref([]),B=e.ref(!1),A=e.ref([]);function x(ve){if(ve.length===0)return[];const xe=ve[0];return"media"in xe&&"clientId"in xe?ve:Jl(ve)}S.value=x(a);const{acceptString:M,canAddFiles:w}=$d({rules:N}),F=Fd({adapter:T,maxConcurrent:p,rules:N,collection:i,onUploadStart:ve=>{v==null||v(ve)},onUploadComplete:(ve,xe)=>{const Se=S.value.findIndex(Ae=>Ae.clientId===ve.id);Se!==-1&&(S.value[Se]={...S.value[Se],media:xe,name:xe.name||xe.file_name,upload:{...ve,status:"completed"}}),E==null||E(xe)},onUploadError:(ve,xe)=>{const Se=S.value.findIndex(Ae=>Ae.clientId===ve.id);Se!==-1&&(S.value[Se]={...S.value[Se],upload:{...ve,status:"error",error:xe.message},errors:[{field:"upload",message:xe.message,code:"UPLOAD_ERROR"}]}),y==null||y({file:ve.file,message:xe.message})},onQueueComplete:()=>{h==null||h(S.value)}}),{dragState:P,getDragProps:D,reorderItems:O}=Wf({enabled:d&&!c,onReorder:ve=>{S.value=O(S.value,ve.fromIndex,ve.toIndex),g==null||g(S.value),h==null||h(S.value)}}),I=e.computed(()=>F.isUploading.value),Z=e.computed(()=>!F.isUploading.value&&F.pendingCount.value===0),z=e.computed(()=>r?S.value.length>=r:!1),K=e.computed(()=>Ud(S.value)),se=e.computed(()=>S.value.length),Be=e.computed(()=>r?Math.max(0,r-S.value.length):1/0);e.watch(Z,ve=>{R==null||R(ve)});function ce(ve){S.value=x(ve),h==null||h(S.value)}async function ie(ve){if(c)return;const xe=Array.from(ve);if(!w(xe.length,S.value.length)){const ge={field:"count",message:`Maximum ${r} files allowed`,code:"MAX_ITEMS"};A.value=[ge],b==null||b([ge]);return}const Se=await F.addFiles(xe),Ae=S.value.length,re=Se.map((ge,Ge)=>({...ge,order:Ae+Ge}));S.value=[...S.value,...re],h==null||h(S.value)}function W(ve){c||(ve.upload&&(ve.upload.status==="uploading"||ve.upload.status==="pending")&&F.cancelUpload(ve.clientId),S.value=S.value.filter(xe=>xe.clientId!==ve.clientId),S.value=S.value.map((xe,Se)=>({...xe,order:Se})),k==null||k(ve),h==null||h(S.value))}function C(ve){const xe=S.value.find(Se=>Se.clientId===ve);xe&&W(xe)}function U(){c||(F.clearAll(),S.value=[],h==null||h(S.value))}function j(ve,xe){c||!d||(S.value=O(S.value,ve,xe),g==null||g(S.value),h==null||h(S.value))}function ne(ve,xe){if(c)return;const Se=S.value.findIndex(Ae=>Ae.clientId===ve);Se!==-1&&(S.value[Se]={...S.value[Se],...xe},h==null||h(S.value))}function de(ve){F.cancelUpload(ve),C(ve)}async function Ke(ve){await F.retryUpload(ve)}async function be(){if(!t||!n)throw new Error("modelType and modelId are required for save()");const ve={modelType:t,modelId:n,collection:i},xe=S.value.filter(Se=>Se.media&&!Se.markedForRemoval).map(Se=>Se.media.uuid);B.value=!0;try{await T.attachMany(xe,ve),await T.reorder(ve,xe)}finally{B.value=!1}}async function _e(){if(!t||!n)throw new Error("modelType and modelId are required for load()");const ve={modelType:t,modelId:n,collection:i};B.value=!0;try{const xe=await T.fetchModelMedia(ve);S.value=Jl(xe),h==null||h(S.value)}finally{B.value=!1}}return e.onMounted(()=>{t&&n&&a.length===0&&_e().catch(console.error)}),e.onUnmounted(()=>{F.clearAll()}),{items:S,setItems:ce,addFiles:ie,removeItem:W,removeItemById:C,clearAll:U,reorderItems:j,updateItem:ne,cancelUpload:de,retryUpload:Ke,save:be,load:_e,isLoading:B,isUploading:I,isReadyToSubmit:Z,isAtMaxItems:z,errors:A,dragState:P,getDragProps:D,adapter:T,formValues:K,acceptString:M,count:se,remainingSlots:Be}}const jL=["aria-disabled"],WL=["accept","multiple","disabled"],HL={class:"media-dropzone__content"},ZL={class:"media-dropzone__title"},GL={class:"media-dropzone__subtitle"},XL=["disabled"],KL={key:0,class:"media-dropzone__helper"},JL=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),s=e.computed(()=>({"media-dropzone":!0,"media-dropzone--drag-over":i.value,"media-dropzone--disabled":t.disabled})),l=e.computed(()=>{const v=[];return t.maxFileSize&&v.push(`Max size: ${qr(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 y;if(v.preventDefault(),i.value=!1,t.disabled)return;const E=(y=v.dataTransfer)==null?void 0:y.files;E&&E.length>0&&n("files",E)}function f(){var v;t.disabled||(v=r.value)==null||v.click()}function p(v){const E=v.target,y=E.files;y&&y.length>0&&n("files",y),E.value=""}function h(v){(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),f())}return(v,E)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(s.value),role:"button",tabindex:"0","aria-disabled":v.disabled,"aria-label":"Upload files",onClick:f,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:p},null,40,WL),e.createElementVNode("div",HL,[e.renderSlot(v.$slots,"icon",{},()=>[E[0]||(E[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",ZL,[e.renderSlot(v.$slots,"title",{},()=>[e.createTextVNode(e.toDisplayString(v.title),1)],!0)]),e.createElementVNode("p",GL,[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(f,["stop"])},[e.renderSlot(v.$slots,"button",{},()=>[e.createTextVNode(e.toDisplayString(v.buttonText),1)],!0)],8,XL),l.value?(e.openBlock(),e.createElementBlock("p",KL,e.toDisplayString(l.value),1)):e.createCommentVNode("",!0)])],42,jL))}}),jd=Fe(JL,[["__scopeId","data-v-b1366c1e"]]),qL=["data-index"],YL={key:0,class:"media-item__drag-handle","aria-label":"Drag to reorder",role:"button",tabindex:"0"},QL={class:"media-item__thumbnail"},eP=["src","alt"],tP={key:1,class:"media-item__file-icon"},aP={key:2,class:"media-item__progress-overlay"},nP={class:"media-item__progress-text"},oP={key:3,class:"media-item__processing-overlay"},iP={key:4,class:"media-item__error-overlay"},rP={class:"media-item__info"},sP=["title"],lP={key:0,class:"media-item__size"},dP={key:1,class:"media-item__error-message"},cP={class:"media-item__actions"},uP=["disabled"],mP=["disabled"],pP=["disabled"],fP=["disabled"],hP=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 g;return(g=t.item.upload)!=null&&g.previewUrl?t.item.upload.previewUrl:t.item.media?t.adapter.getThumbnailUrl(t.item.media):null}),s=e.computed(()=>{var g,b,R;return((g=t.item.upload)==null?void 0:g.status)==="uploading"||((b=t.item.upload)==null?void 0:b.status)==="pending"||((R=t.item.upload)==null?void 0:R.status)==="queued"}),l=e.computed(()=>{var g;return((g=t.item.upload)==null?void 0:g.status)==="processing"}),d=e.computed(()=>{var g;return((g=t.item.upload)==null?void 0:g.status)==="error"||t.item.errors&&t.item.errors.length>0}),c=e.computed(()=>{var g;return(g=t.item.upload)!=null&&g.error?t.item.upload.error:t.item.errors&&t.item.errors.length>0?t.item.errors[0].message:null}),u=e.computed(()=>{var g;return((g=t.item.upload)==null?void 0:g.progress)||0}),m=e.computed(()=>{var g;return t.item.name||((g=t.item.media)==null?void 0:g.file_name)||"Unknown file"}),f=e.computed(()=>{var T,S;const g=((T=t.item.media)==null?void 0:T.size)||((S=t.item.upload)==null?void 0:S.file.size);if(!g)return"";const b=1024,R=["Bytes","KB","MB","GB"],N=Math.floor(Math.log(g)/Math.log(b));return parseFloat((g/Math.pow(b,N)).toFixed(2))+" "+R[N]}),p=e.computed(()=>{var b,R;const g=((b=t.item.media)==null?void 0:b.mime_type)||((R=t.item.upload)==null?void 0:R.file.type);return g==null?void 0:g.startsWith("image/")}),h=e.computed(()=>({"media-item":!0,"media-item--uploading":s.value,"media-item--processing":l.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 E(){t.disabled||n("edit",t.item)}function y(){t.disabled||n("retry",t.item)}function k(){t.disabled||n("cancel",t.item)}return(g,b)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(h.value),"data-index":g.index,onMouseenter:b[0]||(b[0]=R=>i.value=!0),onMouseleave:b[1]||(b[1]=R=>i.value=!1)},[g.sortable&&!g.disabled?(e.openBlock(),e.createElementBlock("div",YL,[...b[2]||(b[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",QL,[r.value&&p.value?(e.openBlock(),e.createElementBlock("img",{key:0,src:r.value,alt:m.value,class:"media-item__image"},null,8,eP)):(e.openBlock(),e.createElementBlock("div",tP,[...b[3]||(b[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)])])),s.value?(e.openBlock(),e.createElementBlock("div",aP,[e.createElementVNode("div",{class:"media-item__progress-bar",style:e.normalizeStyle({width:`${u.value}%`})},null,4),e.createElementVNode("span",nP,e.toDisplayString(u.value)+"%",1)])):e.createCommentVNode("",!0),l.value?(e.openBlock(),e.createElementBlock("div",oP,[...b[4]||(b[4]=[e.createElementVNode("div",{class:"media-item__spinner","aria-label":"Processing"},null,-1)])])):e.createCommentVNode("",!0),d.value?(e.openBlock(),e.createElementBlock("div",iP,[...b[5]||(b[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",rP,[e.createElementVNode("span",{class:"media-item__name",title:m.value},e.toDisplayString(m.value),9,sP),f.value?(e.openBlock(),e.createElementBlock("span",lP,e.toDisplayString(f.value),1)):e.createCommentVNode("",!0),c.value?(e.openBlock(),e.createElementBlock("span",dP,e.toDisplayString(c.value),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",cP,[s.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-item__action media-item__action--cancel",disabled:g.disabled,"aria-label":"Cancel upload",onClick:k},[...b[6]||(b[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,uP)):e.createCommentVNode("",!0),d.value?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button",class:"media-item__action media-item__action--retry",disabled:g.disabled,"aria-label":"Retry upload",onClick:y},[...b[7]||(b[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,mP)):e.createCommentVNode("",!0),g.showEdit&&g.item.media&&!s.value?(e.openBlock(),e.createElementBlock("button",{key:2,type:"button",class:"media-item__action media-item__action--edit",disabled:g.disabled,"aria-label":"Edit",onClick:E},[...b[8]||(b[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,pP)):e.createCommentVNode("",!0),g.showRemove?(e.openBlock(),e.createElementBlock("button",{key:3,type:"button",class:"media-item__action media-item__action--remove",disabled:g.disabled,"aria-label":"Remove",onClick:v},[...b[9]||(b[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,fP)):e.createCommentVNode("",!0)])],42,qL))}}),Wd=Fe(hP,[["__scopeId","data-v-ff81c9ec"]]),vP=["aria-label"],gP=["draggable","data-index","onDragstart","onDragover","onDragend","onDrop"],bP={key:0,class:"media-collection__footer"},yP={class:"media-collection__count"},wP={key:0},kP={key:0,class:"media-collection__uploading"},_P=["name","value"],EP=["name","value"],SP=["name","value"],CP=["name","value"],xP={key:3,class:"media-collection__errors",role:"alert","aria-live":"polite"},VP=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:I=>{n("update:modelValue",I),n("change",I)},onUpload:I=>{n("upload",I)},onUploadComplete:I=>{n("upload-complete",I)},onUploadError:I=>{n("upload-error",I)},onRemove:I=>{n("remove",I)},onReorder:I=>{n("reorder",I)},onError:I=>{n("validation-error",I)},onReadyToSubmitChange:I=>{n("is-ready-to-submit-change",I)}},{items:r,setItems:s,addFiles:l,removeItem:d,reorderItems:c,cancelUpload:u,retryUpload:m,isLoading:f,isUploading:p,isAtMaxItems:h,errors:v,dragState:E,getDragProps:y,adapter:k,formValues:g,acceptString:b,count:R,remainingSlots:N}=Ns(i);e.provide("mediaAdapter",k),e.provide("mediaCollection",{items:r,addFiles:l,removeItem:d,reorderItems:c}),e.watch(()=>t.modelValue,I=>{I!==r.value&&s(I)},{deep:!0});const T=e.computed(()=>t.showUploadZone&&!t.disabled&&!t.readonly&&!h.value),S=e.computed(()=>({"media-collection":!0,"media-collection--disabled":t.disabled,"media-collection--readonly":t.readonly,"media-collection--loading":f.value,"media-collection--has-items":r.value.length>0,"media-collection--dragging":E.value.isDragging}));function B(I){l(I)}function A(I){d(I)}function x(I){m(I.clientId)}function M(I){u(I.clientId)}function w(I){}function F(I,Z,z){if(!t.sortable||t.disabled)return;const K=y(Z,z);K.onDragstart&&K.onDragstart(I)}function P(I,Z){if(!t.sortable||t.disabled)return;I.preventDefault();const z=r.value[Z],K=y(z,Z);K.onDragover&&K.onDragover(I)}function D(I,Z){const z=y(I,Z);z.onDragend&&z.onDragend()}function O(I,Z){I.preventDefault();const z=r.value[Z],K=y(z,Z);K.onDrop&&K.onDrop(I)}return(I,Z)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(S.value)},[e.renderSlot(I.$slots,"dropzone",{addFiles:e.unref(l)},()=>[T.value?(e.openBlock(),e.createBlock(jd,{key:0,accept:e.unref(b),multiple:I.maxItems!==1,disabled:I.disabled,"max-file-size":I.maxFileSize,"max-items":e.unref(N),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(R)} media items`},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(r),(z,K)=>e.renderSlot(I.$slots,"item",{key:z.clientId,item:z,index:K,remove:()=>A(z)},()=>[e.createElementVNode("div",{class:e.normalizeClass(["media-collection__item-wrapper",{"media-collection__item-wrapper--drag-over":e.unref(E).dropIndex===K}]),draggable:I.sortable&&!I.disabled,"data-index":K,onDragstart:se=>F(se,z,K),onDragover:se=>P(se,K),onDragend:se=>D(z,K),onDrop:se=>O(se,K)},[e.createVNode(Wd,{item:z,adapter:e.unref(k),disabled:I.disabled,sortable:I.sortable,"show-remove":!I.readonly,"show-edit":!1,index:K,onRemove:A,onRetry:x,onCancel:M,onEdit:w},null,8,["item","adapter","disabled","sortable","show-remove","index"])],42,gP)],!0)),128))],8,vP)):T.value?e.createCommentVNode("",!0):e.renderSlot(I.$slots,"empty",{key:1},()=>[Z[0]||(Z[0]=e.createElementVNode("div",{class:"media-collection__empty"},[e.createElementVNode("p",null,"No files uploaded")],-1))],!0),e.renderSlot(I.$slots,"footer",{count:e.unref(R),isUploading:e.unref(p)},()=>[e.unref(r).length>0?(e.openBlock(),e.createElementBlock("div",bP,[e.createElementVNode("span",yP,[e.createTextVNode(e.toDisplayString(e.unref(R))+" "+e.toDisplayString(e.unref(R)===1?"file":"files")+" ",1),I.maxItems?(e.openBlock(),e.createElementBlock("span",wP," / "+e.toDisplayString(I.maxItems)+" max",1)):e.createCommentVNode("",!0)]),e.unref(p)?(e.openBlock(),e.createElementBlock("span",kP," Uploading... ")):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)],!0),I.generateFormFields?(e.openBlock(),e.createElementBlock(e.Fragment,{key:2},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(g),(z,K)=>(e.openBlock(),e.createElementBlock("input",{key:`${I.name}-${z.uuid}`,type:"hidden",name:`${I.name}[${K}][uuid]`,value:z.uuid},null,8,_P))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(g),(z,K)=>(e.openBlock(),e.createElementBlock("input",{key:`${I.name}-${z.uuid}-name`,type:"hidden",name:`${I.name}[${K}][name]`,value:z.name},null,8,EP))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(g),(z,K)=>(e.openBlock(),e.createElementBlock("input",{key:`${I.name}-${z.uuid}-order`,type:"hidden",name:`${I.name}[${K}][order]`,value:z.order},null,8,SP))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(g),(z,K)=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:`${I.name}-${z.uuid}-props`},[z.custom_properties?(e.openBlock(),e.createElementBlock("input",{key:0,type:"hidden",name:`${I.name}[${K}][custom_properties]`,value:JSON.stringify(z.custom_properties)},null,8,CP)):e.createCommentVNode("",!0)],64))),128))],64)):e.createCommentVNode("",!0),e.unref(v).length>0?(e.openBlock(),e.createElementBlock("div",xP,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(v),z=>(e.openBlock(),e.createElementBlock("p",{key:z.code||z.message,class:"media-collection__error"},e.toDisplayString(z.message),1))),128))])):e.createCommentVNode("",!0)],2))}}),NP=Fe(VP,[["__scopeId","data-v-10a5bfff"]]);function Hd(o={}){const{initialItem:a,onChange:t,onReplace:n,onUpload:i,onUploadComplete:r,onUploadError:s,onRemove:l,onError:d,onReadyToSubmitChange:c,...u}=o,f={...u,initialItems:a?[a]:[],maxItems:1,sortable:!1,onChange:T=>{t==null||t(T[0]||null)},onUpload:i,onUploadComplete:r,onUploadError:s,onRemove:l,onError:d,onReadyToSubmitChange:c},p=Ns(f),h=e.computed(()=>p.items.value[0]||null),v=e.computed(()=>h.value!==null),E=e.computed(()=>p.formValues.value[0]||null);function y(T){T===null?p.clearAll():p.setItems([T])}async function k(T){const S=h.value;S&&p.removeItem(S),await p.addFiles([T])}function g(){h.value&&p.removeItem(h.value)}async function b(T){const S=h.value;S&&p.removeItem(S),await p.addFiles([T]);const B=p.items.value[0];B&&(n==null||n(S,B))}function R(){var T;(T=h.value)!=null&&T.upload&&p.cancelUpload(h.value.clientId)}async function N(){var T,S;((S=(T=h.value)==null?void 0:T.upload)==null?void 0:S.status)==="error"&&await p.retryUpload(h.value.clientId)}return{item:h,setItem:y,addFile:k,removeItem:g,replaceItem:b,cancelUpload:R,retryUpload:N,save:p.save,load:p.load,isLoading:p.isLoading,isUploading:p.isUploading,isReadyToSubmit:p.isReadyToSubmit,hasItem:v,errors:p.errors,adapter:p.adapter,formValue:E,acceptString:p.acceptString}}const TP=["accept","disabled"],BP={class:"media-attachment__preview"},MP=["name","value"],IP=["name","value"],$P=["name","value"],FP=["name","value"],DP={key:4,class:"media-attachment__errors",role:"alert","aria-live":"polite"},RP=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:s,setItem:l,addFile:d,removeItem:c,replaceItem:u,cancelUpload:m,retryUpload:f,isLoading:p,hasItem:h,errors:v,adapter:E,formValue:y,acceptString:k}=Hd(r);e.provide("mediaAdapter",E),e.watch(()=>t.modelValue,x=>{x!==s.value&&l(x)},{deep:!0});const g=e.computed(()=>t.showUploadZone&&!t.disabled&&!t.readonly&&!h.value),b=e.computed(()=>({"media-attachment":!0,"media-attachment--disabled":t.disabled,"media-attachment--readonly":t.readonly,"media-attachment--loading":p.value,"media-attachment--has-item":h.value}));function R(x){x.length>0&&d(x[0])}function N(){var x;(x=i.value)==null||x.click()}function T(x){const M=x.target,w=M.files;w&&w.length>0&&u(w[0]),M.value=""}function S(x){c()}function B(x){f()}function A(x){m()}return(x,M)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(b.value)},[e.createElementVNode("input",{ref_key:"fileInputRef",ref:i,type:"file",accept:e.unref(k),disabled:x.disabled,class:"media-attachment__hidden-input",onChange:T},null,40,TP),g.value?e.renderSlot(x.$slots,"dropzone",{key:0,addFile:e.unref(d)},()=>[e.createVNode(jd,{accept:e.unref(k),multiple:!1,disabled:x.disabled,"max-file-size":x.maxFileSize,onFiles:R},null,8,["accept","disabled","max-file-size"])],!0):e.unref(h)&&e.unref(s)?e.renderSlot(x.$slots,"preview",{key:1,item:e.unref(s),remove:e.unref(c),replace:N},()=>[e.createElementVNode("div",BP,[e.createVNode(Wd,{item:e.unref(s),adapter:e.unref(E),disabled:x.disabled,sortable:!1,"show-remove":!x.readonly,"show-edit":!1,onRemove:S,onRetry:B,onCancel:A},null,8,["item","adapter","disabled","show-remove"]),x.showReplaceButton&&!x.readonly&&!x.disabled&&e.unref(s).media?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-attachment__replace-button",onClick:N},[...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(y)?(e.openBlock(),e.createElementBlock(e.Fragment,{key:3},[e.createElementVNode("input",{type:"hidden",name:`${x.name}[uuid]`,value:e.unref(y).uuid},null,8,MP),e.createElementVNode("input",{type:"hidden",name:`${x.name}[name]`,value:e.unref(y).name},null,8,IP),e.createElementVNode("input",{type:"hidden",name:`${x.name}[order]`,value:e.unref(y).order},null,8,$P),e.unref(y).custom_properties?(e.openBlock(),e.createElementBlock("input",{key:0,type:"hidden",name:`${x.name}[custom_properties]`,value:JSON.stringify(e.unref(y).custom_properties)},null,8,FP)):e.createCommentVNode("",!0)],64)):e.createCommentVNode("",!0),e.unref(v).length>0?(e.openBlock(),e.createElementBlock("div",DP,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(v),w=>(e.openBlock(),e.createElementBlock("p",{key:w.code||w.message,class:"media-attachment__error"},e.toDisplayString(w.message),1))),128))])):e.createCommentVNode("",!0)],2))}}),AP=Fe(RP,[["__scopeId","data-v-26911174"]]),Hf={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"}},LP=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:s,setItems:l,addFiles:d,removeItem:c,reorderItems:u,updateItem:m,cancelUpload:f,retryUpload:p,isLoading:h,isUploading:v,isReadyToSubmit:E,isAtMaxItems:y,errors:k,dragState:g,getDragProps:b,adapter:R,formValues:N,acceptString:T}=Ns(r);e.provide("mediaAdapter",R),e.provide("mediaCollection",{items:s,addFiles:d,removeItem:c,reorderItems:u}),e.watch(()=>n.modelValue,x=>{x!==s.value&&l(x)},{deep:!0});const S=e.computed(()=>({...Hf,...n.labels})),B=e.computed(()=>({accept:T.value,multiple:n.maxItems!==1,disabled:n.disabled||n.readonly||y.value})),A=e.computed(()=>({items:s.value,isLoading:h.value,isUploading:v.value,isReadyToSubmit:E.value,isAtMaxItems:y.value,errors:k.value,addFiles:d,removeItem:c,reorderItems:u,clearAll:()=>{s.value.forEach(x=>c(x))},cancelUpload:f,retryUpload:p,labels:S.value,dropzoneProps:B.value}));return a({items:s,addFiles:d,removeItem:c,reorderItems:u,updateItem:m,cancelUpload:f,retryUpload:p,isLoading:h,isUploading:v,isReadyToSubmit:E,isAtMaxItems:y,errors:k,dragState:g,getDragProps:b,adapter:R,formValues:N,acceptString:T}),(x,M)=>e.renderSlot(x.$slots,"default",e.normalizeProps(e.guardReactiveProps(A.value)))}}),PP=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:S=>{i("update:modelValue",S),i("change",S)},onUpload:S=>{i("upload",S)},onUploadComplete:S=>{i("upload-complete",S)},onUploadError:S=>{i("upload-error",S)},onRemove:S=>{i("remove",S)},onReplace:(S,B)=>{i("replace",B)},onError:S=>{i("validation-error",S)},onReadyToSubmitChange:S=>{i("is-ready-to-submit-change",S)}},{item:s,setItem:l,addFile:d,removeItem:c,replaceItem:u,cancelUpload:m,retryUpload:f,isLoading:p,isUploading:h,isReadyToSubmit:v,hasItem:E,errors:y,adapter:k,formValue:g,acceptString:b}=Hd(r);e.provide("mediaAdapter",k),e.watch(()=>n.modelValue,S=>{S!==s.value&&l(S)},{deep:!0});const R=e.computed(()=>({...Hf,...n.labels})),N=e.computed(()=>({accept:b.value,multiple:!1,disabled:n.disabled||n.readonly||E.value})),T=e.computed(()=>({item:s.value,hasItem:E.value,isLoading:p.value,isUploading:h.value,isReadyToSubmit:v.value,errors:y.value,addFile:d,removeItem:c,replaceItem:u,cancelUpload:m,retryUpload:f,labels:R.value,dropzoneProps:N.value}));return a({item:s,setItem:l,addFile:d,removeItem:c,replaceItem:u,cancelUpload:m,retryUpload:f,isLoading:p,isUploading:h,isReadyToSubmit:v,hasItem:E,errors:y,adapter:k,formValue:g,acceptString:b}),(S,B)=>e.renderSlot(S.$slots,"default",e.normalizeProps(e.guardReactiveProps(T.value)))}}),UP=["name","value"],OP=["name","value"],zP=["name","value"],jP=["name","value"],WP=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(()=>Ud(t.value));function i(l,d){var u;const c=((u=n.value[l])==null?void 0:u.uuid)||"";return`${a.name}[${c}][${d}]`}function r(l,d){return`${a.name}[${l}][${d}]`}function s(l,d){return a.format==="spatie"?i(l,d):r(l,d)}return(l,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:s(u,"uuid"),value:c.uuid},null,8,UP),e.createElementVNode("input",{type:"hidden",name:s(u,"name"),value:c.name},null,8,OP),e.createElementVNode("input",{type:"hidden",name:s(u,"order"),value:c.order},null,8,zP),c.custom_properties&&Object.keys(c.custom_properties).length>0?(e.openBlock(),e.createElementBlock("input",{key:0,type:"hidden",name:s(u,"custom_properties"),value:JSON.stringify(c.custom_properties)},null,8,jP)):e.createCommentVNode("",!0)],64))),128))}}),HP=["data-testid"],ZP=["data-testid"],GP=["id"],XP=["value","maxlength","disabled","aria-labelledby","placeholder","data-testid","onInput"],KP=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,s){const l=s.target;l instanceof HTMLInputElement&&n("update:items",t.items.map((d,c)=>c!==r?d:{...d,caption:l.value===""?null:l.value}))}return(r,s)=>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,(l,d)=>(e.openBlock(),e.createElementBlock("div",{key:l._key??l.id??`${l.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(l,d)),9,GP),e.createElementVNode("input",{value:l.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,XP)],8,ZP))),128))],8,HP)):e.createCommentVNode("",!0)}}),JP=Fe(KP,[["__scopeId","data-v-a153768a"]]);exports.AlbumBrowser=rf;exports.AlbumManager=O5;exports.AlbumMediaGrid=Q5;exports.AlbumNavRail=Tf;exports.AlbumTree=Vs;exports.ArrayBufferTarget=id;exports.ExistingMediaSelector=kb;exports.ImageEditor=am;exports.ImageEditorModal=nm;exports.LiveStreamManager=l5;exports.ManagedMediaGallery=Yh;exports.MediaAlbumInlineCreate=Bd;exports.MediaAlbumPickerModal=Nf;exports.MediaAlbumUnavailableState=sf;exports.MediaAttachment=AP;exports.MediaAttachmentMetadataFields=JP;exports.MediaBulkActionBar=Rd;exports.MediaCollection=NP;exports.MediaCollectionDropzone=jd;exports.MediaCollectionItem=Wd;exports.MediaEmptyState=Of;exports.MediaFilterChips=Af;exports.MediaInspectorPanel=Rf;exports.MediaLibraryPicker=Vf;exports.MediaLibraryPickerModal=V6;exports.MediaLibraryShell=SL;exports.MediaLibraryToolbar=Bf;exports.MediaLibraryWorkspace=Uf;exports.MediaManagementView=Pf;exports.MediaPreviewSheet=Md;exports.MediaSelectionTray=DL;exports.MediaShortcutHelp=Mf;exports.MediaSourceSheet=ff;exports.MediaThumbnailCell=vf;exports.MediaTrashWorkspace=zf;exports.MediaUploadSheet=hf;exports.MediaUsageList=$f;exports.MediaVariantStrip=Ff;exports.MediaWorkspace=Xh;exports.ModelMediaManager=jg;exports.Muxer=xm;exports.RequiresConfirmationError=Ad;exports.VideoEditor=Yp;exports.VideoEditorDialog=H4;exports.VideoEditorSimple=hM;exports.VideoExportPanel=XI;exports.VideoJobClient=Ss;exports.VideoPlayer=af;exports.VideoTimeline=PM;exports.VideoToolsPanel=NI;exports.VideoUploader=D3;exports.VirtualMediaGrid=gf;exports._sfc_main=LP;exports._sfc_main$1=PP;exports._sfc_main$2=WP;exports.applyTemporaryMediaStoreConfig=Xu;exports.configureAlbumStore=nf;exports.configureMediaStore=Io;exports.createAdapter=jf;exports.createEmptyEditorState=yh;exports.createImageEditor=AL;exports.createMediablesAdapter=Od;exports.createSpatieAdapter=zd;exports.deserializeEditorState=bh;exports.formatFileSize=qr;exports.fromMediaArray=Jl;exports.getFileExtension=bf;exports.getImageDimensions=yf;exports.getMediablesAdapter=LL;exports.getSpatieAdapter=OL;exports.isImageFile=Id;exports.normalizeEditorState=ql;exports.normalizeRecipeForServerRender=x4;exports.recipeHasServerRenderableEdits=C4;exports.recipeHasUnsupportedServerEdits=tf;exports.resetMediablesAdapter=PL;exports.resetSpatieAdapter=zL;exports.restoreAlbumStoreConfig=b5;exports.restoreMediaStoreConfig=Gu;exports.serializeEditorState=Hu;exports.snapshotAlbumStoreConfig=g5;exports.snapshotMediaStoreConfig=Zu;exports.toFormValues=Ud;exports.useAdminMediaStore=Ku;exports.useAlbumDragDrop=of;exports.useAlbumStore=xs;exports.useAlbums=Td;exports.useGlobalImageEditor=RL;exports.useImageEditorModal=Pd;exports.useMediaAttachment=Hd;exports.useMediaCollection=Ns;exports.useMediaDeletion=Lf;exports.useMediaDragSort=Wf;exports.useMediaLibraryPickerController=xf;exports.useMediaLibraryQuery=Dd;exports.useMediaLibrarySession=_f;exports.useMediaLibraryStateMachine=Ef;exports.useMediaLibraryTelemetry=Sf;exports.useMediaLibraryUploads=If;exports.useMediaSelection=es;exports.useMediaStore=xa;exports.useMediaTrash=Ld;exports.useMediaUploadQueue=Fd;exports.useMediaValidation=$d;exports.validateFile=wf;
|
|
357
|
+
//# sourceMappingURL=index-DCTHBp0p.cjs.map
|