@codingfactory/mediables-vue 2.13.0 → 2.15.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-BnAievFi.cjs → PixiFrameExporter-F0BnA8PJ.cjs} +2 -2
- package/dist/{PixiFrameExporter-BnAievFi.cjs.map → PixiFrameExporter-F0BnA8PJ.cjs.map} +1 -1
- package/dist/{PixiFrameExporter-DwbBy1Iu.js → PixiFrameExporter-QBVjL5I-.js} +2 -2
- package/dist/{PixiFrameExporter-DwbBy1Iu.js.map → PixiFrameExporter-QBVjL5I-.js.map} +1 -1
- package/dist/editor-DLvndiXG.cjs +2 -0
- package/dist/editor-DLvndiXG.cjs.map +1 -0
- package/dist/{editor-BoDU3YXD.js → editor-OIsQEaJg.js} +18 -2
- package/dist/editor-OIsQEaJg.js.map +1 -0
- package/dist/index-CdE6UIlk.cjs +357 -0
- package/dist/index-CdE6UIlk.cjs.map +1 -0
- package/dist/{index-BGC4rPDc.js → index-CxgL9IC3.js} +5786 -5758
- package/dist/index-CxgL9IC3.js.map +1 -0
- package/dist/mediables-vanilla.cjs +1 -1
- package/dist/mediables-vanilla.mjs +1 -1
- package/dist/mediables-vue.cjs +1 -1
- package/dist/mediables-vue.mjs +2 -2
- package/dist/style.css +1 -1
- package/package.json +1 -1
- package/dist/editor-BoDU3YXD.js.map +0 -1
- package/dist/editor-D-cJRASf.cjs +0 -2
- package/dist/editor-D-cJRASf.cjs.map +0 -1
- package/dist/index-BGC4rPDc.js.map +0 -1
- package/dist/index-CljyFIEv.cjs +0 -357
- package/dist/index-CljyFIEv.cjs.map +0 -1
package/dist/index-CljyFIEv.cjs
DELETED
|
@@ -1,357 +0,0 @@
|
|
|
1
|
-
"use strict";var Mf=Object.defineProperty;var Ff=(o,a,t)=>a in o?Mf(o,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[a]=t;var Y=(o,a,t)=>Ff(o,typeof a!="symbol"?a+"":a,t);const zr=require("pinia"),e=require("vue"),gt=require("pixi.js"),te=require("./editor-D-cJRASf.cjs"),W=require("@ionic/vue"),$f=require("pixi-filters");function Df(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 Dt=Df(gt),tl=1,Rf=new Set(["free","square","circle"]);function Af(o){if(typeof o!="number"||!Number.isFinite(o))return 0;const a=o%360;return a<0?a+360:a}function Lf(o){const a=typeof o;return a==="string"||a==="number"||a==="boolean"}function Pf(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 jl(o){if(!o||typeof o!="object")return null;const a=o;if(a.version!==tl)return null;const t=a.crop,n=t&&Pf(t.rect)?{...t.rect}:null,i=t&&typeof t.shape=="string"&&Rf.has(t.shape)?t.shape:"free",r=t&&typeof t.aspectRatio=="string"?t.aspectRatio:"free",s=a.transform,l=Af(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 f=u;if(typeof f.id!="string")continue;const m={},p=f.values;if(p&&typeof p=="object"&&!Array.isArray(p))for(const[h,v]of Object.entries(p))Lf(v)&&(m[h]=v);c.push({id:f.id,enabled:f.enabled!==!1,values:m})}return{version:tl,crop:{rect:n,aspectRatio:r,shape:i},transform:{rotation:l},filters:c}}function Eu(o){const a=jl(o);return a?JSON.stringify(a):null}function Uf(o){try{const a=JSON.parse(o);return jl(a)}catch{return null}}function Of(){return{version:tl,crop:{rect:null,aspectRatio:"free",shape:"free"},transform:{rotation:0},filters:[]}}let ra={apiBaseUrl:"/api/v1",isAdmin:!1};function Wd(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 wo(o){ra={...ra,...o}}function xu(){return{...ra}}function Su(o){ra={...o}}function Cu(o){const a=xu();return wo(o),()=>{Su(a)}}function zf(o){const a=o.trim().replace(/\/+$/,"");return a===""?"/api/v1":a.startsWith("/")?a:`/${a}`}function jf(o,a){const t=zf(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 Wf=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()},va=zr.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),f=e.ref(new Map),m=e.ref(new Map),p=e.ref(new Set),h=e.ref(new Map),v=e.ref({}),w=5*60*1e3,x=e.computed(()=>{if(ra.apiScope)return ra.apiScope;if(ra.isAdmin)return"admin"}),T=e.computed(()=>x.value==="admin");function _(){return ra.httpClient||Wf}function g(he){const ge=ra.apiBaseUrl||"/api/v1",pe=x.value?`/${x.value}`:"";return`${ge}${pe}${he}`}function E(he){return`${ra.apiBaseUrl||"/api/v1"}${he}`}function S(he,ge){return`${x.value??"default"}-${he}-${JSON.stringify(ge)}`}function N(he){return Date.now()-he<w}function V(){h.value.clear(),v.value={}}function A(he){if(!he||!he.data)return;const ge={};he.data.forEach(pe=>{const we=`${pe.file_name}-${pe.collection_name||"default"}`,ye=ge[we];(!ye||Object.keys(pe.generated_conversions||{}).length>Object.keys(ye.generated_conversions||{}).length)&&(ge[we]=pe)}),o.value=Object.values(ge),he.meta&&(i.value=he.meta.current_page,r.value=Math.ceil(he.meta.total/he.meta.per_page))}async function j(he=1,ge={}){const pe=S(he,ge),we=h.value.get(pe);if(we&&N(we.timestamp)){const ye=we.data;return A(ye),ye}t.value=!0,n.value=null;try{const ye=new URLSearchParams;ye.append("page",he.toString()),ye.append("per_page",s.value.toString()),T.value&&ye.append("linked","1");for(const Qe in ge)if(Object.prototype.hasOwnProperty.call(ge,Qe)){const et=ge[Qe];et!=null&&et!==""&&ye.append(Qe,String(et))}const De=await _()(g(`/media?${ye}`));return h.value.set(pe,{data:De,timestamp:Date.now()}),A(De),De}catch(ye){throw n.value=ye instanceof Error?ye.message:"Failed to fetch media",o.value=[],new Error(n.value)}finally{t.value=!1}}async function C(he,ge){t.value=!0,n.value=null;const pe=`${he.name}-${Date.now()}`,we={file:he,progress:0,status:"uploading"};f.value.set(pe,we);try{const ye=new FormData;ye.append("file",he),ye.append("collection",ge.collection),ge.ownerUuid&&(ye.append("owner_uuid",ge.ownerUuid),ye.append("owner_type",ge.ownerType||"")),ge.usageUuid&&(ye.append("usage_uuid",ge.usageUuid),ye.append("usage_type",ge.usageType||""),ye.append("usage_purpose",ge.usagePurpose||"")),ge.customProperties&&ye.append("custom_properties",JSON.stringify(ge.customProperties));const De=await _()(g("/media"),{method:"POST",body:ye});return we.status="completed",we.progress=100,we.media=De==null?void 0:De.data,i.value===1&&(De!=null&&De.data)&&(o.value=[De.data,...o.value]),V(),(De==null?void 0:De.data)||null}catch(ye){throw we.status="error",we.error=ye instanceof Error?ye.message:"Upload failed",n.value=we.error,new Error(n.value)}finally{t.value=!1,setTimeout(()=>{f.value.delete(pe)},5e3)}}async function $(he){t.value=!0,n.value=null;const ge=o.value.findIndex(we=>we.uuid===he);let pe;ge!==-1&&(pe=o.value.splice(ge,1)[0]);try{return await _()(g(`/media/${he}`),{method:"DELETE"}),p.value.delete(he),V(),!0}catch(we){throw pe&&ge!==-1&&o.value.splice(ge,0,pe),n.value=we instanceof Error?we.message:"Failed to delete media",new Error(n.value)}finally{t.value=!1}}async function y(he,ge){t.value=!0,n.value=null;try{const we=await _()(g(`/media/${he}`),{method:"PATCH",body:ge,data:ge});if(we!=null&&we.data){const ye=o.value.findIndex(Ne=>Ne.uuid===he);return ye!==-1&&(o.value[ye]={...o.value[ye],...we.data}),V(),we.data}return null}catch(pe){throw n.value=pe instanceof Error?pe.message:"Failed to update media",new Error(n.value)}finally{t.value=!1}}async function R(){t.value=!0,n.value=null;try{const ge=await _()(g("/media/collections"));return a.value=(ge==null?void 0:ge.data)||[],a.value}catch(he){throw n.value=he instanceof Error?he.message:"Failed to fetch collections",a.value=[],new Error(n.value)}finally{t.value=!1}}async function L(he,ge,pe="images",we){c.value=!0,u.value=null;try{const ye=new URLSearchParams;ye.append("collection",pe),we&&ye.append("search",we);const De=await _()(g(`/media/model/${he}/${ge}?${ye}`));return De!=null&&De.data?(d.value=De.data,De.data):[]}catch(ye){throw u.value=ye instanceof Error?ye.message:"Failed to fetch model media",d.value=[],new Error(u.value)}finally{c.value=!1}}async function U(he,ge,pe,we="images"){c.value=!0,u.value=null;const ye=[...d.value];try{const De=await _()(g(`/media/model/${he}/${ge}/attach`),{method:"POST",body:{media_uuids:pe,collection:we}});return await L(he,ge,we),(De==null?void 0:De.data)||[]}catch(Ne){throw d.value=ye,u.value=Ne instanceof Error?Ne.message:"Failed to attach media",new Error(u.value)}finally{c.value=!1}}async function z(he,ge,pe,we="images"){c.value=!0,u.value=null;const ye=[...d.value];d.value=d.value.filter(Ne=>Ne.uuid!==pe);try{return await _()(g(`/media/model/${he}/${ge}/detach`),{method:"POST",body:{media_uuid:pe,collection:we}}),!0}catch(Ne){throw d.value=ye,u.value=Ne instanceof Error?Ne.message:"Failed to detach media",new Error(u.value)}finally{c.value=!1}}async function I(he,ge,pe,we="images"){c.value=!0,u.value=null;const ye=[...d.value],Ne=new Map(d.value.map(De=>[De.uuid,De]));d.value=pe.map(De=>Ne.get(De)).filter(De=>De!==void 0);try{return await _()(g(`/media/model/${he}/${ge}/reorder`),{method:"POST",body:{media_uuids:pe,collection:we}}),!0}catch(De){throw d.value=ye,u.value=De instanceof Error?De.message:"Failed to reorder media",new Error(u.value)}finally{c.value=!1}}async function P(he,ge,pe={}){var rt,_t;const we=_(),ye=ra.apiBaseUrl||"/api/v1";let Ne=Wd(ge.documentId)?ge.documentId:Wd((rt=ge.document)==null?void 0:rt.id)?ge.document.id:null,De=ge.documentRevisionId??null,Qe=typeof ge.documentRevisionNumber=="number"?ge.documentRevisionNumber:typeof((_t=ge.document)==null?void 0:_t.revision)=="number"?ge.document.revision:null;if(ge.document){const be=await we(`${ye}/media/${he}/editor-documents/materialize`,{method:"POST",body:{document_id:Ne,base_document_revision:Qe,document:ge.document}});Ne=be.document_id,De=be.document_revision_id,Qe=be.document_revision_number}if(ge.document&&Ne&&De&&typeof Qe=="number"){const be=new FormData,Te=(ge.mimeType||ge.blob.type||"image/png")==="image/jpeg"?"jpg":"png";be.append("flattened_file",ge.blob,`edited.${Te}`),be.append("document_id",Ne),be.append("document_revision_id",De),be.append("expected_document_revision",String(Qe)),be.append("output_mode",pe.asVariant?"save-as-variant":"save-as-new");const Ke=await we(`${ye}/media/${he}/editor-documents/save`,{method:"POST",body:be});if(Ke.media)return Ke.media;throw new Error("Unexpected response from layered editor save endpoint")}const et=new FormData,kt=(ge.mimeType||ge.blob.type||"image/png")==="image/jpeg"?"jpg":"png";et.append("image_file",ge.blob,`edited.${kt}`);const Ct=Eu(ge.state);Ct&&et.append("editor_state",Ct),et.append("save_as_new","true"),pe.asVariant&&et.append("as_variant","true"),pe.name!==void 0&&et.append("name",pe.name);const bt=await we(`${ye}/editor/${he}/save`,{method:"POST",body:et});if("media"in bt&&bt.media)return bt.media;if("status_url"in bt&&bt.status_url)return Z(we,jf(bt.status_url,ye),pe.pollTimeout??6e4);throw new Error("Unexpected response from editor save endpoint")}async function Z(he,ge,pe){const we=Date.now(),ye=2e3;for(;Date.now()-we<pe;){await new Promise(De=>setTimeout(De,ye));const Ne=await he(ge);if(Ne.status==="completed"&&Ne.media)return Ne.media;if(Ne.status==="failed")throw new Error(Ne.error??"Image processing failed")}throw new Error("Image processing timed out")}function K(he,ge,pe){l.value=pe!==void 0?{type:he,uuid:ge,collection:pe}:{type:he,uuid:ge},v.value[`${he}-${ge}`]={timestamp:Date.now()}}function ve(){l.value={type:null,uuid:null},d.value=[],u.value=null}async function Ve(){if(!l.value.type||!l.value.uuid)return;const he=await L(l.value.type,l.value.uuid,l.value.collection||"images");d.value=he||[]}function ne(){o.value.forEach(he=>p.value.add(he.uuid))}function ae(){p.value.clear()}function F(he){p.value.has(he)?p.value.delete(he):p.value.add(he)}function B(he){return p.value.has(he)}function O(){return Array.from(f.value.values()).some(he=>he.status==="uploading")}function X(he){return f.value.get(he)||m.value.get(he)}function oe(){return[...Array.from(f.value.values()),...Array.from(m.value.values())]}async function ce(){const he=Array.from(p.value);let ge=0;for(const pe of he)try{await $(pe),ge++}catch{}return ae(),ge}function je(he,ge){var pe;return ge&&((pe=he.conversion_urls)!=null&&pe[ge])?he.conversion_urls[ge]||"":he.original_url||he.url||""}return{items:o,collections:a,loading:t,error:n,currentPage:i,totalPages:r,itemsPerPage:s,isAdmin:T,modelContext:l,modelMedia:d,isLoadingModelMedia:c,modelMediaError:u,selectedItems:p,uploadProgress:f,uploadQueue:m,cachedResponses:v,fetchMedia:j,uploadFile:C,deleteMedia:$,updateMedia:y,clearCache:V,fetchCollections:R,fetchModelMedia:L,attachMedia:U,detachMedia:z,reorderMedia:I,saveEditedImage:P,setModelContext:K,clearModelContext:ve,refreshModelMedia:Ve,selectAllItems:ne,clearSelection:ae,toggleSelection:F,isSelected:B,deleteSelectedItems:ce,getHttpClient:_,getApiUrl:g,getEditorApiUrl:E,hasActiveUploads:O,getUploadProgress:X,getAllUploadProgress:oe,getMediaUrl:je}}),Vu=()=>((ra.apiScope!=="admin"||ra.isAdmin!==!0)&&wo({...ra,apiScope:"admin",isAdmin:!0}),va());class Nu{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=te.el("div",{className:"panel-tabs",role:"tablist","aria-label":"Filter categories","data-testid":"v2-category-tabs"}),te.EDITOR_CATEGORIES.forEach(t=>{const n=te.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=te.el("span",{className:"panel-tab-icon","aria-hidden":"true"});i.innerHTML=t.icon,n.appendChild(i)}n.appendChild(te.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 Tu{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=te.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=te.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=te.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 m,p,h,v;u.stopPropagation();const f=!((p=(m=this.state.get("activeFilters"))==null?void 0:m.has)!=null&&p.call(m,a.id));(h=this._onToggle)==null||h.call(this,a.id,f,i),f&&((v=this._onSelect)==null||v.call(this,a.id,i))}});t&&(s.innerHTML=te.checkmark),r.appendChild(s);const l=te.el("div",{className:"filter-row-body"});l.appendChild(te.el("span",{className:"filter-row-name"},a.name));const d=this._buildSummary(a,t);d&&l.appendChild(te.el("span",{className:"filter-row-summary"},d)),r.appendChild(l);const c=te.el("span",{className:"filter-row-chevron","aria-hidden":"true"});return c.innerHTML=te.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(te.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 Iu{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=te.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(te.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(te.el("div",{className:"no-filter-selected"},"Filter not found"));return}const i=te.el("div",{className:"controls-header"});i.appendChild(te.el("span",{className:"controls-title"},n.name)),i.appendChild(te.createButton({label:"Reset",className:"btn-text",onClick:()=>this._handleReset(a,t)})),this.element.appendChild(i);const r=te.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,f=s[u]??c.default,m=this._createControl(a,c,f,t);m&&r.appendChild(m)})}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 te.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 te.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 te.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 te.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 te.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=te.el("div",{className:"button-control"});return d.appendChild(te.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 Hf{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=te.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=te.el("div",{className:"panel-section-title"});if(i.appendChild(te.el("span",{},`Active (${t})`)),t>0&&this._onClearAll&&i.appendChild(te.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(te.el("div",{className:"active-empty"},"No filters applied"));return}const r=te.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=te.el("div",{className:`active-chip ${t?"selected":""}`,"data-filter":a.id,"data-testid":`v2-active-${a.id}`});i.appendChild(te.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=te.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=te.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 mo=["collapsed","half","full"];class Zf{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=te.el("div",{className:"editor-v2-drawer",role:"dialog","aria-label":this._ariaLabel,"data-testid":"v2-bottom-drawer","data-snap":this._snap}),this._handle=te.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=te.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=te.el("div",{className:"drawer-header"}),a&&this._headerSlot.appendChild(a),this.element.appendChild(this._headerSlot),this._body=te.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={}){mo.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=mo.indexOf(this._snap),t=mo[(a+1)%mo.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=mo[0],n=1/0;for(const i of mo){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 Xf=[{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 Bu{constructor(a,t){this.state=a,this.editor=t,this.element=null,this._errorMessage=null,this._unsubscribers=[]}render(){return this.element=te.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(te.el("div",{className:"panel-section-title"},te.el("span",{},"Background"))),this._errorMessage&&this.element.appendChild(te.el("p",{className:"background-panel-error",role:"alert","data-testid":"v2-background-error"},this._errorMessage));const l=te.el("input",{type:"color",className:"color-input",value:s,disabled:r?"disabled":void 0,"aria-label":"Background color","data-testid":"v2-background-color",onInput:w=>{this._runAction(this.editor.setBackgroundColor(w.target.value))}});this.element.appendChild(this._field("Color",l));const d=te.el("div",{className:"background-gradient-grid"});for(const w of Xf){const x=te.el("button",{type:"button",className:"background-gradient-swatch",style:{background:w.style},"aria-label":w.ariaLabel,disabled:r?"disabled":void 0,"data-testid":`v2-background-gradient-${w.id}`,onClick:()=>{this._runAction(this.editor.setBackgroundGradient(w.fill))}},te.el("span",{className:"background-gradient-label"},w.label));d.appendChild(x)}this.element.appendChild(this._field("Gradient",d));const c=te.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:w=>{var T;const x=(T=w.target.files)==null?void 0:T[0];x&&this._runAction(this.editor.setBackgroundImageFromFile(x,{fit:n})),w.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 w=te.el("div",{className:"background-media-grid"});for(const x of u)x!=null&&x.source&&w.appendChild(te.el("button",{type:"button",className:"background-media-choice","aria-label":`Use ${x.label||"media"} as background`,disabled:r?"disabled":void 0,"data-testid":`v2-background-media-${x.id||x.source.mediaUuid||"choice"}`,onClick:()=>{this._runAction(this.editor.setBackgroundMediaSource(x.source,{fit:x.fit||n}))}},x.label||"Media"));this.element.appendChild(this._field("Media",w))}const f=te.el("select",{className:"select-input",disabled:r?"disabled":void 0,"aria-label":"Background image fit","data-testid":"v2-background-fit",onChange:w=>{this._runAction(this.editor.setBackgroundFit(w.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",f));const m=te.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:w=>{this._runAction(this.editor.setBackgroundBlur(Number(w.target.value)))}});this.element.appendChild(this._field("Blur",m)),this.element.appendChild(te.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 te.el("label",{className:"background-field"},te.el("span",{className:"background-field-label"},a),t)}_option(a,t,n){return te.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 Mu{constructor(a,t){this.state=a,this.editor=t,this.element=null,this._listEl=null,this._unsubscribers=[]}render(){return this.element=te.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(te.el("div",{className:"layer-stack-header"},te.el("span",{className:"layer-stack-title"},"Layers"),te.el("span",{className:"layer-stack-order"},"Bottom to top"))),this._listEl=te.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(te.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=te.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 m,p;return(p=(m=this.editor).selectLayer)==null?void 0:p.call(m,i)})},this._thumbnail(a))),u.appendChild(te.el("div",{className:"layer-row-main"},te.el("span",{className:"layer-row-name"},r),te.el("span",{className:"layer-row-meta"},this._layerTypeLabel(a))));const f=te.el("div",{className:"layer-row-actions"});return f.appendChild(this._iconButton({testId:`v2-layer-${s?"hide":"show"}-${i}`,label:`${s?"Hide":"Show"} ${r}`,icon:s?te.eye:te.eyeOff,disabled:l,onClick:()=>this._runAction(()=>{var m,p;return(p=(m=this.editor).setLayerVisibility)==null?void 0:p.call(m,i,!s)})})),f.appendChild(this._iconButton({testId:`v2-layer-${l?"unlock":"lock"}-${i}`,label:`${l?"Unlock":"Lock"} ${r}`,icon:l?te.lockClosed:te.lockOpen,onClick:()=>this._runAction(()=>{var m,p;return(p=(m=this.editor).setLayerLocked)==null?void 0:p.call(m,i,!l)})})),f.appendChild(this._iconButton({testId:`v2-layer-move-up-${i}`,label:`Move ${r} up`,icon:te.chevronRight,disabled:l,onClick:()=>this._runAction(()=>{var m,p;return(p=(m=this.editor).moveLayer)==null?void 0:p.call(m,i,"up")})})),f.appendChild(this._iconButton({testId:`v2-layer-move-down-${i}`,label:`Move ${r} down`,icon:te.chevronLeft,disabled:l,onClick:()=>this._runAction(()=>{var m,p;return(p=(m=this.editor).moveLayer)==null?void 0:p.call(m,i,"down")})})),f.appendChild(this._iconButton({testId:`v2-layer-bring-front-${i}`,label:`Bring ${r} to front`,icon:te.chevronRight,disabled:l,onClick:()=>this._runAction(()=>{var m,p;return(p=(m=this.editor).moveLayer)==null?void 0:p.call(m,i,"front")})})),f.appendChild(this._iconButton({testId:`v2-layer-send-back-${i}`,label:`Send ${r} to back`,icon:te.chevronLeft,disabled:l,onClick:()=>this._runAction(()=>{var m,p;return(p=(m=this.editor).moveLayer)==null?void 0:p.call(m,i,"back")})})),f.appendChild(this._iconButton({testId:`v2-layer-rename-${i}`,label:`Rename ${r}`,icon:te.pencil,disabled:l,onClick:()=>this._renameLayer(i,r)})),f.appendChild(this._iconButton({testId:`v2-layer-duplicate-${i}`,label:`Duplicate ${r}`,icon:te.duplicate,disabled:l,onClick:()=>this._runAction(()=>{var m,p;return(p=(m=this.editor).duplicateLayer)==null?void 0:p.call(m,i)})})),f.appendChild(this._iconButton({testId:`v2-layer-delete-${i}`,label:`Delete ${r}`,icon:te.trash,disabled:l||n<=1,onClick:()=>this._runAction(()=>{var m,p;return(p=(m=this.editor).deleteLayer)==null?void 0:p.call(m,i)})})),u.appendChild(f),u}_thumbnail(a){const t=te.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"?te.layers:te.move;return t}_button({testId:a,label:t,...n},i){const r=te.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=te.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 Gf=[{value:"400",label:"Regular"},{value:"500",label:"Medium"},{value:"600",label:"Semibold"},{value:"700",label:"Bold"},{value:"800",label:"Heavy"}],Jf=[{value:"left",label:"Left"},{value:"center",label:"Center"},{value:"right",label:"Right"}],Kf=[{value:"normal",label:"Normal"},{value:"multiply",label:"Multiply"},{value:"screen",label:"Screen"},{value:"overlay",label:"Overlay"}],Xi={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 Fu{constructor(a,t){this.state=a,this.editor=t,this.element=null,this._errorMessage=null,this._unsubscribers=[]}render(){return this.element=te.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(te.el("div",{className:"text-panel-header"},te.el("div",{className:"panel-section-title"},te.el("span",{},"Text")),te.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(te.el("p",{className:"text-panel-error",role:"alert","data-testid":"v2-text-error"},this._errorMessage)),!a){this.element.appendChild(te.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:Kf,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:te.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:Gf,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:Jf,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=te.el("div",{className:"text-field text-content-field"});i.appendChild(te.el("label",{className:"text-field-label",for:"v2-text-content"},"Content"));let r=t==null?"":String(t);const s=te.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=te.el("div",{className:"text-content-actions"});return l.appendChild(te.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(te.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=te.el("div",{className:"text-control-grid"});for(const n of a)t.appendChild(n);return t}_effectSection(a,t){return te.el("div",{className:"text-effect-section"},te.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=te.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(te.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=te.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=te.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=te.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 te.el("label",{className:"text-field text-checkbox-field"},te.el("span",{className:"text-field-label"},a),s)}_field(a,t){return te.el("label",{className:"text-field"},te.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:{...Xi.stroke,...t.stroke&&typeof t.stroke=="object"?t.stroke:{}},shadow:{...Xi.shadow,...t.shadow&&typeof t.shadow=="object"?t.shadow:{}},glow:{...Xi.glow,...t.glow&&typeof t.glow=="object"?t.glow:{}},backdrop:{...Xi.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 qf{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=te.el("div",{className:"drawer-nav","data-testid":"v2-mobile-nav"}),this._headerEl=te.el("div",{className:"drawer-nav-header"}),this.element.appendChild(this._headerEl),this._bodyEl=te.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 Nu(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 Tu(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 Iu(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 Bu(this.state,this.editor),this._backgroundPanelEl=this._backgroundPanel.render(),this._layerStackPanel=new Mu(this.state,this.editor),this._layerStackPanelEl=this._layerStackPanel.render(),this._textPanel=new Fu(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=te.el("button",{type:"button",className:"drawer-back-btn","aria-label":"Go back","data-testid":"v2-drawer-back",onClick:()=>this._goBack()});n.innerHTML=te.chevronLeft,this._headerEl.appendChild(n)}const t=this._titleForView(this._view);if(this._headerEl.appendChild(te.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(te.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=te.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 Yf{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=te.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=te.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=te.el("div",{className:`mobile-active-chip ${t?"selected":""}`,"data-filter":a.id,"data-testid":`v2-mobile-chip-${a.id}`});i.appendChild(te.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=te.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=te.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 Hd="(max-width: 900px)";let Qf=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=te.el("div",{className:"editor-v2-body"}),this.canvasSection=te.el("div",{className:"editor-v2-canvas"}),this.canvasContainer=te.el("div",{className:"canvas-container"}),this.cropOverlay=te.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,Hd).matches)===!0,this._isMobile?this._buildMobileShell():this._buildDesktopShell(),typeof window<"u"&&window.matchMedia&&(this._mql=window.matchMedia(Hd),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=te.el("div",{className:"editor-v2-panel","data-testid":"v2-inspector-panel"}),this._categoryTabs=new Nu(this.state,this.editor),this._panel.appendChild(this._categoryTabs.render({onSelect:()=>this._handleDesktopCategoryChange()}));const a=te.el("div",{className:"panel-body"});this._desktopFilterListSection=te.el("div",{className:"panel-section"}),this._desktopFilterListSection.appendChild(te.el("div",{className:"panel-section-title"},te.el("span",{},"Filters"))),this._filterListView=new Tu(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 Iu(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=te.el("div",{className:"crop-controls-wrapper",style:{display:"none"}}),a.appendChild(this._desktopCropWrapper),this._activeStack=new Hf(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=te.el("div",{className:"panel-section",style:{display:"none"}}),this._backgroundPanel=new Bu(this.state,this.editor),this._desktopBackgroundSection.appendChild(this._backgroundPanel.render()),a.appendChild(this._desktopBackgroundSection),this._desktopLayerSection=te.el("div",{className:"panel-section",style:{display:"none"}}),this._layerStackPanel=new Mu(this.state,this.editor),this._desktopLayerSection.appendChild(this._layerStackPanel.render()),a.appendChild(this._desktopLayerSection),this._desktopTextSection=te.el("div",{className:"panel-section",style:{display:"none"}}),this._textPanel=new Fu(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 Yf(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 Zf({onSnapChange:r=>{this.canvasContainer&&window.dispatchEvent(new Event("resize"))}}),this._mobileNav=new qf(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=te.el("div",{className:"crop-controls-wrapper",style:{display:"none"}});const n=te.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 ho(o){if(!Number.isFinite(Number(o)))return 0;const a=Number(o)%360;return a<0?a+360:a}function eh(o,a){const t=ho(o);return(ho(a)-t+540)%360-180}function th(){return new Date().toISOString()}function Bs(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 ah extends te.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?te.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=te.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 te.PixiRenderer,this._filterManager=new te.FilterManager(this._state,this._renderer),this._cropManager=new te.CropManager(this._state,this._renderer),this._removeBgManager=null,this._backgroundRemovalAvailable=!1,((r=this._options.backgroundRemoval)==null?void 0:r.enabled)!==!1&&(this._removeBgManager=new te.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=te.el("div",{className:`vanilla-image-editor-v2 ${this._state.get("isDarkMode")?"dark":"light"}`}),this._toolbarContainer=te.el("div",{className:"editor-v2-toolbar"}),this._editorEl.appendChild(this._toolbarContainer),this._layout=new Qf(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=te.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 te.Toolbar(this._state,this),this._toolbarContainer.appendChild(this._toolbar.render()),this._cropControls=new te.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=te.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=await fetch(s,{method:"POST",credentials:"include",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({document_id:i.documentId,base_document_revision:i.documentRevisionNumber,document:r})});let c=null;try{c=await d.json()}catch{c=null}if(!d.ok){const u=(c==null?void 0:c.message)||a;throw new Error(u)}return this._isCurrentDocumentMaterializationContext(l)?(c!=null&&c.document&&this._state.setEditorDocument(c.document,{documentId:c.document_id??i.documentId,documentRevisionId:c.document_revision_id??i.documentRevisionId,documentRevisionNumber:typeof c.document_revision_number=="number"?c.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 f=await u.json(),m=(v=f==null?void 0:f.asset)==null?void 0:v.source;if(!m||typeof m!="object")throw new Error("Background upload did not return a usable layer source");return{...m,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.state&&this._hydrateState(t.state),t.document?await this._hydrateDocument(t.document,{documentId:t.documentId??(Bs((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),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 l,d;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=th(),s={version:2,id:`client-doc-${Date.now()}`,sourceMediaUuid:null,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:{kind:"runtime",runtimeRef:"source-image",originalWidth:n,originalHeight:i,sourceHash:null,previewUrl:typeof a=="string"?a:null},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(s,{documentId:null,documentRevisionId:null,documentRevisionNumber:0}),(d=(l=this._renderer).renderLayerDocument)==null||d.call(l,s,{fallbackImageUrl:typeof a=="string"?a:null})}async _hydrateDocument(a,t={}){var n,i;!a||a.version!==2||(this._state.setEditorDocument(a,{documentId:t.documentId??(Bs(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=ho(((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=te.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)??(Bs(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:ho(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=ho(this._state.get("transform.rotation")??0),n=ho(a),i=eh(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,f;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 m=this._activeBackgroundRemovalLayer();if(this._hasSavedEditorDocumentBinding()&&m!==null&&this._backgroundMaterializeEndpoint()&&!await this._materializeCurrentDocument("Background removal materialization failed"))return this.emit("background-removal-stale",{operationId:a.operationId??null,targetLayerId:m.id}),{stale:!0};const p=this._buildSavedBackgroundRemovalContext(a);if(p){const g=await this._removeBgManager.removeSavedMediaBackground(p.request);if(!this._isCurrentBackgroundRemovalContext(p,g))return this.emit("background-removal-stale",{operationId:p.request.operationId,targetLayerId:p.request.targetLayerId}),{stale:!0};const E=(t=g==null?void 0:g.result)==null?void 0:t.source;if(!E||E.kind!=="edit-asset")throw new Error("Background removal did not return a persisted layer source");const S=(n=g==null?void 0:g.result)==null?void 0:n.previewDataUrl;return typeof S=="string"&&S.startsWith("data:image/")&&(!await this._renderer.loadTexture(S,{isCurrent:()=>!this._destroyed&&this._isCurrentBackgroundRemovalContext(p,g)})||!this._isCurrentBackgroundRemovalContext(p,g))?(this.emit("background-removal-stale",{operationId:p.request.operationId,targetLayerId:p.request.targetLayerId}),{stale:!0}):this._isCurrentBackgroundRemovalContext(p,g)?(this._state.replaceLayerSource(p.request.targetLayerId,E),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=g==null?void 0:g.result)==null?void 0:s.model,processMs:(l=g==null?void 0:g.result)==null?void 0:l.process_ms,source:E,operationId:p.request.operationId,targetLayerId:p.request.targetLayerId}),{model:(d=g==null?void 0:g.result)==null?void 0:d.model,processMs:(c=g==null?void 0:g.result)==null?void 0:c.process_ms,source:E}):(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),w=await this._removeBgManager.preparePreviewRequest(h.imageData,h.options),x=this._resolvePreviewBackgroundRemovalContext(v,w);if(!await this._isCurrentPreviewBackgroundRemovalContext(x))return this.emit("background-removal-stale",{operationId:x.operationId,sourceHash:x.sourceHash,targetLayerId:x.activeLayerId??null}),{stale:!0};const T=await this._removeBgManager.removeBackground(w.blob,w);if(!await this._isCurrentPreviewBackgroundRemovalContext(x,T))return this.emit("background-removal-stale",{operationId:x.operationId,sourceHash:x.sourceHash}),{stale:!0};const _=await this._applyPreviewBackgroundRemovalResult(x,T);return _?(this.emit("background-removed",{model:T.model,processMs:T.processMs,operationId:x.operationId,targetLayerId:x.activeLayerId??null,source:_.source}),{model:T.model,processMs:T.processMs,..._.source?{source:_.source}:{}}):(this.emit("background-removal-stale",{operationId:x.operationId,sourceHash:x.sourceHash,targetLayerId:x.activeLayerId??null}),{stale:!0})}catch(m){throw this.emit("error",{error:m,context:"background-removal"}),m}finally{(f=(u=this._state)==null?void 0:u.set)==null||f.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,f,m,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||((m=(f=globalThis.crypto)==null?void 0:f.randomUUID)==null?void 0:m.call(f))||`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=te.el("div",{className:"editor-loading-overlay"},te.el("div",{className:"editor-loading-spinner"}),te.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 nh(o,a){try{let t=te.getFilter(o);if(t||(te.registerCorePixiFilters(),t=te.getFilter(o)),!t){try{const r=te.getAllFilters()}catch{}return null}const n={...t.defaultParams,...a};return t.createFilter(n)}catch{return null}}const oh=78e5,ih=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,w,x;try{if(!r){n("error",new Error("Editor not initialized"));return}const T=await((v=r.exportBlob)==null?void 0:v.call(r,"png",.92,{maxPixels:oh}));if(!T){n("error",new Error("Failed to export image — the image could not be processed"));return}const _=r.getSerializableState(),g={blob:T.blob,mimeType:T.blob.type||"image/png",dimensions:{width:T.width,height:T.height},state:_},E=((w=r.getSerializableDocument)==null?void 0:w.call(r))??null;if(E){const S=((x=r.getEditorDocumentBinding)==null?void 0:x.call(r))??null;g.document=E,g.documentId=(S==null?void 0:S.documentId)??(l(E.id)?E.id:null),g.documentRevisionId=(S==null?void 0:S.documentRevisionId)??null,g.documentRevisionNumber=(S==null?void 0:S.documentRevisionNumber)??E.revision??null}n("save",g)}catch(T){n("error",T instanceof Error?T:new Error("Failed to export image"))}}function u(){n("cancel")}function f(v){if(v instanceof Error)return v;if(v!==null&&typeof v=="object"&&"error"in v){const w=v.error;if(w instanceof Error)return w;if(typeof w=="string"&&w.trim()!=="")return new Error(w)}return typeof v=="string"&&v.trim()!==""?new Error(v):new Error("Failed to load image")}function m(v){n("error",f(v))}function p(){if(!i.value||r)return;window.PIXI=Dt,te.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 w=t.editorVersion==="v2"?ah:te.VanillaImageEditor,x=new w(i.value,v);r=x,x.setFilterRegistry({getAllFilters:te.getAllFilters,getFilter:te.getFilter,getFiltersByCategory:te.getFiltersByCategory}),x.save=function(){c()},x.on("cancel",u),x.on("error",m),t.initialImage&&x.loadImage(t.initialImage,d())}e.onMounted(()=>{i.value&&(i.value.clientWidth>0?p():(s=new ResizeObserver(v=>{const w=v[0];w&&w.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,w)=>{!r||!v||v===w||h()}),e.watch(()=>t.sessionKey,(v,w)=>{v!==w&&h()}),e.watch(()=>t.initialState,(v,w)=>{v!==w&&h()}),e.watch(()=>[t.initialDocument,t.initialDocumentId,t.initialDocumentRevisionId,t.initialDocumentRevisionNumber],(v,w)=>{v!==w&&h()}),e.onUnmounted(()=>{s==null||s.disconnect(),s=null,r&&(r.destroy(),r=null)}),(v,w)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"containerRef",ref:i,class:"vanilla-editor-wrapper","data-testid":"vanilla-image-editor"},null,512))}}),Be=(o,a)=>{const t=o.__vccOpts||o;for(const[n,i]of a)t[n]=i;return t},$u=Be(ih,[["__scopeId","data-v-8ab74f83"]]),rh={class:"editor-modal-panel"},sh={class:"editor-fill"},lh=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(w){d(w instanceof Error?w:new Error("Failed to save image"))}finally{s.value=!1}},f=()=>{n("cancel"),p()},m=()=>{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 w=i.value.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])');if(w.length===0)return;const x=w[0],T=w[w.length-1];v.shiftKey&&document.activeElement===x?(v.preventDefault(),T.focus()):!v.shiftKey&&document.activeElement===T&&(v.preventDefault(),x.focus())}};return e.onMounted(()=>{document.addEventListener("keydown",h)}),e.onBeforeUnmount(()=>{document.removeEventListener("keydown",h)}),(v,w)=>(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(m,["escape"])},[e.createElementVNode("div",{class:"editor-modal-backdrop",onClick:m}),e.createElementVNode("div",rh,[e.createElementVNode("div",sh,[e.createVNode($u,{"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:f,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)]))}}),Du=Be(lh,[["__scopeId","data-v-bd4e671f"]]),dh={class:"media-workspace"},ch={class:"media-workspace-toolbar"},uh={class:"media-workspace-label"},mh=["value"],ph={class:"media-workspace-grid"},fh=["onClick"],hh=e.defineComponent({__name:"MediaWorkspace",props:{apiScope:{},subScopes:{},initialScopeId:{}},emits:["scope-change","update:media","upload","preview"],setup(o,{emit:a}){var f;const t=o,n=a,i=va(),r=e.ref(t.initialScopeId??((f=t.subScopes[0])==null?void 0:f.id)??""),s=e.computed(()=>t.subScopes),l=e.computed(()=>s.value.find(m=>m.id===r.value));let d=null;function c(){d&&(d(),d=null),t.apiScope&&(d=Cu({apiScope:t.apiScope,isAdmin:t.apiScope==="admin"}))}async function u(){var p;const m={};(p=l.value)!=null&&p.collection&&(m.collection=l.value.collection),await i.fetchMedia(1,m),n("update:media",[...i.items])}return e.watch(()=>t.initialScopeId,m=>{m&&m!==r.value&&(r.value=m)}),e.watch(()=>t.subScopes,m=>{if(m.length===0){r.value="";return}m.some(p=>p.id===r.value)||(r.value=m[0].id)},{deep:!0}),e.watch(()=>t.apiScope,()=>{c(),u()}),e.watch(r,m=>{m&&(n("scope-change",m),u())}),e.onMounted(()=>{c(),u()}),e.onUnmounted(()=>{d&&(d(),d=null)}),(m,p)=>(e.openBlock(),e.createElementBlock("div",dh,[e.createElementVNode("div",ch,[e.createElementVNode("label",uh,[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,mh))),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",ph,[(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,fh))),128))])]))}}),vh=Be(hh,[["__scopeId","data-v-895f26fe"]]),gh={class:"managed-media-gallery"},bh={class:"gallery-grid"},yh=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",gh,[e.createElementVNode("div",bh,[e.renderSlot(a.$slots,"default",{},void 0,!0)])]))}}),wh=Be(yh,[["__scopeId","data-v-10a9b8c5"]]),cr="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>",Wl="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>",kh="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>",Hl="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>",_h="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>",Eh="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>",Zd="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>",Xd="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>",qo="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>",xh="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>",Ru="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>",Au="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>",Gd="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>",Sh="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>",Ch="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>",Jd="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>",jn="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>",Kd="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>",Vh="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>",gn="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>",Nh="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>",Wo="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>",al="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>",Th="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>",qd="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>",Er="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>",ko="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>",Ih="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>",Bh="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>",Mh="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>",Fh="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>",Yo="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>",Yd="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>",Ms="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>",$h="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>",Dh="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>",Fs="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>",Rh="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>",Ah="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>",Lh="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>",Ph="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>",Lu="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>",Zl="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>",Uh="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>",Oh="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>",zh="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>",jh="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>",Pu="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>",Wh="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>",Hh="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>",Xl="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>",Zh="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>",Xh="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>",Jn="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>",Gh="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>",Jh="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>",Qd="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>",jr="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>",Kh="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>",$s="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>",vn="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>",Ho="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>",ec="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>",qh="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>",Uu="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M32 415.5l120-320 120 320M230 303.5H74M326 239.5c12.19-28.69 41-48 74-48h0c46 0 80 32 80 80v144' class='ionicon-fill-none ionicon-stroke-width'/><path d='M320 358.5c0 36 26.86 58 60 58 54 0 100-27 100-106v-15c-20 0-58 1-92 5-32.77 3.86-68 19-68 58z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",xr="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M112 112l20 320c.95 18.49 14.4 32 32 32h184c17.67 0 30.87-13.51 32-32l20-320' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-miterlimit='10' d='M80 112h352' class='ionicon-stroke-width'/><path d='M192 112V72h0a23.93 23.93 0 0124-24h80a23.93 23.93 0 0124 24h0v40M256 176v224M184 176l8 224M328 176l-8 224' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Ou="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>",Yh="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>",Qh="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>",ev="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>",tv="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>",av="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>",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-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>",ov="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>",Gi="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 tc=()=>{};function iv(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 rv(o,a={}){let t,n,i=tc;const r=d=>{clearTimeout(d),i(),i=tc};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((f,m)=>{i=a.rejectOnCancel?m:f,s=d,u&&!n&&(n=setTimeout(()=>{t&&r(t),n=null,f(s())},u)),t=setTimeout(()=>{n&&r(n),n=null,f(d())},c)})}}function sv(o,a=200,t={}){return iv(rv(a,t),o)}const Zo=new Map;function lv(o){const a=e.getCurrentScope();function t(l){var d;const c=Zo.get(o)||new Set;c.add(l),Zo.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=Zo.get(o);d&&(d.delete(l),d.size||r())}function r(){Zo.delete(o)}function s(l,d){var c;(c=Zo.get(o))==null||c.forEach(u=>u(l,d))}return{on:t,once:n,off:i,emit:s,reset:r}}function zu(){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 ju(o){const a=e.ref(new Set),t=e.ref(null),n=e.ref(-1),i=lv("media-selection"),r=zu(),s=e.computed(()=>o.value.filter(E=>a.value.has(E.uuid))),l=e.computed(()=>a.value.size);e.watch(a,E=>{i.emit({type:"selection:changed",count:E.size,selectedIds:Array.from(E)})},{deep:!0});const d=e.computed(()=>o.value.length>0&&o.value.every(E=>a.value.has(E.uuid))),c=e.computed(()=>o.value.some(E=>a.value.has(E.uuid)));function u(E){return a.value.has(E)}function f(E){a.value.has(E)?(a.value.delete(E),t.value===E&&(t.value=null,n.value=-1)):(a.value.add(E),t.value=E,n.value=o.value.findIndex(S=>S.uuid===E),a.value.size===1&&r.selection())}function m(E){a.value.add(E),t.value=E,n.value=o.value.findIndex(S=>S.uuid===E)}function p(E){a.value.delete(E),t.value===E&&(t.value=null,n.value=-1)}function h(){o.value.forEach(E=>a.value.add(E.uuid))}function v(){a.value.clear(),t.value=null,n.value=-1}function w(){d.value?v():h()}function x(E,S){const N=o.value.findIndex(V=>V.uuid===E);if(N!==-1)if(S!=null&&S.shiftKey&&n.value!==-1){const V=Math.min(n.value,N),A=Math.max(n.value,N);for(let j=V;j<=A;j++)a.value.add(o.value[j].uuid)}else f(E)}function T(){if(o.value.length===0)return;let E=n.value+1;E>=o.value.length&&(E=0),v(),m(o.value[E].uuid)}function _(){if(o.value.length===0)return;let E=n.value-1;E<0&&(E=o.value.length-1),v(),m(o.value[E].uuid)}function g(E){switch(E.key){case"ArrowDown":E.preventDefault(),T();break;case"ArrowUp":E.preventDefault(),_();break;case"a":(E.ctrlKey||E.metaKey)&&(E.preventDefault(),h());break;case"Escape":E.preventDefault(),v();break;case" ":t.value&&(E.preventDefault(),f(t.value));break}}return{selectedIds:e.computed(()=>a.value),selectedItems:s,selectedCount:l,isAllSelected:d,isSomeSelected:c,lastSelectedId:e.computed(()=>t.value),isSelected:u,toggle:f,select:m,deselect:p,selectAll:h,clear:v,toggleAll:w,rangeSelect:x,selectNext:T,selectPrevious:_,handleKeydown:g,selectionBus:i}}const dv={class:"flex items-center justify-between w-full px-4"},cv={class:"p-4"},uv={key:0,class:"mb-4 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg"},mv={class:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"},pv=["value"],fv={class:"flex gap-2 mt-4"},hv={class:"flex justify-end mb-4"},vv={key:1,class:"flex justify-center items-center h-64"},gv={key:2,class:"flex flex-col items-center justify-center h-64 text-center"},bv={class:"text-sm text-theme-secondary"},yv={key:0},wv={class:"mb-4"},kv={class:"mb-4"},_v={class:"flex gap-2"},Ev={class:"flex items-center justify-between px-4 py-2"},xv={class:"text-sm text-theme-secondary"},Sv={key:0},Cv={key:0},Vv={key:1},Nv={class:"flex gap-2"},Tv=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)),f=e.ref(!1),m=e.ref({}),p=e.ref(["images","documents","videos"]),h=e.ref(1),v=e.ref(!0),w=e.ref(!1),x=Vu(),T=ju(d);function _(F){var he;const B=F.conversion_urls||{},O=F.proxy_url||F.original_url||F.url||"",X=B.thumb||B.preview||F.preview_url||F.thumbnail_url||O,oe=F.custom_properties||{},ce=oe.width,je=oe.height;return{...F,uuid:F.uuid,name:F.name||F.file_name,file_name:F.file_name,filename:F.file_name,mime_type:F.mime_type,size:F.size,collection_name:F.collection_name||"images",disk:F.disk,original_url:O,url:O,thumbnail_url:X,conversions:F.conversions||{},conversion_urls:B,generated_conversions:F.generated_conversions||{},custom_properties:oe,caption:F.caption||null,alt_text:F.alt_text||null,created_at:F.created_at,updated_at:F.updated_at,is_image:((he=F.mime_type)==null?void 0:he.startsWith("image/"))||!1,...typeof ce=="number"?{width:ce}:{},...typeof je=="number"?{height:je}:{},...F.formatted_size!==void 0?{formatted_size:F.formatted_size}:{}}}e.watch(()=>t.selectedItems,F=>{u.value=new Set(F),T.clear(),F.forEach(B=>T.select(B))});const g=e.computed(()=>{var B;let F=d.value;return(B=m.value.types)!=null&&B.length&&(F=F.filter(O=>{var oe,ce;const X=(oe=O.mime_type)==null?void 0:oe.split("/")[0];return(ce=m.value.types)==null?void 0:ce.includes(X)})),(m.value.sizeMin!==void 0||m.value.sizeMax!==void 0)&&(F=F.filter(O=>{const X=O.size/1048576;return!(m.value.sizeMin!==void 0&&X<m.value.sizeMin||m.value.sizeMax!==void 0&&X>m.value.sizeMax)})),F}),E=e.computed(()=>{var B;let F=0;return m.value.search&&F++,m.value.collection&&F++,(m.value.dateFrom||m.value.dateTo)&&F++,(B=m.value.types)!=null&&B.length&&(F+=m.value.types.length),(m.value.sizeMin!==void 0||m.value.sizeMax!==void 0)&&F++,F}),S=e.computed(()=>{const F=T.selectedCount.value;return F===0?"Select Media":`Select ${t.selectionMode==="multiple"?`${F} ${F===1?"Item":"Items"}`:"Item"}`}),N=e.computed(()=>{const F=T.selectedCount.value;return!!(F===0||t.selectionMode==="single"&&F>1||t.maxSelection&&F>t.maxSelection)}),V=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 A(F=!0){F?(l.value=!0,d.value=[],h.value=1,v.value=!0):w.value=!0;try{const B={collection:m.value.collection||t.collection,per_page:24};switch((s.value||m.value.search)&&(B.search=s.value||m.value.search||""),m.value.dateFrom&&(B.from_date=m.value.dateFrom),m.value.dateTo&&(B.to_date=m.value.dateTo),i.value){case"recent":await x.fetchMedia(h.value,B),F?d.value=x.items.map(O=>_(O)):d.value=[...d.value,...x.items.map(O=>_(O))],v.value=x.currentPage<x.totalPages;break;case"model":if(t.modelType&&t.modelId){const O=await x.fetchModelMedia(t.modelType,t.modelId,B.collection,B.search);d.value=O?O.map(X=>_(X)):[],v.value=!1}break;case"library":await x.fetchMedia(h.value,B),F?d.value=x.items.map(O=>_(O)):d.value=[...d.value,...x.items.map(O=>_(O))],v.value=x.currentPage<x.totalPages;break}}catch{}finally{l.value=!1,w.value=!1}}async function j(F){if(!v.value||w.value){F!=null&&F.target&&F.target.complete();return}h.value++,await A(!1),F!=null&&F.target&&(F.target.complete(),v.value||(F.target.disabled=!0))}function C(F){return F==="recent"||F==="model"||F==="library"}function $(F){i.value=F,A()}function y(F){typeof F=="string"&&C(F)&&$(F)}async function R(F){t.selectionMode==="single"?(T.clear(),T.select(F.uuid)):(T.toggle(F.uuid),t.maxSelection&&T.selectedCount.value>t.maxSelection&&(T.deselect(F.uuid),await(await W.toastController.create({message:`Maximum ${t.maxSelection} items can be selected`,duration:2e3,color:"warning"})).present()))}function L(){n("confirm",T.selectedItems.value)}function U(){n("close")}function z(F){}const I=e.ref(null),P=e.ref(!1);function Z(F){I.value=F,P.value=!0}function K(F){const B=d.value.findIndex(X=>X.uuid===F.uuid);B!==-1&&(d.value[B]=F);const O={};F.alt_text!==void 0&&(O.alt_text=F.alt_text),F.caption!==void 0&&(O.caption=F.caption),F.custom_properties!==void 0&&(O.custom_properties=F.custom_properties),x.updateMedia(F.uuid,O)}function ve(){A()}function Ve(){m.value={},s.value="",A()}const ne=sv(()=>{A(!0)},300);e.watch(s,()=>{t.isOpen&&ne()});async function ae(F){try{await(await W.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 x.deleteMedia(F),await A()}}]})).present()}catch{}}return e.watch(()=>t.isOpen,F=>{F&&A()}),e.onMounted(()=>{t.selectedItems.length>0&&t.selectedItems.forEach(F=>T.select(F))}),(F,B)=>{const O=e.resolveComponent("AdminMediaGrid"),X=e.resolveComponent("AdminMediaListItem");return e.openBlock(),e.createBlock(e.unref(W.IonModal),{"is-open":F.isOpen,onDidDismiss:U,"backdrop-dismiss":!1,class:"media-browser-modal"},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonHeader),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonToolbar),null,{end:e.withCtx(()=>[e.createVNode(e.unref(W.IonButtons),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonButton),{onClick:U},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{name:"close-outline"})]),_:1})]),_:1})]),default:e.withCtx(()=>[e.createVNode(e.unref(W.IonTitle),null,{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(V.value),1)]),_:1})]),_:1}),e.createVNode(e.unref(W.IonToolbar),null,{default:e.withCtx(()=>[e.createElementVNode("div",dv,[e.createVNode(e.unref(W.IonSegment),{value:i.value,onIonChange:B[0]||(B[0]=oe=>y(oe.detail.value)),class:"max-w-xs"},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonSegmentButton),{value:"recent"},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonLabel),null,{default:e.withCtx(()=>[...B[15]||(B[15]=[e.createTextVNode("Recent",-1)])]),_:1})]),_:1}),t.modelType&&t.modelId?(e.openBlock(),e.createBlock(e.unref(W.IonSegmentButton),{key:0,value:"model"},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonLabel),null,{default:e.withCtx(()=>[...B[16]||(B[16]=[e.createTextVNode("Model",-1)])]),_:1})]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(W.IonSegmentButton),{value:"library"},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonLabel),null,{default:e.withCtx(()=>[...B[17]||(B[17]=[e.createTextVNode("Library",-1)])]),_:1})]),_:1})]),_:1},8,["value"]),e.createVNode(e.unref(W.IonButton),{fill:"clear",size:"small",onClick:B[1]||(B[1]=oe=>f.value=!f.value),class:"relative"},{"icon-only":e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{name:"filter-outline"})]),default:e.withCtx(()=>[E.value>0?(e.openBlock(),e.createBlock(e.unref(W.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(E.value),1)]),_:1})):e.createCommentVNode("",!0)]),_:1})])]),_:1})]),_:1}),e.createVNode(e.unref(W.IonContent),null,{default:e.withCtx(()=>[e.createElementVNode("div",cv,[f.value?(e.openBlock(),e.createElementBlock("div",uv,[e.createElementVNode("div",mv,[e.createElementVNode("div",null,[e.createVNode(e.unref(W.IonLabel),null,{default:e.withCtx(()=>[...B[18]||(B[18]=[e.createTextVNode("Collection",-1)])]),_:1}),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":B[2]||(B[2]=oe=>m.value.collection=oe),class:"w-full p-2 border rounded"},[B[19]||(B[19]=e.createElementVNode("option",{value:""},"All Collections",-1)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(p.value,oe=>(e.openBlock(),e.createElementBlock("option",{key:oe,value:oe},e.toDisplayString(oe),9,pv))),128))],512),[[e.vModelSelect,m.value.collection]])]),e.createElementVNode("div",null,[e.createVNode(e.unref(W.IonLabel),null,{default:e.withCtx(()=>[...B[20]||(B[20]=[e.createTextVNode("From Date",-1)])]),_:1}),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":B[3]||(B[3]=oe=>m.value.dateFrom=oe),type:"date",class:"w-full p-2 border rounded"},null,512),[[e.vModelText,m.value.dateFrom]])]),e.createElementVNode("div",null,[e.createVNode(e.unref(W.IonLabel),null,{default:e.withCtx(()=>[...B[21]||(B[21]=[e.createTextVNode("To Date",-1)])]),_:1}),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":B[4]||(B[4]=oe=>m.value.dateTo=oe),type:"date",class:"w-full p-2 border rounded"},null,512),[[e.vModelText,m.value.dateTo]])])]),e.createElementVNode("div",fv,[e.createVNode(e.unref(W.IonButton),{size:"small",onClick:ve},{default:e.withCtx(()=>[...B[22]||(B[22]=[e.createTextVNode("Apply",-1)])]),_:1}),e.createVNode(e.unref(W.IonButton),{size:"small",fill:"clear",onClick:Ve},{default:e.withCtx(()=>[...B[23]||(B[23]=[e.createTextVNode("Clear",-1)])]),_:1})])])):e.createCommentVNode("",!0),e.createVNode(e.unref(W.IonSearchbar),{modelValue:s.value,"onUpdate:modelValue":B[5]||(B[5]=oe=>s.value=oe),placeholder:"Search media...",debounce:300,class:"mb-4"},null,8,["modelValue"]),e.createElementVNode("div",hv,[e.createVNode(e.unref(W.IonButtons),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonButton),{fill:r.value==="grid"?"solid":"clear",size:"small",onClick:B[6]||(B[6]=oe=>r.value="grid")},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{name:"grid-outline"})]),_:1},8,["fill"]),e.createVNode(e.unref(W.IonButton),{fill:r.value==="list"?"solid":"clear",size:"small",onClick:B[7]||(B[7]=oe=>r.value="list")},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{name:"list-outline"})]),_:1},8,["fill"])]),_:1})]),l.value?(e.openBlock(),e.createElementBlock("div",vv,[e.createVNode(e.unref(W.IonSpinner),{name:"crescent"})])):g.value.length===0?(e.openBlock(),e.createElementBlock("div",gv,[e.createVNode(e.unref(W.IonIcon),{name:"images-outline",class:"text-6xl text-theme-secondary mb-4"}),B[24]||(B[24]=e.createElementVNode("h3",{class:"text-lg font-medium text-theme mb-2"}," No Media Found ",-1)),e.createElementVNode("p",bv,e.toDisplayString(s.value?"Try adjusting your search":"No media items available"),1)])):r.value==="grid"?(e.openBlock(),e.createBlock(O,{key:3,"media-items":g.value,"selected-items":e.unref(T).selectedItems.value,"is-loading":!1,"selection-mode":!0,columns:{mobile:2,sm:3,md:4,lg:5,xl:6},onToggleSelect:R,onPreview:z,onEdit:Z,onDelete:ae},null,8,["media-items","selected-items"])):(e.openBlock(),e.createBlock(e.unref(W.IonList),{key:4,lines:"none",class:"rounded-lg overflow-hidden"},{default:e.withCtx(()=>[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(g.value,(oe,ce)=>(e.openBlock(),e.createBlock(X,{key:oe.uuid,media:oe,selected:e.unref(T).isSelected(oe.uuid),"selection-mode":!0,index:ce,onToggleSelect:R,onPreview:z,onEdit:Z,onDelete:ae},null,8,["media","selected","index"]))),128))]),_:1})),!l.value&&g.value.length>0&&i.value!=="model"?(e.openBlock(),e.createBlock(e.unref(W.IonInfiniteScroll),{key:5,threshold:"100px",onIonInfinite:B[8]||(B[8]=oe=>j(oe))},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonInfiniteScrollContent),{"loading-spinner":"crescent","loading-text":"Loading more media..."})]),_:1})):e.createCommentVNode("",!0)])]),_:1}),e.createVNode(e.unref(W.IonModal),{"is-open":P.value,onDidDismiss:B[14]||(B[14]=oe=>P.value=!1)},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonHeader),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonToolbar),null,{end:e.withCtx(()=>[e.createVNode(e.unref(W.IonButtons),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonButton),{onClick:B[9]||(B[9]=oe=>P.value=!1)},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{name:"close-outline"})]),_:1})]),_:1})]),default:e.withCtx(()=>[e.createVNode(e.unref(W.IonTitle),null,{default:e.withCtx(()=>[...B[25]||(B[25]=[e.createTextVNode("Edit Media Info",-1)])]),_:1})]),_:1})]),_:1}),e.createVNode(e.unref(W.IonContent),{class:"p-4"},{default:e.withCtx(()=>[I.value?(e.openBlock(),e.createElementBlock("div",yv,[e.createElementVNode("div",wv,[e.createVNode(e.unref(W.IonLabel),null,{default:e.withCtx(()=>[...B[26]||(B[26]=[e.createTextVNode("Caption",-1)])]),_:1}),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":B[10]||(B[10]=oe=>I.value.caption=oe),type:"text",class:"w-full p-2 border rounded mt-1",placeholder:"Enter caption..."},null,512),[[e.vModelText,I.value.caption]])]),e.createElementVNode("div",kv,[e.createVNode(e.unref(W.IonLabel),null,{default:e.withCtx(()=>[...B[27]||(B[27]=[e.createTextVNode("Alt Text",-1)])]),_:1}),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":B[11]||(B[11]=oe=>I.value.alt_text=oe),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",_v,[e.createVNode(e.unref(W.IonButton),{onClick:B[12]||(B[12]=oe=>K(I.value))},{default:e.withCtx(()=>[...B[28]||(B[28]=[e.createTextVNode("Save",-1)])]),_:1}),e.createVNode(e.unref(W.IonButton),{fill:"clear",onClick:B[13]||(B[13]=oe=>P.value=!1)},{default:e.withCtx(()=>[...B[29]||(B[29]=[e.createTextVNode("Cancel",-1)])]),_:1})])])):e.createCommentVNode("",!0)]),_:1})]),_:1},8,["is-open"]),e.createVNode(e.unref(W.IonFooter),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonToolbar),null,{default:e.withCtx(()=>[e.createElementVNode("div",Ev,[e.createElementVNode("div",xv,[e.unref(T).selectedCount.value>0?(e.openBlock(),e.createElementBlock("span",Sv,[e.createTextVNode(e.toDisplayString(e.unref(T).selectedCount.value)+" selected ",1),t.maxSelection?(e.openBlock(),e.createElementBlock("span",Cv," / "+e.toDisplayString(t.maxSelection)+" max ",1)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("span",Vv," Select "+e.toDisplayString(t.selectionMode==="multiple"?"items":"an item"),1))]),e.createElementVNode("div",Nv,[e.createVNode(e.unref(W.IonButton),{fill:"clear",onClick:U},{default:e.withCtx(()=>[...B[30]||(B[30]=[e.createTextVNode(" Cancel ",-1)])]),_:1}),e.createVNode(e.unref(W.IonButton),{disabled:N.value,onClick:L},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(S.value),1)]),_:1},8,["disabled"])])])]),_:1})]),_:1})]),_:1},8,["is-open"])}}}),Iv=Be(Tv,[["__scopeId","data-v-9a8c0954"]]),Bv={key:1,class:"flex flex-col items-center justify-center py-16"},Mv=["draggable","onDragstart","onDragover","onDrop"],Fv={key:0,class:"absolute top-2 left-2 z-20"},$v=["checked","onChange"],Dv={key:2,class:"absolute top-2 right-2 z-20 opacity-0 group-hover:opacity-100 transition-opacity cursor-move"},Rv=["data-media-id"],Av={key:0,class:"w-full h-full flex items-center justify-center"},Lv=["src","alt","onError","onLoad"],Pv={key:2,class:"w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-700"},Uv={class:"text-center"},Ov={class:"text-4xl text-gray-400 mb-2"},zv={class:"text-sm font-medium text-gray-500"},jv={class:"absolute inset-0 bg-black/70 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2"},Wv=["onClick"],Hv=["onClick"],Zv=["onClick"],Xv={class:"p-3"},Gv={class:"text-sm font-medium truncate mb-1"},Jv={class:"text-xs text-gray-600 dark:text-gray-400"},Kv={key:0},qv={key:0,class:"text-xs text-gray-500 dark:text-gray-500 mt-1 truncate"},Yv=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=N=>t.selectedItems.some(V=>V.uuid===N.uuid),c=e.computed(()=>{const N=t.columns,V=["grid","gap-4"];switch(N.mobile){case 1:V.push("grid-cols-1");break;case 2:V.push("grid-cols-2");break;case 3:V.push("grid-cols-3");break;case 4:V.push("grid-cols-4");break;default:V.push("grid-cols-2");break}switch(N.sm){case 1:V.push("sm:grid-cols-1");break;case 2:V.push("sm:grid-cols-2");break;case 3:V.push("sm:grid-cols-3");break;case 4:V.push("sm:grid-cols-4");break;case 5:V.push("sm:grid-cols-5");break;default:V.push("sm:grid-cols-3");break}switch(N.md){case 2:V.push("md:grid-cols-2");break;case 3:V.push("md:grid-cols-3");break;case 4:V.push("md:grid-cols-4");break;case 5:V.push("md:grid-cols-5");break;case 6:V.push("md:grid-cols-6");break;default:V.push("md:grid-cols-4");break}switch(N.lg){case 3:V.push("lg:grid-cols-3");break;case 4:V.push("lg:grid-cols-4");break;case 5:V.push("lg:grid-cols-5");break;case 6:V.push("lg:grid-cols-6");break;case 7:V.push("lg:grid-cols-7");break;default:V.push("lg:grid-cols-5");break}switch(N.xl){case 4:V.push("xl:grid-cols-4");break;case 5:V.push("xl:grid-cols-5");break;case 6:V.push("xl:grid-cols-6");break;case 7:V.push("xl:grid-cols-7");break;case 8:V.push("xl:grid-cols-8");break;default:V.push("xl:grid-cols-6");break}return V.join(" ")});function u(N,V,A){t.reorderable&&(i.value=V,N.dataTransfer&&(N.dataTransfer.effectAllowed="move",N.dataTransfer.setData("text/html","")))}function f(N,V){t.reorderable&&(N.preventDefault(),r.value=V)}function m(){r.value=null}function p(N,V){if(!t.reorderable||!i.value)return;N.preventDefault();const A=[...t.mediaItems],j=A.findIndex(C=>{var $;return C.uuid===(($=i.value)==null?void 0:$.uuid)});if(j!==-1&&j!==V&&i.value){const[C]=A.splice(j,1);A.splice(V,0,C),n("reorder",A)}i.value=null,r.value=null}function h(N){return N<1024?N+" B":N<1024*1024?(N/1024).toFixed(1)+" KB":(N/(1024*1024)).toFixed(1)+" MB"}function v(N){var A;return N.thumbnail_url||((A=N.conversion_urls)==null?void 0:A.thumb)||N.original_url||N.url||""}function w(N){var j,C,$;const V=((j=N.mime_type)==null?void 0:j.startsWith("image/"))||!1,A=!!(N.thumbnail_url||(C=N.conversion_urls)!=null&&C.thumb||($=N.conversion_urls)!=null&&$.preview||N.original_url||N.url);return V&&A}function x(N){var V;return((V=N.split(".").pop())==null?void 0:V.toUpperCase())||""}function T(N){var A;const V=((A=N.mime_type)==null?void 0:A.toLowerCase())||"";return V.startsWith("image/")?"image":V.startsWith("video/")?"videocam":V.startsWith("audio/")?"musical-notes":V.includes("pdf")?"document-text":V.includes("zip")||V.includes("rar")?"archive":V.includes("sheet")||V.includes("excel")?"grid":V.includes("document")||V.includes("word")?"document-text":"document"}e.onMounted(()=>{typeof window<"u"&&"IntersectionObserver"in window&&(l.value=new IntersectionObserver(N=>{N.forEach(V=>{var A;if(V.isIntersecting){const j=V.target.getAttribute("data-media-id");j&&(s.value.add(j),(A=l.value)==null||A.unobserve(V.target))}})},{rootMargin:"50px"}))}),e.onUnmounted(()=>{l.value&&l.value.disconnect()});function _(N){return!0}function g(){l.value&&e.nextTick(()=>{document.querySelectorAll("[data-media-id]").forEach(V=>{var j;const A=V.getAttribute("data-media-id");A&&!s.value.has(A)&&((j=l.value)==null||j.observe(V))})})}e.watch(()=>t.mediaItems,()=>{s.value.clear(),g()},{immediate:!0,deep:!0});function E(N,V){const A=N.target;delete A.dataset.fallbackIndex}function S(N,V){const A=N.target,j=A.closest("[data-media-id]"),C=[V.original_url,V.url,V.thumbnail_url,"preview_url"in V?V.preview_url:void 0].filter($=>$&&$.trim()!==""&&$!==A.src);if(C.length>0&&A.dataset.fallbackIndex){const $=parseInt(A.dataset.fallbackIndex);if($<C.length){A.dataset.fallbackIndex=($+1).toString(),A.src=C[$]||"";return}}else if(C.length>0){A.dataset.fallbackIndex="1",A.src=C[0]||"";return}if(A.style.display="none",j&&!j.querySelector(".media-fallback-icon")){const y=document.createElement("div");y.className="media-fallback-icon w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-800",y.innerHTML=`
|
|
2
|
-
<div class="text-center">
|
|
3
|
-
<div class="text-4xl text-gray-400 mb-2">${T(V)}</div>
|
|
4
|
-
<p class="text-sm font-medium text-gray-500">${x(V.file_name)}</p>
|
|
5
|
-
</div>
|
|
6
|
-
`,j.appendChild(y)}}return(N,V)=>N.isLoading?(e.openBlock(),e.createElementBlock("div",{key:0,class:e.normalizeClass(c.value)},[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(12,A=>e.createElementVNode("div",{key:`skeleton-${A}`,class:"relative"},[...V[1]||(V[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)):!N.mediaItems||!N.mediaItems.length?(e.openBlock(),e.createElementBlock("div",Bv,[V[2]||(V[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)),V[3]||(V[3]=e.createElementVNode("h3",{class:"text-lg font-medium mb-2"}," No Media Items ",-1)),V[4]||(V[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:V[0]||(V[0]=A=>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(N.mediaItems,(A,j)=>(e.openBlock(),e.createElementBlock("div",{key:A.uuid,class:e.normalizeClass(["relative group",{"ring-2 ring-blue-500 ring-offset-2":r.value===j}]),draggable:N.reorderable,onDragstart:C=>u(C,A),onDragover:C=>f(C,j),onDragleave:m,onDrop:C=>p(C,j)},[N.selectionMode?(e.openBlock(),e.createElementBlock("div",Fv,[e.createElementVNode("input",{type:"checkbox",checked:d(A),onChange:C=>n("toggleSelect",A),class:"w-5 h-5 bg-white dark:bg-gray-800 rounded cursor-pointer"},null,40,$v)])):e.createCommentVNode("",!0),N.$slots.badge?(e.openBlock(),e.createElementBlock("div",{key:1,class:e.normalizeClass(["absolute top-2 z-20",N.selectionMode?"left-10":"left-2"])},[e.renderSlot(N.$slots,"badge",{media:A,index:j},void 0,!0)],2)):e.createCommentVNode("",!0),N.reorderable?(e.openBlock(),e.createElementBlock("div",Dv,[...V[5]||(V[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(A)}])},[e.createElementVNode("div",{class:"relative aspect-square bg-gray-100 dark:bg-gray-700 overflow-hidden","data-media-id":A.uuid},[w(A)&&!_(A.uuid)?(e.openBlock(),e.createElementBlock("div",Av,[...V[6]||(V[6]=[e.createElementVNode("div",{class:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"},null,-1)])])):e.createCommentVNode("",!0),w(A)&&_(A.uuid)?(e.openBlock(),e.createElementBlock("img",{key:1,src:v(A),alt:A.alt_text||A.file_name,class:"w-full h-full object-cover",loading:"lazy",onError:C=>S(C,A),onLoad:C=>E(C)},null,40,Lv)):(e.openBlock(),e.createElementBlock("div",Pv,[e.createElementVNode("div",Uv,[e.createElementVNode("div",Ov,e.toDisplayString(T(A)),1),e.createElementVNode("p",zv,e.toDisplayString(x(A.file_name)),1)])])),e.createElementVNode("div",jv,[e.createElementVNode("button",{onClick:C=>n("preview",A),class:"p-2 bg-white/20 text-white rounded hover:bg-white/30",title:"Preview"},[...V[7]||(V[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,Wv),N.showEditButton&&w(A)?(e.openBlock(),e.createElementBlock("button",{key:0,onClick:C=>n("edit",A),class:"p-2 bg-white/20 text-white rounded hover:bg-white/30",title:"Edit"},[...V[8]||(V[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,Hv)):e.createCommentVNode("",!0),e.createElementVNode("button",{onClick:C=>n("delete",A.uuid),class:"p-2 bg-red-500/20 text-red-300 rounded hover:bg-red-500/30",title:"Delete"},[...V[9]||(V[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,Zv)])],8,Rv),e.createElementVNode("div",Xv,[e.createElementVNode("h4",Gv,e.toDisplayString(A.file_name),1),e.createElementVNode("p",Jv,[e.createTextVNode(e.toDisplayString(h(A.size))+" ",1),A.width&&A.height?(e.openBlock(),e.createElementBlock("span",Kv," • "+e.toDisplayString(A.width)+"x"+e.toDisplayString(A.height),1)):e.createCommentVNode("",!0)]),A.caption?(e.openBlock(),e.createElementBlock("p",qv,e.toDisplayString(A.caption),1)):e.createCommentVNode("",!0)])],2)],42,Mv))),128))],2))}}),Qv=Be(Yv,[["__scopeId","data-v-f0c343b7"]]),eg={class:"model-media-manager"},tg=["accept","multiple"],ag={class:"flex items-center justify-between mb-4"},ng={key:0,class:"text-lg font-medium"},og={class:"flex gap-2"},ig={key:0,class:"flex items-center justify-center py-8"},rg={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"},sg={class:"text-gray-600 dark:text-gray-400"},lg={class:"flex gap-2 mt-4"},dg={key:0,class:"px-2 py-1 bg-blue-500 text-white text-xs font-medium rounded"},cg=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=va(),r=e.ref(!1),s=e.ref(!1),l=e.ref(!1),d=e.ref(!1),c=e.ref(null),u=e.ref(0),f=e.ref(null),m=e.ref(null),p=e.ref(null),h=e.ref(null),v=e.ref(null),w=e.ref(void 0),x=e.ref(null),T=e.ref(null),_=e.computed(()=>{if(t.maxFiles!==void 0)return Math.max(0,t.maxFiles-i.modelMedia.length)}),g=e.computed(()=>i.modelMedia.map(ne=>ne.uuid)),E=e.computed(()=>{if(!(!t.acceptedMimeTypes||t.acceptedMimeTypes.length===0))return t.acceptedMimeTypes.join(",")});function S(){wo({isAdmin:t.mode==="admin"})}async function N(ne){await(await W.toastController.create({message:ne,duration:3e3,color:"danger",position:"bottom"})).present()}async function V(){if(!s.value)if(s.value=!0,S(),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(ne){const ae=ne instanceof Error?ne.message:"Failed to fetch media";n("error",{operation:"fetch",message:ae,details:ne})}finally{r.value=!1,n("loading",!1)}}}e.watch(()=>i.modelMedia,ne=>{s.value&&n("update:media",ne)},{deep:!0}),e.watch(()=>[t.mediableType,t.mediableId,t.collection],()=>{s.value=!1,V()}),e.watch(()=>t.mode,()=>{S()}),e.onMounted(()=>{V()}),e.onUnmounted(()=>{i.clearModelContext()});function A(){return i.modelMedia.length>0}function j(){return t.maxFiles===void 0?!1:i.modelMedia.length>=t.maxFiles}function C(ne){var F,B,O;if(!((F=ne.mime_type)!=null&&F.startsWith("image/")))return null;const ae=ne.original_url||ne.url||((B=ne.conversion_urls)==null?void 0:B.preview)||((O=ne.conversion_urls)==null?void 0:O.thumb)||ne.thumbnail_url;return ae&&ae.trim()!==""?ae:null}function $(){c.value=null,w.value=void 0,f.value=null,m.value=null,p.value=null,h.value=null,v.value=null}function y(){l.value=!0}function R(){var ne;(ne=T.value)==null||ne.click()}function L(){l.value=!1}async function U(ne){if(t.allowEdit&&C(ne)){$(),c.value=ne,u.value++;try{const ae=i.getHttpClient(),F=i.getEditorApiUrl(""),B=await ae(`${F.replace(/\/$/,"")}/editor/${ne.uuid}/edit`);if(!B.editable_source_url)throw new Error("Editor source URL missing from edit context");w.value=B.editable_source_url,f.value=B.editor_state??null,m.value=B.editor_document??null,p.value=B.editor_document_id??null,h.value=B.editor_document_revision_id??null,v.value=B.editor_document_revision_number??null}catch(ae){$();const F=ae instanceof Error?`Unable to load image editor: ${ae.message}`:"Unable to load image editor";await N(F);return}d.value=!0}}function z(){d.value=!1,$()}async function I(ne){if(!c.value)throw new Error("No media selected for editing");const ae=c.value,F=t.editMode==="variant";try{x.value=null;const B=await i.saveEditedImage(ae.uuid,ne,{asVariant:F});F||await i.detachMedia(t.mediableType,t.mediableId,ae.uuid,t.collection),await i.attachMedia(t.mediableType,t.mediableId,[B.uuid],t.collection),n("edit-complete",{originalMedia:ae,editedMedia:B,mode:t.editMode}),d.value=!1,$()}catch(B){const O=B instanceof Error?B.message:"Failed to save edited image";throw x.value=O,await N(O),B}}function P(ne){if(x.value===ne.message){x.value=null;return}N(ne.message)}async function Z(ne){const ae=ne.target,F=ae.files;if(!(!F||F.length===0)){for(let B=0;B<F.length;B++){const O=F[B];if(_.value!==void 0&&_.value<=0)break;if(t.acceptedMimeTypes&&t.acceptedMimeTypes.length>0&&!t.acceptedMimeTypes.includes(O.type)){n("error",{operation:"upload",message:`File type ${O.type} is not accepted`,details:{file:O.name}});continue}if(t.maxFileSize!==void 0&&O.size>t.maxFileSize){n("error",{operation:"upload",message:`File size exceeds limit of ${t.maxFileSize} bytes`,details:{file:O.name,size:O.size}});continue}n("upload-progress",{status:"uploading",progress:0,file:O});try{const X=await i.uploadFile(O,{collection:t.collection});X!=null&&X.uuid&&(await i.attachMedia(t.mediableType,t.mediableId,[X.uuid],t.collection),n("upload-progress",{status:"complete",progress:100,file:O}),n("attach",[X]))}catch(X){const oe=X instanceof Error?X.message:"Upload failed";n("error",{operation:"upload",message:oe,details:X}),n("upload-progress",{status:"error",progress:0,file:O,error:oe})}}ae.value=""}}async function K(ne){const ae=ne.map(F=>F.uuid);try{await i.reorderMedia(t.mediableType,t.mediableId,ae,t.collection),n("reorder",i.modelMedia)}catch(F){const B=F instanceof Error?F.message:"Failed to reorder media";n("error",{operation:"reorder",message:B,details:F}),await N(B)}}async function ve(ne){const ae=i.modelMedia.find(F=>F.uuid===ne);try{await i.detachMedia(t.mediableType,t.mediableId,ne,t.collection),ae&&n("detach",ae)}catch(F){const B=F instanceof Error?F.message:"Failed to detach media";n("error",{operation:"detach",message:B,details:F}),await N(B)}}async function Ve(ne){l.value=!1;const ae=ne.map(O=>O.uuid),F=new Set(g.value);let B=Array.from(new Set(ae)).filter(O=>!F.has(O));if(_.value!==void 0&&B.length>_.value&&(B=B.slice(0,_.value)),B.length!==0)try{await i.attachMedia(t.mediableType,t.mediableId,B,t.collection);const O=i.modelMedia.filter(X=>B.includes(X.uuid));n("attach",O)}catch(O){const X=O instanceof Error?O.message:"Failed to attach media";n("error",{operation:"attach",message:X,details:O})}}return(ne,ae)=>(e.openBlock(),e.createElementBlock("div",eg,[e.createElementVNode("input",{ref_key:"fileInputRef",ref:T,type:"file",accept:E.value,multiple:_.value===void 0||_.value>1,class:"hidden","data-testid":"upload-input",onChange:Z},null,40,tg),e.createElementVNode("div",ag,[ne.title?(e.openBlock(),e.createElementBlock("h3",ng,e.toDisplayString(ne.title),1)):e.createCommentVNode("",!0),e.createElementVNode("div",og,[ne.allowBrowse?(e.openBlock(),e.createBlock(e.unref(W.IonButton),{key:0,fill:"outline",size:"small",disabled:j(),"data-testid":"browse-button",onClick:y},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{slot:"start",icon:e.unref(Fs)},null,8,["icon"]),ae[1]||(ae[1]=e.createTextVNode(" Browse ",-1))]),_:1},8,["disabled"])):e.createCommentVNode("",!0),ne.allowUpload?(e.openBlock(),e.createBlock(e.unref(W.IonButton),{key:1,fill:"solid",size:"small",disabled:j(),"data-testid":"upload-button",onClick:R},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{slot:"start",icon:e.unref(Kd)},null,8,["icon"]),ae[2]||(ae[2]=e.createTextVNode(" Upload ",-1))]),_:1},8,["disabled"])):e.createCommentVNode("",!0)])]),r.value||e.unref(i).isLoadingModelMedia?(e.openBlock(),e.createElementBlock("div",ig,[e.createVNode(e.unref(W.IonSpinner),{"data-testid":"spinner"})])):A()?(e.openBlock(),e.createBlock(Qv,{key:2,"media-items":e.unref(i).modelMedia,reorderable:!!ne.allowReorder,"is-loading":r.value||e.unref(i).isLoadingModelMedia,"show-edit-button":!!ne.allowEdit,"selection-mode":!1,onReorder:K,onDelete:ve,onEdit:U},e.createSlots({_:2},[ne.showPrimaryBadge?{name:"badge",fn:e.withCtx(({index:F})=>[F===0?(e.openBlock(),e.createElementBlock("div",dg," Primary ")):e.createCommentVNode("",!0)]),key:"0"}:void 0]),1032,["media-items","reorderable","is-loading","show-edit-button"])):(e.openBlock(),e.createElementBlock("div",rg,[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Fs),class:"w-12 h-12 text-gray-400 mb-4"},null,8,["icon"]),e.createElementVNode("p",sg,e.toDisplayString(ne.emptyText),1),e.createElementVNode("div",lg,[ne.allowBrowse?(e.openBlock(),e.createBlock(e.unref(W.IonButton),{key:0,fill:"outline",size:"small","data-testid":"browse-button-empty",onClick:y},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{slot:"start",icon:e.unref(Fs)},null,8,["icon"]),ae[3]||(ae[3]=e.createTextVNode(" Browse Library ",-1))]),_:1})):e.createCommentVNode("",!0),ne.allowUpload?(e.openBlock(),e.createBlock(e.unref(W.IonButton),{key:1,fill:"solid",size:"small","data-testid":"upload-button-empty",onClick:R},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{slot:"start",icon:e.unref(Kd)},null,8,["icon"]),ae[4]||(ae[4]=e.createTextVNode(" Upload Files ",-1))]),_:1})):e.createCommentVNode("",!0)])])),e.createVNode(Iv,e.mergeProps({"is-open":l.value,"selected-items":g.value,collection:ne.collection},_.value!==null&&_.value!==void 0?{maxSelection:_.value}:{},{onConfirm:Ve,onClose:L}),null,16,["is-open","selected-items","collection"]),e.createVNode(Du,{modelValue:d.value,"onUpdate:modelValue":ae[0]||(ae[0]=F=>d.value=F),"initial-image":w.value,"initial-state":f.value,"initial-document":m.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:z,onError:P},null,8,["modelValue","initial-image","initial-state","initial-document","initial-document-id","initial-document-revision-id","initial-document-revision-number","session-key"])]))}}),ug=Be(cg,[["__scopeId","data-v-c58d85c8"]]),mg={class:"existing-media-selector","data-testid":"existing-media-selector"},pg={key:0,class:"existing-media-selector__status","data-testid":"existing-media-loading"},fg=["data-testid"],hg={class:"existing-media-selector__section-header"},vg={class:"existing-media-selector__section-title"},gg=["data-testid","aria-label","onClick"],bg={class:"existing-media-selector__grid"},yg=["data-testid","aria-label","aria-pressed","onClick"],wg=["src","alt"],kg={key:0,class:"existing-media-selector__selected-badge"},_g={key:1,class:"existing-media-selector__caption"},Eg={key:0,class:"existing-media-selector__section existing-media-selector__section--albums","data-testid":"existing-media-albums"},xg={class:"existing-media-selector__section-header"},Sg={class:"existing-media-selector__section-title"},Cg={class:"existing-media-selector__albums"},Vg=["data-testid","aria-label","aria-pressed","onClick"],Ng={class:"existing-media-selector__album-name"},Tg={key:0,class:"existing-media-selector__album-count"},Ig={class:"existing-media-selector__album-panel","data-testid":"existing-media-active-album"},Bg={class:"existing-media-selector__section-header"},Mg={class:"existing-media-selector__section-subtitle"},Fg={key:0,class:"existing-media-selector__section-description"},$g={key:0,class:"existing-media-selector__status","data-testid":"existing-media-active-album-loading"},Dg={key:1,class:"existing-media-selector__grid"},Rg=["data-testid","aria-label","aria-pressed","onClick"],Ag=["src","alt"],Lg={key:0,class:"existing-media-selector__selected-badge"},Pg={key:1,class:"existing-media-selector__caption"},Ug={key:2,class:"existing-media-selector__empty","data-testid":"existing-media-active-album-empty"},Og={key:1,class:"existing-media-selector__empty","data-testid":"existing-media-empty"},zg=e.defineComponent({__name:"ExistingMediaSelector",props:{sections:{default:()=>[]},albums:{default:()=>[]},selectedId:{default:null},activeAlbumId:{default:null},activeAlbumItems:{default:()=>[]},activeAlbumTitle:{},activeAlbumDescription:{},isLoading:{type:Boolean,default:!1},isAlbumLoading:{type:Boolean,default:!1},emptyMessage:{default:"No media available yet."},albumBrowseTitle:{default:"Browse Your Albums"},albumSectionTitle:{default:"Selected Album"},activeAlbumEmptyMessage:{default:"No media available in this album yet."}},emits:["select","update:activeAlbumId"],setup(o,{emit:a}){const t=o,n=a,i=e.reactive({}),r=e.computed(()=>t.sections.filter(g=>g.items.length>0)),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 g=t.albums.find(E=>E.id===t.activeAlbumId);return g!=null&&g.name.trim().length?g.name.trim():t.albumSectionTitle}),c=e.computed(()=>{if(typeof t.activeAlbumDescription=="string"&&t.activeAlbumDescription.trim().length>0)return t.activeAlbumDescription.trim();const g=t.albums.find(E=>E.id===t.activeAlbumId);return typeof(g==null?void 0:g.description)=="string"&&g.description.trim().length>0?g.description.trim():""});function u(g){const E=g.initialVisibleCount??6;return E>0?E:6}function f(g){return i[g]===!0}function m(g){i[g]=!f(g)}function p(g){return f(g.id)?g.items:g.items.slice(0,u(g))}function h(g){return g.items.length>u(g)}function v(g){n("select",g)}function w(g){n("update:activeAlbumId",g)}function x(g){var S;const E=(S=g.description)==null?void 0:S.trim();return E&&E.length>0?`Select ${E}`:"Select existing media"}function T(g,E){var N;const S=(N=E.description)==null?void 0:N.trim();return typeof E.alt=="string"&&E.alt.trim().length>0?E.alt.trim():S&&S.length>0?S:g.title}function _(g){const E=typeof g.mediaCount=="number"?` with ${g.mediaCount} item${g.mediaCount===1?"":"s"}`:"";return`Browse album ${g.name}${E}`}return(g,E)=>(e.openBlock(),e.createElementBlock("div",mg,[g.isLoading?(e.openBlock(),e.createElementBlock("div",pg," Loading your media... ")):(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.value,S=>(e.openBlock(),e.createElementBlock("section",{key:S.id,class:"existing-media-selector__section","data-testid":`existing-media-section-${S.id}`},[e.createElementVNode("div",hg,[e.createElementVNode("h3",vg,e.toDisplayString(S.title),1),h(S)?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"existing-media-selector__toggle","data-testid":`existing-media-toggle-${S.id}`,"aria-label":f(S.id)?`Show fewer items from ${S.title}`:`Show more items from ${S.title}`,onClick:N=>m(S.id)},e.toDisplayString(f(S.id)?"See less":"See more"),9,gg)):e.createCommentVNode("",!0)]),e.createElementVNode("div",bg,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(p(S),N=>(e.openBlock(),e.createElementBlock("button",{key:N.id,type:"button",class:e.normalizeClass(["existing-media-selector__item",{"is-selected":g.selectedId===N.id}]),"data-testid":`existing-media-item-${S.id}-${N.id}`,"aria-label":x(N),"aria-pressed":g.selectedId===N.id?"true":"false",onClick:V=>v(N)},[e.createElementVNode("img",{class:"existing-media-selector__image",src:N.previewUrl,alt:T(S,N)},null,8,wg),g.selectedId===N.id?(e.openBlock(),e.createElementBlock("div",kg," Selected ")):e.createCommentVNode("",!0),N.description?(e.openBlock(),e.createElementBlock("div",_g,e.toDisplayString(N.description),1)):e.createCommentVNode("",!0)],10,yg))),128))])],8,fg))),128)),s.value?(e.openBlock(),e.createElementBlock("section",Eg,[e.createElementVNode("div",xg,[e.createElementVNode("h3",Sg,e.toDisplayString(g.albumBrowseTitle),1)]),e.createElementVNode("div",Cg,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(g.albums,S=>(e.openBlock(),e.createElementBlock("button",{key:S.id,type:"button",class:e.normalizeClass(["existing-media-selector__album",{"is-active":g.activeAlbumId===S.id}]),"data-testid":`existing-media-album-${S.id}`,"aria-label":_(S),"aria-pressed":g.activeAlbumId===S.id?"true":"false",onClick:N=>w(S.id)},[e.createElementVNode("span",Ng,e.toDisplayString(S.name),1),typeof S.mediaCount=="number"?(e.openBlock(),e.createElementBlock("span",Tg,e.toDisplayString(S.mediaCount),1)):e.createCommentVNode("",!0)],10,Vg))),128))]),e.createElementVNode("div",Ig,[e.createElementVNode("div",Bg,[e.createElementVNode("div",null,[e.createElementVNode("h4",Mg,e.toDisplayString(d.value),1),c.value?(e.openBlock(),e.createElementBlock("p",Fg,e.toDisplayString(c.value),1)):e.createCommentVNode("",!0)])]),g.isAlbumLoading?(e.openBlock(),e.createElementBlock("div",$g," Loading album... ")):g.activeAlbumItems.length>0?(e.openBlock(),e.createElementBlock("div",Dg,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(g.activeAlbumItems,S=>(e.openBlock(),e.createElementBlock("button",{key:S.id,type:"button",class:e.normalizeClass(["existing-media-selector__item",{"is-selected":g.selectedId===S.id}]),"data-testid":`existing-media-item-album-${S.id}`,"aria-label":x(S),"aria-pressed":g.selectedId===S.id?"true":"false",onClick:N=>v(S)},[e.createElementVNode("img",{class:"existing-media-selector__image",src:S.previewUrl,alt:S.alt||S.description||d.value},null,8,Ag),g.selectedId===S.id?(e.openBlock(),e.createElementBlock("div",Lg," Selected ")):e.createCommentVNode("",!0),S.description?(e.openBlock(),e.createElementBlock("div",Pg,e.toDisplayString(S.description),1)):e.createCommentVNode("",!0)],10,Rg))),128))])):(e.openBlock(),e.createElementBlock("div",Ug,[e.renderSlot(g.$slots,"active-album-empty",{},()=>[e.createTextVNode(e.toDisplayString(g.activeAlbumEmptyMessage),1)],!0)]))])])):e.createCommentVNode("",!0),l.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",Og,[e.renderSlot(g.$slots,"empty",{},()=>[e.createTextVNode(e.toDisplayString(g.emptyMessage),1)],!0)]))],64))]))}}),jg=Be(zg,[["__scopeId","data-v-904abb6b"]]);function Ji(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 Wg(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 Hg=["src","crossorigin"],Zg={class:"preview-controls"},Xg=["aria-label"],Gg={class:"time-display"},Jg={class:"current-time"},Kg={class:"total-time"},qg={key:0,class:"fps-display"},Yg={key:0,class:"loading-overlay"},Qg={key:1,class:"error-overlay"},e0=.1,t0=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}=Dt,r=o,s=t,l=e.ref(),d=e.ref(),c=e.ref(),u=e.ref(!0),f=e.ref(),m=e.ref(0),p=e.ref(0),h=e.ref(!1);let v,w,x=null,T=null,_=null,g=[],E="",S=null,N=0,V=0,A=0,j=0,C=!1,$=0,y=0,R,L=null,U=!1,z=!1,I=0;const P=e.computed(()=>r.source&&typeof r.source=="string"?r.source:""),Z=e.computed(()=>{const be=P.value;if(!(!be||be.startsWith("blob:")))return"anonymous"}),K=e.computed(()=>Wg(h.value,r.fitMode));function ve(be){return typeof be=="number"&&Number.isFinite(be)&&be>=0?be:Number.isFinite(r.fallbackDuration)&&r.fallbackDuration>0?r.fallbackDuration:0}function Ve(be){const ke=ve(be.duration);return ke<=0?!1:be.currentTime>=Math.max(0,ke-e0)}async function ne(){var be,ke;if(!z&&d.value&&!v&&!(!c.value||c.value.readyState<3)){z=!0;try{f.value=void 0;let Te=((be=l.value)==null?void 0:be.clientWidth)||800,Ke=((ke=l.value)==null?void 0:ke.clientHeight)||450;if((Te<=0||Ke<=0)&&(Te=c.value.videoWidth||800,Ke=c.value.videoHeight||450),v=new Dt.Application,await v.init({width:Te,height:Ke,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&&ne()},100),v&&(v.destroy(!0),v=null);return}if(N=c.value.videoWidth,V=c.value.videoHeight,T=document.createElement("canvas"),T.width=N,T.height=V,_=T.getContext("2d"),!_)throw new Error("Unable to create 2D canvas context for video preview");const Ge=Ji(c.value,_,N,V),ze=Dt.Texture.from(T);x=ze.source,w=new Dt.Sprite(ze),w.visible=!0,w.alpha=1,Ct(),v.stage.addChild(w),v.renderer&&!v.renderer.destroyed&&v.render()}O(),r.targetFps<60?ae():v.ticker.add(F),h.value=!0,"ResizeObserver"in window&&(S=new ResizeObserver(Ge=>{C||(C=!0,requestAnimationFrame(()=>{C=!1;const ze=Ge[Ge.length-1],{width:Et,height:ut}=ze.contentRect;if(Et<=0||ut<=0)return;const Xt=Math.round(Et),Wt=Math.round(ut);Xt===A&&Wt===j||(A=Xt,j=Wt,Ct())}))}),S.observe(l.value)),r.filters&&r.filters.length>0&&O(),r.showFps&&De(),I=0}catch{if(Lt(),!U&&!!c.value&&c.value.readyState>=2&&c.value.videoWidth>0&&c.value.videoHeight>0&&I<2){I+=1,window.setTimeout(()=>{U||ne()},I*150);return}f.value="Failed to initialize video preview",s("error",f.value)}finally{z=!1}}}function ae(){const be=1e3/r.targetFps;let ke=performance.now();function Te(){if(U||!v)return;const Ke=performance.now(),Ge=Ke-ke;Ge>=be&&(F(),ke=Ke-Ge%be),L=requestAnimationFrame(Te)}L=requestAnimationFrame(Te)}function F(){if(!(!v||!w||U)&&r.active)try{_&&T&&x&&c.value&&(c.value.readyState>=2&&Ji(c.value,_,T.width,T.height)&&x.update(),c.value.paused||s("frame-update",ce())),r.showFps&&y++,v.renderer&&!v.renderer.destroyed&&v.render()}catch{U=!0}}function B(){for(const be of g)try{be.destroy()}catch{}g=[]}function O(){if(w){if(!r.filters||r.filters.length===0){w.filters=null,B();return}B(),r.filters.forEach(be=>{const ke=X(be);ke&&g.push(ke)}),w.filters=g.length>0?g:null,E=JSON.stringify(r.filters),v&&v.render()}}function X(be){const ke=be.filterId,Te=be.params||{},Ke=te.getFilter(ke);if(Ke&&!te.isFilterCompatibleWithMedia(ke,"video"))return null;if(Ke&&Ke.createFilter)try{return Ke.createFilter(Te)}catch{}const Ge=(ze,Et,ut)=>Math.min(ut,Math.max(Et,ze));switch(ke){case"brightness":{const ze=new n,Et=Ge(typeof Te.brightness=="number"?Te.brightness:typeof Te.value=="number"?Te.value:1,0,5);return ze.brightness(Et,!0),ze}case"contrast":{const ze=new n,Et=Ge(typeof Te.contrast=="number"?Te.contrast:typeof Te.value=="number"?Te.value:1,0,5);return ze.contrast(Et,!0),ze}case"saturation":{const ze=new n,Et=Ge(typeof Te.saturation=="number"?Te.saturation:typeof Te.value=="number"?Te.value:1,0,5);return ze.saturate(Et,!0),ze}case"hue":{const ze=new n,Et=Ge(typeof Te.value=="number"?Te.value:0,-180,180);return ze.hue(Et,!0),ze}case"gaussian-blur":case"blur":{const ze=Ge(typeof Te.blur=="number"?Te.blur:typeof Te.value=="number"?Te.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 Te.value=="number"?Te.value:.3;return oe(Ge(ze,0,1))}default:return null}}function oe(be){const ke=`
|
|
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 Dt.Filter(void 0,ke,{strength:be})}function ce(){var ke;return!v||!w?null:{dataUrl:v.canvas.toDataURL("image/jpeg",.8),timestamp:((ke=c.value)==null?void 0:ke.currentTime)||0,width:N||0,height:V||0}}function je(){var be;m.value=ve((be=c.value)==null?void 0:be.duration),s("duration-change",m.value)}function he(){u.value=!1,f.value=void 0}function ge(){u.value&&(u.value=!1),!h.value&&r.active?ne():h.value}function pe(){var ke,Te,Ke;const be=((ke=c.value)==null?void 0:ke.currentTime)||0;s("frame-update",{dataUrl:null,timestamp:be,width:((Te=c.value)==null?void 0:Te.videoWidth)||0,height:((Ke=c.value)==null?void 0:Ke.videoHeight)||0})}function we(){c.value&&(c.value.currentTime=0),s("play-pause")}function ye(be){var Te;const ke=be.target;if(ke!=null&&ke.error)switch(ke.error.code){case ke.error.MEDIA_ERR_ABORTED:f.value="Video playback aborted";break;case ke.error.MEDIA_ERR_NETWORK:f.value="Network error loading video";break;case ke.error.MEDIA_ERR_DECODE:f.value="Video format not supported";break;case ke.error.MEDIA_ERR_SRC_NOT_SUPPORTED:f.value=`Video source not supported: ${(Te=ke.src)==null?void 0:Te.substring(0,100)}`;break;default:f.value="Failed to load video"}else f.value="Failed to load video";s("error",f.value),u.value=!1}function Ne(be){c.value&&(c.value.currentTime=Math.max(0,Math.min(be,m.value)))}function De(){R=window.setInterval(()=>{const be=performance.now(),ke=be-$;p.value=Math.round(y*1e3/ke),y=0,$=be},1e3)}function Qe(be){if(!Number.isFinite(be)||be<0)return"00:00";const ke=Math.floor(be/60),Te=Math.floor(be%60);return`${ke.toString().padStart(2,"0")}:${Te.toString().padStart(2,"0")}`}function et(){f.value=void 0,u.value=!0,I=0,Lt(),c.value&&c.value.load()}function Lt(){if(S&&(S.disconnect(),S=null),L&&(cancelAnimationFrame(L),L=null),v!=null&&v.ticker&&(v.ticker.stop(),v.ticker.remove(F)),v)try{v.destroy(!0,{children:!0,texture:!0})}catch{}d.value&&(d.value.innerHTML=""),B(),v=null,w=null,x=null,T=null,_=null,h.value=!1,C=!1,E=""}function kt(){v&&(C||(C=!0,requestAnimationFrame(()=>{C=!1,Ct()})))}function Ct(){if(!v||!w||!N||!V||!l.value)return;const be=Math.round(l.value.clientWidth),ke=Math.round(l.value.clientHeight);if(be<=0||ke<=0)return;v.renderer.resize(be,ke);const Te=v.screen.width/N,Ke=v.screen.height/V;let Ge=1;switch(r.fitMode){case"cover":Ge=Math.max(Te,Ke);break;case"none":Ge=1;break;case"contain":default:Ge=Math.min(Te,Ke);break}w.scale.set(Ge),w.anchor.set(.5),w.position.set(v.screen.width/2,v.screen.height/2),w.visible=!0,w.alpha=1,v.renderer&&!v.renderer.destroyed&&v.render()}e.watch(()=>r.filters,()=>{h.value&&O()},{deep:!0}),e.watch(()=>r.active,async be=>{if(be&&!v&&c.value&&c.value.readyState>=2){await ne();return}v&&(be&&(await e.nextTick(),l.value&&l.value.getBoundingClientRect(),w&&_&&T&&x&&(c.value&&c.value.readyState>=2&&Ji(c.value,_,T.width,T.height)&&x.update(),Ct(),v.renderer&&!v.renderer.destroyed&&v.render())),r.targetFps>=60&&v.ticker&&(be?v.ticker.start():v.ticker.stop()))}),e.watch(P,be=>{be?(u.value=!0,f.value=void 0,e.nextTick(()=>{c.value&&c.value.load()})):(u.value=!1,f.value="No video source provided")},{immediate:!0});async function bt(){if(c.value){f.value=void 0,Ve(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{}}}f.value="Unable to start preview playback",s("error",f.value)}}e.watch(()=>r.isPlaying,be=>{c.value&&(be?bt():c.value.pause())}),e.watch(()=>r.playhead,be=>{c.value&&Math.abs(c.value.currentTime-be)>.5&&Ne(be)}),e.watch(()=>r.fitMode,()=>{Ct()}),e.onMounted(()=>{U=!1,e.nextTick(()=>{l.value&&l.value.getBoundingClientRect(),c.value}),window.addEventListener("resize",kt),$=performance.now(),e.nextTick(()=>{c.value&&c.value.readyState>=2&&!h.value?ne():c.value&&c.value.src&&c.value.readyState===0&&c.value.load()})}),e.onUnmounted(()=>{if(U=!0,L&&(cancelAnimationFrame(L),L=null),window.removeEventListener("resize",kt),S&&(S.disconnect(),S=null),R&&clearInterval(R),v&&v.ticker&&(v.ticker.stop(),v.ticker.remove(F)),v){try{v.destroy(!0,{children:!0,texture:!0})}catch{}v=null}g.forEach(be=>{try{be.destroy()}catch{}}),g=[],w=null,x=null,T=null,_=null,c.value&&(c.value.pause(),c.value.removeAttribute("src"),c.value.load())});async function rt(be){if(!await _t()||!c.value||!_||!T||!x)return null;const Te=c.value,Ke=Number.isFinite(m.value)&&m.value>0?m.value:Number.isFinite(Te.duration)&&Te.duration>0?Te.duration:0,Ge=Math.max(0,Math.min(be,Ke));return await new Promise(Et=>{let ut=!1,Xt=0;const Wt=()=>{ut||(ut=!0,Te.removeEventListener("seeked",ca),window.clearTimeout(Xt),Et())},ca=()=>{Wt()},ta=Number.isFinite(Te.currentTime)?Te.currentTime:0;if(Math.abs(ta-Ge)<.016){requestAnimationFrame(()=>Wt());return}Te.addEventListener("seeked",ca),Xt=window.setTimeout(()=>Wt(),700),Te.currentTime=Ge}),Ji(Te,_,T.width,T.height)?(x.update(),v.render(),v.canvas):null}async function _t(){if(!c.value)return!1;if(!v){if(!(c.value.readyState>=2))return!1;await ne()}if(!v||!w||!_||!T||!x)return!1;if(r.filters&&r.filters.length>0){const be=w.filters,ke=Array.isArray(be)?be.length:0,Ke=JSON.stringify(r.filters)!==E;(ke===0||ke!==r.filters.length||Ke)&&O()}return await e.nextTick(),await new Promise(be=>{requestAnimationFrame(()=>be())}),!0}return a({captureFrameAt:rt,ensureReadyForCapture:_t,duration:m,pixiCanvas:e.computed(()=>v?v.canvas:null),videoElement:e.computed(()=>c.value??null)}),(be,ke)=>(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:P.value,onLoadedmetadata:je,onLoadeddata:he,onCanplay:ge,onTimeupdate:pe,onEnded:we,onError:ye,style:e.normalizeStyle(K.value),crossorigin:Z.value,preload:"auto",playsinline:"",controls:""},null,44,Hg),e.createElementVNode("div",Zg,[e.createElementVNode("button",{class:"play-button",onClick:ke[0]||(ke[0]=Te=>be.$emit("play-pause")),"aria-label":be.isPlaying?"Pause":"Play"},[e.createVNode(e.unref(W.IonIcon),{icon:be.isPlaying?e.unref(Lu):e.unref(Pu)},null,8,["icon"])],8,Xg),e.createElementVNode("div",Gg,[e.createElementVNode("span",Jg,e.toDisplayString(Qe(be.playhead)),1),ke[1]||(ke[1]=e.createElementVNode("span",{class:"separator"},"/",-1)),e.createElementVNode("span",Kg,e.toDisplayString(Qe(m.value)),1)]),be.showFps?(e.openBlock(),e.createElementBlock("div",qg,e.toDisplayString(p.value)+" FPS ",1)):e.createCommentVNode("",!0)]),u.value?(e.openBlock(),e.createElementBlock("div",Yg,[e.createVNode(e.unref(W.IonSpinner),{name:"crescent"}),ke[2]||(ke[2]=e.createElementVNode("p",null,"Loading video...",-1))])):e.createCommentVNode("",!0),f.value?(e.openBlock(),e.createElementBlock("div",Qg,[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Hl)},null,8,["icon"]),e.createElementVNode("p",null,e.toDisplayString(f.value),1),e.createElementVNode("button",{onClick:et},"Retry")])):e.createCommentVNode("",!0)],512))}}),nl=Be(t0,[["__scopeId","data-v-dd1744f4"]]);var Gl=(o,a,t)=>{if(!a.has(o))throw TypeError("Cannot "+t)},J=(o,a,t)=>(Gl(o,a,"read from private field"),t?t.call(o):a.get(o)),Je=(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)},jt=(o,a,t,n)=>(Gl(o,a,"write to private field"),a.set(o,t),t),a0=(o,a,t,n)=>({set _(i){jt(o,a,i)},get _(){return J(o,a,n)}}),at=(o,a,t)=>(Gl(o,a,"access private method"),t),nt=new Uint8Array(8),Xa=new DataView(nt.buffer),Pt=o=>[(o%256+256)%256],dt=o=>(Xa.setUint16(0,o,!1),[nt[0],nt[1]]),n0=o=>(Xa.setInt16(0,o,!1),[nt[0],nt[1]]),Wu=o=>(Xa.setUint32(0,o,!1),[nt[1],nt[2],nt[3]]),Re=o=>(Xa.setUint32(0,o,!1),[nt[0],nt[1],nt[2],nt[3]]),o0=o=>(Xa.setInt32(0,o,!1),[nt[0],nt[1],nt[2],nt[3]]),Wn=o=>(Xa.setUint32(0,Math.floor(o/2**32),!1),Xa.setUint32(4,o,!1),[nt[0],nt[1],nt[2],nt[3],nt[4],nt[5],nt[6],nt[7]]),Jl=o=>(Xa.setInt16(0,2**8*o,!1),[nt[0],nt[1]]),Wa=o=>(Xa.setInt32(0,2**16*o,!1),[nt[0],nt[1],nt[2],nt[3]]),Ds=o=>(Xa.setInt32(0,2**30*o,!1),[nt[0],nt[1],nt[2],nt[3]]),_a=(o,a=!1)=>{let t=Array(o.length).fill(null).map((n,i)=>o.charCodeAt(i));return a&&t.push(0),t},Sr=o=>o&&o[o.length-1],Kl=o=>{let a;for(let t of o)(!a||t.presentationTimestamp>a.presentationTimestamp)&&(a=t);return a},Za=(o,a,t=!0)=>{let n=o*a;return t?Math.round(n):n},Hu=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]},Zu=Hu(0),Xu=o=>[Wa(o[0]),Wa(o[1]),Ds(o[2]),Wa(o[3]),Wa(o[4]),Ds(o[5]),Wa(o[6]),Wa(o[7]),Ds(o[8])],ni=o=>!o||typeof o!="object"?o:Array.isArray(o)?o.map(ni):Object.fromEntries(Object.entries(o).map(([a,t])=>[a,ni(t)])),_o=o=>o>=0&&o<2**32,At=(o,a,t)=>({type:o,contents:a&&new Uint8Array(a.flat(10)),children:t}),xt=(o,a,t,n,i)=>At(o,[Pt(a),Wu(t),n??[]],i),i0=o=>{let a=512;return o.fragmented?At("ftyp",[_a("iso5"),Re(a),_a("iso5"),_a("iso6"),_a("mp41")]):At("ftyp",[_a("isom"),Re(a),_a("isom"),o.holdsAvc?_a("avc1"):[],_a("mp41")])},ol=o=>({type:"mdat",largeSize:o}),r0=o=>({type:"free",size:o}),ur=(o,a,t=!1)=>At("moov",null,[s0(a,o),...o.map(n=>l0(n,a)),t?P0(o):null]),s0=(o,a)=>{let t=Za(Math.max(0,...a.filter(s=>s.samples.length>0).map(s=>{const l=Kl(s.samples);return l.presentationTimestamp+l.duration})),sl),n=Math.max(...a.map(s=>s.id))+1,i=!_o(o)||!_o(t),r=i?Wn:Re;return xt("mvhd",+i,0,[r(o),r(o),Re(sl),r(t),Wa(1),Jl(1),Array(10).fill(0),Xu(Zu),Array(24).fill(0),Re(n)])},l0=(o,a)=>At("trak",null,[d0(o,a),c0(o,a)]),d0=(o,a)=>{let t=Kl(o.samples),n=Za(t?t.presentationTimestamp+t.duration:0,sl),i=!_o(a)||!_o(n),r=i?Wn:Re,s;return o.info.type==="video"?s=typeof o.info.rotation=="number"?Hu(o.info.rotation):o.info.rotation:s=Zu,xt("tkhd",+i,3,[r(a),r(a),Re(o.id),Re(0),r(n),Array(8).fill(0),dt(0),dt(0),Jl(o.info.type==="audio"?1:0),dt(0),Xu(s),Wa(o.info.type==="video"?o.info.width:0),Wa(o.info.type==="video"?o.info.height:0)])},c0=(o,a)=>At("mdia",null,[u0(o,a),m0(o.info.type==="video"?"vide":"soun"),p0(o)]),u0=(o,a)=>{let t=Kl(o.samples),n=Za(t?t.presentationTimestamp+t.duration:0,o.timescale),i=!_o(a)||!_o(n),r=i?Wn:Re;return xt("mdhd",+i,0,[r(a),r(a),Re(o.timescale),r(n),dt(21956),dt(0)])},m0=o=>xt("hdlr",0,0,[_a("mhlr"),_a(o),Re(0),Re(0),Re(0),_a("mp4-muxer-hdlr",!0)]),p0=o=>At("minf",null,[o.info.type==="video"?f0():h0(),v0(),y0(o)]),f0=()=>xt("vmhd",0,1,[dt(0),dt(0),dt(0),dt(0)]),h0=()=>xt("smhd",0,0,[dt(0),dt(0)]),v0=()=>At("dinf",null,[g0()]),g0=()=>xt("dref",0,0,[Re(1)],[b0()]),b0=()=>xt("url ",0,1),y0=o=>{const a=o.compositionTimeOffsetTable.length>1||o.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return At("stbl",null,[w0(o),F0(o),$0(o),D0(o),R0(o),A0(o),a?L0(o):null])},w0=o=>xt("stsd",0,0,[Re(1)],[o.info.type==="video"?k0(J0[o.info.codec],o):I0(q0[o.info.codec],o)]),k0=(o,a)=>At(o,[Array(6).fill(0),dt(1),dt(0),dt(0),Array(12).fill(0),dt(a.info.width),dt(a.info.height),Re(4718592),Re(4718592),Re(0),dt(1),Array(32).fill(0),dt(24),n0(65535)],[K0[a.info.codec](a),a.info.decoderConfig.colorSpace?S0(a):null]),_0={bt709:1,bt470bg:5,smpte170m:6},E0={bt709:1,smpte170m:6,"iec61966-2-1":13},x0={rgb:0,bt709:1,bt470bg:5,smpte170m:6},S0=o=>At("colr",[_a("nclx"),dt(_0[o.info.decoderConfig.colorSpace.primaries]),dt(E0[o.info.decoderConfig.colorSpace.transfer]),dt(x0[o.info.decoderConfig.colorSpace.matrix]),Pt((o.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),C0=o=>o.info.decoderConfig&&At("avcC",[...new Uint8Array(o.info.decoderConfig.description)]),V0=o=>o.info.decoderConfig&&At("hvcC",[...new Uint8Array(o.info.decoderConfig.description)]),N0=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 xt("vpcC",1,0,[Pt(n),Pt(i),Pt(l),Pt(2),Pt(2),Pt(2),dt(0)])},T0=()=>{let t=(1<<7)+1;return At("av1C",[t,0,0,0])},I0=(o,a)=>At(o,[Array(6).fill(0),dt(1),dt(0),dt(0),Re(0),dt(a.info.numberOfChannels),dt(16),dt(0),dt(0),Wa(a.info.sampleRate)],[Y0[a.info.codec](a)]),B0=o=>{let a=new Uint8Array(o.info.decoderConfig.description);return xt("esds",0,0,[Re(58753152),Pt(32+a.byteLength),dt(1),Pt(0),Re(75530368),Pt(18+a.byteLength),Pt(64),Pt(21),Wu(0),Re(130071),Re(130071),Re(92307584),Pt(a.byteLength),...a,Re(109084800),Pt(1),Pt(2)])},M0=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 At("dOps",[Pt(0),Pt(o.info.numberOfChannels),dt(a),Re(o.info.sampleRate),Jl(t),Pt(0)])},F0=o=>xt("stts",0,0,[Re(o.timeToSampleTable.length),o.timeToSampleTable.map(a=>[Re(a.sampleCount),Re(a.sampleDelta)])]),$0=o=>{if(o.samples.every(t=>t.type==="key"))return null;let a=[...o.samples.entries()].filter(([,t])=>t.type==="key");return xt("stss",0,0,[Re(a.length),a.map(([t])=>Re(t+1))])},D0=o=>xt("stsc",0,0,[Re(o.compactlyCodedChunkTable.length),o.compactlyCodedChunkTable.map(a=>[Re(a.firstChunk),Re(a.samplesPerChunk),Re(1)])]),R0=o=>xt("stsz",0,0,[Re(0),Re(o.samples.length),o.samples.map(a=>Re(a.size))]),A0=o=>o.finalizedChunks.length>0&&Sr(o.finalizedChunks).offset>=2**32?xt("co64",0,0,[Re(o.finalizedChunks.length),o.finalizedChunks.map(a=>Wn(a.offset))]):xt("stco",0,0,[Re(o.finalizedChunks.length),o.finalizedChunks.map(a=>Re(a.offset))]),L0=o=>xt("ctts",0,0,[Re(o.compositionTimeOffsetTable.length),o.compositionTimeOffsetTable.map(a=>[Re(a.sampleCount),Re(a.sampleCompositionTimeOffset)])]),P0=o=>At("mvex",null,o.map(U0)),U0=o=>xt("trex",0,0,[Re(o.id),Re(1),Re(0),Re(0),Re(0)]),ac=(o,a)=>At("moof",null,[O0(o),...a.map(z0)]),O0=o=>xt("mfhd",0,0,[Re(o)]),Gu=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},z0=o=>At("traf",null,[j0(o),W0(o),H0(o)]),j0=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:Gu(t)};return xt("tfhd",0,a,[Re(o.id),Re(n.duration),Re(n.size),Re(n.flags)])},W0=o=>xt("tfdt",1,0,[Wn(Za(o.currentChunk.startTimestamp,o.timescale))]),H0=o=>{let a=o.currentChunk.samples.map(v=>v.timescaleUnitsToNextSample),t=o.currentChunk.samples.map(v=>v.size),n=o.currentChunk.samples.map(Gu),i=o.currentChunk.samples.map(v=>Za(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,f=s.size>1,m=!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*+f,h|=1024*+m,h|=2048*+p,xt("trun",1,h,[Re(o.currentChunk.samples.length),Re(o.currentChunk.offset-o.currentChunk.moofOffset||0),c?Re(n[0]):[],o.currentChunk.samples.map((v,w)=>[u?Re(a[w]):[],f?Re(t[w]):[],m?Re(n[w]):[],p?o0(i[w]):[]])])},Z0=o=>At("mfra",null,[...o.map(X0),G0()]),X0=(o,a)=>xt("tfra",1,0,[Re(o.id),Re(63),Re(o.finalizedChunks.length),o.finalizedChunks.map(n=>[Wn(Za(n.startTimestamp,o.timescale)),Wn(n.moofOffset),Re(a+1),Re(1),Re(1)])]),G0=()=>xt("mfro",0,0,[Re(0)]),J0={avc:"avc1",hevc:"hvc1",vp9:"vp09",av1:"av01"},K0={avc:C0,hevc:V0,vp9:N0,av1:T0},q0={aac:"mp4a",opus:"Opus"},Y0={aac:B0,opus:M0},Wr=class{},ql=class extends Wr{constructor(){super(...arguments),this.buffer=null}},Ju=class extends Wr{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.")}},Q0=class extends Wr{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")}},Mn,fo,Ku=class{constructor(){this.pos=0,Je(this,Mn,new Uint8Array(8)),Je(this,fo,new DataView(J(this,Mn).buffer)),this.offsets=new WeakMap}seek(o){this.pos=o}writeU32(o){J(this,fo).setUint32(0,o,!1),this.write(J(this,Mn).subarray(0,4))}writeU64(o){J(this,fo).setUint32(0,Math.floor(o/2**32),!1),J(this,fo).setUint32(4,o,!1),this.write(J(this,Mn).subarray(0,8))}writeAscii(o){for(let a=0;a<o.length;a++)J(this,fo).setUint8(a%8,o.charCodeAt(a)),a%8===7&&this.write(J(this,Mn));o.length%8!==0&&this.write(J(this,Mn).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}}};Mn=new WeakMap;fo=new WeakMap;var mr,On,fi,Qo,pr,il,eb=class extends Ku{constructor(o){super(),Je(this,pr),Je(this,mr,void 0),Je(this,On,new ArrayBuffer(2**16)),Je(this,fi,new Uint8Array(J(this,On))),Je(this,Qo,0),jt(this,mr,o)}write(o){at(this,pr,il).call(this,this.pos+o.byteLength),J(this,fi).set(o,this.pos),this.pos+=o.byteLength,jt(this,Qo,Math.max(J(this,Qo),this.pos))}finalize(){at(this,pr,il).call(this,this.pos),J(this,mr).buffer=J(this,On).slice(0,Math.max(J(this,Qo),this.pos))}};mr=new WeakMap;On=new WeakMap;fi=new WeakMap;Qo=new WeakMap;pr=new WeakSet;il=function(o){let a=J(this,On).byteLength;for(;a<o;)a*=2;if(a===J(this,On).byteLength)return;let t=new ArrayBuffer(a),n=new Uint8Array(t);n.set(J(this,fi),0),jt(this,On,t),jt(this,fi,n)};var tb=2**24,ab=2,oi,Fn,ei,Qa,ba,Cr,rl,Yl,qu,Ql,Yu,ii,Vr,ed=class extends Ku{constructor(o){var a,t;super(),Je(this,Cr),Je(this,Yl),Je(this,Ql),Je(this,ii),Je(this,oi,void 0),Je(this,Fn,[]),Je(this,ei,void 0),Je(this,Qa,void 0),Je(this,ba,[]),jt(this,oi,o),jt(this,ei,((a=o.options)==null?void 0:a.chunked)??!1),jt(this,Qa,((t=o.options)==null?void 0:t.chunkSize)??tb)}write(o){J(this,Fn).push({data:o.slice(),start:this.pos}),this.pos+=o.byteLength}flush(){var t,n;if(J(this,Fn).length===0)return;let o=[],a=[...J(this,Fn)].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 J(this,Fn))i.start<=r.start&&r.start<i.start+i.size&&i.data.set(r.data,r.start-i.start);J(this,ei)?(at(this,Cr,rl).call(this,i.data,i.start),at(this,ii,Vr).call(this)):(n=(t=J(this,oi).options).onData)==null||n.call(t,i.data,i.start)}J(this,Fn).length=0}finalize(){J(this,ei)&&at(this,ii,Vr).call(this,!0)}};oi=new WeakMap;Fn=new WeakMap;ei=new WeakMap;Qa=new WeakMap;ba=new WeakMap;Cr=new WeakSet;rl=function(o,a){let t=J(this,ba).findIndex(l=>l.start<=a&&a<l.start+J(this,Qa));t===-1&&(t=at(this,Ql,Yu).call(this,a));let n=J(this,ba)[t],i=a-n.start,r=o.subarray(0,Math.min(J(this,Qa)-i,o.byteLength));n.data.set(r,i);let s={start:i,end:i+r.byteLength};if(at(this,Yl,qu).call(this,n,s),n.written[0].start===0&&n.written[0].end===J(this,Qa)&&(n.shouldFlush=!0),J(this,ba).length>ab){for(let l=0;l<J(this,ba).length-1;l++)J(this,ba)[l].shouldFlush=!0;at(this,ii,Vr).call(this)}r.byteLength<o.byteLength&&at(this,Cr,rl).call(this,o.subarray(r.byteLength),a+r.byteLength)};Yl=new WeakSet;qu=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)};Ql=new WeakSet;Yu=function(o){let t={start:Math.floor(o/J(this,Qa))*J(this,Qa),data:new Uint8Array(J(this,Qa)),written:[],shouldFlush:!1};return J(this,ba).push(t),J(this,ba).sort((n,i)=>n.start-i.start),J(this,ba).indexOf(t)};ii=new WeakSet;Vr=function(o=!1){var a,t;for(let n=0;n<J(this,ba).length;n++){let i=J(this,ba)[n];if(!(!i.shouldFlush&&!o)){for(let r of i.written)(t=(a=J(this,oi).options).onData)==null||t.call(a,i.data.subarray(r.start,r.end),i.start+r.start);J(this,ba).splice(n--,1)}}};var nb=class extends ed{constructor(o){var a;super(new Ju({onData:(t,n)=>o.stream.write({type:"write",data:t,position:n}),chunked:!0,chunkSize:(a=o.options)==null?void 0:a.chunkSize}))}},sl=1e3,ob=["avc","hevc","vp9","av1"],ib=["aac","opus"],rb=2082844800,sb=["strict","offset","cross-track-offset"],Oe,We,Nr,ga,Zt,zt,vo,go,td,$n,Dn,ri,ll,Qu,dl,em,ad,tm,cl,am,nd,nm,fr,ul,ja,Ya,od,om,si,Tr,Ir,id,Eo,ki,hr,ml,im=class{constructor(o){if(Je(this,ll),Je(this,dl),Je(this,ad),Je(this,cl),Je(this,nd),Je(this,fr),Je(this,ja),Je(this,od),Je(this,si),Je(this,Ir),Je(this,Eo),Je(this,hr),Je(this,Oe,void 0),Je(this,We,void 0),Je(this,Nr,void 0),Je(this,ga,void 0),Je(this,Zt,null),Je(this,zt,null),Je(this,vo,Math.floor(Date.now()/1e3)+rb),Je(this,go,[]),Je(this,td,1),Je(this,$n,[]),Je(this,Dn,[]),Je(this,ri,!1),at(this,ll,Qu).call(this,o),o.video=ni(o.video),o.audio=ni(o.audio),o.fastStart=ni(o.fastStart),this.target=o.target,jt(this,Oe,{firstTimestampBehavior:"strict",...o}),o.target instanceof ql)jt(this,We,new eb(o.target));else if(o.target instanceof Ju)jt(this,We,new ed(o.target));else if(o.target instanceof Q0)jt(this,We,new nb(o.target));else throw new Error(`Invalid target: ${o.target}`);at(this,cl,am).call(this),at(this,dl,em).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(at(this,hr,ml).call(this),!J(this,Oe).video)throw new Error("No video track declared.");if(typeof J(this,Oe).fastStart=="object"&&J(this,Zt).samples.length===J(this,Oe).fastStart.expectedVideoChunks)throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${J(this,Oe).fastStart.expectedVideoChunks}).`);let s=at(this,fr,ul).call(this,J(this,Zt),o,a,t,n,i,r);if(J(this,Oe).fastStart==="fragmented"&&J(this,zt)){for(;J(this,Dn).length>0&&J(this,Dn)[0].decodeTimestamp<=s.decodeTimestamp;){let l=J(this,Dn).shift();at(this,ja,Ya).call(this,J(this,zt),l)}s.decodeTimestamp<=J(this,zt).lastDecodeTimestamp?at(this,ja,Ya).call(this,J(this,Zt),s):J(this,$n).push(s)}else at(this,ja,Ya).call(this,J(this,Zt),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(at(this,hr,ml).call(this),!J(this,Oe).audio)throw new Error("No audio track declared.");if(typeof J(this,Oe).fastStart=="object"&&J(this,zt).samples.length===J(this,Oe).fastStart.expectedAudioChunks)throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${J(this,Oe).fastStart.expectedAudioChunks}).`);let r=at(this,fr,ul).call(this,J(this,zt),o,a,t,n,i);if(J(this,Oe).fastStart==="fragmented"&&J(this,Zt)){for(;J(this,$n).length>0&&J(this,$n)[0].decodeTimestamp<=r.decodeTimestamp;){let s=J(this,$n).shift();at(this,ja,Ya).call(this,J(this,Zt),s)}r.decodeTimestamp<=J(this,Zt).lastDecodeTimestamp?at(this,ja,Ya).call(this,J(this,zt),r):J(this,Dn).push(r)}else at(this,ja,Ya).call(this,J(this,zt),r)}finalize(){if(J(this,ri))throw new Error("Cannot finalize a muxer more than once.");if(J(this,Oe).fastStart==="fragmented"){for(let a of J(this,$n))at(this,ja,Ya).call(this,J(this,Zt),a);for(let a of J(this,Dn))at(this,ja,Ya).call(this,J(this,zt),a);at(this,Ir,id).call(this,!1)}else J(this,Zt)&&at(this,si,Tr).call(this,J(this,Zt)),J(this,zt)&&at(this,si,Tr).call(this,J(this,zt));let o=[J(this,Zt),J(this,zt)].filter(Boolean);if(J(this,Oe).fastStart==="in-memory"){let a;for(let n=0;n<2;n++){let i=ur(o,J(this,vo)),r=J(this,We).measureBox(i);a=J(this,We).measureBox(J(this,ga));let s=J(this,We).pos+r+a;for(let l of J(this,go)){l.offset=s;for(let{data:d}of l.samples)s+=d.byteLength,a+=d.byteLength}if(s<2**32)break;a>=2**32&&(J(this,ga).largeSize=!0)}let t=ur(o,J(this,vo));J(this,We).writeBox(t),J(this,ga).size=a,J(this,We).writeBox(J(this,ga));for(let n of J(this,go))for(let i of n.samples)J(this,We).write(i.data),i.data=null}else if(J(this,Oe).fastStart==="fragmented"){let a=J(this,We).pos,t=Z0(o);J(this,We).writeBox(t);let n=J(this,We).pos-a;J(this,We).seek(J(this,We).pos-4),J(this,We).writeU32(n)}else{let a=J(this,We).offsets.get(J(this,ga)),t=J(this,We).pos-a;J(this,ga).size=t,J(this,ga).largeSize=t>=2**32,J(this,We).patchBox(J(this,ga));let n=ur(o,J(this,vo));if(typeof J(this,Oe).fastStart=="object"){J(this,We).seek(J(this,Nr)),J(this,We).writeBox(n);let i=a-J(this,We).pos;J(this,We).writeBox(r0(i))}else J(this,We).writeBox(n)}at(this,Eo,ki).call(this),J(this,We).finalize(),jt(this,ri,!0)}};Oe=new WeakMap;We=new WeakMap;Nr=new WeakMap;ga=new WeakMap;Zt=new WeakMap;zt=new WeakMap;vo=new WeakMap;go=new WeakMap;td=new WeakMap;$n=new WeakMap;Dn=new WeakMap;ri=new WeakMap;ll=new WeakSet;Qu=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 Wr))throw new TypeError("The target must be provided and an instance of Target.");if(o.video){if(!ob.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(!ib.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&&!sb.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.")};dl=new WeakSet;em=function(){var o;if(J(this,We).writeBox(i0({holdsAvc:((o=J(this,Oe).video)==null?void 0:o.codec)==="avc",fragmented:J(this,Oe).fastStart==="fragmented"})),jt(this,Nr,J(this,We).pos),J(this,Oe).fastStart==="in-memory")jt(this,ga,ol(!1));else if(J(this,Oe).fastStart!=="fragmented"){if(typeof J(this,Oe).fastStart=="object"){let a=at(this,ad,tm).call(this);J(this,We).seek(J(this,We).pos+a)}jt(this,ga,ol(!0)),J(this,We).writeBox(J(this,ga))}at(this,Eo,ki).call(this)};ad=new WeakSet;tm=function(){if(typeof J(this,Oe).fastStart!="object")return;let o=0,a=[J(this,Oe).fastStart.expectedVideoChunks,J(this,Oe).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};cl=new WeakSet;am=function(){if(J(this,Oe).video&&jt(this,Zt,{id:1,info:{type:"video",codec:J(this,Oe).video.codec,width:J(this,Oe).video.width,height:J(this,Oe).video.height,rotation:J(this,Oe).video.rotation??0,decoderConfig:null},timescale:J(this,Oe).video.frameRate??57600,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),J(this,Oe).audio&&(jt(this,zt,{id:J(this,Oe).video?2:1,info:{type:"audio",codec:J(this,Oe).audio.codec,numberOfChannels:J(this,Oe).audio.numberOfChannels,sampleRate:J(this,Oe).audio.sampleRate,decoderConfig:null},timescale:J(this,Oe).audio.sampleRate,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),J(this,Oe).audio.codec==="aac")){let o=at(this,nd,nm).call(this,2,J(this,Oe).audio.sampleRate,J(this,Oe).audio.numberOfChannels);J(this,zt).info.decoderConfig={codec:J(this,Oe).audio.codec,description:o,numberOfChannels:J(this,Oe).audio.numberOfChannels,sampleRate:J(this,Oe).audio.sampleRate}}};nd=new WeakSet;nm=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};fr=new WeakSet;ul=function(o,a,t,n,i,r,s){let l=n/1e6,d=(n-(s??0))/1e6,c=i/1e6,u=at(this,od,om).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:Za(c,o.timescale)}};ja=new WeakSet;Ya=function(o,a){J(this,Oe).fastStart!=="fragmented"&&o.samples.push(a);const t=Za(a.presentationTimestamp-a.decodeTimestamp,o.timescale);if(o.lastTimescaleUnits!==null){let i=Za(a.decodeTimestamp,o.timescale,!1),r=Math.round(i-o.lastTimescaleUnits);if(o.lastTimescaleUnits+=r,o.lastSample.timescaleUnitsToNextSample=r,J(this,Oe).fastStart!=="fragmented"){let s=Sr(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=Sr(o.compositionTimeOffsetTable);l.sampleCompositionTimeOffset===t?l.sampleCount++:o.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:t})}}else o.lastTimescaleUnits=0,J(this,Oe).fastStart!=="fragmented"&&(o.timeToSampleTable.push({sampleCount:1,sampleDelta:Za(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(J(this,Oe).fastStart==="fragmented"){let r=J(this,Zt)??J(this,zt);const s=J(this,Oe).minFragmentDuration??1;o===r&&a.type==="key"&&i>=s&&(n=!0,at(this,Ir,id).call(this))}else n=i>=.5}n&&(o.currentChunk&&at(this,si,Tr).call(this,o),o.currentChunk={startTimestamp:a.presentationTimestamp,samples:[]}),o.currentChunk.samples.push(a)};od=new WeakSet;om=function(o,a,t){var s,l;const n=J(this,Oe).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(J(this,Oe).firstTimestampBehavior==="offset"||J(this,Oe).firstTimestampBehavior==="cross-track-offset"){t.firstDecodeTimestamp===void 0&&(t.firstDecodeTimestamp=a);let d;J(this,Oe).firstTimestampBehavior==="offset"?d=t.firstDecodeTimestamp:d=Math.min(((s=J(this,Zt))==null?void 0:s.firstDecodeTimestamp)??1/0,((l=J(this,zt))==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}};si=new WeakSet;Tr=function(o){if(J(this,Oe).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),J(this,go).push(o.currentChunk),(o.compactlyCodedChunkTable.length===0||Sr(o.compactlyCodedChunkTable).samplesPerChunk!==o.currentChunk.samples.length)&&o.compactlyCodedChunkTable.push({firstChunk:o.finalizedChunks.length,samplesPerChunk:o.currentChunk.samples.length}),J(this,Oe).fastStart==="in-memory"){o.currentChunk.offset=0;return}o.currentChunk.offset=J(this,We).pos;for(let a of o.currentChunk.samples)J(this,We).write(a.data),a.data=null;at(this,Eo,ki).call(this)}};Ir=new WeakSet;id=function(o=!0){if(J(this,Oe).fastStart!=="fragmented")throw new Error("Can't finalize a fragment unless 'fastStart' is set to 'fragmented'.");let a=[J(this,Zt),J(this,zt)].filter(l=>l&&l.currentChunk);if(a.length===0)return;let t=a0(this,td)._++;if(t===1){let l=ur(a,J(this,vo),!0);J(this,We).writeBox(l)}let n=J(this,We).pos,i=ac(t,a);J(this,We).writeBox(i);{let l=ol(!1),d=0;for(let u of a)for(let f of u.currentChunk.samples)d+=f.size;let c=J(this,We).measureBox(l)+d;c>=2**32&&(l.largeSize=!0,c=J(this,We).measureBox(l)+d),l.size=c,J(this,We).writeBox(l)}for(let l of a){l.currentChunk.offset=J(this,We).pos,l.currentChunk.moofOffset=n;for(let d of l.currentChunk.samples)J(this,We).write(d.data),d.data=null}let r=J(this,We).pos;J(this,We).seek(J(this,We).offsets.get(i));let s=ac(t,a);J(this,We).writeBox(s),J(this,We).seek(r);for(let l of a)l.finalizedChunks.push(l.currentChunk),J(this,go).push(l.currentChunk),l.currentChunk=null;o&&at(this,Eo,ki).call(this)};Eo=new WeakSet;ki=function(){J(this,We)instanceof ed&&J(this,We).flush()};hr=new WeakSet;ml=function(){if(J(this,ri))throw new Error("Cannot add new video or audio chunks after the file has been finalized.")};const hi=30;class xo extends Error{constructor({message:t="",code:n=""},...i){super(t,...i);Y(this,"message");Y(this,"code");this.code=n,this.message=t}}class en extends xo{}class Rt extends xo{}class Br extends xo{}class nc extends xo{}function lb(o,a=hi){if(a<1)throw new Rt({code:"invalidArgument",message:"FPS must be greater or equal to 1"});return Math.round(o*a)}function bo(o,a=hi){if(a<1)throw new Rt({code:"invalidArgument",message:"FPS must be greater or equal to 1"});return Math.round(o/a*1e3)}class $e{constructor(a=0){Y(this,"time");this.time=Math.round(a)}get millis(){return this.time}set millis(a){this.time=Math.round(a)}get frames(){return lb(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 $e(a.millis+this.millis)}subtract(a){return new $e(this.millis-a.millis)}static fromSeconds(a){const t=new $e;return t.millis=a*1e3,t}static fromFrames(a,t){const n=new $e;return n.millis=bo(a,t),n}copy(){return new $e(this.millis)}toJSON(){return this.millis}static fromJSON(a){return new $e(a)}}function oc(o,a){return[o.slice(0,a),o.slice(a)].filter(t=>t.length>0)}function vr(o,a){return a?Math.floor(Math.random()*(a-o+1)+o):o}function db(o,a,t){t<0&&(t=0);const n=o[a];o.splice(a,1),o.splice(t,0,n)}function ic(o){return typeof o!="function"?!1:/^class\s/.test(Function.prototype.toString.call(o))}function cb(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 ub(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,f=Math.floor(u),m=Math.ceil(u);if(m>=s.length)l[c]=s[f];else{const p=u-f;l[c]=s[f]*(1-p)+s[m]*p}}}return i}async function mb(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(pb)}function pb(o,a){const t=o.hardwareAcceleration??"",n=a.hardwareAcceleration??"";return t<n?-1:t>n?1:0}async function fb(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 rc(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 sc(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 Ki{constructor(a){Y(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 $e}get stop(){var a;return((a=this.words.at(-1))==null?void 0:a.stop)??new $e}}var pl=(o=>(o.en="en",o.de="de",o))(pl||{});class lc{constructor(a,t,n,i){Y(this,"id",crypto.randomUUID());Y(this,"text");Y(this,"start");Y(this,"stop");Y(this,"confidence");this.text=a,this.start=new $e(t),this.stop=new $e(n),this.confidence=i}get duration(){return this.stop.subtract(this.start)}}class An{constructor(a=[],t=pl.en){Y(this,"id",crypto.randomUUID());Y(this,"language",pl.en);Y(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>=vr(...a)?(yield r,r=void 0):t&&(r==null?void 0:r.duration.seconds)>=vr(...t)?(yield r,r=void 0):n&&r.text.length>=vr(...n)&&(yield r,r=void 0)),r?r.words.push(l):r=new Ki([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=sc(i.start.seconds),s=sc(i.stop.seconds);n+=`${t}
|
|
22
|
-
`+rc(r)+" --> "+rc(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 lc(s.text,s.start.millis-n,s.stop.millis-n)),i.length==a)return new An([new Ki(i)]);return new An([new Ki(i)])}copy(){return An.fromJSON(this.toJSON())}static fromJSON(a){const t=new An;for(const n of a){const i=new Ki;for(const r of n)i.words.push(new lc(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 en({code:"unexpectedIOError",message:"An unexpected error occurred while fetching the file"});return An.fromJSON(await n.json())}}function gr(o,a,t){return o+(a-o)*t}function hb(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,f=Math.round(gr(r,d,t)),m=Math.round(gr(s,c,t)),p=Math.round(gr(l,u,t));return`#${((1<<24)+(f<<16)+(m<<8)+p).toString(16).slice(1)}`}const vb={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 Ue{constructor(a,t,n={}){Y(this,"input");Y(this,"output");Y(this,"options");if(a.length!==t.length)throw new Rt({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=vb[this.options.easing](a);if(typeof n=="number"&&typeof i=="number")return gr(n,i,r);if(typeof n=="string"&&typeof i=="string")return hb(n,i,r);if(this.output.length==1)return this.output[0];throw new Rt({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 Ue([],[]);return Object.assign(t,a),t}}class xa{constructor(){Y(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 Ie(o){return function(a,t){a.constructor.__serializableProperties||(a.constructor.__serializableProperties=[]),a.constructor.__serializableProperties.push({propertyKey:t,serializer:o})}}function _i(o){return class extends o{constructor(){super(...arguments);Y(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 rd(o,a,t=0){if(!(o instanceof gt.Container||o instanceof gt.Filter||t==3))for(const n in o){const i=o[n];n&&(i instanceof Ue&&(o[n]=i.value(a)),i!=null&&typeof i=="object"&&Object.keys(i).length&&rd(i,a,t+1))}}var gb=Object.defineProperty,Hr=(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&&gb(a,t,i),i};const Ei=class rm extends _i(xa){constructor(t={}){super();Y(this,"_name");Y(this,"_start",new $e);Y(this,"_stop",$e.fromSeconds(16));Y(this,"type","base");Y(this,"source");Y(this,"view",new gt.Container);Y(this,"createdAt",new Date);Y(this,"disabled",!1);Y(this,"state","IDLE");Y(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",$e.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=$e.fromFrames(t)),!t||t.millis<=this.start.millis||t.millis>=this.stop.millis)throw new Rt({code:"splitOutOfRange",message:"Cannot split clip at the specified time"});if(!this.track)throw new Rt({code:"trackNotAttached",message:"Track must be attached to a track"});const n=this.copy();this.stop=t.copy(),n.start=t.copy().addMillis(1),rd(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 rm.fromJSON(JSON.parse(JSON.stringify(this)))}set(t){return t&&Object.assign(this,t),this.trigger("update",void 0),this}};Hr([Ie()],Ei.prototype,"_name");Hr([Ie($e)],Ei.prototype,"_start");Hr([Ie($e)],Ei.prototype,"_stop");Hr([Ie()],Ei.prototype,"disabled");let xi=Ei;var bb=Object.defineProperty,Kn=(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&&bb(a,t,i),i};class Ga extends _i(xa){constructor(){super(...arguments);Y(this,"state","IDLE");Y(this,"metadata");Y(this,"objectURL");Y(this,"duration",$e.fromSeconds(16));Y(this,"added",!1);Y(this,"type","base");Y(this,"name","");Y(this,"mimeType");Y(this,"externalURL");Y(this,"external",!1);Y(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 Rt({code:"fileNotAccessible",message:"The desired file cannot be accessed"});return this.file}async loadFile(t){this.name=t.name,this.mimeType=gl(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 en({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=gl(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();fb(t,this.name)}async thumbnail(){return document.createElement("div")}static async from(t,n,i=new this){return i.from(t,n)}}Kn([Ie()],Ga.prototype,"objectURL");Kn([Ie()],Ga.prototype,"duration");Kn([Ie()],Ga.prototype,"type");Kn([Ie()],Ga.prototype,"name");Kn([Ie()],Ga.prototype,"mimeType");Kn([Ie()],Ga.prototype,"externalURL");Kn([Ie()],Ga.prototype,"external");const dc="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3C/svg%3E";function yb(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 cc(o){if(!o||!o.body)return dc;const a=o.body.scrollWidth,t=o.body.scrollHeight,n=o.cloneNode(!0),i=n.getElementsByTagName("style").item(0),r=n.getElementsByTagName("body").item(0);if(r==null||r.setAttribute("xmlns","http://www.w3.org/1999/xhtml"),!r)return dc;const 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,"+yb(c)}class uc extends Ga{constructor(){super();Y(this,"type","html");Y(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=cc(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=cc(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 wb(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 f=0;f<s.length;f+=n){let m=0;const p=Math.min(f+n,s.length);for(let h=f;h<p;h++)m+=s[h]*s[h];m=Math.sqrt(m/(p-f)),m<t?(u+=n,c===null&&(c=f)):(c!==null&&u>=d&&r.push({start:$e.fromSeconds(c/l),stop:$e.fromSeconds(f/l)}),c=null,u=0)}return c!==null&&u>=d&&r.push({start:$e.fromSeconds(c/l),stop:$e.fromSeconds(s.length/l)}),r}const Rs=3e3;class bn extends Ga{constructor(){super(...arguments);Y(this,"type","audio");Y(this,"decoding",!1);Y(this,"_silences");Y(this,"transcript");Y(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 f=0;f<l;f+=d){let m=0;for(let p=f;p<f+s;p++)m+=Math.abs(c[f]);u.push(Math.log1p(m/s*100))}return u.map(f=>Math.round(f/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,Rs,!0),l=s.getChannelData(0),d=Math.floor(Math.max(n*Rs/1e3,0)),c=i?Math.floor(Math.min(i*Rs/1e3,s.length)):s.length,u=Math.floor((c-d)/t),f=new Float32Array(t);for(let m=0;m<t;m++){const p=d+m*u,h=p+u;let v=-1/0;for(let w=p;w<h;w++){const x=l[w];x>v&&(v=x)}f[m]=r?Math.log2(1+v):v}return f}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=wb(r,t),i.close(),this._silences}}class fl extends Ga{constructor(){super(...arguments);Y(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 Pn extends bn{constructor(){super(...arguments);Y(this,"type","video");Y(this,"downloadInProgress",!0)}async loadUrl(t,n){const i=await fetch(t,n);if(!(i!=null&&i.ok))throw new en({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=gl(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 Rt({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 kb{static fromJSON(a){return[new $e(a[0]),new $e(a[1])]}}var _b=Object.defineProperty,Eb=Object.getOwnPropertyDescriptor,Co=(o,a,t,n)=>{for(var i=n>1?void 0:n?Eb(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&&_b(a,t,i),i};const qn=class sm extends xi{constructor(t={}){super();Y(this,"source",new bn);Y(this,"_offset",new $e);Y(this,"playing",!1);Y(this,"duration",new $e);Y(this,"range",[new $e,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=$e.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=$e.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",$e.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 nc({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=$e.fromFrames(t)),typeof n=="number"&&(n=$e.fromFrames(n)),t.millis>=n.millis)throw new Rt({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=sm.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=$e.fromFrames(t)),!t||t.millis<=this.start.millis||t.millis>=this.stop.millis)throw new Rt({code:"invalidKeyframe",message:"Cannot split clip at the specified time"});if(!this.track)throw new nc({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),rd(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 Rt({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=>mc(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(!mc(s,l.range))continue;const d=new $e(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}};Co([Ie($e)],qn.prototype,"_offset",2);Co([Ie($e)],qn.prototype,"duration",2);Co([Ie(kb)],qn.prototype,"range",2);Co([Ie(An)],qn.prototype,"transcript",1);Co([Ie()],qn.prototype,"muted",1);Co([Ie()],qn.prototype,"volume",1);let Zr=qn;function mc(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 qi{static fromJSON(a){return typeof a=="object"?Ue.fromJSON(a):a}}class As{static fromJSON(a){return typeof a.x=="object"&&(a.x=Ue.fromJSON(a.x)),typeof a.y=="object"&&(a.y=Ue.fromJSON(a.y)),a}}let xb=class{constructor(o){Y(this,"target");Y(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 Ue(i,r,{easing:n})}};function Sb(o){const a=new Proxy(o,{get(t,n){return n=="to"?(i,r)=>{if(!t.animation)throw new Rt({code:"undefinedKeyframe",message:"Cannot use 'to() before selecting a property"});const s=new $e(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 Cb extends xb{}var Vb=Object.defineProperty,Nb=Object.getOwnPropertyDescriptor,hn=(o,a,t,n)=>{for(var i=n>1?void 0:n?Nb(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&&Vb(a,t,i),i};function Xr(o){class a extends o{constructor(){super(...arguments);Y(this,"filters");Y(this,"_height");Y(this,"_width");Y(this,"_position",{x:this.view.position.x,y:this.view.position.y});Y(this,"_scale");Y(this,"rotation",this.view.angle);Y(this,"alpha",1);Y(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 Ue||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 gt.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 gt.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 Sb(new Cb(this))}}return hn([Ie(qi)],a.prototype,"_height",2),hn([Ie(qi)],a.prototype,"_width",2),hn([Ie(As)],a.prototype,"_position",2),hn([Ie(As)],a.prototype,"_scale",2),hn([Ie(qi)],a.prototype,"rotation",2),hn([Ie(qi)],a.prototype,"alpha",2),hn([Ie(As)],a.prototype,"translate",2),hn([Ie()],a.prototype,"anchor",1),a}function Gr(o,a,t){const n=t.value;return t.value=function(...i){var f,m,p,h;const r=i[0].subtract(this.start),s={width:((m=(f=this.track)==null?void 0:f.composition)==null?void 0:m.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 w;typeof this._scale.y=="number"?w=this._scale.y:typeof this._scale.y=="function"?w=this._scale.y.bind(this)(r):w=this._scale.y.value(r),(this._width||this._height)&&(v*=this.view.scale._x,w*=this.view.scale._y),this.view.scale.set(v,w)}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 Tb=Object.defineProperty,Ib=Object.getOwnPropertyDescriptor,Bb=(o,a,t,n)=>{for(var i=Ib(a,t),r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&Tb(a,t,i),i};const lm=class dm extends Xr(xi){constructor(t,n={}){super();Y(this,"type","image");Y(this,"element",new Image);Y(this,"source",new fl);Y(this,"sprite",new gt.Sprite);this.view.addChild(this.sprite),t instanceof fl&&(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=gt.Texture.from(this.element),this.state="READY",t()},this.element.onerror=i=>{this.state="ERROR",n(new en({code:"sourceNotProcessable",message:"An error occurred while processing the input medium."}))}})}update(t){}copy(){const t=dm.fromJSON(JSON.parse(JSON.stringify(this)));return t.filters=this.filters,t.source=this.source,t}};Bb([Gr],lm.prototype,"update");let Mb=lm;const Yi={"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 Fb=Object.defineProperty,Jr=(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&&Fb(a,t,i),i};const Si=class hl extends _i(xa){constructor(t){super();Y(this,"loaded",!1);Y(this,"family");Y(this,"weight");Y(this,"source");Y(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=hl.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(Yi).map(t=>({family:t,variants:Yi[t].weights.map(n=>({family:t,source:`url(${Yi[t].url})`,weight:n}))}))}static fromFamily({family:t,weight:n}){return new hl({family:t,source:`url(${Yi[t].url})`,weight:n})}};Jr([Ie()],Si.prototype,"family");Jr([Ie()],Si.prototype,"weight");Jr([Ie()],Si.prototype,"source");Jr([Ie()],Si.prototype,"style");let Qt=Si;const Ha=4,cm={center:.5,justify:.5,left:0,right:1},um={alphabetic:0,top:0,middle:.5,hanging:1,bottom:1,ideographic:1};var $b=Object.defineProperty,Db=Object.getOwnPropertyDescriptor,da=(o,a,t,n)=>{for(var i=Db(a,t),r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&$b(a,t,i),i};const na=class mm extends Xr(xi){constructor(t){super();Y(this,"type","text");Y(this,"_text","");Y(this,"_textCase");Y(this,"_anchor",{x:0,y:0});Y(this,"_font",new Qt);Y(this,"style",new gt.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 gt.Text({text:this.transformedText,style:this.style,resolution:Ha,scale:Ha});this.view.addChild(n)}this.view.children[0]instanceof gt.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*Ha}set maxWidth(t){t?(this.style.wordWrap=!0,this.style.wordWrapWidth=t/Ha):this.style.wordWrap=!1}get textAlign(){return this.style.align}set textAlign(t){this.style.align=t,this.anchor.x=cm[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=um[t]}get fillStyle(){const{fill:t}=this.style;return new gt.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 gt.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 gt.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 gt.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=mm.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)*Ha;this.view.pivot={x:(t-i)*this._anchor.x,y:(n-i)*this._anchor.y}}set(t){return super.set(t)}};da([Ie()],na.prototype,"text");da([Ie(Qt)],na.prototype,"font");da([Ie()],na.prototype,"maxWidth");da([Ie()],na.prototype,"textAlign");da([Ie()],na.prototype,"padding");da([Ie()],na.prototype,"textBaseline");da([Ie()],na.prototype,"fillStyle");da([Ie()],na.prototype,"anchor");da([Ie()],na.prototype,"stroke");da([Ie()],na.prototype,"textCase");da([Ie()],na.prototype,"shadow");da([Ie()],na.prototype,"fontSize");da([Ie()],na.prototype,"leading");da([Gr],na.prototype,"update");let Vo=na;function Ls(o){const a=o.split(" ").map(t=>`${t} `);return a[a.length-1]=a[a.length-1].replace(/ $/,""),a}const Rb={get(o,a){const t=o[a];return typeof t=="number"?t*Ha:Array.isArray(t)&&typeof t[0]=="number"?t.map(n=>n*Ha):t}};function Ab(o){return new Proxy(o,Rb)}class Lb{constructor(){Y(this,"tokens",[])}get width(){return this.tokens.reduce((a,t)=>a+t.metrics.lineWidths[0],0)}get height(){return Math.max(...this.tokens.map(a=>a.metrics.lineHeight))}}class pc{constructor(){Y(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 Pb{static fromJSON(a){return a.map(t=>(t.font&&(t.font=Qt.fromJSON(t.font)),t))}}var Ub=Object.defineProperty,Ob=Object.getOwnPropertyDescriptor,No=(o,a,t,n)=>{for(var i=n>1?void 0:n?Ob(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&&Ub(a,t,i),i};const Yn=class pm extends Vo{constructor(t){super();Y(this,"type","complex_text");Y(this,"_maxWidth");Y(this,"_textAlign","left");Y(this,"_textBaseline","top");Y(this,"model",new gt.Container);Y(this,"segments",[]);Y(this,"metrics",new pc);Y(this,"background");Y(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=cm[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=um[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=pm.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:Ls(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:Ls(n.substring(t[l].start,t[l].stop))}),!((t[l].stop??n.length)>=n.length)&&i.push({index:void 0,tokens:Ls(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 pc;for(const d of t){const c=d.index!=null?n[d.index]:this.style;for(let u=0;u<d.tokens.length;u++){const f=Ab(gt.CanvasTextMetrics.measureText(d.tokens[u],c)),m=(((r=i.lines.at(-1))==null?void 0:r.width)??0)+f.lineWidths[0],p=this.maxWidth??Number.POSITIVE_INFINITY,h=(s=d.tokens.at(u-1))==null?void 0:s.match(/(\n|\\n).$/gim);(m>p||h||!i.lines.length)&&i.lines.push(new Lb),this.model.addChild(new gt.Text({text:d.tokens[u],style:c,resolution:Ha,scale:Ha})),(l=i.lines.at(-1))==null||l.tokens.push({metrics:f,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 gt.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)*Ha;this.view.pivot={x:(i-s)*this._anchor.x,y:(r-s)*this._anchor.y},this.drawBackground()}};No([Ie()],Yn.prototype,"background",2);No([Ie(Pb)],Yn.prototype,"styles",2);No([Ie()],Yn.prototype,"text",1);No([Ie()],Yn.prototype,"maxWidth",1);No([Ie()],Yn.prototype,"textAlign",1);No([Ie()],Yn.prototype,"textBaseline",1);let Kr=Yn;const fm="KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO3ZhciBtPSh0PT4odFt0LkFWTUVESUFfVFlQRV9VTktOT1dOPS0xXT0iQVZNRURJQV9UWVBFX1VOS05PV04iLHRbdC5BVk1FRElBX1RZUEVfVklERU89MF09IkFWTUVESUFfVFlQRV9WSURFTyIsdFt0LkFWTUVESUFfVFlQRV9BVURJTz0xXT0iQVZNRURJQV9UWVBFX0FVRElPIix0W3QuQVZNRURJQV9UWVBFX0RBVEE9Ml09IkFWTUVESUFfVFlQRV9EQVRBIix0W3QuQVZNRURJQV9UWVBFX1NVQlRJVExFPTNdPSJBVk1FRElBX1RZUEVfU1VCVElUTEUiLHRbdC5BVk1FRElBX1RZUEVfQVRUQUNITUVOVD00XT0iQVZNRURJQV9UWVBFX0FUVEFDSE1FTlQiLHRbdC5BVk1FRElBX1RZUEVfTkI9NV09IkFWTUVESUFfVFlQRV9OQiIsdCkpKG18fHt9KSxvPSh0PT4odC5GRm1wZWdXb3JrZXJMb2FkZWQ9IkZGbXBlZ1dvcmtlckxvYWRlZCIsdC5XQVNNUnVudGltZUluaXRpYWxpemVkPSJXQVNNUnVudGltZUluaXRpYWxpemVkIix0LkxvYWRXQVNNPSJMb2FkV0FTTSIsdC5HZXRBVlBhY2tldD0iR2V0QVZQYWNrZXQiLHQuR2V0QVZQYWNrZXRzPSJHZXRBVlBhY2tldHMiLHQuR2V0QVZTdHJlYW09IkdldEFWU3RyZWFtIix0LkdldEFWU3RyZWFtcz0iR2V0QVZTdHJlYW1zIix0LlJlYWRBVlBhY2tldD0iUmVhZEFWUGFja2V0Iix0LkFWUGFja2V0U3RyZWFtPSJBVlBhY2tldFN0cmVhbSIsdC5SZWFkTmV4dEFWUGFja2V0PSJSZWFkTmV4dEFWUGFja2V0Iix0LlN0b3BSZWFkQVZQYWNrZXQ9IlN0b3BSZWFkQVZQYWNrZXQiLHQpKShvfHx7fSk7Y29uc3QgQT0iS0daMWJtTjBhVzl1S0NsN0luVnpaU0J6ZEhKcFkzUWlPMnhsZENCbU8zTmxiR1l1Y0c5emRFMWxjM05oWjJVb2UzUjVjR1U2SWtaR2JYQmxaMWR2Y210bGNreHZZV1JsWkNKOUtTeHpaV3htTG1Ga1pFVjJaVzUwVEdsemRHVnVaWElvSW0xbGMzTmhaMlVpTEdGemVXNWpJR1oxYm1OMGFXOXVLR3dwZTJOdmJuTjBlM1I1Y0dVNmRDeGtZWFJoT21NOWUzMHNiWE5uU1dRNmIzMDliQzVrWVhSaE8zUnllWHRwWmloMFBUMDlJa3h2WVdSWFFWTk5JaWw3WTI5dWMzUjdkMkZ6YlV4dllXUmxjbEJoZEdnNlpYMDlZM3g4ZTMwN1pqMWhkMkZwZENoaGQyRnBkQ0JwYlhCdmNuUW9aU2twTG1SbFptRjFiSFFvS1gxbGJITmxJR2xtS0hROVBUMGlSMlYwUVZaVGRISmxZVzBpS1h0amIyNXpkSHRtYVd4bE9tVXNjM1J5WldGdFZIbHdaVHB6TEhOMGNtVmhiVWx1WkdWNE9tRjlQV01zY2oxbUxtZGxkRUZXVTNSeVpXRnRLR1VzY3l4aEtUdHpaV3htTG5CdmMzUk5aWE56WVdkbEtIdDBlWEJsT25Rc2JYTm5TV1E2Ynl4eVpYTjFiSFE2Y24wc1czSXVZMjlrWldOd1lYSXVaWGgwY21Ga1lYUmhMbUoxWm1abGNsMHBmV1ZzYzJVZ2FXWW9kRDA5UFNKSFpYUkJWbE4wY21WaGJYTWlLWHRqYjI1emRIdG1hV3hsT21WOVBXTXNjejFtTG1kbGRFRldVM1J5WldGdGN5aGxLVHR6Wld4bUxuQnZjM1JOWlhOellXZGxLSHQwZVhCbE9uUXNiWE5uU1dRNmJ5eHlaWE4xYkhRNmMzMHNjeTV0WVhBb1lUMCtZUzVqYjJSbFkzQmhjaTVsZUhSeVlXUmhkR0V1WW5WbVptVnlLU2w5Wld4elpTQnBaaWgwUFQwOUlrZGxkRUZXVUdGamEyVjBJaWw3WTI5dWMzUjdabWxzWlRwbExIUnBiV1U2Y3l4emRISmxZVzFVZVhCbE9tRXNjM1J5WldGdFNXNWtaWGc2Y24wOVl5eHVQV1l1WjJWMFFWWlFZV05yWlhRb1pTeHpMR0VzY2lrN2MyVnNaaTV3YjNOMFRXVnpjMkZuWlNoN2RIbHdaVHAwTEcxelowbGtPbThzY21WemRXeDBPbTU5TEZ0dUxtUmhkR0V1WW5WbVptVnlYU2w5Wld4elpTQnBaaWgwUFQwOUlrZGxkRUZXVUdGamEyVjBjeUlwZTJOdmJuTjBlMlpwYkdVNlpTeDBhVzFsT25OOVBXTXNZVDFtTG1kbGRFRldVR0ZqYTJWMGN5aGxMSE1wTzNObGJHWXVjRzl6ZEUxbGMzTmhaMlVvZTNSNWNHVTZkQ3h0YzJkSlpEcHZMSEpsYzNWc2REcGhmU3hoTG0xaGNDaHlQVDV5TG1SaGRHRXVZblZtWm1WeUtTbDlaV3h6WlNCcFppaDBQVDA5SWxKbFlXUkJWbEJoWTJ0bGRDSXBlMk52Ym5OMGUyWnBiR1U2WlN4emRHRnlkRHB6TEdWdVpEcGhMSE4wY21WaGJWUjVjR1U2Y2l4emRISmxZVzFKYm1SbGVEcHVmVDFqTEdROVppNXlaV0ZrUVZaUVlXTnJaWFFvYnl4bExITXNZU3h5TEc0cE8zTmxiR1l1Y0c5emRFMWxjM05oWjJVb2UzUjVjR1U2ZEN4dGMyZEpaRHB2TEhKbGMzVnNkRHBrZlNsOWZXTmhkR05vS0dVcGUzTmxiR1l1Y0c5emRFMWxjM05oWjJVb2UzUjVjR1U2ZEN4dGMyZEpaRHB2TEdWeWNrMXpaenBsSUdsdWMzUmhibU5sYjJZZ1JYSnliM0kvWlM1dFpYTnpZV2RsT2lKVmJtdHViM2R1SUVWeWNtOXlJbjBwZlgwcGZTa29LVHNLIixnPXQ9PlVpbnQ4QXJyYXkuZnJvbShhdG9iKHQpLGU9PmUuY2hhckNvZGVBdCgwKSksVj10eXBlb2Ygc2VsZjwidSImJnNlbGYuQmxvYiYmbmV3IEJsb2IoW2coQSldLHt0eXBlOiJ0ZXh0L2phdmFzY3JpcHQ7Y2hhcnNldD11dGYtOCJ9KTtmdW5jdGlvbiBFKHQpe2xldCBlO3RyeXtpZihlPVYmJihzZWxmLlVSTHx8c2VsZi53ZWJraXRVUkwpLmNyZWF0ZU9iamVjdFVSTChWKSwhZSl0aHJvdyIiO2NvbnN0IHM9bmV3IFdvcmtlcihlLHtuYW1lOnQ/Lm5hbWV9KTtyZXR1cm4gcy5hZGRFdmVudExpc3RlbmVyKCJlcnJvciIsKCk9Pnsoc2VsZi5VUkx8fHNlbGYud2Via2l0VVJMKS5yZXZva2VPYmplY3RVUkwoZSl9KSxzfWNhdGNoe3JldHVybiBuZXcgV29ya2VyKCJkYXRhOnRleHQvamF2YXNjcmlwdDtiYXNlNjQsIitBLHtuYW1lOnQ/Lm5hbWV9KX1maW5hbGx5e2UmJihzZWxmLlVSTHx8c2VsZi53ZWJraXRVUkwpLnJldm9rZU9iamVjdFVSTChlKX19Y29uc3QgdT0xZTY7Y2xhc3MgcHtmZm1wZWdXb3JrZXI7ZmZtcGVnV29ya2VyTG9hZFN0YXR1czttc2dJZDtmaWxlO2NvbnN0cnVjdG9yKGUpe3RoaXMuZmZtcGVnV29ya2VyPW5ldyBFLHRoaXMuZmZtcGVnV29ya2VyTG9hZFN0YXR1cz1uZXcgUHJvbWlzZSgocyxhKT0+e3RoaXMuZmZtcGVnV29ya2VyLmFkZEV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGk9Pntjb25zdHt0eXBlOnIsZXJyTXNnOmR9PWkuZGF0YTtyPT09by5GRm1wZWdXb3JrZXJMb2FkZWQmJnRoaXMucG9zdChvLkxvYWRXQVNNLHt3YXNtTG9hZGVyUGF0aDplLndhc21Mb2FkZXJQYXRofSkscj09PW8uV0FTTVJ1bnRpbWVJbml0aWFsaXplZCYmcyghMCkscj09PW8uTG9hZFdBU00mJmQmJmEoZCl9KX0pLHRoaXMubXNnSWQ9MH1wb3N0KGUscyxhKXt0aGlzLmZmbXBlZ1dvcmtlci5wb3N0TWVzc2FnZSh7dHlwZTplLG1zZ0lkOmE/P3RoaXMubXNnSWQrKyxkYXRhOnN9KX1hc3luYyBsb2FkKGUpe2NvbnN0IHM9YXdhaXQgdGhpcy5mZm1wZWdXb3JrZXJMb2FkU3RhdHVzO3JldHVybiB0aGlzLmZpbGU9ZSxzfWRlc3Ryb3koKXt0aGlzLmZpbGU9dm9pZCAwLHRoaXMuZmZtcGVnV29ya2VyLnRlcm1pbmF0ZSgpfWdldEFWU3RyZWFtKGU9bS5BVk1FRElBX1RZUEVfVklERU8scz0tMSl7cmV0dXJuIG5ldyBQcm9taXNlKChhLGkpPT57aWYoIXRoaXMuZmlsZSl7aSgiZmlsZSBpcyBub3QgbG9hZGVkIik7cmV0dXJufWNvbnN0IHI9dGhpcy5tc2dJZCxkPSh7ZGF0YTpufSk9PntuLnR5cGU9PT1vLkdldEFWU3RyZWFtJiZuLm1zZ0lkPT09ciYmKG4uZXJyTXNnP2kobi5lcnJNc2cpOmEobi5yZXN1bHQpLHRoaXMuZmZtcGVnV29ya2VyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGQpKX07dGhpcy5mZm1wZWdXb3JrZXIuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsZCksdGhpcy5wb3N0KG8uR2V0QVZTdHJlYW0se2ZpbGU6dGhpcy5maWxlLHN0cmVhbVR5cGU6ZSxzdHJlYW1JbmRleDpzfSl9KX1nZXRBVlN0cmVhbXMoKXtyZXR1cm4gbmV3IFByb21pc2UoKGUscyk9PntpZighdGhpcy5maWxlKXtzKCJmaWxlIGlzIG5vdCBsb2FkZWQiKTtyZXR1cm59Y29uc3QgYT10aGlzLm1zZ0lkLGk9KHtkYXRhOnJ9KT0+e3IudHlwZT09PW8uR2V0QVZTdHJlYW1zJiZyLm1zZ0lkPT09YSYmKHIuZXJyTXNnP3Moci5lcnJNc2cpOmUoci5yZXN1bHQpLHRoaXMuZmZtcGVnV29ya2VyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGkpKX07dGhpcy5mZm1wZWdXb3JrZXIuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsaSksdGhpcy5wb3N0KG8uR2V0QVZTdHJlYW1zLHtmaWxlOnRoaXMuZmlsZX0pfSl9Z2V0QVZQYWNrZXQoZSxzPW0uQVZNRURJQV9UWVBFX1ZJREVPLGE9LTEpe3JldHVybiBuZXcgUHJvbWlzZSgoaSxyKT0+e2lmKCF0aGlzLmZpbGUpe3IoImZpbGUgaXMgbm90IGxvYWRlZCIpO3JldHVybn1jb25zdCBkPXRoaXMubXNnSWQsbj1oPT57Y29uc3QgbD1oLmRhdGE7bC50eXBlPT09by5HZXRBVlBhY2tldCYmbC5tc2dJZD09PWQmJihsLmVyck1zZz9yKGwuZXJyTXNnKTppKGwucmVzdWx0KSx0aGlzLmZmbXBlZ1dvcmtlci5yZW1vdmVFdmVudExpc3RlbmVyKCJtZXNzYWdlIixuKSl9O3RoaXMuZmZtcGVnV29ya2VyLmFkZEV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLG4pLHRoaXMucG9zdChvLkdldEFWUGFja2V0LHtmaWxlOnRoaXMuZmlsZSx0aW1lOmUsc3RyZWFtVHlwZTpzLHN0cmVhbUluZGV4OmF9KX0pfWdldEFWUGFja2V0cyhlKXtyZXR1cm4gbmV3IFByb21pc2UoKHMsYSk9PntpZighdGhpcy5maWxlKXthKCJmaWxlIGlzIG5vdCBsb2FkZWQiKTtyZXR1cm59Y29uc3QgaT10aGlzLm1zZ0lkLHI9ZD0+e2NvbnN0IG49ZC5kYXRhO24udHlwZT09PW8uR2V0QVZQYWNrZXRzJiZuLm1zZ0lkPT09aSYmKG4uZXJyTXNnP2Eobi5lcnJNc2cpOnMobi5yZXN1bHQpLHRoaXMuZmZtcGVnV29ya2VyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLHIpKX07dGhpcy5mZm1wZWdXb3JrZXIuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsciksdGhpcy5wb3N0KG8uR2V0QVZQYWNrZXRzLHtmaWxlOnRoaXMuZmlsZSx0aW1lOmV9KX0pfXJlYWRBVlBhY2tldChlPTAscz0wLGE9bS5BVk1FRElBX1RZUEVfVklERU8saT0tMSl7Y29uc3Qgcj1uZXcgQ291bnRRdWV1aW5nU3RyYXRlZ3koe2hpZ2hXYXRlck1hcms6MX0pLGQ9dGhpcy5tc2dJZDtsZXQgbj0wO3JldHVybiBuZXcgUmVhZGFibGVTdHJlYW0oe3N0YXJ0Omg9PntpZighdGhpcy5maWxlKXtoLmVycm9yKCJmaWxlIGlzIG5vdCBsb2FkZWQiKTtyZXR1cm59Y29uc3QgbD1mPT57Y29uc3QgYz1mLmRhdGE7Yy50eXBlPT09by5SZWFkQVZQYWNrZXQmJmMubXNnSWQ9PT1kJiZjLmVyck1zZyYmKGguZXJyb3IoYy5lcnJNc2cpLHRoaXMuZmZtcGVnV29ya2VyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGwpKSxjLnR5cGU9PT1vLkFWUGFja2V0U3RyZWFtJiZjLm1zZ0lkPT09ZCYmKGMucmVzdWx0P2guZW5xdWV1ZShjLnJlc3VsdCk6aC5jbG9zZSgpKX07dGhpcy5mZm1wZWdXb3JrZXIuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsbCksdGhpcy5wb3N0KG8uUmVhZEFWUGFja2V0LHtmaWxlOnRoaXMuZmlsZSxzdGFydDplLGVuZDpzLHN0cmVhbVR5cGU6YSxzdHJlYW1JbmRleDppfSl9LHB1bGw6KCk9PntuPjAmJnRoaXMucG9zdChvLlJlYWROZXh0QVZQYWNrZXQsdm9pZCAwLGQpLG4rK30sY2FuY2VsOigpPT57dGhpcy5wb3N0KG8uU3RvcFJlYWRBVlBhY2tldCx2b2lkIDAsZCl9fSxyKX1nZXRWaWRlb1N0cmVhbShlKXtyZXR1cm4gdGhpcy5nZXRBVlN0cmVhbShtLkFWTUVESUFfVFlQRV9WSURFTyxlKX1nZXRBdWRpb1N0cmVhbShlKXtyZXR1cm4gdGhpcy5nZXRBVlN0cmVhbShtLkFWTUVESUFfVFlQRV9BVURJTyxlKX1zZWVrVmlkZW9QYWNrZXQoZSl7cmV0dXJuIHRoaXMuZ2V0QVZQYWNrZXQoZSxtLkFWTUVESUFfVFlQRV9WSURFTyl9c2Vla0F1ZGlvUGFja2V0KGUpe3JldHVybiB0aGlzLmdldEFWUGFja2V0KGUsbS5BVk1FRElBX1RZUEVfQVVESU8pfXJlYWRWaWRlb1BhY2tldChlLHMpe3JldHVybiB0aGlzLnJlYWRBVlBhY2tldChlLHMsbS5BVk1FRElBX1RZUEVfVklERU8pfXJlYWRBdWRpb1BhY2tldChlLHMpe3JldHVybiB0aGlzLnJlYWRBVlBhY2tldChlLHMsbS5BVk1FRElBX1RZUEVfQVVESU8pfWdlblZpZGVvRGVjb2RlckNvbmZpZyhlKXtyZXR1cm57Y29kZWM6ZS5jb2RlY3Bhci5jb2RlY19zdHJpbmcsY29kZWRXaWR0aDplLmNvZGVjcGFyLndpZHRoLGNvZGVkSGVpZ2h0OmUuY29kZWNwYXIuaGVpZ2h0LGRlc2NyaXB0aW9uOmUuY29kZWNwYXIuZXh0cmFkYXRhPy5sZW5ndGg+MD9lLmNvZGVjcGFyLmV4dHJhZGF0YTp2b2lkIDB9fWdlbkVuY29kZWRWaWRlb0NodW5rKGUpe3JldHVybiBuZXcgRW5jb2RlZFZpZGVvQ2h1bmsoe3R5cGU6ZS5rZXlmcmFtZT09PTE/ImtleSI6ImRlbHRhIix0aW1lc3RhbXA6ZS50aW1lc3RhbXAqdSxkdXJhdGlvbjplLmR1cmF0aW9uKnUsZGF0YTplLmRhdGF9KX1nZW5BdWRpb0RlY29kZXJDb25maWcoZSl7cmV0dXJue2NvZGVjOmUuY29kZWNwYXIuY29kZWNfc3RyaW5nfHwiIixzYW1wbGVSYXRlOmUuY29kZWNwYXIuc2FtcGxlX3JhdGUsbnVtYmVyT2ZDaGFubmVsczplLmNvZGVjcGFyLmNoYW5uZWxzLGRlc2NyaXB0aW9uOmUuY29kZWNwYXIuZXh0cmFkYXRhPy5sZW5ndGg+MD9lLmNvZGVjcGFyLmV4dHJhZGF0YTp2b2lkIDB9fWdlbkVuY29kZWRBdWRpb0NodW5rKGUpe3JldHVybiBuZXcgRW5jb2RlZEF1ZGlvQ2h1bmsoe3R5cGU6ZS5rZXlmcmFtZT09PTE/ImtleSI6ImRlbHRhIix0aW1lc3RhbXA6ZS50aW1lc3RhbXAqdSxkdXJhdGlvbjplLmR1cmF0aW9uKnUsZGF0YTplLmRhdGF9KX1hc3luYyBnZXRWaWRlb0RlY29kZXJDb25maWcoKXtjb25zdCBlPWF3YWl0IHRoaXMuZ2V0VmlkZW9TdHJlYW0oKTtyZXR1cm4gdGhpcy5nZW5WaWRlb0RlY29kZXJDb25maWcoZSl9YXN5bmMgc2Vla0VuY29kZWRWaWRlb0NodW5rKGUpe2NvbnN0IHM9YXdhaXQgdGhpcy5zZWVrVmlkZW9QYWNrZXQoZSk7cmV0dXJuIHRoaXMuZ2VuRW5jb2RlZFZpZGVvQ2h1bmsocyl9YXN5bmMgZ2V0QXVkaW9EZWNvZGVyQ29uZmlnKCl7Y29uc3QgZT1hd2FpdCB0aGlzLmdldEF1ZGlvU3RyZWFtKCk7cmV0dXJuIHRoaXMuZ2VuQXVkaW9EZWNvZGVyQ29uZmlnKGUpfWFzeW5jIHNlZWtFbmNvZGVkQXVkaW9DaHVuayhlKXtjb25zdCBzPWF3YWl0IHRoaXMuc2Vla0F1ZGlvUGFja2V0KGUpO3JldHVybiB0aGlzLmdlbkVuY29kZWRBdWRpb0NodW5rKHMpfX1jbGFzcyBre3ZpZGVvO2N1cnJlbnRGcmFtZXM9MDt0b3RhbEZyYW1lcztjdXJyZW50VGltZTtmcHM7Zmlyc3RUaW1lc3RhbXA7Y29uc3RydWN0b3IoZSxzKXt0aGlzLmN1cnJlbnRUaW1lPWVbMF0qMWU2LHRoaXMuZmlyc3RUaW1lc3RhbXA9ZVswXSoxZTYsdGhpcy50b3RhbEZyYW1lcz0oZVsxXS1lWzBdKSpzKzEsdGhpcy5mcHM9cyx0aGlzLnZpZGVvPW5ldyBWaWRlb0RlY29kZXIoe291dHB1dDp0aGlzLmhhbmRsZUZyYW1lT3V0cHV0LmJpbmQodGhpcyksZXJyb3I6dGhpcy5oYW5kbGVFcnJvci5iaW5kKHRoaXMpfSl9cG9zdEZyYW1lKGUpe3NlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImZyYW1lIixmcmFtZTplfSksdGhpcy5jdXJyZW50VGltZSs9TWF0aC5mbG9vcigxL3RoaXMuZnBzKjFlNiksdGhpcy5jdXJyZW50RnJhbWVzKz0xfWhhbmRsZUZyYW1lT3V0cHV0KGUpe2NvbnN0IHM9ZS50aW1lc3RhbXAsYT1lLmR1cmF0aW9uPz8wLGk9cythO2lmKCF0aGlzLmlzRnJhbWVJblJhbmdlKHMpKXtlLmNsb3NlKCk7cmV0dXJufWZvcig7aT50aGlzLmN1cnJlbnRUaW1lJiZ0aGlzLmN1cnJlbnRGcmFtZXM8PXRoaXMudG90YWxGcmFtZXM7KXRoaXMucG9zdEZyYW1lKGUpO2UuY2xvc2UoKX1pc0ZyYW1lSW5SYW5nZShlKXtyZXR1cm4gZT49dGhpcy5maXJzdFRpbWVzdGFtcH1oYW5kbGVFcnJvcihlKXtjb25zb2xlLmVycm9yKCJlcnJvciBpbiB3b3JrZXIiLGUpLHNlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImVycm9yIixtZXNzYWdlOmUubWVzc2FnZT8/IkFuIHVua25vd24gd29ya2VyIGVycm9yIG9jY3VycmVkIn0pLHNlbGYuY2xvc2UoKX19ZnVuY3Rpb24gSSh0KXtyZXR1cm4gYXN5bmMgZT0+e3RyeXthd2FpdCB0KGUpfWNhdGNoKHMpe3NlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImVycm9yIixtZXNzYWdlOnM/Lm1lc3NhZ2U/PyJBbiB1bmtvd24gd29ya2VyIGVycm9yIG9jY3VyZWQifSl9fX1mdW5jdGlvbiBXKHQpe3JldHVybiB0LmNvZGVjPT0idnAwOSImJih0LmNvZGVjPSJ2cDA5LjAwLjEwLjA4IiksdH1jb25zdCBaPTMwO2FzeW5jIGZ1bmN0aW9uIFAodCl7aWYodC5kYXRhPy50eXBlIT0iaW5pdCIpcmV0dXJuO2NvbnN0e2ZpbGU6ZSxyYW5nZTpzLGZwczphfT10LmRhdGEsaT1uZXcgcCh7d2FzbUxvYWRlclBhdGg6Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9ucG0vQGRpZmZ1c2lvbnN0dWRpby9mZm1wZWctd2FzbUAxLjAuMC9kaXN0L2ZmbXBlZy5qcyJ9KTthd2FpdCBpLmxvYWQoZSk7Y29uc3Qgcj1hd2FpdCBpLmdldFZpZGVvRGVjb2RlckNvbmZpZygpO1cocik7Y29uc3QgZD1uZXcgayhzLGEpO2QudmlkZW8uY29uZmlndXJlKHIpO2NvbnN0IG49aS5yZWFkQVZQYWNrZXQoc1swXSxzWzFdKS5nZXRSZWFkZXIoKTtuLnJlYWQoKS50aGVuKGFzeW5jIGZ1bmN0aW9uIGgoe2RvbmU6bCx2YWx1ZTpmfSl7aWYobCl7YXdhaXQgZC52aWRlby5mbHVzaCgpLHNlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImRvbmUifSksc2VsZi5jbG9zZSgpO3JldHVybn1jb25zdCBjPWkuZ2VuRW5jb2RlZFZpZGVvQ2h1bmsoZik7cmV0dXJuIGQudmlkZW8uZGVjb2RlUXVldWVTaXplPlomJmF3YWl0IG5ldyBQcm9taXNlKEw9PntkLnZpZGVvLm9uZGVxdWV1ZT0oKT0+TCgpfSksYy50aW1lc3RhbXA8PXNbMV0qMWU2JiZkLnZpZGVvLmRlY29kZShjKSxuLnJlYWQoKS50aGVuKGgpfSl9c2VsZi5hZGRFdmVudExpc3RlbmVyKCJtZXNzYWdlIixJKFApKX0pKCk7Cg==",zb=o=>Uint8Array.from(atob(o),a=>a.charCodeAt(0)),fc=typeof self<"u"&&self.Blob&&new Blob([zb(fm)],{type:"text/javascript;charset=utf-8"});function jb(o){let a;try{if(a=fc&&(self.URL||self.webkitURL).createObjectURL(fc),!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,"+fm,{name:o==null?void 0:o.name})}finally{a&&(self.URL||self.webkitURL).revokeObjectURL(a)}}class Wb{constructor(){Y(this,"frames",[]);Y(this,"state","active");Y(this,"onenqueue");Y(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 Hb(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 Zb=Object.defineProperty,Xb=Object.getOwnPropertyDescriptor,Gb=(o,a,t,n)=>{for(var i=Xb(a,t),r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&Zb(a,t,i),i};const hm=class vm extends Xr(Zr){constructor(t,n={}){super();Y(this,"source",new Pn);Y(this,"type","video");Y(this,"worker");Y(this,"buffer");Y(this,"canvas",document.createElement("canvas"));Y(this,"context",this.canvas.getContext("2d"));Y(this,"element",document.createElement("video"));Y(this,"textrues",{html5:gt.Texture.from(this.element),canvas:gt.Texture.from(this.canvas)});Y(this,"sprite",new gt.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 Pn&&(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 en({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($e.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=vm.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 Wb,this.worker=new jb,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)??hi}),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}};Gb([Gr,Hb],hm.prototype,"update");let vl=hm;class li extends Zr{constructor(t,n={}){super();Y(this,"type","audio");Y(this,"source",new bn);Y(this,"element",new Audio);t instanceof bn&&(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 en({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=li.fromJSON(JSON.parse(JSON.stringify(this)));return t.source=this.source,t}}const Jb={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 gl(o){if(!Object.keys(Jb.MIXED).includes(o??""))throw new Rt({message:`${o} is not an accepted mime type`,code:"invalid_mimetype"});return o}var Kb=Object.defineProperty,qb=Object.getOwnPropertyDescriptor,Yb=(o,a,t,n)=>{for(var i=qb(a,t),r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=s(a,t,i)||i);return i&&Kb(a,t,i),i};const Qb=class gm extends Xr(xi){constructor(t,n={}){super();Y(this,"type","html");Y(this,"source",new uc);Y(this,"element",new Image);Y(this,"canvas",document.createElement("canvas"));Y(this,"context",this.canvas.getContext("2d"));Y(this,"sprite",new gt.Sprite);this.view.addChild(this.sprite),Object.assign(this,n),t instanceof uc&&(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=gt.Texture.from(this.canvas,!0),this.trigger("load",void 0))}),this.element.addEventListener("error",i=>{this.state="ERROR",this.trigger("error",new en({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 en({code:"sourceNotProcessable",message:"Cannot display source with height or width at 0"}));this.state="READY",t()},this.element.onerror=i=>{n(new en({code:"sourceNotProcessable",message:"An error occurred while processing the input medium."}))}})}update(t){}copy(){const t=gm.fromJSON(JSON.parse(JSON.stringify(this)));return t.filters=this.filters,t.source=this.source,t}};Yb([Gr],Qb.prototype,"update");const bm=["DEFAULT","STACK"];class hc{constructor(){Y(this,"mode",bm[0]);Y(this,"pauseAlignmet",!1)}add(a,t){let n=!0;for(let i=0;i<t.clips.length&&(n=bc(a,t.clips[i]),!!n);i++)gc(a,t.clips[i]);n&&(t.clips.push(a),t.clips.sort(vc))}update(a,t){if(!this.pauseAlignmet){t.clips.sort(vc);for(let n=0;n<t.clips.length;n++)if(a.id!=t.clips[n].id){if(!bc(a,t.clips[n]))break;gc(a,t.clips[n])}}}offset(a,t){this.pauseAlignmet=!0;for(const n of t.clips)n.offsetBy(a);this.pauseAlignmet=!1}}class ey{constructor(){Y(this,"mode",bm[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 $e(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 $e(r))}n=i.stop.millis+1}}offset(){}}function vc(o,a){return o.start.millis-a.start.millis}function gc(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 bc(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 To extends _i(xa){constructor(){super(...arguments);Y(this,"_disabled",!1);Y(this,"view",new gt.Container);Y(this,"clips",[]);Y(this,"pointer",0);Y(this,"composition");Y(this,"type","base");Y(this,"strategy",new hc)}get disabled(){return this._disabled}set disabled(t){var n;t&&this.clipRef&&Us(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 ey,this.strategy.update(new xi,this)):this.strategy=new hc,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,db(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($e.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(Us(this.clipRef)&&(!Ps(n,this.clipRef)||(i=this.clipRef)!=null&&i.disabled)&&(this.clipRef&&this.view.removeChild(this.clipRef.view),(r=this.clipRef)==null||r.exit()),!!Ps(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(Ps(n,d)&&!d.disabled)return this.pointer=l,Us(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 $e}get start(){var t;return((t=this.clips.at(0))==null?void 0:t.start)??new $e}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 Ps(o,a){return a?o>=a.start.millis&&o<=a.stop.millis:!1}function Us(o){return o?!!o.view.parent:!1}class ty{static fromType(a){switch(a.type){case"video":return new ay;case"audio":return new oy;case"html":return new iy;case"image":return new ny;case"text":return new yc;case"complex_text":return new yc;case"caption":return new sy;default:return new To}}}class ym extends To{constructor(){super(...arguments);Y(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 ay extends ym{constructor(){super(...arguments);Y(this,"type","video")}async seek(t){var n;(n=this.composition)!=null&&n.rendering?this.view.removeChildren():super.seek(t)}}class ny extends To{constructor(){super(...arguments);Y(this,"type","image")}}class oy extends ym{constructor(){super(...arguments);Y(this,"type","audio")}}class yc extends To{constructor(){super(...arguments);Y(this,"type","text")}}class iy extends To{constructor(){super(...arguments);Y(this,"type","html")}}var ry=Object.defineProperty,sd=(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&&ry(a,t,i),i};class Ci extends xa{constructor(t={}){super();Y(this,"generatorOptions");Y(this,"type","CLASSIC");Y(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 Rt({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 $e,i=await Qt.fromFamily({family:"Figtree",weight:"700"}).load();for(const d of t.clip.transcript.iter(this.generatorOptions))await t.add(new Vo({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 Ue([0,8],[.96,1],{easing:"easeOut"}),alpha:new Ue([0,4],[0,1],{easing:"easeOut"})}))}}sd([Ie()],Ci.prototype,"generatorOptions");sd([Ie()],Ci.prototype,"type");sd([Ie()],Ci.prototype,"position");class sy extends To{constructor(){super(...arguments);Y(this,"clip");Y(this,"type","caption");Y(this,"preset",new Ci)}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 ly=Object.defineProperty,qr=(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 Vi extends xa{constructor(t={}){super();Y(this,"generatorOptions");Y(this,"type","SPOTLIGHT");Y(this,"color");Y(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 Rt({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 $e,i=await Qt.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(f=>f.text);await t.add(new Kr({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)}))}}}qr([Ie()],Vi.prototype,"generatorOptions");qr([Ie()],Vi.prototype,"type");qr([Ie()],Vi.prototype,"color");qr([Ie()],Vi.prototype,"position");var dy=Object.defineProperty,ld=(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&&dy(a,t,i),i};class Yr extends xa{constructor(t={}){super();Y(this,"type","GUINEA");Y(this,"colors");Y(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,f;if(!((r=t.clip)!=null&&r.transcript)||!((s=t.composition)!=null&&s.width))throw new Rt({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 $e,i=await Qt.fromFamily({family:"The Bold Font",weight:"500"}).load();for(const m of t.clip.transcript.iter({length:[18]})){const{segments:p,words:h}=this.splitSequence(m);for(let v=0;v<m.words.length;v++){const w=(c=(d=h[v])==null?void 0:d.at(0))==null?void 0:c.start,x=(f=(u=h[v])==null?void 0:u.at(-1))==null?void 0:f.stop;!w||!x||await t.add(new Kr({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:x.add(n),start:w.add(n),styles:[{fillStyle:this.colors[0],fontSize:23},{fillStyle:this.colors[1],fontSize:23},{fillStyle:this.colors[2],fontSize:23}],segments:[{index:vr(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=[...oc(n,r).map(d=>d.trim())],l=oc(t.words,s[0].split(/ /).length);return{segments:s,words:l}}}ld([Ie()],Yr.prototype,"type");ld([Ie()],Yr.prototype,"colors");ld([Ie()],Yr.prototype,"position");var cy=Object.defineProperty,dd=(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&&cy(a,t,i),i};class Qr extends xa{constructor(t={}){super();Y(this,"generatorOptions");Y(this,"type","CASCADE");Y(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 Rt({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 $e,i=await Qt.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(f=>f.text).slice(0,c+1).join(" ");await t.add(new Vo({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)}))}}}dd([Ie()],Qr.prototype,"generatorOptions");dd([Ie()],Qr.prototype,"type");dd([Ie()],Qr.prototype,"position");var uy=Object.defineProperty,cd=(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 es extends xa{constructor(t={}){super();Y(this,"generatorOptions");Y(this,"type","SOLAR");Y(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 Rt({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=await Qt.fromFamily({family:"Urbanist",weight:"800"}).load(),i=((d=t.clip)==null?void 0:d.offset)??new $e,r=new $f.GlowFilter({color:"#fffe41",alpha:.25,distance:90,quality:.05});for(const c of t.clip.transcript.iter(this.generatorOptions))await t.add(new Vo({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 Ue([0,8],[.96,1],{easing:"easeOut"}),alpha:new Ue([0,4],[0,1],{easing:"easeOut"}),filters:r}))}}cd([Ie()],es.prototype,"generatorOptions");cd([Ie()],es.prototype,"type");cd([Ie()],es.prototype,"position");var my=Object.defineProperty,ts=(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&&my(a,t,i),i};class Ni extends xa{constructor(t={}){super();Y(this,"generatorOptions");Y(this,"type","WHISPER");Y(this,"color");Y(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 Rt({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 $e,i=await Qt.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(f=>f.text);await t.add(new Kr({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}))}}}ts([Ie()],Ni.prototype,"generatorOptions");ts([Ie()],Ni.prototype,"type");ts([Ie()],Ni.prototype,"color");ts([Ie()],Ni.prototype,"position");var py=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&&py(a,t,i),i};class ns extends xa{constructor(t={}){super();Y(this,"type","VERDANT");Y(this,"generatorOptions");Y(this,"color");Y(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 Rt({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 $e,i=await Qt.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(f=>f.text);await t.add(new Kr({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}]}))}}}as([Ie()],ns.prototype,"type");as([Ie()],ns.prototype,"generatorOptions");as([Ie()],ns.prototype,"color");as([Ie()],ns.prototype,"position");class fy extends _i(xa){constructor({height:t=1080,width:n=1920,background:i="#000000",backend:r="webgpu"}={}){super();Y(this,"_duration",new $e);Y(this,"renderer");Y(this,"stage",new gt.Container);Y(this,"settings");Y(this,"tracks",[]);Y(this,"frame",0);Y(this,"fixedDuration");Y(this,"state","IDLE");Y(this,"fps",hi);Y(this,"canvas");Y(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)),gt.autoDetectRenderer({...this.settings,preference:r}).then(s=>{this.renderer=s,this.trigger("init",void 0)}).catch(s=>{this.trigger("error",new xo({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 $e?this.fixedDuration=t:this.fixedDuration=$e.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=ty.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 ic(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;ic(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($e.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 xo({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($e.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($e.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(Zr)){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 f=await l.source.decode(t,n),m=f.numberOfChannels-1;for(let p=0;p<t;p++){const h=r.getChannelData(p),v=f.getChannelData(p>m?m:p);for(let w=0;w<h.length-1;w++)w<d+c||w>d+u||w-d<0||(h[w]+=(v[w-d]??0)*l.volume,h[w]>1&&(h[w]=1),h[w]<-1&&(h[w]=-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/hi;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 hy(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 bl=[8e3,12e3,16e3,24e3,48e3],vy="https://cdn.jsdelivr.net/npm/@diffusionstudio/libopus-wasm@1.0.0/dist/opus.wasm",gy="https://cdn.jsdelivr.net/npm/@diffusionstudio/libopus-wasm@1.0.0/dist/opus.js";class by{constructor(a){Y(this,"output");Y(this,"error");Y(this,"config");Y(this,"encoder");Y(this,"opus");Y(this,"meta");this.output=a.output,this.error=a.error}async configure(a){const t=await import(gy),{numberOfChannels:n,sampleRate:i}=this.config=a;if(!bl.includes(i))throw new Br({code:"sampleRateNotSupported",message:`Unsupported sample rate, supported: ${bl.join()}`});this.opus=await t.default({locateFile(r,s){return r.endsWith(".wasm")?vy:s+r}}),this.encoder=this.opus._opus_encoder_create(i,n,2048),this.meta={decoderConfig:{codec:"opus",description:hy(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 Br({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 f=4e3,m=this.opus._malloc(f),p=this.opus._opus_encode(this.encoder,u,s,m,f);if(p>0){const h=new Uint8Array(this.opus.HEAPU8.subarray(m,m+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(m),l+=s,n+=d}}}function yy(o){const a=bl;let t=48e3;for(const n of a)Math.abs(o-n)<Math.abs(o-t)&&(t=n);return t}class wy{constructor(a,t){Y(this,"canvas");Y(this,"muxer");Y(this,"videoEncoder");Y(this,"frame",0);Y(this,"sampleRate");Y(this,"numberOfChannels");Y(this,"videoBitrate");Y(this,"gpuBatchSize");Y(this,"fps");Y(this,"height");Y(this,"width");Y(this,"audio");this.canvas=a,this.width=a.width,this.height=a.height,this.fps=(t==null?void 0:t.fps)??30,this.sampleRate=yy((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 mb({height:Math.round(this.height),width:Math.round(this.width),bitrate:this.videoBitrate,fps:this.fps});this.muxer=new im({target:new ql,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 Br({code:"initializationError",message:"Encoder must be initialized using {audio: true} to use this method"});this.muxer||await this.init();const t=ub(a,this.sampleRate,this.numberOfChannels),n=new by({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:cb(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 Br({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 ky(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 pi=class pi{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 Ue([n,i],[1,0],{easing:r}),t.alpha=new Ue([n,i],[0,1],{easing:r}),t.start=$e.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 Ue([n,i],[1,0],{easing:r}),t.alpha=new Ue([n,i],[0,1],{easing:r}),t.start=$e.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 Ue([i,r],[0,-1920],{easing:s}),d.x=new Ue([i,r],[1920,0],{easing:s});break;case"wipe-right":l.x=new Ue([i,r],[0,1920],{easing:s}),d.x=new Ue([i,r],[-1920,0],{easing:s});break;case"wipe-up":l.y=new Ue([i,r],[0,-1080],{easing:s}),d.y=new Ue([i,r],[1080,0],{easing:s});break;case"wipe-down":l.y=new Ue([i,r],[0,1080],{easing:s}),d.y=new Ue([i,r],[-1080,0],{easing:s});break}a.translate=l,t.translate=d,t.start=$e.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 Ue([i,r],[0,-1920],{easing:s}),d.x=new Ue([i,r],[1920,0],{easing:s});break;case"slide-right":l.x=new Ue([i,r],[0,1920],{easing:s}),d.x=new Ue([i,r],[-1920,0],{easing:s});break;case"slide-up":l.y=new Ue([i,r],[0,-1080],{easing:s}),d.y=new Ue([i,r],[1080,0],{easing:s});break;case"slide-down":l.y=new Ue([i,r],[0,1080],{easing:s}),d.y=new Ue([i,r],[-1080,0],{easing:s});break}a.translate=l,t.translate=d,t.start=$e.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 Ue([i,r],[1,2],{easing:s}),a.alpha=new Ue([i,r],[1,0],{easing:s}),t.scale=new Ue([i,r],[.5,1],{easing:s}),t.alpha=new Ue([i,r],[0,1],{easing:s})):(a.scale=new Ue([i,r],[1,.5],{easing:s}),a.alpha=new Ue([i,r],[1,0],{easing:s}),t.scale=new Ue([i,r],[2,1],{easing:s}),t.alpha=new Ue([i,r],[0,1],{easing:s})),t.start=$e.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 fl.fromColor(d),u=new Mb(c,{start:$e.fromFrames(i),stop:$e.fromFrames(r)});a.alpha=new Ue([i,l],[1,0],{easing:s}),u.alpha=new Ue([i,l,r],[0,1,0],{easing:s}),t.alpha=new Ue([l,r],[0,1],{easing:s}),await this.composition.add(u),t.start=$e.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[...pi.TRANSITIONS]}static previewTransition(a){return pi.TRANSITIONS.find(t=>t.type===a)}isVideoClip(a){return"alpha"in a&&"scale"in a&&"translate"in a}};pi.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 vi=pi;function Ta(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 Qi(o){return o>5?o/100:o}function Ia(o,a,t){return Math.min(t,Math.max(a,o))}function ia(){return new Dt.ColorMatrixFilter}function _y(o,a){switch(o){case"brightness":{const t=ia(),n=Ta(a.value??a.brightness,1);return t.brightness(Ia(Qi(n),0,5),!1),t}case"contrast":{const t=ia(),n=Ta(a.value??a.contrast,1);return t.contrast(Ia(Qi(n),0,5),!1),t}case"saturation":{const t=ia(),n=Ta(a.value??a.saturation,1);return t.saturate(Ia(Qi(n),0,5),!1),t}case"hue":{const t=ia(),n=Ta(a.degrees??a.value,0);return t.hue(Ia(n,-180,180),!1),t}case"blur":case"softFocus":{const t=o==="softFocus"?1:0,n=Ta(a.radius??a.blur??a.value,t);return new Dt.BlurFilter({strength:Ia(n,0,32),quality:4})}case"grayscale":{const t=ia(),n=Ia(Ta(a.amount,100),0,100);return n<=0?null:(n>=100?t.desaturate():t.saturate(1-n/100,!1),t)}case"sepia":{if(Ia(Ta(a.amount,100),0,100)<=0)return null;const n=ia();return n.sepia(!1),n}case"invert":{if(Ia(Ta(a.amount,100),0,100)<=0)return null;const n=ia();return n.negative(!1),n}case"warmth":{const t=ia(),n=Ia(Ta(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=ia(),n=Ia(Ta(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=ia();return t.sepia(!1),t.saturate(1.4,!1),t.contrast(1.1,!1),t}case"blackAndWhite":{const t=ia(),n=Ia(Qi(Ta(a.contrast,120)),.5,3);return t.desaturate(),t.contrast(n,!1),t}case"cinematic":{const t=ia();return t.contrast(1.2,!1),t.brightness(.95,!1),t.saturate(.85,!1),t}case"dramatic":{const t=ia();return t.contrast(1.4,!1),t.brightness(.9,!1),t.saturate(1.1,!1),t.sepia(!1),t}case"dreamy":{const t=ia();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=Dt);class wm{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 fy({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,f;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||(f=l==null?void 0:l.renderer)!=null&&f.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 ky(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 vi(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=Pn.from)==null?void 0:n.call(Pn,r,{crossOrigin:"anonymous"}))??await Pn.from(r),l=new vl(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 m=Math.max(0,Math.floor((a.sourceIn||0)*this.fps)),p=a.sourceOut!==void 0?Math.max(m+1,Math.floor(a.sourceOut*this.fps)):null;d=m,c=p;try{if(l.offset=l.offset||{frames:0},l.offset.frames=m,p!==null){const h=Math.max(1,p-m);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 m=Math.max(1,c-d);u.offset=u.offset||{frames:0},u.offset.frames=d,u.duration=u.duration||{frames:m},u.duration.frames=m}catch{}const f=Math.floor(a.timelineStart*this.fps);f>0&&u.offsetBy(f),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(m=>requestAnimationFrame(m)),this.applyFiltersToClip(a.id,a.filters))}catch{}}async addTextOverlay(a){try{const t=Qt.fromFamily({family:a.fontFamily||"Arial",weight:a.fontWeight||"400"}),n=new Vo({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 Ue([s,l],[a.animation.rotation.from,a.animation.rotation.to],{easing:d}):a.animation.type==="scale"&&a.animation.scale&&(n.scale=new Ue([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 f=null;if(u&&u.signature===c)f=u.instance;else{if(u)try{u.instance.destroy()}catch{}f=this.createPixiFilter(d),f?i.set(d.id,{instance:f,signature:c}):i.delete(d.id)}f&&s.push(f)}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(te.getFilter(a.filterId)&&!te.isFilterCompatibleWithMedia(a.filterId,"video"))return null;let r=nh(a.filterId,n);return r||(r=_y(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,f,m,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)??((m=(f=this.composition)==null?void 0:f.renderer)==null?void 0:m.canvas);if(!n)throw new Error("Export failed: composition canvas is not initialized");(p=a.onProgress)==null||p.call(a,0);const i=new wy(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),f=this.fitMode==="contain"?c:u;a.scale=f}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 Ey=["src"],xy={class:"preview-controls"},Sy=["aria-label"],Cy={class:"time-display"},Vy={class:"current-time"},Ny={class:"total-time"},Ty={key:2,class:"loading-overlay"},Iy={key:3,class:"error-overlay"},By=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),f=e.ref(0),m=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"}}),w=e.computed(()=>{var C,$;return(C=t.media)!=null&&C.url?t.media.url:((($=t.media)==null?void 0:$.file)instanceof File,"")});async function x(){var C,$,y;if(!(!r.value||!t.recipe))try{l.value=!0,d.value="Initializing video engine...";const R=((C=t.recipe.source)==null?void 0:C.original_width)||1920,L=(($=t.recipe.source)==null?void 0:$.original_height)||1080,U=((y=t.recipe.output)==null?void 0:y.fps)||30;p=new wm(R,L,U,{fitMode:t.fitMode}),p.attachPlayer(r.value),d.value="Loading composition...",await p.loadFromRecipe(t.recipe),m.value=p.durationInSeconds,n("duration-change",m.value),T(),l.value=!1,n("engine-ready",p),t.autoPlay&&(p.play(),u.value=!0)}catch(R){const L=R instanceof Error?R.message:String(R);c.value=`Failed to initialize: ${L}`,l.value=!1}}function T(){if(!p)return;const C=setInterval(()=>{p&&u.value&&(f.value=p.currentTimeInSeconds,n("time-update",f.value))},100);j.value=C}function _(){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 g(C){const $=Math.floor(C/60),y=Math.floor(C%60);return`${$}:${y.toString().padStart(2,"0")}`}function E(){c.value=null,h.value&&x()}function S(){!h.value&&s.value&&(m.value=s.value.duration,n("duration-change",m.value))}function N(){!h.value&&s.value&&(f.value=s.value.currentTime,n("time-update",f.value))}function V(){u.value=!1,n("play-state-change",!1)}function A(C){c.value="Failed to load video",n("error",c.value)}e.onMounted(()=>{h.value&&t.recipe&&x()}),e.onUnmounted(()=>{p&&(p.destroy(),p=null),j.value&&(clearInterval(j.value),j.value=null),s.value&&(s.value.pause(),s.value.removeAttribute("src"),s.value.load())}),e.watch(()=>t.recipe,async C=>{if(h.value&&C)if(C.timeline,p)try{await p.loadFromRecipe(C),m.value=p.durationInSeconds,n("duration-change",m.value)}catch{}else await x()}),e.watch(()=>t.enableEngine,async C=>{C?(await e.nextTick(),await x()):p&&(j.value&&(clearInterval(j.value),j.value=null),p.destroy(),p=null)}),e.watch(()=>t.fitMode,async C=>{if(!(!h.value||!p))try{p.setFitMode(C||"contain")}catch{}});const j=e.ref(null);return(C,$)=>(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:w.value,onLoadedmetadata:S,onTimeupdate:N,onEnded:V,onError:A,style:e.normalizeStyle({width:"100%",height:"100%",objectFit:v.value}),playsinline:"",controls:""},null,44,Ey)),e.createElementVNode("div",xy,[e.createElementVNode("button",{class:"play-button",onClick:_,"aria-label":u.value?"Pause":"Play"},[e.createVNode(e.unref(W.IonIcon),{icon:u.value?e.unref(Lu):e.unref(Pu)},null,8,["icon"])],8,Sy),e.createElementVNode("div",Cy,[e.createElementVNode("span",Vy,e.toDisplayString(g(f.value)),1),$[0]||($[0]=e.createElementVNode("span",{class:"separator"},"/",-1)),e.createElementVNode("span",Ny,e.toDisplayString(g(m.value)),1)])]),l.value?(e.openBlock(),e.createElementBlock("div",Ty,[e.createVNode(e.unref(W.IonSpinner),{name:"crescent"}),e.createElementVNode("p",null,e.toDisplayString(d.value),1)])):e.createCommentVNode("",!0),c.value?(e.openBlock(),e.createElementBlock("div",Iy,[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Hl)},null,8,["icon"]),e.createElementVNode("p",null,e.toDisplayString(c.value),1),e.createElementVNode("button",{onClick:E},"Retry")])):e.createCommentVNode("",!0)],512))}}),yl=Be(By,[["__scopeId","data-v-e199ac48"]]),My=["aria-label"],Fy=["aria-label"],$y={class:"clip-content"},Dy={key:0,class:"clip-thumbnail"},Ry=["src","alt"],Ay=["src"],Ly=["data-visual-mode"],Py={class:"clip-info"},Uy={class:"clip-label"},Oy={class:"clip-duration"},zy={key:3,class:"filter-indicators"},jy={key:4,class:"speed-indicator"},Wy=["aria-label","data-testid"],Hy={key:1,class:"selection-overlay"},Zy=420,Xy=8,Gy=48,Jy=32,wc=1,Ky=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),f=e.ref(!1),m=e.ref(!1),p=e.ref(null),h=e.computed(()=>{const O=(t.clip.timelineEnd-t.clip.timelineStart)*t.scale;return{left:`${t.clip.timelineStart*t.scale-t.scrollOffset}px`,width:`${O}px`}}),v=e.computed(()=>t.clip.label||`Clip ${t.clip.id.slice(-4)}`),w=e.computed(()=>{const B=t.clip.timelineEnd-t.clip.timelineStart;return N(B)}),x=e.computed(()=>t.clip.filters&&t.clip.filters.length>0),T=e.computed(()=>t.clip.filters||[]),_=e.computed(()=>t.clip.waveformSamples??[]),g=e.computed(()=>t.clip.filmstripFrames??[]),E=e.computed(()=>_.value.length>0),S=e.computed(()=>g.value.length>0);function N(B){if(B<1)return`${Math.round(B*30)}f`;if(B<60)return`${B.toFixed(1)}s`;{const O=Math.floor(B/60),X=Math.floor(B%60);return`${O}:${X.toString().padStart(2,"0")}`}}function V(B){return!B||typeof B!="string"?Qd:B.includes("color")||B.includes("brightness")?gn:B.includes("blur")?Fh:B.includes("style")?qo:B.includes("effect")?vn:Qd}function A(){r.value||n("select")}function j(B){B.button===0&&(y("move",B.clientX),B.preventDefault())}function C(B){if(B.touches.length!==1)return;const O=B.touches[0];if(!t.isMobile){y("move",O.clientX),B.preventDefault();return}c.value=O.clientX,u.value=O.clientY,f.value=!1,m.value=!1,R(),L(),p.value=window.setTimeout(()=>{m.value=!0,L(),t.selected||n("select"),n("long-press")},Zy),document.addEventListener("touchmove",U),document.addEventListener("touchend",z),document.addEventListener("touchcancel",z),B.preventDefault()}function $(B,O){const X="touches"in O?O.touches[0].clientX:O.clientX;s.value=B==="start"?"trim-start":"trim-end",y(s.value,X),O.preventDefault(),O.stopPropagation()}function y(B,O){R(),L(),r.value=!0,s.value=B,l.value=O,B==="move"?d.value=t.clip.timelineStart:B==="trim-start"?d.value=t.clip.sourceIn:B==="trim-end"&&(d.value=t.clip.sourceOut),document.addEventListener("mousemove",I),document.addEventListener("mouseup",Z),document.addEventListener("touchmove",P),document.addEventListener("touchend",Z),t.selected||n("select")}function R(){p.value!==null&&(window.clearTimeout(p.value),p.value=null)}function L(){document.removeEventListener("touchmove",U),document.removeEventListener("touchend",z),document.removeEventListener("touchcancel",z)}function U(B){if(B.touches.length!==1)return;const O=B.touches[0],X=O.clientX-c.value,oe=O.clientY-u.value;Math.hypot(X,oe)<Xy||(f.value=!0,R(),L(),y("move",O.clientX),I(B),B.preventDefault())}function z(){const B=!f.value&&!m.value&&!r.value;R(),L(),f.value=!1,m.value=!1,B&&n("select")}function I(B){if(!r.value||!s.value)return;const O="touches"in B?B.touches[0].clientX:B.clientX,X="touches"in B?B.touches[0].clientY:B.clientY,ce=O-l.value;s.value==="move"?(n("drag",ce),n("drag-abs",O,X)):s.value==="trim-start"?(n("trim-start",ce),n("trim-start-abs",O)):s.value==="trim-end"&&(n("trim-end",ce),n("trim-end-abs",O))}function P(B){I(B)}function Z(){r.value=!1,s.value=null,document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",Z),document.removeEventListener("touchmove",P),document.removeEventListener("touchend",Z)}function K(){e.nextTick(()=>{Ve()})}function ve(B){var he,ge;const O=Math.max(0,t.clip.timelineEnd-t.clip.timelineStart),X=Math.max(1,Math.round(O*t.scale)),oe=t.isMobile?Jy:Gy,ce=Math.max(1,Math.round(B.clientWidth||((he=B.parentElement)==null?void 0:he.clientWidth)||X)),je=Math.max(1,Math.round(B.clientHeight||((ge=B.parentElement)==null?void 0:ge.clientHeight)||oe));return{width:ce,height:je}}function Ve(){if(S.value||!i.value)return;const B=i.value,O=B.getContext("2d");if(!O)return;const{width:X,height:oe}=ve(B),ce=window.devicePixelRatio||1;if(B.width=Math.max(1,Math.round(X*ce)),B.height=Math.max(1,Math.round(oe*ce)),O.setTransform(ce,0,0,ce,0,0),O.clearRect(0,0,X,oe),_.value.length>0){ae(O,X,oe,_.value);return}ne(O,X,oe)}function ne(B,O,X){const oe=X/2;B.strokeStyle="rgba(255, 255, 255, 0.3)",B.lineWidth=1,B.beginPath(),B.moveTo(0,oe),B.lineTo(O,oe);for(let ce=0;ce<O;ce+=4){const je=Math.sin(ce*.05)*(X*.3);B.moveTo(ce,oe-je),B.lineTo(ce,oe+je)}B.stroke()}function ae(B,O,X,oe){const ce=t.clip.sourceIn,je=t.clip.sourceOut,he=Math.max(.001,je-ce),ge=oe.filter(Ne=>Ne.endTime>=ce&&Ne.time<=je);if(ge.length===0){ne(B,O,X);return}const pe=X/2,we=X*.44,ye=X*.32;B.fillStyle="rgba(255, 255, 255, 0.26)",ge.forEach(Ne=>{const De=Math.max(Ne.time,ce),Qe=Math.min(Ne.endTime,je),et=(De-ce)/he*O,Lt=Math.max(wc,(Qe-De)/he*O),kt=F(Ne.rms)*ye;B.fillRect(et,pe-kt,Lt,kt*2)}),B.fillStyle="rgba(255, 255, 255, 0.72)",ge.forEach(Ne=>{const De=Math.max(Ne.time,ce),Qe=Math.min(Ne.endTime,je),et=(De-ce)/he*O,Lt=Math.max(wc,(Qe-De)/he*O),kt=F(Ne.peak)*we;B.fillRect(et,pe-kt,Lt,kt*2)})}function F(B){return Math.min(1,Math.max(0,B))}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",Ve)}),e.onUnmounted(()=>{Z(),R(),L(),window.removeEventListener("resize",Ve)}),(B,O)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["timeline-clip",{selected:B.selected,mobile:B.isMobile,"has-filters":x.value}]),style:e.normalizeStyle(h.value),onClick:A,onMousedown:j,onTouchstart:C},[e.createElementVNode("div",{class:"trim-handle trim-start",onMousedown:O[0]||(O[0]=e.withModifiers(X=>$("start",X),["stop"])),onTouchstart:O[1]||(O[1]=e.withModifiers(X=>$("start",X),["stop"])),"aria-label":`Trim start of ${B.clip.label||"clip"}`},[...O[7]||(O[7]=[e.createElementVNode("div",{class:"trim-grip"},null,-1)])],40,My),e.createElementVNode("div",{class:"trim-handle trim-end",onMousedown:O[2]||(O[2]=e.withModifiers(X=>$("end",X),["stop"])),onTouchstart:O[3]||(O[3]=e.withModifiers(X=>$("end",X),["stop"])),"aria-label":`Trim end of ${B.clip.label||"clip"}`},[...O[8]||(O[8]=[e.createElementVNode("div",{class:"trim-grip"},null,-1)])],40,Fy),e.createElementVNode("div",$y,[B.clip.thumbnail?(e.openBlock(),e.createElementBlock("div",Dy,[e.createElementVNode("img",{src:B.clip.thumbnail,alt:B.clip.label||"Video clip"},null,8,Ry)])):e.createCommentVNode("",!0),S.value?(e.openBlock(),e.createElementBlock("div",{key:1,class:e.normalizeClass(["clip-analysis-strip clip-filmstrip",{compact:B.isMobile}]),"aria-hidden":"true"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(g.value,X=>(e.openBlock(),e.createElementBlock("img",{key:X.id,class:"clip-filmstrip-frame",src:X.uri,alt:"",draggable:"false"},null,8,Ay))),128))],2)):(e.openBlock(),e.createElementBlock("div",{key:2,class:e.normalizeClass(["clip-analysis-strip clip-waveform",{compact:B.isMobile}]),"data-visual-mode":E.value?"waveform":"placeholder","aria-hidden":"true"},[e.createElementVNode("canvas",{ref_key:"waveformCanvas",ref:i},null,512)],10,Ly)),e.createElementVNode("div",Py,[e.createElementVNode("span",Uy,e.toDisplayString(v.value),1),e.createElementVNode("span",Oy,e.toDisplayString(w.value),1)]),x.value?(e.openBlock(),e.createElementBlock("div",zy,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(T.value,X=>(e.openBlock(),e.createBlock(e.unref(W.IonIcon),{key:X.id||X.filterId,icon:V(X.filterId||X.id),title:`Filter: ${X.filterId||X.id}`},null,8,["icon","title"]))),128))])):e.createCommentVNode("",!0),B.clip.speed&&B.clip.speed!==1?(e.openBlock(),e.createElementBlock("div",jy,e.toDisplayString(B.clip.speed)+"x ",1)):e.createCommentVNode("",!0)]),B.selected&&B.canDelete?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"clip-delete-button","aria-label":`Delete ${B.clip.label||"clip"}`,"data-testid":`timeline-clip-delete-${B.clip.id}`,title:"Delete clip",onClick:O[4]||(O[4]=e.withModifiers(X=>n("delete"),["stop"])),onMousedown:O[5]||(O[5]=e.withModifiers(()=>{},["stop"])),onTouchstart:O[6]||(O[6]=e.withModifiers(()=>{},["stop"]))},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(xr)},null,8,["icon"])],40,Wy)):e.createCommentVNode("",!0),B.selected?(e.openBlock(),e.createElementBlock("div",Hy)):e.createCommentVNode("",!0)],38))}}),kc=Be(Ky,[["__scopeId","data-v-deeaa999"]]),qy={class:"timeline-track-header__meta"},Yy=["data-testid"],Qy=["data-testid","value","aria-label","onKeydown"],e1={class:"timeline-track-header__type"},t1=["aria-label"],a1=["aria-pressed","aria-label"],n1=["aria-pressed","aria-label"],o1=["aria-pressed","aria-label"],i1=["aria-pressed","aria-label"],r1={class:"timeline-track-header__menu-row"},s1=["data-testid","aria-label","aria-expanded"],l1=["aria-label"],d1=["data-testid"],c1=["data-testid"],u1=["data-testid"],m1=["data-testid"],p1=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(),f()}async function f(){var x,T;s.value=t.track.name,r.value=!0,await e.nextTick(),(x=l.value)==null||x.focus(),(T=l.value)==null||T.select()}function m(x){const T=x.target;T&&(s.value=T.value)}function p(){if(!r.value)return;const x=s.value.trim();r.value=!1,!(x===""||x===t.track.name)&&n("rename-track",t.track.id,x)}function h(){r.value=!1}function v(x){c(),n("reorder-track",t.track.id,x)}function w(){c(),n("delete-track",t.track.id)}return(x,T)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["timeline-track-header",{"is-hidden":x.track.hidden===!0}])},[e.createElementVNode("div",qy,[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-${x.track.id}`,value:s.value,"aria-label":`Rename ${x.track.name}`,onInput:m,onKeydown:[e.withKeys(e.withModifiers(p,["prevent"]),["enter"]),e.withKeys(e.withModifiers(h,["prevent"]),["escape"])],onBlur:p},null,40,Qy)):(e.openBlock(),e.createElementBlock("span",{key:0,class:"timeline-track-header__name","data-testid":`timeline-track-name-${x.track.id}`,onDblclick:f},e.toDisplayString(x.track.name),41,Yy)),e.createElementVNode("span",e1,e.toDisplayString(x.track.type),1)]),e.createElementVNode("div",{class:"timeline-track-header__actions","aria-label":`Track controls for ${x.track.name}`},[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["timeline-track-header__button",{"is-active":x.track.locked===!0}]),"aria-pressed":x.track.locked===!0,"aria-label":x.track.locked===!0?`Unlock ${x.track.name}`:`Lock ${x.track.name}`,title:"Lock",onClick:T[0]||(T[0]=_=>n("toggle-lock",x.track.id))}," Lock ",10,a1),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["timeline-track-header__button",{"is-active":x.track.hidden===!0}]),"aria-pressed":x.track.hidden===!0,"aria-label":x.track.hidden===!0?`Show ${x.track.name}`:`Hide ${x.track.name}`,title:"Hide",onClick:T[1]||(T[1]=_=>n("toggle-hidden",x.track.id))}," Hide ",10,n1),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["timeline-track-header__button",{"is-active":x.track.muted===!0}]),"aria-pressed":x.track.muted===!0,"aria-label":x.track.muted===!0?`Unmute ${x.track.name}`:`Mute ${x.track.name}`,title:"Mute",onClick:T[2]||(T[2]=_=>n("toggle-muted",x.track.id))}," Mute ",10,o1),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["timeline-track-header__button",{"is-active":x.track.solo===!0}]),"aria-pressed":x.track.solo===!0,"aria-label":x.track.solo===!0?`Disable solo for ${x.track.name}`:`Solo ${x.track.name}`,title:"Solo",onClick:T[3]||(T[3]=_=>n("toggle-solo",x.track.id))}," Solo ",10,i1)],8,t1),e.createElementVNode("div",r1,[e.createElementVNode("button",{type:"button",class:"timeline-track-header__menu-button","data-testid":`timeline-track-menu-${x.track.id}`,"aria-label":`More actions for ${x.track.name}`,"aria-expanded":i.value,"aria-haspopup":!0,onClick:d}," ⋯ ",8,s1),i.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"timeline-track-header__menu",role:"menu","aria-label":`${x.track.name} actions`},[e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":`timeline-track-rename-action-${x.track.id}`,onClick:u}," Rename ",8,d1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":`timeline-track-move-up-${x.track.id}`,onClick:T[4]||(T[4]=_=>v("up"))}," Move up ",8,c1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":`timeline-track-move-down-${x.track.id}`,onClick:T[5]||(T[5]=_=>v("down"))}," Move down ",8,u1),e.createElementVNode("button",{type:"button",role:"menuitem",class:"timeline-track-header__menu-button--danger","data-testid":`timeline-track-delete-${x.track.id}`,onClick:w}," Delete track ",8,m1)],8,l1)):e.createCommentVNode("",!0)])],2))}}),f1=Be(p1,[["__scopeId","data-v-54e2bc6a"]]);class km{constructor(a=30){this.fps=30,this.fps=a}setFps(a){this.fps=a}async convertTimelineClipToEngine(a,t){const n=new vl(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 Pn.from(i.url),s=await this.convertTimelineClipToEngine(i,r);await t.add(s)}catch{}a.duration&&(t.duration=$e.fromFrames(this.secondsToFrames(a.duration)))}extractTimelineFromComposition(a){const t=[];return(a.clips||[]).forEach((i,r)=>{var s,l;i instanceof vl&&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 h1={class:"time-markers"},v1=["data-track-id"],g1=["data-track-id"],b1=["aria-label","title"],y1={key:0,class:"timeline-scrollbar"},_c=152,Ec=80,w1=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(),f=e.ref(0),m=e.computed(()=>n.selectedClipId??l.value);e.watch(()=>n.selectedClipId,Q=>{Q!==void 0&&(l.value=Q)});const p=new km(n.fps);e.watch(()=>n.fps,Q=>{p.setFps(Q)});const h=e.ref(!1),v=e.ref(null),w=e.ref(0),x=e.ref(0),T=e.ref(null),_=e.ref(null),g=e.ref(0),E=e.ref(0),S=e.ref(0),N=e.ref(!1),V=e.ref(0),A=e.ref(n.zoomLevel),j=e.computed(()=>n.zoomLevel),C=e.computed(()=>n.tracks!==void 0&&n.tracks.length>0&&!i.value),$=e.computed(()=>C.value?_c:0),y=e.computed(()=>Math.max(0,F.value-$.value));function R(Q){return Q.trackId??`legacy-track-${Q.track??0}`}function L(Q,ue){return{id:Q,type:"video",name:`Track ${ue+1}`,order:ue}}const U=e.computed(()=>{const Q=new Map;for(const ue of n.clips){const re=R(ue),ie=Q.get(re);if(ie){ie.push(ue);continue}Q.set(re,[ue])}return Q}),z=e.computed(()=>{if(!C.value)return[];const Q=[...n.tracks??[]].sort((ie,Se)=>ie.order-Se.order),ue=new Set(Q.map(ie=>ie.id)),re=[];for(const ie of U.value.keys())ue.has(ie)||re.push(L(ie,Q.length+re.length));return[...Q,...re].map(ie=>({track:ie,clips:U.value.get(ie.id)??[],height:ie.height??Ec}))}),I=e.computed(()=>new Set(z.value.filter(Q=>Q.track.locked===!0).map(Q=>Q.track.id)));function P(Q){const ue=n.clips.find(re=>re.id===Q);return ue?!I.value.has(R(ue)):!1}function Z(Q){const ue=n.clips.find(Se=>Se.id===Q);if(!ue)return null;const re=R(ue),ie=n.clips.filter(Se=>Se.id!==Q&&R(Se)===re&&Se.timelineStart>=ue.timelineEnd-1e-9).map(Se=>Se.timelineStart);return ie.length?Math.min(...ie):null}function K(Q){const ue=Q.sourceMaxOut??n.duration,re=Q.timelineStart+(ue-Q.sourceIn),ie=Z(Q.id),Se=ie!=null?Math.max(Q.timelineStart,ie):1/0;return Math.min(re,Se)}function ve(Q,ue=Ec){const re=Q.sourceMinIn??0,Se=(Q.sourceMaxOut??n.duration)-re,Ae=Q.sourceIn-re;return{left:`${(Q.timelineStart-Ae)*j.value-c.value}px`,width:`${Se*j.value}px`,top:"0px",height:`${ue}px`,opacity:m.value===Q.id?.25:.15}}const Ve=e.computed(()=>n.useFrameMode?n.zoomLevel:n.zoomLevel/n.fps),ne=e.computed(()=>p.secondsToFrames(n.duration)),ae=e.computed(()=>n.useFrameMode?ne.value*Ve.value:n.duration*j.value),F=e.computed(()=>{var Q;return f.value||((Q=s.value)==null?void 0:Q.clientWidth)||800}),B=e.computed(()=>ae.value>y.value),O=e.computed(()=>Math.max(0,ae.value-y.value)),X=e.computed(()=>c.value>0),oe=e.computed(()=>c.value<O.value),ce=e.computed(()=>n.useFrameMode?p.secondsToFrames(n.playhead)*Ve.value-c.value:n.playhead*j.value-c.value),je=e.computed(()=>T.value===null?null:n.useFrameMode?p.secondsToFrames(T.value)*Ve.value-c.value:T.value*j.value-c.value),he=e.computed(()=>{const Q=y.value,ue=Math.max(50,Q/ae.value*Q),re=c.value/O.value*(Q-ue);return{width:`${ue}px`,left:`${re}px`}}),ge=e.computed(()=>{const Q=[],ue=pe();for(let re=0;re<=n.duration;re+=ue){const ie=re*j.value-c.value;ie>=-50&&ie<=y.value+50&&Q.push({position:ie+$.value,label:we(re),time:re})}return Q});function pe(){const ue=80/j.value;return ue<=1?1:ue<=5?5:ue<=10?10:ue<=30?30:ue<=60?60:Math.ceil(ue/60)*60}function we(Q){if(n.useFrameMode)return`F${p.secondsToFrames(Q)}`;{const ue=Math.floor(Q/60),re=Math.floor(Q%60),ie=Math.floor(Q%1*n.fps);return j.value>100?`${ue}:${re.toString().padStart(2,"0")}:${ie.toString().padStart(2,"0")}`:`${ue}:${re.toString().padStart(2,"0")}`}}function ye(Q){const ue=s.value.getBoundingClientRect();let ie=(Q.clientX-ue.left-$.value+c.value)/j.value;const Se=n.clips.find(Ae=>ie>=Ae.timelineStart&&ie<=Ae.timelineEnd);if(Se)ie=Math.max(Se.timelineStart,Math.min(Se.timelineEnd,ie));else if(n.selectedClipId){const Ae=n.clips.find(qe=>qe.id===n.selectedClipId);if(Ae){const qe=Math.abs(ie-Ae.timelineStart),ft=Math.abs(ie-Ae.timelineEnd);ie=qe<ft?Ae.timelineStart:Ae.timelineEnd}}else ie=Math.max(0,Math.min(ie,n.duration));r("update:playhead",ie)}function Ne(Q){if(!B.value)return;const ue=Math.abs(Q.deltaX)>Math.abs(Q.deltaY)?Q.deltaX:Q.deltaY;ue!==0&&(Q.preventDefault(),c.value=Math.max(0,Math.min(O.value,c.value+ue)))}function De(Q){return[...Q===void 0?n.clips:n.clips.filter(re=>R(re)===Q)].sort((re,ie)=>re.timelineStart-ie.timelineStart)}function Qe(Q){const ue=n.clips.find(Se=>Se.id===Q),re=De(ue?R(ue):void 0),ie=re.findIndex(Se=>Se.id===Q);return{previous:ie>0?re[ie-1]:null,next:ie!==-1&&ie<re.length-1?re[ie+1]:null}}function et(Q){const ue=Q.timelineEnd-Q.timelineStart,{previous:re,next:ie}=Qe(Q.id),Se=re?re.timelineEnd:0,Ae=ie?ie.timelineStart-ue:Math.max(Q.timelineStart,n.duration-ue);return{minStart:Se,maxStart:Math.max(Se,Ae)}}function Lt(){return 12/Math.max(j.value,1)}function kt(Q){return Array.from(new Set(Q.filter(ue=>typeof ue=="number"&&Number.isFinite(ue))))}function Ct(Q,ue,re,ie){const Se=Math.max(re,Math.min(Q,ie));if(!n.snapEnabled)return{value:Se,guideTime:null};const Ae=Lt();let qe=Se,ft=null,Vt=Number.POSITIVE_INFINITY;for(const ht of kt(ue)){if(ht<re||ht>ie)continue;const vt=Math.abs(ht-Se);vt<=Ae&&vt<Vt&&(qe=ht,ft=ht,Vt=vt)}return{value:qe,guideTime:ft}}function bt(Q){if(Q.touches.length===2){N.value=!0;const ue=Q.touches[0],re=Q.touches[1];V.value=Math.hypot(re.clientX-ue.clientX,re.clientY-ue.clientY),A.value=n.zoomLevel}else Q.touches.length===1&&(g.value=Q.touches[0].clientX,E.value=Q.touches[0].clientY,S.value=g.value)}function rt(Q){if(N.value&&Q.touches.length===2){const ue=Q.touches[0],re=Q.touches[1],Se=Math.hypot(re.clientX-ue.clientX,re.clientY-ue.clientY)/V.value;Math.max(10,Math.min(200,A.value*Se)),r("update:playhead",n.playhead)}else if(Q.touches.length===1&&!N.value){const ue=Q.touches[0],re=S.value-ue.clientX;Math.abs(re)>Math.abs(ue.clientY-E.value)&&(Q.preventDefault(),c.value=Math.max(0,Math.min(O.value,c.value+re)),S.value=ue.clientX)}}function _t(){N.value=!1}function be(Q){const ue=Q.target;if(ue.closest(".playhead-handle"))return;const re=Q.button===1,ie=!!ue.closest(".video-track");(re||!ie&&B.value)&&ke(Q)}function ke(Q){h.value=!0,v.value="pan",w.value=Q.clientX,x.value=c.value,document.addEventListener("mousemove",Ge),document.addEventListener("mouseup",ze)}function Te(Q){Q.preventDefault(),Q.stopPropagation(),h.value=!0,v.value="playhead";const ue="touches"in Q?Q.touches[0].clientX:Q.clientX;w.value=ue,x.value=n.playhead,"touches"in Q?(document.addEventListener("touchmove",Ge),document.addEventListener("touchend",ze)):(document.addEventListener("mousemove",Ge),document.addEventListener("mouseup",ze))}function Ke(Q){Q.preventDefault(),Q.stopPropagation(),h.value=!0,v.value="scrollbar";const ue="touches"in Q?Q.touches[0].clientX:Q.clientX;w.value=ue,x.value=c.value,"touches"in Q?(document.addEventListener("touchmove",Ge),document.addEventListener("touchend",ze)):(document.addEventListener("mousemove",Ge),document.addEventListener("mouseup",ze))}function Ge(Q){if(!h.value)return;const re=("touches"in Q?Q.touches[0].clientX:Q.clientX)-w.value;if(v.value==="playhead"){const ie=re/j.value;let Se=x.value+ie;if(n.selectedClipId){const Ae=n.clips.find(qe=>qe.id===n.selectedClipId);Ae?Se=Math.max(Ae.timelineStart,Math.min(Ae.timelineEnd,Se)):Se=Math.max(0,Math.min(n.duration,Se))}else{const Ae=n.clips.find(qe=>n.playhead>=qe.timelineStart&&n.playhead<=qe.timelineEnd);Ae?Se=Math.max(Ae.timelineStart,Math.min(Ae.timelineEnd,Se)):Se=Math.max(0,Math.min(n.duration,Se))}r("update:playhead",Se)}else if(v.value==="scrollbar"){const ie=re/y.value*ae.value;c.value=Math.max(0,Math.min(O.value,x.value+ie))}else if(v.value==="pan"){const ie=x.value-re;c.value=Math.max(0,Math.min(O.value,ie))}}function ze(){h.value=!1,v.value=null,T.value=null,_.value=null,document.removeEventListener("mousemove",Ge),document.removeEventListener("mouseup",ze),document.removeEventListener("touchmove",Ge),document.removeEventListener("touchend",ze)}function Et(Q){l.value=l.value===Q?null:Q,r("clip-select",l.value)}function ut(Q){P(Q)&&(l.value=Q,r("clip-select",Q),r("clip-long-press",Q))}function Xt(Q){!P(Q)||n.clips.length<=1||(l.value=Q,r("clip-select",Q),r("clip-delete",Q))}function Wt(Q,ue){if(!P(Q))return;const re=n.clips.find(Se=>Se.id===Q);if(!re||Math.abs(ue)<2)return;const ie=ue/j.value*n.sensitivity;if(n.useFrameMode){const Se=p.secondsToFrames(re.sourceIn),Ae=p.secondsToFrames(ie),qe=Math.max(0,Se+Ae),ft=p.framesToSeconds(qe);r("trim",Q,"start",ft)}else{const Se=Math.max(0,re.sourceIn+ie);r("trim",Q,"start",Se)}}function ca(Q,ue){if(!P(Q))return;const re=n.clips.find(Mt=>Mt.id===Q);if(!re||!s.value)return;const ie=s.value.getBoundingClientRect(),Se=ue-ie.left-$.value,Ae=80;Se<Ae?c.value=Math.max(0,c.value-8):Se>ie.width-$.value-Ae&&(c.value=Math.min(O.value,c.value+8));const qe=Se+c.value,ft=1/n.fps;let Vt=qe/j.value;const{previous:ht}=Qe(re.id),vt=Ct(Vt,[0,ht==null?void 0:ht.timelineEnd,n.playhead],0,re.timelineEnd-ft);Vt=vt.value,T.value=vt.guideTime;let Ut=re.sourceIn+(Vt-re.timelineStart);Ut=Math.round(Ut*n.fps)/n.fps,r("trim",Q,"start",Ut)}function ta(Q,ue){if(!P(Q))return;const re=n.clips.find(Ft=>Ft.id===Q);if(!re||!s.value)return;const ie=s.value.getBoundingClientRect(),Se=ue-ie.left-$.value,Ae=80;Se<Ae?c.value=Math.max(0,c.value-8):Se>ie.width-$.value-Ae&&(c.value=Math.min(O.value,c.value+8));const qe=Se+c.value,ft=1/n.fps,Vt=K(re);let ht=qe/j.value;const{next:vt}=Qe(re.id),Ut=Ct(ht,[vt==null?void 0:vt.timelineStart,n.playhead],re.timelineStart+ft,Vt);ht=Ut.value,T.value=Ut.guideTime;let Mt=re.sourceIn+(ht-re.timelineStart);Mt=Math.round(Mt*n.fps)/n.fps,r("trim",Q,"end",Mt)}function ya(Q){var re;if(!C.value||!s.value)return null;const ue=Array.from(s.value.querySelectorAll(".timeline-track-lane__body"));for(const ie of ue){const Se=ie.getBoundingClientRect();if(Q>=Se.top&&Q<=Se.bottom){const Ae=ie.getAttribute("data-track-id");if(!Ae)continue;return((re=n.tracks)==null?void 0:re.find(ft=>ft.id===Ae))??null}}return null}function Sa(Q,ue,re){if(!P(Q))return;const ie=n.clips.find(Ft=>Ft.id===Q);if(!ie||!s.value)return;const Se=s.value.getBoundingClientRect(),Ae=ue-Se.left-$.value,qe=80;Ae<qe?c.value=Math.max(0,c.value-8):Ae>Se.width-$.value-qe&&(c.value=Math.min(O.value,c.value+8));const ft=Ae+c.value,Vt=ie.timelineEnd-ie.timelineStart,ht=et(ie);let vt=ft/j.value;const Ut=Ct(vt,[ht.minStart,ht.maxStart,n.playhead,n.playhead-Vt],ht.minStart,ht.maxStart);vt=Ut.value,T.value=Ut.guideTime,vt=Math.round(vt*n.fps)/n.fps;let Mt;if(typeof re=="number"){const Ft=ya(re);_.value=(Ft==null?void 0:Ft.id)??null,Ft&&Ft.id!==(ie.trackId??null)&&Ft.locked!==!0&&(Mt=Ft.id)}Mt!==void 0?r("clip-move",Q,vt,Mt):r("clip-move",Q,vt)}function wa(Q,ue){if(!P(Q))return;const re=n.clips.find(Ae=>Ae.id===Q);if(!re||Math.abs(ue)<2)return;const ie=ue/j.value*n.sensitivity,Se=Ae=>Math.max(0,Math.round(Ae*n.fps)/n.fps);if(n.useFrameMode){const Ae=p.secondsToFrames(re.sourceOut),qe=p.secondsToFrames(ie),ft=K(re),Vt=re.sourceIn+(ft-re.timelineStart),ht=p.secondsToFrames(Vt),vt=Math.min(ht,Ae+qe),Ut=p.framesToSeconds(vt);r("trim",Q,"end",Ut)}else{const Ae=K(re),qe=re.sourceIn+(Ae-re.timelineStart),ft=Math.min(qe,re.sourceOut+ie),Vt=Se(ft);r("trim",Q,"end",Vt)}}function nn(Q,ue){if(!P(Q))return;const re=n.clips.find(Ae=>Ae.id===Q);if(!re||Math.abs(ue)<2)return;const ie=ue/j.value*n.sensitivity,Se=Ae=>Math.max(0,Math.round(Ae*n.fps)/n.fps);if(n.useFrameMode){const Ae=p.secondsToFrames(re.timelineStart),qe=p.secondsToFrames(ie),ft=Math.max(0,Ae+qe),Vt=p.framesToSeconds(ft);r("clip-move",Q,Vt)}else{const Ae=Math.max(0,re.timelineStart+ie),qe=Se(Ae);r("clip-move",Q,qe)}}return a({handleTrimStart:Wt,handleTrimEnd:wa,handleClipDrag:nn,handleTrimStartAbs:ca,handleTrimEndAbs:ta,handleClipDragAbs:Sa,handleClipLongPress:ut}),e.watch(()=>n.playhead,Q=>{const ue=Q*j.value;ue<c.value+50?c.value=Math.max(0,ue-50):ue>c.value+y.value-50&&(c.value=Math.min(O.value,ue-y.value+50))}),e.onMounted(()=>{const Q=new ResizeObserver(ue=>{ue[0]&&(f.value=Math.round(ue[0].contentRect.width))});s.value&&Q.observe(s.value),e.onUnmounted(()=>Q.disconnect())}),e.onUnmounted(()=>{ze()}),e.watch([ae,F],()=>{c.value>O.value&&(c.value=O.value)}),e.watch(T,(Q,ue)=>{const re=Q!==null;re!==(ue!==null)&&r("snap-state-change",re)}),(Q,ue)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-timeline",{mobile:i.value}]),ref_key:"timelineRef",ref:s,onWheel:Ne},[e.createElementVNode("div",{class:"timeline-ruler",onClick:ye},[e.createElementVNode("div",h1,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(ge.value,re=>(e.openBlock(),e.createElementBlock("span",{key:re.position,class:"time-marker",style:e.normalizeStyle({left:`${re.position}px`})},e.toDisplayString(re.label),5))),128))])]),e.createElementVNode("div",{class:e.normalizeClass(["timeline-content",{"is-pannable":B.value,"is-panning":h.value&&v.value==="pan","overflow-left":X.value,"overflow-right":oe.value}]),onTouchstart:bt,onTouchmove:rt,onTouchend:_t,onMousedown:be},[C.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"timeline-track-lanes",style:e.normalizeStyle({"--timeline-track-header-width":`${_c}px`})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(z.value,re=>(e.openBlock(),e.createElementBlock("div",{key:re.track.id,class:e.normalizeClass(["timeline-track-lane",{"timeline-track-lane--locked":re.track.locked,"timeline-track-lane--hidden":re.track.hidden,"timeline-track-lane--drop-target":_.value===re.track.id&&re.track.locked!==!0,"timeline-track-lane--drop-rejected":_.value===re.track.id&&re.track.locked===!0}]),style:e.normalizeStyle({height:`${re.height}px`}),"data-track-id":re.track.id},[e.createVNode(f1,{class:"timeline-track-lane__header",track:re.track,onToggleLock:ue[0]||(ue[0]=ie=>r("toggle-lock",ie)),onToggleHidden:ue[1]||(ue[1]=ie=>r("toggle-hidden",ie)),onToggleMuted:ue[2]||(ue[2]=ie=>r("toggle-muted",ie)),onToggleSolo:ue[3]||(ue[3]=ie=>r("toggle-solo",ie)),onRenameTrack:ue[4]||(ue[4]=(ie,Se)=>r("rename-track",ie,Se)),onDeleteTrack:ue[5]||(ue[5]=ie=>r("delete-track",ie)),onReorderTrack:ue[6]||(ue[6]=(ie,Se)=>r("reorder-track",ie,Se))},null,8,["track"]),e.createElementVNode("div",{class:"video-track timeline-track-lane__body","data-track-id":re.track.id},[re.track.hidden?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(re.clips,ie=>(e.openBlock(),e.createElementBlock("div",{key:`${ie.id}-extent`,class:"clip-extent",style:e.normalizeStyle(ve(ie,re.height)),"aria-hidden":"true"},null,4))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(re.clips,ie=>(e.openBlock(),e.createBlock(kc,{key:ie.id,clip:ie,scale:j.value,"scroll-offset":c.value,selected:m.value===ie.id,"is-mobile":i.value,"can-delete":n.clips.length>1&&P(ie.id),"data-locked":re.track.locked===!0?"true":void 0,onSelect:Se=>Et(ie.id),onDelete:Se=>Xt(ie.id),onLongPress:Se=>ut(ie.id),onTrimStartAbs:Se=>ca(ie.id,Se),onTrimEndAbs:Se=>ta(ie.id,Se),onDragAbs:(Se,Ae)=>Sa(ie.id,Se,Ae)},null,8,["clip","scale","scroll-offset","selected","is-mobile","can-delete","data-locked","onSelect","onDelete","onLongPress","onTrimStartAbs","onTrimEndAbs","onDragAbs"]))),128))],64))],8,g1)],14,v1))),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,re=>(e.openBlock(),e.createElementBlock("div",{key:`${re.id}-extent`,class:"clip-extent",style:e.normalizeStyle(ve(re)),"aria-hidden":"true"},null,4))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Q.clips,re=>(e.openBlock(),e.createBlock(kc,{key:re.id,clip:re,scale:j.value,"scroll-offset":c.value,selected:m.value===re.id,"is-mobile":i.value,"can-delete":n.clips.length>1&&P(re.id),onSelect:ie=>Et(re.id),onDelete:ie=>Xt(re.id),onLongPress:ie=>ut(re.id),onTrimStartAbs:ie=>ca(re.id,ie),onTrimEndAbs:ie=>ta(re.id,ie),onDragAbs:(ie,Se)=>Sa(re.id,ie,Se)},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:`${$.value+ce.value}px`}),onMousedown:Te,onTouchstart:Te},[...ue[8]||(ue[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:`${$.value+ce.value}px`})},null,4)):e.createCommentVNode("",!0),je.value!==null?(e.openBlock(),e.createElementBlock("div",{key:3,class:"snap-guide",style:e.normalizeStyle({left:`${$.value+je.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:ue[7]||(ue[7]=re=>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,b1))],34),B.value?(e.openBlock(),e.createElementBlock("div",y1,[e.createElementVNode("div",{class:"scrollbar-thumb",style:e.normalizeStyle(he.value),onMousedown:Ke,onTouchstart:Ke},null,36)])):e.createCommentVNode("",!0)],34))}}),wl=Be(w1,[["__scopeId","data-v-2484f443"]]),k1={key:0,class:"control-group primary-controls"},_1=["disabled"],E1=["disabled"],x1=["disabled"],S1=["disabled"],C1=["disabled"],V1=["disabled"],N1={key:1,class:"control-group mobile-action-controls"},T1=["aria-expanded"],I1={key:0,class:"mobile-action-menu",role:"menu","aria-label":"Clip actions","data-testid":"timeline-mobile-action-menu"},B1=["disabled"],M1=["disabled"],F1=["disabled"],$1=["disabled"],D1=["disabled"],R1=["disabled"],A1={class:"control-group zoom-controls"},L1={class:"zoom-slider"},P1=["value"],U1={class:"control-group playback-controls"},O1=["aria-label"],z1={key:2,class:"control-group speed-control"},j1=["value"],W1=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(m){switch(m){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(m){const p=m.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 f(m){const p=m.target;t("speed-change",Number(p.value))}return(m,p)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["timeline-controls",{mobile:m.isMobile}])},[m.isMobile?(e.openBlock(),e.createElementBlock("div",N1,[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(W.IonIcon),{icon:e.unref(Ih)},null,8,["icon"]),p[20]||(p[20]=e.createElementVNode("span",{class:"control-label"},"Actions",-1))],8,T1),n.value?(e.openBlock(),e.createElementBlock("div",I1,[m.showAddTrack?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",role:"menuitem",disabled:!m.canAddTrack,"data-testid":"timeline-mobile-btn-add-track",onClick:p[7]||(p[7]=h=>i("add-track"))},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(cr)},null,8,["icon"]),p[21]||(p[21]=e.createTextVNode(" Add Track ",-1))],8,B1)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",role:"menuitem",disabled:!m.canUndo,"data-testid":"timeline-mobile-btn-undo",onClick:p[8]||(p[8]=h=>i("undo"))},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Xd)},null,8,["icon"]),p[22]||(p[22]=e.createTextVNode(" Undo ",-1))],8,M1),e.createElementVNode("button",{type:"button",role:"menuitem",disabled:!m.canRedo,"data-testid":"timeline-mobile-btn-redo",onClick:p[9]||(p[9]=h=>i("redo"))},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Zd)},null,8,["icon"]),p[23]||(p[23]=e.createTextVNode(" Redo ",-1))],8,F1),e.createElementVNode("button",{type:"button",role:"menuitem",disabled:!m.canSplit,"data-testid":"timeline-mobile-btn-split",onClick:p[10]||(p[10]=h=>i("split"))},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Er)},null,8,["icon"]),p[24]||(p[24]=e.createTextVNode(" Split ",-1))],8,$1),e.createElementVNode("button",{type:"button",role:"menuitem",disabled:!m.selectedClip,"data-testid":"timeline-mobile-btn-duplicate",onClick:p[11]||(p[11]=h=>i("duplicate"))},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(al)},null,8,["icon"]),p[25]||(p[25]=e.createTextVNode(" Duplicate ",-1))],8,D1),e.createElementVNode("button",{type:"button",role:"menuitem",class:"danger-menu-item",disabled:!m.canDelete,"data-testid":"timeline-mobile-btn-delete",onClick:p[12]||(p[12]=h=>i("delete"))},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(xr)},null,8,["icon"]),p[26]||(p[26]=e.createTextVNode(" Delete ",-1))],8,R1)])):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("div",k1,[m.showAddTrack?(e.openBlock(),e.createElementBlock("button",{key:0,class:"control-button",disabled:!m.canAddTrack,"data-testid":"timeline-btn-add-track","aria-label":"Add video track",title:"Add Track",onClick:p[0]||(p[0]=h=>m.$emit("add-track"))},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(cr)},null,8,["icon"]),p[16]||(p[16]=e.createElementVNode("span",{class:"control-label"},"Add Track",-1))],8,_1)):e.createCommentVNode("",!0),e.createElementVNode("button",{class:"control-button",disabled:!m.canUndo,"data-testid":"timeline-btn-undo","aria-label":"Undo",title:"Undo",onClick:p[1]||(p[1]=h=>m.$emit("undo"))},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Xd)},null,8,["icon"])],8,E1),e.createElementVNode("button",{class:"control-button",disabled:!m.canRedo,"data-testid":"timeline-btn-redo","aria-label":"Redo",title:"Redo",onClick:p[2]||(p[2]=h=>m.$emit("redo"))},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Zd)},null,8,["icon"])],8,x1),e.createElementVNode("button",{class:"control-button",disabled:!m.canSplit,"data-testid":"timeline-btn-split","aria-label":"Split selected clip at playhead",title:"Split",onClick:p[3]||(p[3]=h=>m.$emit("split"))},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Er)},null,8,["icon"]),p[17]||(p[17]=e.createElementVNode("span",{class:"control-label"},"Split",-1))],8,S1),e.createElementVNode("button",{class:"control-button",disabled:!m.selectedClip,"data-testid":"timeline-btn-duplicate","aria-label":"Duplicate selected clip",title:"Duplicate",onClick:p[4]||(p[4]=h=>m.$emit("duplicate"))},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(al)},null,8,["icon"]),p[18]||(p[18]=e.createElementVNode("span",{class:"control-label"},"Duplicate",-1))],8,C1),e.createElementVNode("button",{class:"control-button danger-button",disabled:!m.canDelete,"data-testid":"timeline-btn-delete","aria-label":"Delete selected clip",title:"Delete",onClick:p[5]||(p[5]=h=>m.$emit("delete"))},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(xr)},null,8,["icon"]),p[19]||(p[19]=e.createElementVNode("span",{class:"control-label"},"Delete",-1))],8,V1)])),e.createElementVNode("div",A1,[e.createElementVNode("button",{class:"control-button zoom-button",onClick:p[13]||(p[13]=h=>m.$emit("zoom-out")),"aria-label":"Zoom out"},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Gh)},null,8,["icon"])]),e.createElementVNode("div",L1,[e.createElementVNode("input",{type:"range",value:m.zoomLevel,onInput:r,min:"10",max:"200",step:"5","aria-label":"Timeline zoom"},null,40,P1)]),e.createElementVNode("button",{class:"control-button zoom-button",onClick:p[14]||(p[14]=h=>m.$emit("zoom-in")),"aria-label":"Zoom in"},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(cr)},null,8,["icon"])]),e.createElementVNode("button",{class:"control-button",onClick:s,"aria-label":"Fit timeline to window"},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Mh)},null,8,["icon"]),p[27]||(p[27]=e.createElementVNode("span",{class:"control-label"},"Fit",-1))])]),e.createElementVNode("div",U1,[e.createElementVNode("button",{class:"control-button",onClick:c,"aria-label":"Skip to start"},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Zh)},null,8,["icon"])]),e.createElementVNode("button",{class:"control-button",onClick:d,"aria-label":"Previous frame"},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(zh)},null,8,["icon"])]),e.createElementVNode("button",{class:"control-button play-button",onClick:p[15]||(p[15]=h=>m.$emit("play-pause")),"aria-label":m.isPlaying?"Pause":"Play"},[e.createVNode(e.unref(W.IonIcon),{icon:m.isPlaying?e.unref(Zl):e.unref(Xl)},null,8,["icon"])],8,O1),e.createElementVNode("button",{class:"control-button",onClick:l,"aria-label":"Next frame"},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Hh)},null,8,["icon"])]),e.createElementVNode("button",{class:"control-button",onClick:u,"aria-label":"Skip to end"},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Xh)},null,8,["icon"])])]),m.isMobile?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",z1,[p[29]||(p[29]=e.createElementVNode("label",{class:"speed-label"},"Speed:",-1)),e.createElementVNode("select",{value:m.playbackSpeed,onChange:f,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,j1)]))],2))}}),kl=Be(W1,[["__scopeId","data-v-c7b0395a"]]),H1={key:0,class:"category-section"},Z1={class:"category-carousel-wrapper"},X1=["disabled"],G1=["onClick","data-testid","aria-label"],J1={class:"category-name"},K1=["disabled"],q1={class:"filter-section"},Y1={class:"filter-carousel-wrapper"},Q1=["disabled"],ew=["onClick","onKeydown","data-testid","aria-label"],tw=["onClick"],aw={class:"filter-preview"},nw={class:"filter-placeholder"},ow={class:"filter-name"},iw=["disabled"],rw={class:"carousel-pagination"},sw=["onClick"],lw={key:1,class:"filter-adjustments"},dw={class:"adjustment-header"},cw={class:"adjustment-actions"},uw={key:0},mw={key:0,class:"slider-control"},pw={class:"control-label"},fw={class:"slider-wrapper"},hw={class:"slider-value"},vw={key:1,class:"color-control"},gw={class:"control-label"},bw={class:"color-wrapper"},yw=["value","onInput","disabled"],ww={class:"color-value"},kw={key:2,class:"toggle-control"},_w={class:"control-label"},Ew={key:3,class:"select-control"},xw={class:"control-label"},Sw=["value","onChange","disabled"],Cw=["value"],Vw={key:1,class:"no-params"},Nw=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(),f={all:vn,adjust:Wo,color:gn,blur:Gi,light:Ho,effects:Ms,stylize:qo,advanced:vn,distortion:Yo,transform:Yo};function m(I){return I.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function p(I){return I.replace(/[-_]/g," ").replace(/\b\w/g,P=>P.toUpperCase())}function h(I){return f[I.toLowerCase()]??vn}const v=e.computed(()=>{const I=Array.from(new Set(t.filters.map(P=>P.category).filter(P=>typeof P=="string"&&P.length>0))).sort((P,Z)=>P.localeCompare(Z));return[{id:"all",name:"All",icon:vn},...I.map(P=>({id:P,name:p(P),icon:h(P)}))]}),w=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 x(I){var P;return((P=t.activeFilters)==null?void 0:P.has(I))||!1}function T(I){if(r.value=I,!x(I.id)&&(n("apply-filter",I),I.params&&I.params.length>0)){const P=new Map;I.params.forEach(Z=>{P.set(Z.id,Z.default)}),d.value.set(I.id,P)}n("preview-filter",I)}function _(I){var P;n("remove-filter",I),d.value.delete(I),((P=r.value)==null?void 0:P.id)===I&&(r.value=null)}function g(I){if(typeof I=="number"&&Number.isFinite(I))return I;if(typeof I=="string"){const P=Number(I);return Number.isFinite(P)?P:null}return null}function E(I,P){var F;const Z=t.filters.find(B=>B.id===I),K=Z==null?void 0:Z.params.find(B=>B.id===P),ve=(K==null?void 0:K.default)??0,Ve=B=>typeof ve=="number"?g(B)??ve:typeof ve=="boolean"?typeof B=="boolean"?B:ve:typeof B=="string"?B:ve,ne=(F=t.activeFilters)==null?void 0:F.get(I);if(ne&&ne.params){const B=ne.params[P];if(B!=null)return Ve(B)}const ae=d.value.get(I);if(ae){const B=ae.get(P);if(B!=null)return Ve(B)}return ve}function S(I,P,Z){var K;d.value.has(I)||d.value.set(I,new Map),(K=d.value.get(I))==null||K.set(P,Z),n("update-param",I,P,Z)}function N(I){if(typeof I=="boolean")return I?"On":"Off";if(typeof I=="string"){const Z=g(I);return Z===null?"0":Number.isInteger(Z)?Z.toString():Z.toFixed(2)}const P=g(I);return P===null?"0":Number.isInteger(P)?P.toString():P.toFixed(2)}function V(){if(r.value&&(n("apply-filter",r.value),r.value.params&&r.value.params.length>0)){const I=new Map;r.value.params.forEach(P=>{I.set(P.id,P.default)}),d.value.set(r.value.id,I)}}function A(I){const P=t.filters.find(Z=>Z.id===I);P&&P.params&&P.params.forEach(Z=>{S(I,Z.id,Z.default)})}function j(I){return{basic:Wo,color:gn,blur:Gi,light:Ho,effects:Ms,stylize:qo,adjustment:Wo,"color-matrix":gn,glow:vn,distortion:Yo}[I]||vn}function C(I){return{adjustment:Wo,brightness:Ho,contrast:Wo,saturation:gn,blur:Gi,"gaussian-blur":Gi,"color-matrix":gn,grayscale:qo,sepia:qo,vignette:Yo,glow:vn,glitch:Ms,godray:Ho,lightmap:Ho}[I.id]||j(I.category)}function $(){s.value>0&&(s.value--,z(c.value,s.value))}function y(){s.value<v.value.length-3&&(s.value++,z(c.value,s.value))}function R(){l.value>0&&(l.value--,z(u.value,l.value))}function L(){l.value<w.value.length-4&&(l.value++,z(u.value,l.value))}function U(I){l.value=I*4,z(u.value,l.value)}function z(I,P){var Z;if(I){const K=((Z=I.querySelector(".category-chip, .filter-card"))==null?void 0:Z.clientWidth)||100;I.scrollTo({left:P*(K+8),behavior:"smooth"})}}return(I,P)=>{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",H1,[e.createElementVNode("div",Z1,[e.createElementVNode("button",{onClick:$,class:"carousel-nav carousel-nav-left",disabled:s.value===0,"aria-label":"Previous categories","data-testid":"btn-filter-category-prev"},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Gd)},null,8,["icon"])],8,X1),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:ve=>i.value=K.id,class:e.normalizeClass(["category-chip",{active:i.value===K.id}]),"data-testid":`btn-filter-category-${m(K.id)}`,"aria-label":`Filter category ${K.name}`},[e.createVNode(e.unref(W.IonIcon),{icon:K.icon,class:"category-icon"},null,8,["icon"]),e.createElementVNode("span",J1,e.toDisplayString(K.name),1)],10,G1))),128))],512),e.createElementVNode("button",{onClick:y,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(W.IonIcon),{icon:e.unref(Jd)},null,8,["icon"])],8,K1)])])):e.createCommentVNode("",!0),e.createElementVNode("div",q1,[e.createElementVNode("div",Y1,[e.createElementVNode("button",{onClick:R,class:"carousel-nav carousel-nav-left",disabled:l.value===0,"aria-label":"Previous filters","data-testid":"btn-filter-carousel-prev"},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Gd)},null,8,["icon"])],8,Q1),e.createElementVNode("div",{ref_key:"filterCarouselRef",ref:u,class:"filter-carousel"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(w.value,K=>{var ve;return e.openBlock(),e.createElementBlock("div",{key:K.id,class:e.normalizeClass(["filter-card",{active:x(K.id),selected:((ve=r.value)==null?void 0:ve.id)===K.id}]),onClick:Ve=>T(K),onKeydown:[e.withKeys(Ve=>T(K),["enter"]),e.withKeys(e.withModifiers(Ve=>T(K),["prevent"]),["space"])],role:"button",tabindex:"0","data-testid":`btn-video-filter-${m(K.id)}`,"aria-label":`Select filter ${K.name}`},[x(K.id)?(e.openBlock(),e.createElementBlock("div",{key:0,class:"filter-checkmark",onClick:e.withModifiers(Ve=>_(K.id),["stop"])},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Ru)},null,8,["icon"])],8,tw)):e.createCommentVNode("",!0),e.createElementVNode("div",aw,[e.createElementVNode("div",nw,[e.createVNode(e.unref(W.IonIcon),{icon:C(K),class:"filter-icon"},null,8,["icon"])])]),e.createElementVNode("span",ow,e.toDisplayString(K.name),1)],42,ew)}),128))],512),e.createElementVNode("button",{onClick:L,class:"carousel-nav carousel-nav-right",disabled:l.value>=Math.max(0,w.value.length-4),"aria-label":"Next filters","data-testid":"btn-filter-carousel-next"},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Jd)},null,8,["icon"])],8,iw)]),e.createElementVNode("div",rw,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Math.ceil(w.value.length/4),(K,ve)=>(e.openBlock(),e.createElementBlock("span",{key:ve,class:e.normalizeClass(["pagination-dot",{active:Math.floor(l.value/4)===ve}]),onClick:Ve=>U(ve)},null,10,sw))),128))])]),r.value?(e.openBlock(),e.createElementBlock("div",lw,[e.createElementVNode("div",dw,[e.createElementVNode("h4",null,e.toDisplayString(r.value.name),1),e.createElementVNode("div",cw,[x(r.value.id)?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("button",{key:0,onClick:V,class:"apply-btn","data-testid":"btn-apply-selected-filter"}," Apply Filter ")),x(r.value.id)?(e.openBlock(),e.createElementBlock("button",{key:1,onClick:P[0]||(P[0]=K=>_(r.value.id)),class:"remove-btn","data-testid":"btn-remove-selected-filter"}," Remove Filter ")):e.createCommentVNode("",!0),x(r.value.id)&&((Z=r.value.params)==null?void 0:Z.length)>0?(e.openBlock(),e.createElementBlock("button",{key:2,onClick:P[1]||(P[1]=K=>A(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",uw,[(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",mw,[e.createElementVNode("label",pw,e.toDisplayString(K.label||K.id),1),e.createElementVNode("div",fw,[e.createVNode(e.unref(W.IonRange),{value:E(r.value.id,K.id),onIonChange:ve=>S(r.value.id,K.id,ve.detail.value),min:K.min,max:K.max,step:K.step||.01,color:"primary",class:"compact-slider",disabled:!x(r.value.id),"data-testid":`range-filter-${m(r.value.id)}-${m(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",hw,e.toDisplayString(N(E(r.value.id,K.id))),1)])])):K.type==="color"?(e.openBlock(),e.createElementBlock("div",vw,[e.createElementVNode("label",gw,e.toDisplayString(K.label||K.id),1),e.createElementVNode("div",bw,[e.createElementVNode("input",{type:"color",value:E(r.value.id,K.id),onInput:ve=>S(r.value.id,K.id,ve.target.value),disabled:!x(r.value.id),class:"color-input"},null,40,yw),e.createElementVNode("span",ww,e.toDisplayString(E(r.value.id,K.id)),1)])])):K.type==="toggle"?(e.openBlock(),e.createElementBlock("div",kw,[e.createElementVNode("label",_w,e.toDisplayString(K.label||K.id),1),e.createVNode(e.unref(W.IonToggle),{checked:!!E(r.value.id,K.id),onIonChange:ve=>S(r.value.id,K.id,ve.detail.checked),disabled:!x(r.value.id),color:"primary"},null,8,["checked","onIonChange","disabled"])])):K.type==="select"?(e.openBlock(),e.createElementBlock("div",Ew,[e.createElementVNode("label",xw,e.toDisplayString(K.label||K.id),1),e.createElementVNode("select",{value:E(r.value.id,K.id),onChange:ve=>S(r.value.id,K.id,ve.target.value),disabled:!x(r.value.id),class:"select-input"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(K.options,ve=>(e.openBlock(),e.createElementBlock("option",{key:String(ve.value),value:ve.value},e.toDisplayString(ve.label),9,Cw))),128))],40,Sw)])):e.createCommentVNode("",!0)]))),128))])):(e.openBlock(),e.createElementBlock("div",Vw," This filter has no adjustable parameters "))])):e.createCommentVNode("",!0)],2)}}}),_l=Be(Nw,[["__scopeId","data-v-9efd15d9"]]);class Tw{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 Iw={class:"video-filter-preview"},Bw={class:"preview-title"},Mw={class:"filter-controls"},Fw={class:"control-input"},$w=["value","onInput","min","max","step"],Dw={class:"param-value"},Rw={class:"preview-container"},Aw={key:0,class:"filter-presets"},Lw=["onClick"],Pw={class:"preview-actions"},Uw=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 f=e.computed(()=>{var V;return((V=t.filter)==null?void 0:V.paramRanges)||{}}),m=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 V;if(i.value){t.useVideoEngine&&t.composition&&(u=new Tw(t.composition));try{if(l=new Dt.Application,await l.init({width:i.value.clientWidth,height:i.value.clientHeight,background:0,resolution:window.devicePixelRatio||1,autoDensity:!0,canvas:i.value}),(V=t.currentFrame)!=null&&V.dataUrl){const A=await Dt.Assets.load(t.currentFrame.dataUrl);d=new Dt.Sprite(A);const j=Math.min(l.screen.width/d.texture.width,l.screen.height/d.texture.height);d.scale.set(j),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 V={id:t.filter.id,filterId:t.filter.id,params:s.value,intensity:s.value.value??s.value.intensity??1};u.applyFilters([V]).then(()=>{}).catch(A=>{}),c&&(c.destroy(),c=null),c=w(t.filter.id,s.value),c&&(d.filters=r.value?null:[c])}else c&&(c.destroy(),c=null),c=w(t.filter.id,s.value),c&&(d.filters=r.value?null:[c])}function w(V,A){switch(V){case"brightness":{const j=new Dt.ColorMatrixFilter,C=1+(A.value??0);return typeof j.brightness=="function"&&j.brightness(C,!1),j}case"contrast":{const j=new Dt.ColorMatrixFilter,C=A.value??1;return typeof j.contrast=="function"&&j.contrast(C,!1),j}case"saturation":{const j=new Dt.ColorMatrixFilter,C=A.value??1;return typeof j.saturate=="function"&&j.saturate(C,!1),j}case"hue":{const j=new Dt.ColorMatrixFilter,C=A.value??0;return typeof j.hue=="function"&&j.hue(C,!1),j}case"gaussian-blur":{const j=A.value??5;return new Dt.BlurFilter({strength:j,quality:4})}case"sepia":{const j=new Dt.ColorMatrixFilter;return typeof j.sepia=="function"&&j.sepia(!1),j}case"grayscale":{const j=new Dt.ColorMatrixFilter;return typeof j.desaturate=="function"&&j.desaturate(),j}default:return null}}function x(V,A){const j=A.target,C=Number.parseFloat(j.value),$=Number.isFinite(C)?C:0;s.value={...s.value,[V]:$},t.useVideoEngine&&u&&t.filter&&u.updateFilterParams(t.filter.id,s.value),n("update-params",s.value),v()}function T(V){return V.charAt(0).toUpperCase()+V.slice(1).replace(/_/g," ")}function _(V,A){var C;const j=typeof V=="number"?V:Number(V);return Number.isFinite(j)?A==="hue"||A==="angle"?`${j}°`:A==="value"&&((C=t.filter)==null?void 0:C.id)==="brightness"?`${Math.round((1+j)*100)}%`:Number.isInteger(j)?j.toString():j.toFixed(2):"0"}function g(){var V;s.value=((V=t.filter)==null?void 0:V.defaultParams)||{},n("update-params",s.value),v()}function E(V){s.value={...V.params},n("update-params",s.value),v()}function S(V){return JSON.stringify(V.params)===JSON.stringify(s.value)}function N(){n("apply")}return e.watch(()=>t.filter,V=>{V&&(s.value={...V.defaultParams},v())}),e.watch(()=>t.currentFrame,async V=>{if(V!=null&&V.dataUrl&&d){const A=await Dt.Assets.load(V.dataUrl);d.texture=A}}),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()}),(V,A)=>{var j;return e.openBlock(),e.createElementBlock("div",Iw,[e.createElementVNode("h4",Bw,e.toDisplayString((j=V.filter)==null?void 0:j.name)+" Settings",1),e.createElementVNode("div",Mw,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(f.value,(C,$)=>(e.openBlock(),e.createElementBlock("div",{key:$,class:"control-group"},[e.createElementVNode("label",null,e.toDisplayString(T($)),1),e.createElementVNode("div",Fw,[e.createElementVNode("input",{type:"range",value:s.value[$],onInput:y=>x($,y),min:C.min,max:C.max,step:C.step,class:"param-slider"},null,40,$w),e.createElementVNode("span",Dw,e.toDisplayString(_(s.value[$],$)),1)])]))),128))]),e.createElementVNode("div",Rw,[e.createElementVNode("canvas",{ref_key:"previewCanvas",ref:i,class:"preview-canvas"},null,512),e.createElementVNode("button",{class:"compare-button",onMousedown:A[0]||(A[0]=C=>r.value=!0),onMouseup:A[1]||(A[1]=C=>r.value=!1),onTouchstart:A[2]||(A[2]=C=>r.value=!0),onTouchend:A[3]||(A[3]=C=>r.value=!1)},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Yo)},null,8,["icon"]),A[4]||(A[4]=e.createTextVNode(" Hold to compare ",-1))],32)]),m.value?(e.openBlock(),e.createElementBlock("div",Aw,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(p.value,C=>(e.openBlock(),e.createElementBlock("button",{key:C.name,class:e.normalizeClass(["preset-button",{active:S(C)}]),onClick:$=>E(C)},e.toDisplayString(C.name),11,Lw))),128))])):e.createCommentVNode("",!0),e.createElementVNode("div",Pw,[e.createElementVNode("button",{class:"action-button",onClick:g},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Jn)},null,8,["icon"]),A[5]||(A[5]=e.createTextVNode(" Reset ",-1))]),e.createElementVNode("button",{class:"action-button primary",onClick:N},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Au)},null,8,["icon"]),A[6]||(A[6]=e.createTextVNode(" Apply Filter ",-1))])])])}}}),El=Be(Uw,[["__scopeId","data-v-3de3dd04"]]),_m={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"}},Em={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"}},xm={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"}},Sm={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"}},Cm=[_m,Em,xm,Sm],ud={"mobile-share":_m,"hd-web":Em,original:xm,"server-master":Sm},Ow=["mobile-share","hd-web"],zw=["hd-web","original","mobile-share"],jw=["server-master","hd-web","original","mobile-share"];function os(o){return typeof o=="string"?ud[o]:o}function Ww(o){const{bitrate:a,codec:t,format:n,fps:i,quality:r}=os(o).settings,s={format:n,codec:t,quality:r,fps:i};return typeof a=="number"&&(s.bitrate=a),s}function Hw(o){const a=os(o);return a.settings.mobileSuitable&&a.settings.advancedVisibility==="standard"}function Zw(o=Cm){return o.filter(a=>Hw(a))}function Xw(o,a){const t=os(o).settings.maxClientDurationSeconds;return t!==null&&Number.isFinite(a)&&a>=0&&a<=t}function Gw(o,a){const t=os(o),n=a.endpoints.client&&Xw(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 Jw(o,a){return Gw(o,a)!==null}function Kw(o){const a=qw(o);for(const t of a){const n=ud[t];if(Yw(n,o.includeAdvanced===!0)&&!(o.device==="mobile"&&!n.settings.mobileSuitable)&&Jw(n,o))return n}return null}function qw(o){return o.device==="mobile"?Ow:o.includeAdvanced===!0?jw:zw}function Yw(o,a){return o.settings.advancedVisibility==="hidden"?!1:o.settings.advancedVisibility==="standard"||a}const Qw={class:"export-settings"},ek={class:"setting-group preset-setting"},tk={class:"setting-copy"},ak={class:"setting-description"},nk=["value"],ok={key:0,class:"advanced-toggle","data-testid":"export-advanced-toggle"},ik={class:"preset-summary","data-testid":"export-preset-summary"},rk={class:"estimated-size"},sk={key:0,class:"export-progress"},lk={class:"progress-header"},dk={class:"progress-percentage"},ck={class:"progress-time"},uk={class:"action-buttons"},mk=["disabled"],pk=["disabled"],fk=["disabled"],hk={class:"export-options"},vk="hd-web",gk=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=Cm,s={"360p":1,"480p":2.5,"720p":5,"1080p":8,"1440p":16,"2160p":35},l=e.ref(!1),d=e.ref(g()),c=e.ref(!0),u=e.ref(!1),f=e.ref(0),m=e.ref(0),p=e.ref(0);let h=null;const v=e.computed(()=>t.isMobile?Zw():r.filter(C=>C.settings.advancedVisibility==="hidden"?!1:C.settings.advancedVisibility==="standard"||l.value)),w=e.computed(()=>v.value.find(C=>C.id===d.value)??ud[g()]),x=e.computed(()=>Ww(w.value)),T=e.computed(()=>{const C=x.value,$=[C.quality,C.format.toUpperCase(),C.codec.toUpperCase(),`${C.fps} fps`],y=E(C.bitrate);return y!==null&&$.push(y),$.join(" / ")}),_=e.computed(()=>{const C=x.value,y=(typeof C.bitrate=="number"?C.bitrate/1e6:s[C.quality])*t.duration/8;return y<1e3?`~${Math.round(y)} MB`:`~${(y/1e3).toFixed(1)} GB`});function g(){var C;return((C=Kw({durationSeconds:t.duration,device:t.isMobile?"mobile":"desktop",endpoints:i,includeAdvanced:l.value}))==null?void 0:C.id)??vk}function E(C){return typeof C!="number"?null:`${Number((C/1e6).toFixed(1))} Mbps`}function S(){t.isExporting?(n("cancel-export"),A()):N()}function N(){const C=x.value,$={quality:C.quality,format:C.format,optimizeForWeb:c.value,includeWatermark:u.value,presetId:w.value.id,codec:C.codec,fps:C.fps};typeof C.bitrate=="number"&&($.bitrate=C.bitrate),n("export",$),V()}function V(){f.value=Date.now(),m.value=0,h=window.setInterval(()=>{if(m.value=Math.floor((Date.now()-f.value)/1e3),t.exportProgress>0){const C=m.value/t.exportProgress*100;p.value=Math.max(0,C-m.value)}},1e3)}function A(){h&&(clearInterval(h),h=null)}function j(C){const $=Math.floor(C/60),y=Math.floor(C%60);return`${$}:${y.toString().padStart(2,"0")}`}return e.watch([()=>t.isMobile,()=>l.value],()=>{v.value.some($=>$.id===d.value)||(d.value=g())},{immediate:!0}),e.watch(()=>t.isExporting,C=>{C||A()}),e.onUnmounted(()=>{A()}),(C,$)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["editor-controls",{mobile:C.isMobile}])},[e.createElementVNode("div",Qw,[$[8]||($[8]=e.createElementVNode("h3",{class:"section-title"},"Export Settings",-1)),e.createElementVNode("div",ek,[e.createElementVNode("div",tk,[$[6]||($[6]=e.createElementVNode("label",{for:"export-preset-select"},"Preset",-1)),e.createElementVNode("span",ak,e.toDisplayString(w.value.description),1)]),e.withDirectives(e.createElementVNode("select",{id:"export-preset-select","onUpdate:modelValue":$[0]||($[0]=y=>d.value=y),class:"setting-select preset-select","data-testid":"export-preset-select"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(v.value,y=>(e.openBlock(),e.createElementBlock("option",{key:y.id,value:y.id},e.toDisplayString(y.label),9,nk))),128))],512),[[e.vModelSelect,d.value]])]),C.isMobile?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("label",ok,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":$[1]||($[1]=y=>l.value=y),type:"checkbox","data-testid":"export-advanced-toggle-input"},null,512),[[e.vModelCheckbox,l.value]]),$[7]||($[7]=e.createElementVNode("span",null,"Advanced presets",-1))])),e.createElementVNode("div",ik,e.toDisplayString(T.value),1),e.createElementVNode("div",rk,[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Rh)},null,8,["icon"]),e.createElementVNode("span",null,"Estimated size: "+e.toDisplayString(_.value),1)])]),C.isExporting?(e.openBlock(),e.createElementBlock("div",sk,[e.createElementVNode("div",lk,[$[9]||($[9]=e.createElementVNode("span",null,"Exporting...",-1)),e.createElementVNode("span",dk,e.toDisplayString(C.exportProgress??0)+"%",1)]),e.createVNode(e.unref(W.IonProgressBar),{value:(C.exportProgress??0)/100},null,8,["value"]),e.createElementVNode("div",ck,[e.createElementVNode("span",null,e.toDisplayString(j(m.value))+" elapsed",1),e.createElementVNode("span",null,e.toDisplayString(j(p.value))+" remaining",1)])])):e.createCommentVNode("",!0),e.createElementVNode("div",uk,[e.createElementVNode("button",{class:"control-button secondary",onClick:$[2]||($[2]=y=>C.$emit("save-draft")),disabled:!C.canExport||C.isExporting},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(jr)},null,8,["icon"]),$[10]||($[10]=e.createTextVNode(" Save Draft ",-1))],8,mk),e.createElementVNode("button",{class:"control-button secondary",onClick:$[3]||($[3]=y=>C.$emit("reset")),disabled:C.isExporting},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Jn)},null,8,["icon"]),$[11]||($[11]=e.createTextVNode(" Reset ",-1))],8,pk),e.createElementVNode("button",{class:"control-button primary",onClick:S,disabled:!C.canExport&&!C.isExporting,"data-testid":"video-export-button"},[e.createVNode(e.unref(W.IonIcon),{icon:C.isExporting?e.unref(jn):e.unref(ko)},null,8,["icon"]),e.createTextVNode(" "+e.toDisplayString(C.isExporting?"Cancel":"Export Video"),1)],8,fk)]),e.createElementVNode("div",hk,[e.createVNode(e.unref(W.IonItem),{lines:"none"},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonCheckbox),{modelValue:c.value,"onUpdate:modelValue":$[4]||($[4]=y=>c.value=y)},null,8,["modelValue"]),e.createVNode(e.unref(W.IonLabel),null,{default:e.withCtx(()=>[...$[12]||($[12]=[e.createTextVNode("Optimize for web streaming",-1)])]),_:1})]),_:1}),e.createVNode(e.unref(W.IonItem),{lines:"none"},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonCheckbox),{modelValue:u.value,"onUpdate:modelValue":$[5]||($[5]=y=>u.value=y)},null,8,["modelValue"]),e.createVNode(e.unref(W.IonLabel),null,{default:e.withCtx(()=>[...$[13]||($[13]=[e.createTextVNode("Include watermark",-1)])]),_:1})]),_:1})])],2))}}),xl=Be(gk,[["__scopeId","data-v-d26ca1bc"]]),bk={class:"thumbnail-picker"},yk={class:"thumbnail-grid"},wk=["onClick"],kk=["src","alt"],_k={key:1,class:"thumbnail-placeholder"},Ek={class:"thumbnail-time"},xk={class:"custom-selector"},Sk={class:"time-input-group"},Ck=["max"],Vk={class:"time-value"},Nk=["disabled"],Tk={class:"picker-actions"},Ik=["disabled"],Bk=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 x=[];if(t.duration<=10)for(let _=0;_<Math.min(9,t.duration);_++)x.push(_);else{const _=t.duration/10;for(let g=1;g<=9;g++)x.push(_*g)}return x}async function c(x){try{const T=document.createElement("video");return T.crossOrigin="anonymous",T.src=await u(),new Promise(_=>{T.addEventListener("loadedmetadata",()=>{T.currentTime=x}),T.addEventListener("seeked",()=>{const g=document.createElement("canvas");g.width=T.videoWidth,g.height=T.videoHeight;const E=g.getContext("2d");E?(E.drawImage(T,0,0),_(g.toDataURL("image/jpeg",.8))):_(null),T.remove()}),T.addEventListener("error",()=>{_(null),T.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 f(){const x=d();i.value=x.map(_=>({time:_,loading:!0}));const T=3;for(let _=0;_<i.value.length;_+=T){const g=i.value.slice(_,_+T);await Promise.all(g.map(async E=>{const S=await c(E.time);S&&(E.dataUrl=S),E.loading=!1}))}}function m(x){r.value=x,s.value=i.value[x].time}function p(){r.value=-1}async function h(){l.value=!0;try{const x=await c(s.value);if(x){const T=i.value.findIndex(_=>Math.abs(_.time-s.value)<.1);T>=0?(i.value[T].dataUrl=x,r.value=T):(i.value.push({time:s.value,dataUrl:x}),r.value=i.value.length-1,i.value.sort((_,g)=>_.time-g.time),r.value=i.value.findIndex(_=>_.time===s.value))}}finally{l.value=!1}}function v(){const x=r.value>=0?i.value[r.value].time:s.value;n("select",x)}function w(x){const T=Math.floor(x/60),_=Math.floor(x%60),g=Math.floor(x%1*100);return T>0?`${T}:${_.toString().padStart(2,"0")}.${g.toString().padStart(2,"0")}`:`${_}.${g.toString().padStart(2,"0")}s`}return e.onMounted(()=>{f()}),(x,T)=>(e.openBlock(),e.createElementBlock("div",bk,[T[5]||(T[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)=>(e.openBlock(),e.createElementBlock("div",{key:g,class:e.normalizeClass(["thumbnail-item",{selected:r.value===g}]),onClick:E=>m(g)},[_.dataUrl?(e.openBlock(),e.createElementBlock("img",{key:0,src:_.dataUrl,alt:`Frame at ${w(_.time)}`},null,8,kk)):(e.openBlock(),e.createElementBlock("div",_k,[e.createVNode(e.unref(W.IonSpinner),{name:"crescent"})])),e.createElementVNode("div",Ek,e.toDisplayString(w(_.time)),1)],10,wk))),128))]),e.createElementVNode("div",xk,[T[3]||(T[3]=e.createElementVNode("label",null,"Custom time:",-1)),e.createElementVNode("div",Sk,[e.withDirectives(e.createElementVNode("input",{type:"range","onUpdate:modelValue":T[0]||(T[0]=_=>s.value=_),min:0,max:x.duration,step:.1,onInput:p,class:"time-slider"},null,40,Ck),[[e.vModelText,s.value]]),e.createElementVNode("span",Vk,e.toDisplayString(w(s.value)),1)]),e.createElementVNode("button",{class:"capture-button",onClick:h,disabled:l.value},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(xh)},null,8,["icon"]),T[2]||(T[2]=e.createTextVNode(" Capture Frame ",-1))],8,Nk)]),e.createElementVNode("div",Tk,[e.createElementVNode("button",{class:"action-button",onClick:T[1]||(T[1]=_=>x.$emit("cancel"))}," Cancel "),e.createElementVNode("button",{class:"action-button primary",onClick:v,disabled:r.value===-1},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Au)},null,8,["icon"]),T[4]||(T[4]=e.createTextVNode(" Set Thumbnail ",-1))],8,Ik)])]))}}),Mk=Be(Bk,[["__scopeId","data-v-336c322c"]]),Fk={class:"text-overlay-panel p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg"},$k={class:"mb-4"},Dk={class:"space-y-2 max-h-64 overflow-y-auto"},Rk={class:"flex items-center justify-between"},Ak={class:"flex-1"},Lk={class:"font-medium text-gray-900 dark:text-white"},Pk={class:"text-sm text-gray-500 dark:text-gray-400"},Uk={class:"flex items-center space-x-2"},Ok=["onClick"],zk=["onClick"],jk={key:0,class:"text-center py-8 text-gray-500 dark:text-gray-400"},Wk={class:"bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 w-full max-w-lg mx-4"},Hk={class:"text-lg font-semibold text-gray-900 dark:text-white mb-4"},Zk={class:"space-y-4"},Xk={class:"grid grid-cols-2 gap-4"},Gk={class:"grid grid-cols-2 gap-4"},Jk={key:0,class:"p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"},Kk={class:"grid grid-cols-2 gap-3"},qk={class:"flex justify-end space-x-3 mt-6"},Yk=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(m){Object.assign(s,m),i.value=m}function d(){n.value=!1,i.value=null,Object.assign(s,r())}function c(){const m={text:s.text,fontSize:s.fontSize,color:s.color,position:s.position,startTime:s.startTime,duration:s.duration};if(s.animationType&&(m.animation={type:s.animationType},s.animationDuration!==void 0&&(m.animation.duration=s.animationDuration),s.animationEasing&&(m.animation.easing=s.animationEasing),m.animation))switch(s.animationType){case"rotate":m.animation.rotation={from:0,to:360};break;case"scale":m.animation.scale={from:.5,to:1};break;case"slide":m.animation.translate={fromX:-100,toX:0,fromY:0,toY:0};break}i.value?t("update-overlay",i.value.id,m):t("add-overlay",m),d()}function u(m){confirm("Are you sure you want to remove this text overlay?")&&t("remove-overlay",m)}function f(m){const p=Math.floor(m/60),h=Math.floor(m%60);return`${p}:${h.toString().padStart(2,"0")}`}return(m,p)=>(e.openBlock(),e.createElementBlock("div",Fk,[e.createElementVNode("div",$k,[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",Dk,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(m.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",Rk,[e.createElementVNode("div",Ak,[e.createElementVNode("div",Lk,e.toDisplayString(h.text.substring(0,30))+e.toDisplayString(h.text.length>30?"...":""),1),e.createElementVNode("div",Pk,e.toDisplayString(f(h.startTime??0))+" - "+e.toDisplayString(f((h.startTime||0)+(h.duration||5))),1)]),e.createElementVNode("div",Uk,[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,Ok),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,zk)])])]))),128)),m.overlays.length===0?(e.openBlock(),e.createElementBlock("div",jk," 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",Wk,[e.createElementVNode("h4",Hk,e.toDisplayString(i.value?"Edit":"Add")+" Text Overlay ",1),e.createElementVNode("div",Zk,[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",Xk,[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",Gk,[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",Jk,[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",Kk,[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",qk,[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)]))}}),Sl=Be(Yk,[["__scopeId","data-v-f86e688c"]]),Qk={class:"transition-selector p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg"},e2={class:"grid grid-cols-3 gap-3 max-h-96 overflow-y-auto"},t2=["onClick"],a2={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"},n2={key:0,class:"w-8 h-8 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},o2={key:0,"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"},i2={key:1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M14 5l7 7m0 0l-7 7m7-7H3"},r2={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"},s2={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"},l2={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"},d2={class:"text-sm font-medium text-gray-900 dark:text-white text-center"},c2={key:0,class:"mt-4 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"},u2={class:"space-y-3"},m2={class:"flex items-center space-x-2"},p2=["disabled"],f2=["disabled"],h2={key:1,class:"mt-4"},v2={class:"space-y-2 max-h-32 overflow-y-auto"},g2={class:"text-sm text-gray-700 dark:text-gray-300"},b2=["onClick"],y2=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(vi.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 f(){if(!r.value)return;const h={type:r.value.type,duration:s.value,easing:l.value};n("preview-transition",h)}function m(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",Qk,[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",e2,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,w=>{var x;return e.openBlock(),e.createElementBlock("div",{key:w.type,onClick:T=>c(w),class:e.normalizeClass(["transition-item cursor-pointer rounded-lg p-3 border-2 transition-all",((x=r.value)==null?void 0:x.type)===w.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",a2,[p(w.type)?(e.openBlock(),e.createElementBlock("svg",n2,[w.type.includes("fade")?(e.openBlock(),e.createElementBlock("path",o2)):w.type.includes("wipe")?(e.openBlock(),e.createElementBlock("path",i2)):w.type.includes("slide")?(e.openBlock(),e.createElementBlock("path",r2)):w.type.includes("zoom")?(e.openBlock(),e.createElementBlock("path",s2)):(e.openBlock(),e.createElementBlock("path",l2))])):e.createCommentVNode("",!0)]),e.createElementVNode("div",d2,e.toDisplayString(w.name),1)],10,t2)}),128))]),r.value?(e.openBlock(),e.createElementBlock("div",c2,[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",u2,[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",m2,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":v[0]||(v[0]=w=>s.value=w),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]=w=>s.value=w),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]=w=>l.value=w),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,p2),e.createElementVNode("button",{onClick:f,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,f2)])])):e.createCommentVNode("",!0),h.appliedTransitions.length>0?(e.openBlock(),e.createElementBlock("div",h2,[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",v2,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(h.appliedTransitions,(w,x)=>(e.openBlock(),e.createElementBlock("div",{key:x,class:"flex items-center justify-between p-2 bg-gray-50 dark:bg-gray-700 rounded"},[e.createElementVNode("div",g2,e.toDisplayString(w.name)+" ("+e.toDisplayString(w.duration)+"s) ",1),e.createElementVNode("button",{onClick:T=>m(x),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,b2)]))),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))]))}}),Cl=Be(y2,[["__scopeId","data-v-ffcc612d"]]),w2={class:"audio-track-manager p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg"},k2={class:"mb-4"},_2={class:"mb-4 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"},E2={class:"flex items-center justify-between mb-2"},x2={class:"text-sm text-gray-600 dark:text-gray-400"},S2={class:"flex items-center space-x-2"},C2={class:"space-y-3 max-h-64 overflow-y-auto"},V2={class:"flex items-center justify-between mb-2"},N2={class:"font-medium text-gray-900 dark:text-white"},T2={class:"flex items-center space-x-2"},I2=["onClick","title"],B2={key:0,class:"w-5 h-5",fill:"currentColor",viewBox:"0 0 20 20"},M2={key:1,class:"w-5 h-5",fill:"currentColor",viewBox:"0 0 20 20"},F2=["onClick"],$2=["onClick"],D2={class:"flex items-center space-x-2"},R2={class:"text-xs text-gray-500 dark:text-gray-400 w-10"},A2=["value","onInput","disabled"],L2={class:"mt-2 text-xs text-gray-500 dark:text-gray-400"},P2={key:0,class:"ml-2"},U2={key:1,class:"ml-2"},O2={key:0,class:"text-center py-8 text-gray-500 dark:text-gray-400"},z2={class:"bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 w-full max-w-lg mx-4"},j2={class:"text-lg font-semibold text-gray-900 dark:text-white mb-4"},W2={class:"space-y-4"},H2={class:"space-y-2"},Z2={class:"flex items-center"},X2={class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"},G2={class:"grid grid-cols-2 gap-4"},J2={class:"grid grid-cols-2 gap-4"},K2={class:"flex items-center"},q2={class:"flex justify-end space-x-3 mt-6"},Y2=["disabled"],Q2=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(_){const g=_.target;g.files&&g.files[0]&&(d.sourceFile=g.files[0],d.name=d.name||g.files[0].name.replace(/\.[^/.]+$/,""))}function f(_){Object.assign(d,_),r.value=_}function m(){i.value=!1,r.value=null,Object.assign(d,l())}function p(){if(!c.value)return;const _={source:d.sourceFile??d.sourceUrl??"",name:d.name,volume:d.volume,startTime:d.startTime,loop:d.loop};d.duration!==void 0&&(_.duration=d.duration),d.fadeIn>0&&(_.fadeIn=d.fadeIn),d.fadeOut>0&&(_.fadeOut=d.fadeOut),r.value?n("update-track",r.value.id,_):n("add-track",_),m()}function h(_){confirm("Are you sure you want to remove this audio track?")&&n("remove-track",_)}function v(_,g){const E=g.target,S=parseFloat(E.value);n("update-volume",_.id,S)}function w(_){n("toggle-mute",_.id,!_.muted)}function x(){n("update-master-volume",s.value)}function T(_){const g=Math.floor(_/60),E=Math.floor(_%60);return`${g}:${E.toString().padStart(2,"0")}`}return(_,g)=>(e.openBlock(),e.createElementBlock("div",w2,[e.createElementVNode("div",k2,[g[11]||(g[11]=e.createElementVNode("h3",{class:"text-lg font-semibold text-gray-900 dark:text-white mb-2"}," Audio Tracks ",-1)),e.createElementVNode("button",{onClick:g[0]||(g[0]=E=>i.value=!0),class:"w-full px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"},[...g[10]||(g[10]=[e.createElementVNode("svg",{class:"w-5 h-5 inline-block mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 4v16m8-8H4"})],-1),e.createTextVNode(" Add Audio Track ",-1)])])]),e.createElementVNode("div",_2,[e.createElementVNode("div",E2,[g[12]||(g[12]=e.createElementVNode("label",{class:"text-sm font-medium text-gray-700 dark:text-gray-300"}," Master Volume ",-1)),e.createElementVNode("span",x2,e.toDisplayString(Math.round(s.value*100))+"% ",1)]),e.createElementVNode("div",S2,[g[13]||(g[13]=e.createElementVNode("svg",{class:"w-4 h-4 text-gray-500",fill:"currentColor",viewBox:"0 0 20 20"},[e.createElementVNode("path",{"fill-rule":"evenodd",d:"M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM12.293 7.293a1 1 0 011.414 0L15 8.586l1.293-1.293a1 1 0 111.414 1.414L16.414 10l1.293 1.293a1 1 0 01-1.414 1.414L15 11.414l-1.293 1.293a1 1 0 01-1.414-1.414L13.586 10l-1.293-1.293a1 1 0 010-1.414z","clip-rule":"evenodd"})],-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[1]||(g[1]=E=>s.value=E),onInput:x,type:"range",min:"0",max:"1",step:"0.01",class:"flex-1"},null,544),[[e.vModelText,s.value,void 0,{number:!0}]]),g[14]||(g[14]=e.createElementVNode("svg",{class:"w-4 h-4 text-gray-500",fill:"currentColor",viewBox:"0 0 20 20"},[e.createElementVNode("path",{"fill-rule":"evenodd",d:"M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM14.657 2.929a1 1 0 011.414 0l3 3a1 1 0 010 1.414l-3 3a1 1 0 01-1.414-1.414L16.586 7l-1.929-1.929a1 1 0 010-1.414z","clip-rule":"evenodd"})],-1))])]),e.createElementVNode("div",C2,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(_.audioLayers,E=>(e.openBlock(),e.createElementBlock("div",{key:E.id,class:"p-3 border border-gray-200 dark:border-gray-700 rounded-lg"},[e.createElementVNode("div",V2,[e.createElementVNode("div",N2,e.toDisplayString(E.name),1),e.createElementVNode("div",T2,[e.createElementVNode("button",{onClick:S=>w(E),class:e.normalizeClass(["p-1 rounded",E.muted?"text-red-600 bg-red-50 dark:bg-red-900":"text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700"]),title:E.muted?"Unmute":"Mute"},[E.muted?(e.openBlock(),e.createElementBlock("svg",M2,[...g[16]||(g[16]=[e.createElementVNode("path",{"fill-rule":"evenodd",d:"M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM12.293 7.293a1 1 0 011.414 0L15 8.586l1.293-1.293a1 1 0 111.414 1.414L16.414 10l1.293 1.293a1 1 0 01-1.414 1.414L15 11.414l-1.293 1.293a1 1 0 01-1.414-1.414L13.586 10l-1.293-1.293a1 1 0 010-1.414z","clip-rule":"evenodd"},null,-1)])])):(e.openBlock(),e.createElementBlock("svg",B2,[...g[15]||(g[15]=[e.createElementVNode("path",{"fill-rule":"evenodd",d:"M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM14.657 2.929a1 1 0 011.414 0l3 3a1 1 0 010 1.414l-3 3a1 1 0 01-1.414-1.414L16.586 7l-1.929-1.929a1 1 0 010-1.414z","clip-rule":"evenodd"},null,-1)])]))],10,I2),e.createElementVNode("button",{onClick:S=>f(E),class:"p-1 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900 rounded",title:"Settings"},[...g[17]||(g[17]=[e.createElementVNode("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})],-1)])],8,F2),e.createElementVNode("button",{onClick:S=>h(E.id),class:"p-1 text-red-600 hover:bg-red-50 dark:hover:bg-red-900 rounded",title:"Remove"},[...g[18]||(g[18]=[e.createElementVNode("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})],-1)])],8,$2)])]),e.createElementVNode("div",D2,[e.createElementVNode("span",R2,e.toDisplayString(Math.round((E.volume||1)*100))+"% ",1),e.createElementVNode("input",{value:E.volume||1,onInput:S=>v(E,S),type:"range",min:"0",max:"1",step:"0.01",class:"flex-1",disabled:E.muted},null,40,A2)]),e.createElementVNode("div",L2,[e.createTextVNode(e.toDisplayString(T(E.startTime||0))+" - "+e.toDisplayString(T((E.startTime||0)+(E.duration||0)))+" ",1),E.fadeIn?(e.openBlock(),e.createElementBlock("span",P2,"Fade In: "+e.toDisplayString(E.fadeIn)+"s",1)):e.createCommentVNode("",!0),E.fadeOut?(e.openBlock(),e.createElementBlock("span",U2,"Fade Out: "+e.toDisplayString(E.fadeOut)+"s",1)):e.createCommentVNode("",!0)])]))),128)),_.audioLayers.length===0?(e.openBlock(),e.createElementBlock("div",O2," 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(m,["self"])},[e.createElementVNode("div",z2,[e.createElementVNode("h4",j2,e.toDisplayString(r.value?"Edit":"Add")+" Audio Track ",1),e.createElementVNode("div",W2,[e.createElementVNode("div",null,[g[20]||(g[20]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Audio Source ",-1)),e.createElementVNode("div",H2,[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",Z2,[g[19]||(g[19]=e.createElementVNode("span",{class:"text-sm text-gray-500 dark:text-gray-400 mr-2"},"or URL:",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[2]||(g[2]=E=>d.sourceUrl=E),type:"url",placeholder:"https://example.com/audio.mp3",class:"flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,d.sourceUrl]])])])]),e.createElementVNode("div",null,[g[21]||(g[21]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Track Name ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[3]||(g[3]=E=>d.name=E),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":g[4]||(g[4]=E=>d.volume=E),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",G2,[e.createElementVNode("div",null,[g[22]||(g[22]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Start Time (seconds) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[5]||(g[5]=E=>d.startTime=E),type:"number",min:"0",step:"0.1",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,d.startTime,void 0,{number:!0}]])]),e.createElementVNode("div",null,[g[23]||(g[23]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Duration (seconds) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[6]||(g[6]=E=>d.duration=E),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",J2,[e.createElementVNode("div",null,[g[24]||(g[24]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Fade In (seconds) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[7]||(g[7]=E=>d.fadeIn=E),type:"number",min:"0",max:"10",step:"0.1",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,d.fadeIn,void 0,{number:!0}]])]),e.createElementVNode("div",null,[g[25]||(g[25]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Fade Out (seconds) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[8]||(g[8]=E=>d.fadeOut=E),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",K2,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[9]||(g[9]=E=>d.loop=E),type:"checkbox",id:"loop-checkbox",class:"mr-2 rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500"},null,512),[[e.vModelCheckbox,d.loop]]),g[26]||(g[26]=e.createElementVNode("label",{for:"loop-checkbox",class:"text-sm text-gray-700 dark:text-gray-300"}," Loop audio track ",-1))])]),e.createElementVNode("div",q2,[e.createElementVNode("button",{onClick:m,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,Y2)])])])):e.createCommentVNode("",!0)]))}}),Vl=Be(Q2,[["__scopeId","data-v-593719ac"]]);function it(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 xc(o){return typeof o=="boolean"?o?"On":"Off":typeof o=="number"?Number.isInteger(o)?String(o):o.toFixed(2):String(o??"")}let Sc=!1;function e_(){if(Sc)return;Sc=!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 t_{constructor({filters:a=[],callbacks:t={}}){e_(),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=it("div",{className:"mvfp"}),this._catRow=it("div",{className:"mvfp-row"}),this._root.appendChild(this._catRow),this._filterRow=it("div",{className:"mvfp-row"}),this._root.appendChild(this._filterRow),this._activeRow=it("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=it("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=it("div",{className:`mvfp-filter${t?" active":""}${n?" selected":""}`,onClick:()=>this._selectFilter(a)});if(t){const r=it("div",{className:"mvfp-check",onClick:s=>{s.stopPropagation(),this._removeFilter(a.id)}});r.innerHTML="✓",i.appendChild(r)}i.appendChild(it("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(it("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=it("div",{className:`mvfp-achip${i?" selected":""}`}),s=it("span",{style:{cursor:"pointer"},onClick:()=>{this._selectedFilterId=t,this._renderFilters(),n.params&&n.params.length>0&&this.openDrawer(t)}},n.name),l=it("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=it("div",{className:"mvfp-drawer"});const a=it("div",{className:"mvfp-drawer-hdr"});this._drawerTitle=it("span",{className:"mvfp-drawer-title"},"Filter");const t=it("div",{className:"mvfp-drawer-actions"});t.appendChild(it("button",{className:"mvfp-drawer-btn",onClick:()=>this._resetDrawerFilter()},"Reset")),t.appendChild(it("button",{className:"mvfp-drawer-btn danger",onClick:()=>{this._drawerFilterId&&(this._removeFilter(this._drawerFilterId),this.closeDrawer())}},"Remove"));const n=it("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=it("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(it("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=it("div",{className:"mvfp-ctl"}),l=it("label",{className:"mvfp-ctl-label"},i.label||i.id);s.appendChild(l);const d=i.type||"slider";if(d==="slider"||d==="range"){const c=it("div",{className:"mvfp-slider-row"}),u=it("span",{className:"mvfp-range-val"},xc(r)),f=it("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:m=>{var h,v;const p=parseFloat(m.target.value);u.textContent=xc(p),(v=(h=this._cb).onUpdateParam)==null||v.call(h,a.id,i.id,p)}});c.appendChild(f),c.appendChild(u),s.appendChild(c)}else if(d==="toggle"||d==="checkbox"){const c=it("div",{className:"mvfp-toggle-row"}),u=it("input",{type:"checkbox",checked:r?"checked":void 0,onChange:f=>{var m,p;return(p=(m=this._cb).onUpdateParam)==null?void 0:p.call(m,a.id,i.id,f.target.checked)}});c.appendChild(u),s.appendChild(c)}else if(d==="color"){const c=it("div",{className:"mvfp-color-row"}),u=it("input",{type:"color",className:"mvfp-color-input",value:typeof r=="string"?r:"#000000",onInput:f=>{var m,p;return(p=(m=this._cb).onUpdateParam)==null?void 0:p.call(m,a.id,i.id,f.target.value)}});c.appendChild(u),s.appendChild(c)}else if(d==="select"||d==="dropdown"){const c=it("div",{className:"mvfp-select-row"}),u=it("select",{className:"mvfp-select",onChange:f=>{var m,p;return(p=(m=this._cb).onUpdateParam)==null?void 0:p.call(m,a.id,i.id,f.target.value)}});for(const f of i.options||[]){const m=it("option",{value:f.value},f.label||String(f.value));f.value===r&&(m.selected=!0),u.appendChild(m)}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 a_=[200,500,1e3];function n_(o){return{"360p":[640,360],"480p":[854,480],"720p":[1280,720],"1080p":[1920,1080],"1440p":[2560,1440],"2160p":[3840,2160]}[o??""]??[1920,1080]}function Cc(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 o_(o){return new Promise(a=>{window.setTimeout(a,o)})}async function Vc(){return await Promise.resolve().then(()=>require("./PixiFrameExporter-BnAievFi.cjs"))}function Nc(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 Vm(o){let a=null;return{canExportClientSide:async()=>{try{const{isWebCodecsSupported:i}=await Vc();return i()}catch{return!1}},renderRecipeWithPixi:async(i,r,s)=>{var p,h,v,w;const l=i.timeline[0],d=l?Math.max(0,l.sourceIn):0,c=l?l.sourceOut:void 0,[u,f]=n_((r==null?void 0:r.quality)??((p=i.output)==null?void 0:p.quality)),m=((h=i.output)==null?void 0:h.fps)||30;o.setPlaying(!1),o.forcePixiPreview.value=!0,await e.nextTick();try{let x=!1;for(const R of a_){await o_(R);const L=o.getPreviewRef();if(!(!L||typeof L.captureFrameAt!="function")){if(typeof L.ensureReadyForCapture=="function"){if(x=await L.ensureReadyForCapture(),x)break;continue}x=!0;break}}const T=o.getPreviewRef();if(!T||typeof T.captureFrameAt!="function")throw new Error("PIXI preview not available for export. Ensure the preview is mounted.");if(!x)throw new Error("PIXI preview not ready for frame capture after retries. The video may still be loading.");const{exportWithPixiFrames:_,isWebCodecsSupported:g}=await Vc();if(!g())throw new Error("WebCodecs is not supported in this browser. Export requires Chrome 94+ or equivalent.");a=new AbortController;const E={width:u,height:f,fps:m,trimStart:d,signal:a.signal};c!==void 0&&(E.trimEnd=c),s&&(E.onProgress=s);const S=o.getSourceUrl();S!==""&&(E.sourceUrl=S);const N=Cc(T)??((v=i.source)==null?void 0:v.duration)??c??0,V=await _({captureFrameAt:R=>{var L;return((L=T.captureFrameAt)==null?void 0:L.call(T,R))??Promise.resolve(null)},duration:{value:N}},E),A=new File([V],`edited-video-${Date.now()}.mp4`,{type:"video/mp4"}),j=Cc(T),C=((w=i.source)==null?void 0:w.duration)??0,y=Math.max(0,(c??j??C)-d);return{file:A,recipe:i,meta:{duration:y,width:u,height:f,format:"mp4",sizeBytes:A.size,size_bytes:A.size}}}finally{o.forcePixiPreview.value=!1,a=null}},cancelClientExport:()=>{a==null||a.abort(),a=null},resetClientExport:()=>{a=null}}}const So="default-video-track",yn="default-media-source";function Nm(o){var r,s;const a=r_(o),t=s_(o),n=l_(o.timeline,((r=t[0])==null?void 0:r.id)??So,((s=a[0])==null?void 0:s.id)??yn),i={version:o.version,source:{...o.source},mediaSources:a,tracks:d_(t,n),clips:n,markers:o.markers?o.markers.map(l=>({...l})):[],transitions:o.transitions?o.transitions.map(Bm):[],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(Mm)),o.visualLayers&&(i.visualLayers=o.visualLayers.map(Fm)),o.audioTracks&&(i.audioTracks=[...o.audioTracks]),o.posterFrame&&(i.posterFrame=o.posterFrame),o.metadata&&(i.metadata={...o.metadata}),i}function i_(o){const a={version:"1.0",source:{...o.source},timeline:o.clips.map(t=>({...t})),mediaSources:o.mediaSources.map(Tm),tracks:o.tracks.map(Im),markers:o.markers.map(t=>({...t})),transitions:o.transitions.map(Bm),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(Mm)),o.visualLayers&&(a.visualLayers=o.visualLayers.map(Fm)),o.audioTracks&&(a.audioTracks=[...o.audioTracks]),o.posterFrame&&(a.posterFrame=o.posterFrame),o.metadata&&(a.metadata={...o.metadata}),a}function r_(o){var t,n;if(o.mediaSources&&o.mediaSources.length>0)return o.mediaSources.map(Tm);const a={id:((t=o.timeline.find(i=>i.sourceRefId))==null?void 0:t.sourceRefId)??yn,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 s_(o){var a;return o.tracks&&o.tracks.length>0?o.tracks.map(Im):[{id:((a=o.timeline.find(t=>t.trackId))==null?void 0:a.trackId)??So,type:"video",name:"Video",order:0}]}function l_(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 d_(o,a){return o.map(t=>{const n=a.filter(i=>i.trackId===t.id).map(i=>i.id);return{...t,clipIds:n}})}function Tm(o){const a={...o};return o.metadata&&(a.metadata={...o.metadata}),a}function Im(o){const a={...o};return o.clipIds&&(a.clipIds=[...o.clipIds]),a}function Bm(o){const a={...o};return o.params&&(a.params={...o.params}),a}function Mm(o){return{...o,segments:o.segments.map(t=>{const n={...t};return t.words&&(n.words=t.words.map(i=>({...i}))),n})}}function Fm(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 $m="video-project-draft-snapshot:v1",Nl="mediables:video-project-drafts",c_=(o,a={})=>{var m,p;const t=tn(a.now)??Date.now(),n=tn(a.createdAt)??t,i=tn(a.updatedAt)??t,r=__(o),s={id:Ea(a.id)??C_(i),payloadKind:r,createdAt:new Date(n).toISOString(),updatedAt:new Date(i).toISOString(),deviceKind:a.deviceKind??"unknown"},l=Ea(a.projectId),d=Ea(a.sourceMediaUuid)??Ea(o.source.media_uuid),c=Tl(a.durationSeconds)??E_(o),u=Ea(a.editorVersion)??Ea((m=o.metadata)==null?void 0:m.editor_version),f=Ea(a.title)??Ea((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),f!==null&&(s.title=f),a.saveReason!==void 0&&(s.saveReason=a.saveReason),{schemaVersion:$m,metadata:s,payload:o}},Dm=(o,a=Nl)=>{const t=Ea(a)??Nl,n=Fc(o.metadata.projectId??"unsaved-project"),i=Fc(o.metadata.id);return`${t}:${n}:${i}`},u_=o=>JSON.stringify(o),m_=o=>{if(typeof o!="string"||o.trim().length===0)return null;try{const a=JSON.parse(o);return y_(a)?a:null}catch{return null}},p_=o=>{const a=[];for(const t of o){const n=Ea(t.key),i=m_(t.value);n===null||i===null||a.push({key:n,snapshot:i})}return di(a)},f_=(o,a)=>{const t=S_(a.maxCount),n=tn(a.now)??Date.now(),i=Um(a.maxAgeMs),r=[],s=[];let l=0;for(const d of di(o)){if(!Lm(d,a.projectId)){r.push(d);continue}if(Pm(d.snapshot,n,i)||l>=t){s.push(d);continue}r.push(d),l+=1}return{retained:di(r),removed:di(s)}},h_=(o,a={})=>{const t={key:Dm(o),snapshot:o};if(!Lm(t,a.projectId))return!1;const n=tn(a.now)??Date.now(),i=Um(a.maxAgeMs);if(Pm(o,n,i))return!1;const r=a.savedAt===null?null:tn(a.savedAt);return r===null?!0:Mr(o)>r},v_=(o,a={})=>di(o).filter(t=>h_(t.snapshot,a)),g_=(o,a,t={})=>{const n=v_(o,t);if(a==="mobile"){const i=n[0]??null;return i===null?[]:[i]}return n},b_=async(o,a,t=Dm(a))=>(await o.setItem(t,u_(a)),{key:t,snapshot:a}),Tc=async(o,a=Nl)=>{const t=await o.listKeys(a),n=[];for(const i of t)n.push({key:i,value:await o.getItem(i)});return p_(n)},Ic=async(o,a)=>{for(const t of a)await o.removeItem(t.key)},y_=o=>!an(o)||o.schemaVersion!==$m||!w_(o.metadata)?!1:o.metadata.payloadKind==="project"?Rm(o.payload):k_(o.payload),w_=o=>an(o)?md(o.id)&&N_(o.payloadKind)&&Mc(o.createdAt)&&Mc(o.updatedAt)&&T_(o.deviceKind)&&er(o.projectId)&&er(o.sourceMediaUuid)&&V_(o.durationSeconds)&&er(o.editorVersion)&&er(o.title)&&I_(o.saveReason):!1,k_=o=>an(o)?o.version==="1.0"&&Am(o.source)&&Array.isArray(o.timeline)&&Array.isArray(o.filters)&&an(o.audio)&&an(o.output):!1,Rm=o=>an(o)?o.version==="1.0"&&Am(o.source)&&Array.isArray(o.mediaSources)&&Array.isArray(o.tracks)&&Array.isArray(o.clips)&&Array.isArray(o.markers)&&Array.isArray(o.filters)&&an(o.audio)&&an(o.output):!1,Am=o=>an(o)?md(o.media_uuid)&&ci(o.duration)&&ci(o.original_width)&&ci(o.original_height):!1,__=o=>Rm(o)?"project":"recipe",E_=o=>Tl(o.duration)??Tl(o.source.duration),Lm=(o,a)=>{const t=Ea(a);return t===null?!0:o.snapshot.metadata.projectId===t},Pm=(o,a,t)=>t===null?!1:a-Mr(o)>t,di=o=>[...o].sort(x_),x_=(o,a)=>{const t=Mr(a.snapshot)-Mr(o.snapshot);if(t!==0)return t;const n=Bc(a.snapshot)-Bc(o.snapshot);return n!==0?n:o.snapshot.metadata.id.localeCompare(a.snapshot.metadata.id)},Mr=o=>tn(o.metadata.updatedAt)??0,Bc=o=>tn(o.metadata.createdAt)??0,S_=o=>!Number.isFinite(o)||o<0?0:Math.floor(o),Um=o=>o===void 0||!Number.isFinite(o)||o<0?null:Math.floor(o),tn=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},Mc=o=>typeof o=="string"&&tn(o)!==null,C_=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}`},Fc=o=>encodeURIComponent(o.trim()),Ea=o=>{if(typeof o!="string")return null;const a=o.trim();return a.length>0?a:null},md=o=>Ea(o)!==null,er=o=>o===void 0||md(o),Tl=o=>{if(!ci(o))return null;const a=Number(o.toFixed(6));return Object.is(a,-0)?0:a},ci=o=>typeof o=="number"&&Number.isFinite(o)&&o>=0,V_=o=>o===void 0||ci(o),N_=o=>o==="recipe"||o==="project",T_=o=>o==="desktop"||o==="mobile"||o==="tablet"||o==="unknown",I_=o=>o===void 0||o==="autosave"||o==="manual"||o==="before-export"||o==="before-close",an=o=>typeof o=="object"&&o!==null&&!Array.isArray(o),B_=1,M_="master",gi=-60,Il=12,pd=0,wn=-90,Fr=6,F_=4,Om=8;function zm(){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:Om}}}function $_(o,a=zm()){return Ml(a[o])}function jm(o){return Number.isNaN(o)?pd:o<=0||o===Number.NEGATIVE_INFINITY?gi:bi(20*Math.log10(o))}function Bl(o){const a=bi(o);return a<=gi?0:_n(Math.pow(10,a/20),6)}function bi(o){return Number.isNaN(o)?pd:o===Number.NEGATIVE_INFINITY?gi:o===Number.POSITIVE_INFINITY?Il:_n(Ti(o,gi,Il),3)}function Wm(o){return Number.isFinite(o)?_n(Ti(o,-1,1),3):0}function D_(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 R_(o,a={}){const t=X_(a.effectSlotCount),n=new Set;return{schemaVersion:B_,capabilities:a.capabilities?q_(a.capabilities):zm(),tracks:o.map((i,r)=>L_(i,r,t,n)),master:P_(a.master,t)}}function Hm(o){const a=bi(o);return{valueDb:a,minDb:gi,maxDb:Il,unityDb:pd,linearGain:Bl(a)}}function A_(o,a="constant-power"){return{value:Wm(o),mode:a}}function Zm(o=wn,a=wn,t=o){const n=Os(o),i=Os(a),r=Os(t);return{peakDb:n,rmsDb:i,peakHoldDb:r,clipping:n>=0||r>=0}}function Xm(o){const a=Km(o);return{id:`empty-effect-slot-${a}`,index:a,kind:"empty",label:"Empty",enabled:!1,bypassed:!0,wetMix:0,parameters:{}}}function L_(o,a,t,n){const i=Jm(o.id),s={id:Z_(i??`legacy-audio-track-${a+1}`,n),kind:"legacy-url",name:j_(o.name,a),order:a,source:U_(o.source),controls:{fader:Hm(o.faderDb??jm(o.volume??1)),pan:A_(o.pan??0),muted:o.muted??!1,solo:o.solo??!1,meter:Zm(o.peakDb,o.rmsDb,o.peakHoldDb)},timeline:O_(o),effectSlots:Gm(o.effectSlots,t)};return i!==void 0&&(s.legacyTrackId=i),s}function P_(o,a){return{id:M_,name:W_(o==null?void 0:o.name),fader:Hm((o==null?void 0:o.faderDb)??jm((o==null?void 0:o.volume)??1)),muted:(o==null?void 0:o.muted)??!1,meter:Zm(o==null?void 0:o.peakDb,o==null?void 0:o.rmsDb,o==null?void 0:o.peakHoldDb),effectSlots:Gm(o==null?void 0:o.effectSlots,a)}}function U_(o){const a=o.trim();return a===""?{type:"missing"}:{type:"url",url:a}}function O_(o){const a={startTime:J_(o.startTime??0),loop:o.loop??!1},t=G_(o.duration);t!==void 0&&(a.duration=t);const n=$c(o.fadeIn);n!==void 0&&(a.fadeIn=n);const i=$c(o.fadeOut);return i!==void 0&&(a.fadeOut=i),a}function Gm(o,a){const t=new Map;for(const n of o??[]){const i=z_(n,a);t.set(i.index,i)}return Array.from({length:a},(n,i)=>t.get(i)??Xm(i))}function z_(o,a){const t=Km(o.index),n=a>0?Math.min(t,a-1):0,i=o.kind;return i==="empty"?Xm(n):{id:Jm(o.id)??`${i}-effect-slot-${n}`,index:n,kind:i,label:H_(o.label,i),enabled:o.enabled,bypassed:o.bypassed,wetMix:K_(o.wetMix),parameters:{...o.parameters}}}function j_(o,a){const t=o==null?void 0:o.trim();return t&&t!==""?t:`Audio ${a+1}`}function W_(o){const a=o==null?void 0:o.trim();return a&&a!==""?a:"Master"}function H_(o,a){const t=o.trim();return t!==""?t:a}function Z_(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 Jm(o){const a=o==null?void 0:o.trim();if(!(!a||a===""))return a}function X_(o){return o===void 0||!Number.isFinite(o)?F_:Math.trunc(Ti(o,0,Om))}function Km(o){return!Number.isFinite(o)||o<0?0:Math.trunc(o)}function G_(o){if(!(o===void 0||!Number.isFinite(o)||o<=0))return _n(o,3)}function $c(o){if(!(o===void 0||!Number.isFinite(o)||o<0))return _n(o,3)}function J_(o){return!Number.isFinite(o)||o<0?0:_n(o,3)}function K_(o){return Number.isFinite(o)?_n(Ti(o,0,1),3):1}function Os(o){return Number.isNaN(o)||o===Number.NEGATIVE_INFINITY?wn:o===Number.POSITIVE_INFINITY?Fr:_n(Ti(o,wn,Fr),3)}function q_(o){return{mobile:Ml(o.mobile),desktop:Ml(o.desktop)}}function Ml(o){return{...o}}function Ti(o,a,t){return Math.min(t,Math.max(a,o))}function _n(o,a){const t=10**a;return Math.round(o*t)/t}const Y_=/^(\d{2,}:[0-5]\d:[0-5]\d,\d{3})\s+-->\s+(\d{2,}:[0-5]\d:[0-5]\d,\d{3})$/,Q_=/^(\d{2,}):([0-5]\d):([0-5]\d),(\d{3})$/,eE="srt-cue";class kn extends Error{constructor(a,t,n={}){super(t),this.name="CaptionSrtError",this.code=a,this.context=n}}function tE(o,a={}){var s,l;const t=aE(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&&Pc(n[r]);)r+=1;if(r>=n.length)break;const d=r+1,c=nE(((s=n[r])==null?void 0:s.trim())??"",d);if(r+=1,r>=n.length)throw new kn("missing-timing",`Cue ${c} is missing its timing line.`,{cueIndex:i.length,cueNumber:c,lineNumber:d});const u=r+1,f=oE(((l=n[r])==null?void 0:l.trim())??"",c,u);r+=1;const m=[];for(;r<n.length&&!Pc(n[r]);)m.push(n[r]??""),r+=1;i.push({cueNumber:c,id:`${t}-${i.length+1}`,startTime:f.startTime,endTime:f.endTime,text:m.join(`
|
|
339
|
-
`)})}return qm(i),i}function Dc(o){return qm(o),o.length===0?"":`${o.map((a,t)=>rE(a,t+1)).join(`
|
|
340
|
-
|
|
341
|
-
`)}
|
|
342
|
-
`}function qm(o){const a=o.map((t,n)=>{const i=Lc(t,n),r=Fl(t.startTime,"startTime",i),s=Fl(t.endTime,"endTime",i);if(s<=r)throw new kn("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 kn("overlapping-cues",`Caption cue "${i.cue.id}" overlaps cue "${n.cue.id}".`,Lc(i.cue,i.cueIndex))}}function Rc(o){const a=Fl(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 aE(o){return o===void 0||o.trim()===""?eE:o.trim()}function nE(o,a){if(!/^[1-9]\d*$/.test(o))throw new kn("invalid-cue-number",`Invalid SRT cue number at line ${a}.`,{lineNumber:a});return Number.parseInt(o,10)}function oE(o,a,t){const n=Y_.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 kn("invalid-timing",`Invalid SRT timing line for cue ${a} at line ${t}.`,{cueNumber:a,lineNumber:t});return{startTime:Ac(i,a,t),endTime:Ac(r,a,t)}}function Ac(o,a,t){const n=Q_.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 kn("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),f=Number.parseInt(l,10);return d*60*60+c*60+u+f/1e3}function Fl(o,a,t){if(!Number.isFinite(o)||o<0)throw new kn("invalid-time",`Caption cue ${a} must be a finite, non-negative number.`,t);return Math.round(o*1e3)}function Lc(o,a){const t={cueIndex:a,segmentId:o.id},n=iE(o);return n!==void 0&&(t.cueNumber=n),t}function iE(o){if(!(!("cueNumber"in o)||typeof o.cueNumber!="number"))return o.cueNumber}function rE(o,a){return[a.toString(),`${Rc(o.startTime)} --> ${Rc(o.endTime)}`,sE(o.text)].join(`
|
|
343
|
-
`)}function sE(o){return o.replace(/\r\n?/g,`
|
|
344
|
-
`)}function Pc(o){return o===void 0||o.trim()===""}const lE=["linear","ease-in","ease-out","ease-in-out"];class $r extends Error{constructor(a,t="Invalid keyframe automation."){super(t),this.name="KeyframeAutomationError",this.issues=a}}const dE={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 cE(o){return typeof o=="string"&&lE.includes(o)}function uE(o){return o==="mobile"?{platform:o,editingMode:"preset-only",canApplyPresets:!0,canEditKeyframes:!1}:{platform:o,editingMode:"detailed",canApplyPresets:!0,canEditKeyframes:!0}}function mE(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 Ym(o,a={}){const t=[],n=new Set,i={...dE,...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})}cE(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 pE(o,a={}){const t=mE(o),n=Ym(t,a);if(!n.valid)throw new $r(n.issues);return t}function fE(o={}){return fd({id:"fade-in",label:"Fade in",target:"opacity",startValue:o.fromOpacity??0,endValue:o.toOpacity??1,timing:hd(o,"ease-out")})}function hE(o={}){return fd({id:"fade-out",label:"Fade out",target:"opacity",startValue:o.fromOpacity??1,endValue:o.toOpacity??0,timing:hd(o,"ease-in")})}function vE(o={}){return fd({id:"zoom-in",label:"Zoom in",target:"scale",startValue:o.fromScale??1,endValue:o.toScale??1.1,timing:hd(o,"ease-out")})}function fd(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=Ym(a,{target:o.target});if(!t.valid)throw new $r(t.issues);return{id:o.id,label:o.label,target:o.target,editingMode:"preset-only",keyframes:a}}function hd(o,a){const t=o.startTime??0,n=o.duration??1;if(!Number.isFinite(t)||t<0)throw new $r([{code:"invalid-time",message:"Preset start time must be a finite non-negative number.",time:t}]);if(!Number.isFinite(n)||n<=0)throw new $r([{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 Hn extends Error{constructor(a,t){super(t),this.name="VisualLayerSchemaError",this.code=a}}function gE(o){gd(o.id,"caption track id");const a={id:o.id,source:o.source,stylePreset:o.stylePreset??"default",animation:o.animation??"none",segments:bE(o.segments)};return o.language!==void 0&&(a.language=o.language),a}function bE(o){const a=o.map(t=>{gd(t.id,"caption segment id");const n=vd(t.startTime,"caption segment startTime"),i=Qm(t.endTime,"caption segment endTime");if(i<=n)throw new Hn("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 Hn("invalid-caption-segment",`Caption segment "${i.id}" overlaps segment "${n.id}".`)}return a}function yE(o,a){return a.map(t=>{gd(t.id,"caption word id");const n=vd(t.startTime,"caption word startTime"),i=Qm(t.endTime,"caption word endTime");if(i<=n)throw new Hn("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 vd(o,a){const t=wE(o,a);if(t<0)throw new Hn("invalid-time",`${a} must be non-negative.`);return Math.round(t*1e3)/1e3}function Qm(o,a){const t=vd(o,a);if(t<=0)throw new Hn("invalid-duration",`${a} must be greater than zero.`);return t}function wE(o,a){if(!kE(o))throw new Hn("invalid-time",`${a} must be a finite number.`);return o}function gd(o,a){if(o.trim()==="")throw new Hn("empty-id",`${a} cannot be empty.`)}function kE(o){return Number.isFinite(o)}function Uc(o){var f,m,p,h;_E(o);const a=SE(o),t=CE(o),n=((f=a[0])==null?void 0:f.id)??yn,i=((m=t[0])==null?void 0:m.id)??So,r=EE(o.clips,i,n),s=VE(t,r),l=[],d=BE(o),c=ME(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(w=>{const x={...w};return w.words&&(x.words=w.words.map(T=>({...T}))),x})}))),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(IE)),u}function _E(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=xE(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 EE(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),f=s?Number(n.sourceOut):Number(c)+l/i;f>u||(f=u+Math.max(.033,l/Math.max(1e-6,i)));const m={id:n.id,type:n.type??"clip",trackId:n.trackId??a,sourceRefId:n.sourceRefId??t,timelineStart:n.timelineStart,timelineEnd:n.timelineEnd,sourceIn:u,sourceOut:f,speed:i,filters:n.filters?[...n.filters]:[]};return n.keyframes&&(m.keyframes=n.keyframes.map(p=>({...p}))),m})}function xE(o){return o.trackId??`legacy-track-${o.track??0}`}function SE(o){var t,n,i,r,s,l,d,c;if(o.mediaSources&&o.mediaSources.length>0)return o.mediaSources.map(NE);const a={id:((t=o.clips.find(u=>u.sourceRefId))==null?void 0:t.sourceRefId)??yn,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 CE(o){var a;return o.tracks&&o.tracks.length>0?o.tracks.map(TE):[{id:((a=o.clips.find(t=>t.trackId))==null?void 0:a.trackId)??So,type:"video",name:"Video",order:0}]}function VE(o,a){return o.map(t=>({...t,clipIds:a.filter(n=>n.trackId===t.id).map(n=>n.id)}))}function NE(o){const a={...o};return o.metadata&&(a.metadata={...o.metadata}),a}function TE(o){const a={...o};return o.clipIds&&(a.clipIds=[...o.clipIds]),a}function IE(o){const a={...o};return o.params&&(a.params={...o.params}),a}function BE(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 ME(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 Ua(o){return arguments.length===0?{ok:!0,value:void 0}:{ok:!0,value:o}}function It(o,a){return{ok:!1,reason:o,message:a}}const FE={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 Yt(o){return FE[o]}const ui=1e-6;function zs(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($E(a,o.desiredDuration,t))return{ok:!0,start:a};let n=a;for(const i of t)if(!(i.timelineEnd<=n+ui)){if(i.timelineStart-n>=o.desiredDuration-ui&&n+ui>=a)return{ok:!0,start:n};n=Math.max(n,i.timelineEnd)}return{ok:!0,start:n}}function $E(o,a,t){const n=o+a;for(const i of t)if(!(i.timelineEnd<=o+ui)&&!(i.timelineStart>=n-ui))return!1;return!0}const DE={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 Oc(o,a){return DE[a].has(o)}function RE(o){const a=new Set;for(const t of o.clips)typeof t.sourceRefId=="string"&&t.sourceRefId!==""&&a.add(t.sourceRefId);return a}function AE(o,a){return RE(o).has(a)}function tr(o,a=30){const t=typeof o=="number"?o:Number(o);return Number.isFinite(t)&&t>0?t:a}function ep(o,a,t){var mt,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),f=tr(((mt=a==null?void 0:a.output)==null?void 0:mt.fps)??(t==null?void 0:t.frame_rate)),m=e.shallowRef(null),p=new km(f),h=e.ref(f),v=e.ref(!1),w=e.ref(!1);a&&a.timeline&&a.timeline.length>0?($(a),(Ot=a.output)!=null&&Ot.fps&&(h.value=tr(a.output.fps,h.value),p.setFps(h.value))):(E(),a&&(($a=a.output)!=null&&$a.fps&&(h.value=tr(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 x=e.ref(1),T=e.computed(()=>i.selectedClipId?i.clips.find(H=>H.id===i.selectedClipId)??null:null);e.watch(T,H=>{x.value=(H==null?void 0:H.speed)??1},{immediate:!0});const _=e.computed(()=>s.value.length>0),g=e.computed(()=>l.value.length>0);function E(){const H=typeof(t==null?void 0:t.duration)=="number"&&t.duration>0?t.duration:1;t&&(i.media=t),i.originalDuration=H,i.totalDuration=H;const G=ya();i.mediaSources=[S(H)],i.tracks=[N([G])];const se={id:G,type:"clip",trackId:So,sourceRefId:yn,timelineStart:0,timelineEnd:H,sourceIn:0,sourceOut:H,sourceMinIn:0,sourceMaxOut:H,speed:1};i.clips=[se],i.selectedClipId=G,d.value=G,!(t||n.startsWith("temp-"))&&(async()=>{try{const de=await fetch(`/api/v1/video/${encodeURIComponent(n)}`);if(!de.ok)throw new Error(`Failed to fetch media: ${de.status}`);const _e=await de.json(),Le=typeof _e=="object"&&_e!==null&&"data"in _e?_e.data:_e;if(!Le||typeof Le!="object")throw new Error("Failed to parse media payload");const tt=Le;i.media=tt,a||(h.value=tr(tt.frame_rate,h.value),p.setFps(h.value));const He=typeof tt.duration=="number"&&tt.duration>0?tt.duration:H;if(i.hasChanges||i.clips.length!==1||i.clips[0].id!==G)return;i.originalDuration=He,i.totalDuration=He,i.mediaSources=[S(He,tt)],i.tracks=[N([G])];const Pe=i.clips[0];Pe.timelineStart=0,Pe.timelineEnd=He,Pe.sourceIn=0,Pe.sourceOut=He,Pe.sourceMinIn=0,Pe.sourceMaxOut=He,ke(),c=!0}catch{}})()}function S(H,G=t){const se={id:yn,type:"media",mediaUuid:n,duration:H,width:(G==null?void 0:G.width)??1920,height:(G==null?void 0:G.height)??1080};return G!=null&&G.filename&&(se.filename=G.filename),G!=null&&G.mime_type&&(se.mimeType=G.mime_type),typeof(G==null?void 0:G.frame_rate)=="number"&&(se.frameRate=G.frame_rate),typeof(G==null?void 0:G.has_audio)=="boolean"&&(se.hasAudio=G.has_audio),G!=null&&G.thumbnail_url&&(se.thumbnailUrl=G.thumbnail_url),se}function N(H){return{id:So,type:"video",name:"Video",order:0,clipIds:H}}function V(H){return`track-${H}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function A(H,G){const se=H.charAt(0).toUpperCase()+H.slice(1),de=G.filter(_e=>_e.type===H).length;return de===0?se:`${se} ${de+1}`}function j(H,G){if(H.originalDuration!==1)return;H.originalDuration=G,H.totalDuration===1&&(H.totalDuration=G);const se=H.clips[0],de=!a&&H.clips.length===1&&se!==void 0&&se.timelineStart===0&&se.timelineEnd===1&&se.sourceIn===0&&se.sourceOut===1;for(const _e of H.clips)(_e.sourceMaxOut===1||_e.sourceMaxOut===void 0)&&(_e.sourceMaxOut=G);if(H.mediaSources)for(const _e of H.mediaSources)_e.id===yn&&(_e.duration===1||_e.duration===void 0)&&(_e.duration=G);de&&se!==void 0&&(se.sourceOut=G,se.timelineEnd=G)}function C(H){if(!Number.isFinite(H)||H<=0||c)return;const G=i.hasChanges;i.originalDuration=H,i.totalDuration=Math.max(i.totalDuration,H),i.media&&(i.media.duration=H);for(const _e of i.clips)_e.sourceMaxOut=H;if(i.mediaSources)for(const _e of i.mediaSources)(_e.id===yn||_e.mediaUuid===n)&&(_e.duration=H);const se=i.clips[0];!a&&i.clips.length===1&&se!==void 0&&se.timelineStart===0&&se.timelineEnd===1&&se.sourceIn===0&&se.sourceOut===1&&se!==void 0&&(se.sourceOut=H,se.timelineEnd=se.timelineStart+(se.sourceOut-se.sourceIn)),ke();for(const _e of s.value)j(_e,H);for(const _e of l.value)j(_e,H);c=!0,e.nextTick(()=>{G||(i.hasChanges=!1)})}function $(H){const G=Nm(H);i.mediaSources=G.mediaSources,i.tracks=G.tracks,i.transitions=G.transitions,i.clips=G.clips.map(se=>({...se,sourceMinIn:se.sourceMinIn??0,sourceMaxOut:se.sourceMaxOut??H.source.duration})),i.filters=[],i.audioVolume=H.audio.volume,i.audioFadeIn=H.audio.fadeIn||0,i.audioFadeOut=H.audio.fadeOut||0,i.exportFormat=H.output.format,i.exportQuality=H.output.quality,i.originalDuration=H.source.duration,i.textOverlays=H.textOverlays?[...H.textOverlays]:[],i.audioTracks=H.audioTracks?[...H.audioTracks]:[],i.captionTracks=H.captionTracks?H.captionTracks.map(on):[],i.visualLayers=H.visualLayers?H.visualLayers.map(se=>({...se})):[],i.clips.length>0?(i.selectedClipId=i.clips[0].id,d.value=i.selectedClipId):(delete i.selectedClipId,d.value=void 0),ke()}function y(){s.value.push(JSON.parse(JSON.stringify(i))),l.value=[],i.hasChanges=!0}function R(){if(!_.value)return;const H=s.value.pop();l.value.push(JSON.parse(JSON.stringify(i))),Object.assign(i,H)}function L(){if(!g.value)return;const H=l.value.pop();s.value.push(JSON.parse(JSON.stringify(i))),Object.assign(i,H)}function U(H,G,se){y();const de=i.clips.find(He=>He.id===H);if(!de)return;const _e=1/h.value,Le=de.sourceMinIn??0,tt=de.sourceMaxOut??i.originalDuration;if(G==="start"){const He=de.sourceIn,Pe=Math.max(Le,Math.min(se,de.sourceOut-_e));de.sourceIn=Pe;const ot=Pe-He;de.timelineStart+=ot}else{const He=Math.max(de.sourceIn+_e,Math.min(se,tt));de.sourceOut=He;const Pe=de.sourceOut-de.sourceIn;de.timelineEnd=de.timelineStart+Pe}ke(),m.value&&m.value.trimClip(H,de.sourceIn,de.sourceOut)}function z(H){y();const G=i.clips.find(tt=>H>tt.timelineStart&&H<tt.timelineEnd);if(!G)return;const se=H-G.timelineStart,de=G.sourceIn+se,_e={id:ya(),type:"clip",timelineStart:H,timelineEnd:G.timelineEnd,sourceIn:de,sourceOut:G.sourceOut,speed:G.speed??1,sourceMinIn:G.sourceMinIn??0,sourceMaxOut:G.sourceMaxOut??i.originalDuration,filters:[...G.filters||[]]};G.trackId&&(_e.trackId=G.trackId),G.sourceRefId&&(_e.sourceRefId=G.sourceRefId),G.timelineEnd=H,G.sourceOut=de;const Le=i.clips.indexOf(G);i.clips.splice(Le+1,0,_e),ne(),i.selectedClipId=_e.id}function I(){z(i.playheadPosition)}function P(H){var se;const G=H??i.selectedClipId??d.value??((se=i.clips[0])==null?void 0:se.id);G&&(i.selectedClipId=G,d.value=G)}function Z(){return i.selectedClipId?K(i.selectedClipId):It("no_selection",Yt("no_selection"))}function K(H){const G=i.clips.findIndex(se=>se.id===H);return G===-1?It("source_not_found","Clip not found."):(y(),i.clips.splice(G,1),ne(),ve(G),ke(),Ua())}function ve(H){if(!i.clips.length){delete i.selectedClipId,d.value=void 0;return}const G=Math.max(0,Math.min(H,i.clips.length-1)),se=i.clips[G];se&&(i.selectedClipId=se.id,d.value=se.id)}function Ve(H){return H.trackId??`legacy-track-${H.track??0}`}function ne(){const H=i.tracks;if(H)for(const G of H)G.clipIds=i.clips.filter(se=>Ve(se)===G.id).map(se=>se.id)}function ae(H="video"){y();const G=i.tracks??[],se=G.reduce((_e,Le)=>Math.max(_e,Le.order),-1),de={id:V(H),type:H,name:A(H,G),order:se+1,clipIds:[]};return i.tracks=[...G,de],i.hasChanges=!0,de}function F(H){if(H.length===0)return;const G=new Set(H),se=i.clips.findIndex(de=>G.has(de.id));i.clips=i.clips.filter(de=>!G.has(de.id)),i.transitions&&i.transitions.length>0&&(i.transitions=i.transitions.filter(de=>!G.has(de.fromClipId)&&!G.has(de.toClipId))),ne(),i.selectedClipId!==void 0&&G.has(i.selectedClipId)&&ve(se>=0?se:0),ke()}function B(H){const G=i.tracks??[],se=G.find(_e=>_e.id===H);if(!se)return It("track_missing",Yt("track_missing"));if(G.length<=1)return It("invariant_violation","Can't delete the last remaining track. Add another track first.");y();const de=i.clips.filter(_e=>Ve(_e)===se.id).map(_e=>_e.id);return F(de),i.tracks=G.filter(_e=>_e.id!==se.id),i.hasChanges=!0,Ua()}function O(H,G){const de=(i.tracks??[]).find(Le=>Le.id===H);if(!de)return It("track_missing",Yt("track_missing"));const _e=G.trim();return _e===""?It("invariant_violation","Track name cannot be empty."):(de.name===_e||(y(),de.name=_e,i.hasChanges=!0),Ua())}function X(H,G){const se=i.tracks??[],de=se.find(ot=>ot.id===H);if(!de)return It("track_missing",Yt("track_missing"));const _e=[...se].sort((ot,st)=>ot.order-st.order),Le=_e.findIndex(ot=>ot.id===de.id),tt=G==="up"?Le+1:Le-1,He=_e[tt];if(!He)return It("invariant_violation","Track is already at the edge.");y();const Pe=de.order;return de.order=He.order,He.order=Pe,i.hasChanges=!0,Ua()}function oe(H){let G=i.tracks??[];if(G.length===0){const de=N([]);i.tracks=[de],G=i.tracks}if(H){const de=G.find(_e=>_e.id===H);return de?de.locked===!0?{ok:!1,reason:"track_locked"}:{ok:!0,track:de}:{ok:!1,reason:"track_missing"}}const se=G.find(de=>de.type==="video"&&de.locked!==!0)??G.find(de=>de.locked!==!0);return se?{ok:!0,track:se}:{ok:!1,reason:"no_editable_track"}}function ce(H){const G=1/h.value;return typeof H.duration=="number"&&Number.isFinite(H.duration)&&H.duration>G?H.duration:i.originalDuration>G?i.originalDuration:Math.max(G,i.totalDuration)}function je(H){const G=i.clips.filter(se=>Ve(se)===H);return G.length>0?G.reduce((se,de)=>Math.max(se,de.timelineEnd),0):Math.max(0,Math.min(i.playheadPosition,i.totalDuration))}function he(H){const G=i.mediaSources??[],se=G.find(de=>de.id===H.id);return se||(i.mediaSources=[...G,H],i.hasChanges=!0,H)}function ge(H,G){return we(H,"clip",G)}function pe(H,G){if(!(i.mediaSources??[]).find(_e=>_e.id===H))return It("source_not_found",Yt("source_not_found"));let de=G;if(!de){const _e=(i.tracks??[]).find(Le=>Le.type==="audio"&&Le.locked!==!0);de=(_e==null?void 0:_e.id)??ae("audio").id}return we(H,"audio",de)}function we(H,G,se){const de=(i.mediaSources??[]).find(Gt=>Gt.id===H);if(!de)return It("source_not_found",Yt("source_not_found"));const _e=oe(se);if(!_e.ok){const Gt=_e.reason==="no_editable_track"?"track_missing":_e.reason;return It(Gt,Yt(Gt))}const Le=_e.track;if(!Oc(G,Le.type))return It("track_type_mismatch",Yt("track_type_mismatch"));const tt=i.clips.filter(Gt=>Ve(Gt)===Le.id),He=ce(de),Pe=je(Le.id),ot=zs({trackClips:tt,desiredDuration:He,preferredStart:Pe});if(!ot.ok)return It("overlap",Yt("overlap"));y();const st=ya(),Ze={id:st,type:G,trackId:Le.id,sourceRefId:de.id,timelineStart:ot.start,timelineEnd:ot.start+He,sourceIn:0,sourceOut:He,sourceMinIn:0,sourceMaxOut:He,speed:1};return i.clips.push(Ze),i.selectedClipId=st,d.value=st,ne(),ke(),Ua(Ze)}function ye(H){const G=T.value,se=(i.mediaSources??[]).find(He=>He.id===H);if(!G||!se)return!1;y();const de=1/h.value,_e=ce(se),Le=Math.max(de,G.timelineEnd-G.timelineStart),tt=Math.max(de,Math.min(Le,_e));return G.sourceRefId=se.id,G.sourceIn=0,G.sourceOut=tt,G.sourceMinIn=0,G.sourceMaxOut=_e,G.timelineEnd=G.timelineStart+tt,ke(),!0}function Ne(H){const G=i.mediaSources??[];return G.length<=1||AE({clips:i.clips},H)?!1:(y(),i.mediaSources=G.filter(se=>se.id!==H),!0)}function De(H,G){const se=(i.tracks??[]).find(de=>de.id===H);return se?(y(),se[G]=se[G]!==!0,!0):!1}function Qe(H){return De(H,"locked")}function et(H){return De(H,"hidden")}function Lt(H){return De(H,"muted")}function kt(H){return De(H,"solo")}function Ct(H){if(i.clips.length<=1)return!1;const G=i.clips.findIndex(Le=>Le.id===H),se=G===-1?void 0:i.clips[G];if(!se)return!1;const de=Math.max(0,se.timelineEnd-se.timelineStart),_e=Ve(se);if(y(),i.clips.splice(G,1),ne(),de>0)for(const Le of i.clips)Ve(Le)!==_e||Le.timelineStart<se.timelineEnd||(Le.timelineStart=Math.max(0,Le.timelineStart-de),Le.timelineEnd=Math.max(Le.timelineStart,Le.timelineEnd-de));return i.playheadPosition>=se.timelineEnd?i.playheadPosition=Math.max(0,i.playheadPosition-de):i.playheadPosition>se.timelineStart&&(i.playheadPosition=se.timelineStart),ve(G),ke(),i.hasChanges=!0,!0}function bt(){return i.selectedClipId?Ct(i.selectedClipId):!1}function rt(){return[...i.clips].sort((H,G)=>H.timelineStart-G.timelineStart)}function _t(H){const G=i.clips.find(Ze=>Ze.id===H);if(!G)return null;const se=Ve(G),de=rt().filter(Ze=>Ve(Ze)===se),_e=de.findIndex(Ze=>Ze.id===H);if(_e===-1)return null;const Le=de[_e],tt=Le.timelineEnd-Le.timelineStart,He=_e>0?de[_e-1]:null,Pe=_e<de.length-1?de[_e+1]:null,ot=He?He.timelineEnd:0,st=Pe?Pe.timelineStart-tt:Math.max(Le.timelineStart,i.totalDuration-tt);return{minStart:ot,maxStart:Math.max(ot,st)}}function be(H,G,se){const de=i.clips.find(st=>st.id===H);if(!de)return It("source_not_found","Clip not found.");if(se===void 0||se===de.trackId){const st=_t(H),Ze=st?Math.min(st.maxStart,Math.max(st.minStart,G)):Math.max(0,G);if(Ze===de.timelineStart)return Ua();y();const Gt=Ze-de.timelineStart;return de.timelineStart=Ze,de.timelineEnd+=Gt,ke(),m.value&&m.value.moveClip(H,Ze),Ua()}const Le=(i.tracks??[]).find(st=>st.id===se);if(!Le)return It("track_missing",Yt("track_missing"));if(Le.locked===!0)return It("track_locked",Yt("track_locked"));if(!Oc(de.type,Le.type))return It("track_type_mismatch",Yt("track_type_mismatch"));const tt=i.clips.filter(st=>Ve(st)===Le.id&&st.id!==de.id),He=de.timelineEnd-de.timelineStart,Pe=zs({trackClips:tt,desiredDuration:He,preferredStart:Math.max(0,G),ignoreClipId:de.id});if(!Pe.ok)return It("overlap",Yt("overlap"));y(),de.trackId=Le.id;const ot=de.timelineStart;return de.timelineStart=Pe.start,de.timelineEnd=Pe.start+He,ne(),ke(),m.value&&ot!==Pe.start&&m.value.moveClip(H,Pe.start),Ua()}function ke(){if(i.clips.length===0){i.totalDuration=0;return}const H=i.clips.reduce((G,se)=>se.timelineEnd>G.timelineEnd?se:G);i.totalDuration=H.timelineEnd}function Te(){i.zoomLevel=Math.min(200,i.zoomLevel*1.2)}function Ke(){i.zoomLevel=Math.max(10,i.zoomLevel/1.2)}function Ge(H){i.zoomLevel=Math.max(10,Math.min(600,Math.round(H)))}function ze(){i.isPlaying=!i.isPlaying}function Et(H){i.isPlaying=H}function ut(H){i.playheadPosition=Math.max(0,Math.min(H,i.totalDuration))}function Xt(){const H=Uc(i);try{localStorage.setItem(`video-draft-${n}`,JSON.stringify(H))}catch{}return H}function Wt(){i.hasChanges=!1}function ca(){return confirm("Are you sure you want to reset all changes?")?(y(),E(),i.hasChanges=!1,!0):!1}function ta(){return Uc(i)}function ya(){return`clip-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}async function Sa(H=1920,G=1080){if(u.value)try{m.value=new wm(H,G,h.value),await wa()}catch{m.value=null}}async function wa(){if(!(!m.value||w.value)){w.value=!0;try{const H=ta();await m.value.loadFromRecipe(H);const G=p.secondsToFrames(i.playheadPosition);m.value.seek(G)}catch{}finally{w.value=!1}}}function nn(H){}function Q(H){return p.secondsToFrames(H)}function ue(H){return p.framesToSeconds(H)}function re(H){const G=ue(H);ut(G),m.value&&m.value.seek(H)}function ie(){v.value=!v.value}function Se(){wa()}function Ae(H){u.value=!1,m.value=null}e.watch(()=>i.clips,()=>{i.hasChanges=!0,u.value&&m.value&&wa()},{deep:!0}),e.watch(()=>i.filters,()=>{i.hasChanges=!0,u.value&&m.value&&wa()},{deep:!0}),e.watch(()=>i.clips.map(H=>H.id),()=>{var G;if(!i.clips.length){delete i.selectedClipId,d.value=void 0;return}if(!i.clips.some(se=>se.id===i.selectedClipId)){const se=d.value&&((G=i.clips.find(de=>de.id===d.value))==null?void 0:G.id);i.selectedClipId=se??i.clips[0].id,d.value=i.selectedClipId}},{deep:!0});function qe(H){const G=i.selectedClipId?i.clips.find(se=>se.id===i.selectedClipId):i.clips[0];G&&(G.filters=[...H],i.hasChanges=!0)}function ft(H){i.textOverlays=[...H]}function Vt(H){i.audioTracks=[...H]}function ht(H){i.captionTracks=H.map(on),i.hasChanges=!0}function vt(H){i.visualLayers=H.map(G=>({...G})),i.hasChanges=!0}function Ut(H){i.transitions=H.map(G=>{const se={...G};return G.params&&(se.params={...G.params}),se}),i.hasChanges=!0}function Mt(H,G){const se=i.clips.find(de=>de.id===H);se&&(se.keyframes=G.map(de=>({...de})),i.hasChanges=!0)}function Ft(H){y(),$(H),i.hasChanges=!0}function on(H){return{...H,segments:H.segments.map(G=>{const se={...G};return G.words&&(se.words=G.words.map(de=>({...de}))),se})}}e.watch(u,H=>{H?Sa():m.value&&(m.value.destroy(),m.value=null)}),e.watch(v,()=>{}),e.watch(h,H=>{p.setFps(H)});function Fa(){if(!i.selectedClipId)return It("no_selection",Yt("no_selection"));const H=i.clips.find(He=>He.id===i.selectedClipId);if(!H)return It("no_selection",Yt("no_selection"));const G=Ve(H),se=i.clips.filter(He=>Ve(He)===G),de=H.timelineEnd-H.timelineStart,_e=zs({trackClips:se,desiredDuration:de,preferredStart:H.timelineEnd});if(!_e.ok)return It("overlap",Yt("overlap"));y();const Le={...H,id:ya(),timelineStart:_e.start,timelineEnd:_e.start+de,filters:[...H.filters||[]]},tt=i.clips.indexOf(H);return i.clips.splice(tt+1,0,Le),ne(),i.selectedClipId=Le.id,i.hasChanges=!0,Ua(Le)}function Ca(H){const G=H??800,se=i.totalDuration;if(se<=0){i.zoomLevel=50;return}const de=G*.8/se;i.zoomLevel=Math.max(10,Math.min(600,Math.round(de)))}function Va(){const H=1/h.value;ut(Math.min(i.playheadPosition+H,i.totalDuration))}function ua(){const H=1/h.value;ut(Math.max(i.playheadPosition-H,0))}function yt(){ut(0)}function wt(){ut(i.totalDuration)}function ma(H){if(!Number.isFinite(H)||H<=0)return;const G=T.value??i.clips[0];if(!G){x.value=H;return}const se=G.speed??1;if(se===H){x.value=H;return}y();const de=Math.max(1/h.value,G.sourceOut-G.sourceIn),_e=de/se,Le=de/H,tt=Le-_e;G.speed=H,G.timelineEnd=G.timelineStart+Le;const He=i.clips.findIndex(Pe=>Pe.id===G.id);if(He!==-1&&tt!==0)for(let Pe=He+1;Pe<i.clips.length;Pe+=1){const ot=i.clips[Pe];ot.timelineStart+=tt,ot.timelineEnd+=tt}ke(),i.playheadPosition=Math.max(0,Math.min(i.playheadPosition,i.totalDuration)),i.hasChanges=!0,x.value=H}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:T,zoomLevel:e.computed(()=>i.zoomLevel),playbackSpeed:x,useVideoEngine:u,compositionAdapter:e.computed(()=>m.value),fps:h,useFrameMode:v,handleTrim:U,handleSplit:z,handleClipSelect:P,splitAtPlayhead:I,deleteSelectedClip:Z,deleteClip:K,rippleDeleteClip:Ct,rippleDeleteSelectedClip:bt,duplicateSelectedClip:Fa,addTimelineTrack:ae,deleteTimelineTrack:B,renameTimelineTrack:O,reorderTimelineTrack:X,appendMediaSourceToTimeline:ge,appendAudioSourceToTimeline:pe,registerMediaSource:he,replaceSelectedClipSource:ye,removeMediaSource:Ne,toggleTrackLock:Qe,toggleTrackHidden:et,toggleTrackMuted:Lt,toggleTrackSolo:kt,setFilters:qe,setTextOverlays:ft,setAudioTracks:Vt,setCaptionTracks:ht,setVisualLayers:vt,setTransitions:Ut,setClipKeyframes:Mt,loadRecipe:Ft,moveClip:be,saveDraft:Xt,clearHasChanges:Wt,resetChanges:ca,generateRecipe:ta,zoomIn:Te,zoomOut:Ke,setZoomLevel:Ge,fitToWindow:Ca,togglePlayback:ze,setPlaying:Et,seekTo:ut,frameForward:Va,frameBackward:ua,skipToStart:yt,skipToEnd:wt,setPlaybackSpeed:ma,updateSourceDuration:C,undo:R,redo:L,canUndo:_,canRedo:g,initializeComposition:Sa,syncCompositionWithState:wa,syncWithComposition:nn,convertToFrames:Q,convertToSeconds:ue,seekToFrame:re,toggleFrameMode:ie,onCompositionReady:Se,onCompositionError:Ae}}const LE=[{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}}}],PE={dropShadow:"drop-shadow",softFocus:"blur",blackAndWhite:"grayscale",gaussianBlur:"blur","gaussian-blur":"blur"};function is(o){return typeof o=="object"&&o!==null}function UE(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 rs(o){if(typeof o=="number"||typeof o=="string"||typeof o=="boolean")return o}function OE(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=rs(o.default);return t!==void 0&&(a.default=t),o.options!==void 0&&(a.options=o.options),a}function tp(o,a,t){const n=te.getFilter(o),i={},r=(n==null?void 0:n.defaultParams)??t;if(r&&is(r))for(const[s,l]of Object.entries(r))i[s]=rs(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 ap(o){const a={};for(const t of o){if(t.type!=="slider")continue;const n=t.property??t.id;a[n]={min:t.min??0,max:t.max??100,step:t.step??1}}return a}function zE(o,a,t,n){const i=n.map(OE);return{id:o,name:a,category:t,controls:i,params:i,defaultParams:tp(o,i),paramRanges:ap(i)}}function jE(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=rs((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:tp(o.id,t,o.defaultParams),paramRanges:ap(t)}}function WE(o,a){return a.toLowerCase()==="unlisted"?!1:te.isFilterCompatibleWithMedia(o,"video")}function js(o){return PE[o]??o}function ti(o){const a=UE(o,1);return Math.max(0,Math.min(1,a))}function ai(o){if(!is(o))return{};const a={};for(const[t,n]of Object.entries(o))a[t]=rs(n)??null;return a}function HE(o){return!is(o)||typeof o.filterId!="string"?null:{filterId:o.filterId,params:ai(o.params),intensity:ti(o.intensity)}}function ZE(o){if(!is(o)||typeof o.id!="string"||typeof o.name!="string")return null;const t=(Array.isArray(o.filters)?o.filters:[]).map(i=>HE(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 np(){te.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 y=new Map,R=te.getRegisteredFilters();for(const L of R)WE(L.id,L.category)&&y.set(L.id,zE(L.id,L.name,L.category,L.controls));for(const L of LE)y.has(L.id)||y.set(L.id,jE(L));return Array.from(y.values())}),l=e.computed(()=>{const y=new Map;for(const R of s.value)y.set(R.id,R);return y}),d=e.computed(()=>o.value.length>0),c=e.computed(()=>{const y={};for(const R of s.value)y[R.category]||(y[R.category]=[]),y[R.category].push(R);return y});function u(y){const R=l.value.get(y);if(R)return R;const L=js(y);return l.value.get(L)??null}function f(y){const R=l.value.get(y);if(R)return R.id;const L=js(y),U=l.value.get(L);return U?U.id:null}function m(y){const R=y?u(y):a.value;if(!R)return;const L=R.defaultParams||{},U={id:A(),filterId:R.id,params:{...L},intensity:1};return o.value.push(U),i.value=U.id,a.value=R,Object.keys(r).forEach(z=>delete r[z]),Object.assign(r,U.params),t.value=null,U}function p(y){const R=u(y);if(!R)return;a.value=R;const L=R.defaultParams||C(y);Object.assign(r,L),t.value={id:"preview",filterId:R.id,params:{...L},intensity:1}}function h(y){if(Object.assign(r,y),t.value&&(t.value.params={...r}),i.value){const R=o.value.find(L=>L.id===i.value);R&&(R.params={...r})}}function v(y){const R=o.value.findIndex(L=>L.id===y);R!==-1&&o.value.splice(R,1)}function w(y,R){if(y<0||y>=o.value.length||R<0||R>=o.value.length)return;const[L]=o.value.splice(y,1);o.value.splice(R,0,L)}function x(y,R){const L=o.value.find(U=>U.id===y);L&&(L.intensity=Math.max(0,Math.min(1,R)))}function T(y){const R=o.value.find(L=>L.id===y);R&&(R.intensity=R.intensity>0?0:1)}function _(){o.value=[],t.value=null,a.value=null,i.value=null,Object.keys(r).forEach(y=>delete r[y])}function g(y){const R={id:j(),name:y,filters:o.value.map(U=>({filterId:U.filterId,params:ai(U.params),intensity:ti(U.intensity)})),created_at:new Date().toISOString()};n.value.push(R);const L=n.value.map(U=>({...U}));return localStorage.setItem("video-filter-presets",JSON.stringify(L)),R}function E(y){const R=n.value.find(L=>L.id===y);if(R){_();for(const L of R.filters){const U=u(L.filterId);U&&o.value.push({id:A(),filterId:U.id,params:{...L.params},intensity:ti(L.intensity)})}}}function S(y){const R=n.value.findIndex(L=>L.id===y);R!==-1&&(n.value.splice(R,1),localStorage.setItem("video-filter-presets",JSON.stringify(n.value)))}function N(){try{const y=localStorage.getItem("video-filter-presets");if(!y)return;const R=JSON.parse(y);if(!Array.isArray(R))return;n.value=R.map(L=>ZE(L)).filter(L=>L!==null)}catch{}}function V(){if(o.value.length===0)return"No filters applied";const y=o.value.map(R=>{const L=$(R.filterId);return(L==null?void 0:L.name)||R.filterId});return y.length===1?y[0]:y.length===2?`${y[0]} + ${y[1]}`:`${y[0]} + ${y.length-1} more`}function A(){return`filter-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function j(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function C(y){const R=u(y);return R?R.defaultParams||{}:{}}function $(y){return u(y)}return N(),{videoCompatibleFilters:s,activeFilters:o,selectedFilter:a,previewFilter:t,filterPresets:n,filterParams:r,hasActiveFilters:d,filtersByCategory:c,applyFilter:m,previewFilterEffect:p,updateFilterParams:h,removeFilter:v,reorderFilters:w,updateFilterIntensity:x,toggleFilter:T,clearAllFilters:_,saveFilterPreset:g,loadFilterPreset:E,deleteFilterPreset:S,getFilterSummary:V,setActiveFilters(y){var L;const R=[];for(const U of y){const z=f(U.filterId);if(!z){const I=js(U.filterId);R.push({...U,filterId:I,params:ai(U.params),intensity:ti(U.intensity)});continue}R.push({...U,filterId:z,params:ai(U.params),intensity:ti(U.intensity)})}o.value=R,i.value=((L=o.value[0])==null?void 0:L.id)??null,Object.keys(r).forEach(U=>delete r[U]),o.value[0]&&Object.assign(r,ai(o.value[0].params))}}}class op{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 Qt({source:"https://fonts.googleapis.com/css2?family=Inter:wght@400",family:"Inter",weight:"400"})),this.fonts.set("bold",new Qt({source:"https://fonts.googleapis.com/css2?family=Inter:wght@700",family:"Inter",weight:"700"})),this.fonts.set("serif",new Qt({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 Qt({source:t,family:n,weight:i});this.fonts.set(a,r)}loadLocalFont(a,t,n="400"){const i=new Qt({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 Vo(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=$e.fromSeconds(a.startTime)),a.duration!==void 0){const r=a.startTime||0;t.stop=$e.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 Ue([i,l],[0,1],{easing:d});break;case"fade-out":a.alpha=new Ue([i,l],[1,0],{easing:d});break;case"rotate":t.rotation&&(a.rotation=new Ue([i,l],[t.rotation.from,t.rotation.to],{easing:d}));break;case"scale":t.scale&&(a.scale=new Ue([i,l],[t.scale.from,t.scale.to],{easing:d}));break;case"slide":t.translate&&(a.translate={x:new Ue([i,l],[t.translate.fromX,t.translate.toX],{easing:d}),y:new Ue([i,l],[t.translate.fromY,t.translate.toY],{easing:d})});break;case"typewriter":a.alpha=new Ue([i,l],[0,1],{easing:"linear"});break;case"custom":t.rotation&&(a.rotation=new Ue([i,l],[t.rotation.from,t.rotation.to],{easing:d})),t.scale&&(a.scale=new Ue([i,l],[t.scale.from,t.scale.to],{easing:d})),t.translate&&(a.translate={x:new Ue([i,l],[t.translate.fromX,t.translate.toX],{easing:d}),y:new Ue([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:Ci,cascade:Qr,guinea:Yr,solar:es,spotlight:Vi,whisper:Ni}[t],s=await this.composition.createTrack("caption"),l=new Zr({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 ip{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 bn.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 li(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 bn)return a;if(typeof a=="string"&&a.trim()!=="")return await bn.from(a);if(a instanceof File)return await bn.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=$e.fromSeconds(a.startTime)),a.duration!==void 0){const i=a.startTime||0;n.stop=$e.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 Ue(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 li(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 li(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 rp(o,a){return function(){return o.apply(a,arguments)}}const{toString:XE}=Object.prototype,{getPrototypeOf:bd}=Object,{iterator:ss,toStringTag:sp}=Symbol,ls=(o=>a=>{const t=XE.call(a);return o[t]||(o[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),Ma=o=>(o=o.toLowerCase(),a=>ls(a)===o),ds=o=>a=>typeof a===o,{isArray:Io}=Array,yi=ds("undefined");function Ii(o){return o!==null&&!yi(o)&&o.constructor!==null&&!yi(o.constructor)&&sa(o.constructor.isBuffer)&&o.constructor.isBuffer(o)}const lp=Ma("ArrayBuffer");function GE(o){let a;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?a=ArrayBuffer.isView(o):a=o&&o.buffer&&lp(o.buffer),a}const JE=ds("string"),sa=ds("function"),dp=ds("number"),Bi=o=>o!==null&&typeof o=="object",KE=o=>o===!0||o===!1,br=o=>{if(ls(o)!=="object")return!1;const a=bd(o);return(a===null||a===Object.prototype||Object.getPrototypeOf(a)===null)&&!(sp in o)&&!(ss in o)},qE=o=>{if(!Bi(o)||Ii(o))return!1;try{return Object.keys(o).length===0&&Object.getPrototypeOf(o)===Object.prototype}catch{return!1}},YE=Ma("Date"),QE=Ma("File"),ex=Ma("Blob"),tx=Ma("FileList"),ax=o=>Bi(o)&&sa(o.pipe),nx=o=>{let a;return o&&(typeof FormData=="function"&&o instanceof FormData||sa(o.append)&&((a=ls(o))==="formdata"||a==="object"&&sa(o.toString)&&o.toString()==="[object FormData]"))},ox=Ma("URLSearchParams"),[ix,rx,sx,lx]=["ReadableStream","Request","Response","Headers"].map(Ma),dx=o=>o.trim?o.trim():o.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Mi(o,a,{allOwnKeys:t=!1}={}){if(o===null||typeof o>"u")return;let n,i;if(typeof o!="object"&&(o=[o]),Io(o))for(n=0,i=o.length;n<i;n++)a.call(null,o[n],n,o);else{if(Ii(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 cp(o,a){if(Ii(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 Un=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,up=o=>!yi(o)&&o!==Un;function $l(){const{caseless:o}=up(this)&&this||{},a={},t=(n,i)=>{const r=o&&cp(a,i)||i;br(a[r])&&br(n)?a[r]=$l(a[r],n):br(n)?a[r]=$l({},n):Io(n)?a[r]=n.slice():a[r]=n};for(let n=0,i=arguments.length;n<i;n++)arguments[n]&&Mi(arguments[n],t);return a}const cx=(o,a,t,{allOwnKeys:n}={})=>(Mi(a,(i,r)=>{t&&sa(i)?o[r]=rp(i,t):o[r]=i},{allOwnKeys:n}),o),ux=o=>(o.charCodeAt(0)===65279&&(o=o.slice(1)),o),mx=(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)},px=(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&&bd(o)}while(o&&(!t||t(o,a))&&o!==Object.prototype);return a},fx=(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},hx=o=>{if(!o)return null;if(Io(o))return o;let a=o.length;if(!dp(a))return null;const t=new Array(a);for(;a-- >0;)t[a]=o[a];return t},vx=(o=>a=>o&&a instanceof o)(typeof Uint8Array<"u"&&bd(Uint8Array)),gx=(o,a)=>{const n=(o&&o[ss]).call(o);let i;for(;(i=n.next())&&!i.done;){const r=i.value;a.call(o,r[0],r[1])}},bx=(o,a)=>{let t;const n=[];for(;(t=o.exec(a))!==null;)n.push(t);return n},yx=Ma("HTMLFormElement"),wx=o=>o.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,n,i){return n.toUpperCase()+i}),zc=(({hasOwnProperty:o})=>(a,t)=>o.call(a,t))(Object.prototype),kx=Ma("RegExp"),mp=(o,a)=>{const t=Object.getOwnPropertyDescriptors(o),n={};Mi(t,(i,r)=>{let s;(s=a(i,r,o))!==!1&&(n[r]=s||i)}),Object.defineProperties(o,n)},_x=o=>{mp(o,(a,t)=>{if(sa(o)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const n=o[t];if(sa(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+"'")})}})},Ex=(o,a)=>{const t={},n=i=>{i.forEach(r=>{t[r]=!0})};return Io(o)?n(o):n(String(o).split(a)),t},xx=()=>{},Sx=(o,a)=>o!=null&&Number.isFinite(o=+o)?o:a;function Cx(o){return!!(o&&sa(o.append)&&o[sp]==="FormData"&&o[ss])}const Vx=o=>{const a=new Array(10),t=(n,i)=>{if(Bi(n)){if(a.indexOf(n)>=0)return;if(Ii(n))return n;if(!("toJSON"in n)){a[i]=n;const r=Io(n)?[]:{};return Mi(n,(s,l)=>{const d=t(s,i+1);!yi(d)&&(r[l]=d)}),a[i]=void 0,r}}return n};return t(o,0)},Nx=Ma("AsyncFunction"),Tx=o=>o&&(Bi(o)||sa(o))&&sa(o.then)&&sa(o.catch),pp=((o,a)=>o?setImmediate:a?((t,n)=>(Un.addEventListener("message",({source:i,data:r})=>{i===Un&&r===t&&n.length&&n.shift()()},!1),i=>{n.push(i),Un.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",sa(Un.postMessage)),Ix=typeof queueMicrotask<"u"?queueMicrotask.bind(Un):typeof process<"u"&&process.nextTick||pp,Bx=o=>o!=null&&sa(o[ss]),le={isArray:Io,isArrayBuffer:lp,isBuffer:Ii,isFormData:nx,isArrayBufferView:GE,isString:JE,isNumber:dp,isBoolean:KE,isObject:Bi,isPlainObject:br,isEmptyObject:qE,isReadableStream:ix,isRequest:rx,isResponse:sx,isHeaders:lx,isUndefined:yi,isDate:YE,isFile:QE,isBlob:ex,isRegExp:kx,isFunction:sa,isStream:ax,isURLSearchParams:ox,isTypedArray:vx,isFileList:tx,forEach:Mi,merge:$l,extend:cx,trim:dx,stripBOM:ux,inherits:mx,toFlatObject:px,kindOf:ls,kindOfTest:Ma,endsWith:fx,toArray:hx,forEachEntry:gx,matchAll:bx,isHTMLForm:yx,hasOwnProperty:zc,hasOwnProp:zc,reduceDescriptors:mp,freezeMethods:_x,toObjectSet:Ex,toCamelCase:wx,noop:xx,toFiniteNumber:Sx,findKey:cp,global:Un,isContextDefined:up,isSpecCompliantForm:Cx,toJSONObject:Vx,isAsyncFn:Nx,isThenable:Tx,setImmediate:pp,asap:Ix,isIterable:Bx};function Xe(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)}le.inherits(Xe,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:le.toJSONObject(this.config),code:this.code,status:this.status}}});const fp=Xe.prototype,hp={};["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=>{hp[o]={value:o}});Object.defineProperties(Xe,hp);Object.defineProperty(fp,"isAxiosError",{value:!0});Xe.from=(o,a,t,n,i,r)=>{const s=Object.create(fp);return le.toFlatObject(o,s,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),Xe.call(s,o.message,a,t,n,i),s.cause=o,s.name=o.name,r&&Object.assign(s,r),s};const Mx=null;function Dl(o){return le.isPlainObject(o)||le.isArray(o)}function vp(o){return le.endsWith(o,"[]")?o.slice(0,-2):o}function jc(o,a,t){return o?o.concat(a).map(function(i,r){return i=vp(i),!t&&r?"["+i+"]":i}).join(t?".":""):a}function Fx(o){return le.isArray(o)&&!o.some(Dl)}const $x=le.toFlatObject(le,{},null,function(a){return/^is[A-Z]/.test(a)});function cs(o,a,t){if(!le.isObject(o))throw new TypeError("target must be an object");a=a||new FormData,t=le.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(v,w){return!le.isUndefined(w[v])});const n=t.metaTokens,i=t.visitor||u,r=t.dots,s=t.indexes,d=(t.Blob||typeof Blob<"u"&&Blob)&&le.isSpecCompliantForm(a);if(!le.isFunction(i))throw new TypeError("visitor must be a function");function c(h){if(h===null)return"";if(le.isDate(h))return h.toISOString();if(le.isBoolean(h))return h.toString();if(!d&&le.isBlob(h))throw new Xe("Blob is not supported. Use a Buffer instead.");return le.isArrayBuffer(h)||le.isTypedArray(h)?d&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,v,w){let x=h;if(h&&!w&&typeof h=="object"){if(le.endsWith(v,"{}"))v=n?v:v.slice(0,-2),h=JSON.stringify(h);else if(le.isArray(h)&&Fx(h)||(le.isFileList(h)||le.endsWith(v,"[]"))&&(x=le.toArray(h)))return v=vp(v),x.forEach(function(_,g){!(le.isUndefined(_)||_===null)&&a.append(s===!0?jc([v],g,r):s===null?v:v+"[]",c(_))}),!1}return Dl(h)?!0:(a.append(jc(w,v,r),c(h)),!1)}const f=[],m=Object.assign($x,{defaultVisitor:u,convertValue:c,isVisitable:Dl});function p(h,v){if(!le.isUndefined(h)){if(f.indexOf(h)!==-1)throw Error("Circular reference detected in "+v.join("."));f.push(h),le.forEach(h,function(x,T){(!(le.isUndefined(x)||x===null)&&i.call(a,x,le.isString(T)?T.trim():T,v,m))===!0&&p(x,v?v.concat(T):[T])}),f.pop()}}if(!le.isObject(o))throw new TypeError("data must be an object");return p(o),a}function Wc(o){const a={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(o).replace(/[!'()~]|%20|%00/g,function(n){return a[n]})}function yd(o,a){this._pairs=[],o&&cs(o,this,a)}const gp=yd.prototype;gp.append=function(a,t){this._pairs.push([a,t])};gp.toString=function(a){const t=a?function(n){return a.call(this,n,Wc)}:Wc;return this._pairs.map(function(i){return t(i[0])+"="+t(i[1])},"").join("&")};function Dx(o){return encodeURIComponent(o).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function bp(o,a,t){if(!a)return o;const n=t&&t.encode||Dx;le.isFunction(t)&&(t={serialize:t});const i=t&&t.serialize;let r;if(i?r=i(a,t):r=le.isURLSearchParams(a)?a.toString():new yd(a,t).toString(n),r){const s=o.indexOf("#");s!==-1&&(o=o.slice(0,s)),o+=(o.indexOf("?")===-1?"?":"&")+r}return o}class Hc{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){le.forEach(this.handlers,function(n){n!==null&&a(n)})}}const yp={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Rx=typeof URLSearchParams<"u"?URLSearchParams:yd,Ax=typeof FormData<"u"?FormData:null,Lx=typeof Blob<"u"?Blob:null,Px={isBrowser:!0,classes:{URLSearchParams:Rx,FormData:Ax,Blob:Lx},protocols:["http","https","file","blob","url","data"]},wd=typeof window<"u"&&typeof document<"u",Rl=typeof navigator=="object"&&navigator||void 0,Ux=wd&&(!Rl||["ReactNative","NativeScript","NS"].indexOf(Rl.product)<0),Ox=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",zx=wd&&window.location.href||"http://localhost",jx=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:wd,hasStandardBrowserEnv:Ux,hasStandardBrowserWebWorkerEnv:Ox,navigator:Rl,origin:zx},Symbol.toStringTag,{value:"Module"})),ea={...jx,...Px};function Wx(o,a){return cs(o,new ea.classes.URLSearchParams,{visitor:function(t,n,i,r){return ea.isNode&&le.isBuffer(t)?(this.append(n,t.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)},...a})}function Hx(o){return le.matchAll(/\w+|\[(\w*)]/g,o).map(a=>a[0]==="[]"?"":a[1]||a[0])}function Zx(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 wp(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&&le.isArray(i)?i.length:s,d?(le.hasOwnProp(i,s)?i[s]=[i[s],n]:i[s]=n,!l):((!i[s]||!le.isObject(i[s]))&&(i[s]=[]),a(t,n,i[s],r)&&le.isArray(i[s])&&(i[s]=Zx(i[s])),!l)}if(le.isFormData(o)&&le.isFunction(o.entries)){const t={};return le.forEachEntry(o,(n,i)=>{a(Hx(n),i,t,0)}),t}return null}function Xx(o,a,t){if(le.isString(o))try{return(a||JSON.parse)(o),le.trim(o)}catch(n){if(n.name!=="SyntaxError")throw n}return(t||JSON.stringify)(o)}const Fi={transitional:yp,adapter:["xhr","http","fetch"],transformRequest:[function(a,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=le.isObject(a);if(r&&le.isHTMLForm(a)&&(a=new FormData(a)),le.isFormData(a))return i?JSON.stringify(wp(a)):a;if(le.isArrayBuffer(a)||le.isBuffer(a)||le.isStream(a)||le.isFile(a)||le.isBlob(a)||le.isReadableStream(a))return a;if(le.isArrayBufferView(a))return a.buffer;if(le.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 Wx(a,this.formSerializer).toString();if((l=le.isFileList(a))||n.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return cs(l?{"files[]":a}:a,d&&new d,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),Xx(a)):a}],transformResponse:[function(a){const t=this.transitional||Fi.transitional,n=t&&t.forcedJSONParsing,i=this.responseType==="json";if(le.isResponse(a)||le.isReadableStream(a))return a;if(a&&le.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"?Xe.from(l,Xe.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:ea.classes.FormData,Blob:ea.classes.Blob},validateStatus:function(a){return a>=200&&a<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};le.forEach(["delete","get","head","post","put","patch"],o=>{Fi.headers[o]={}});const Gx=le.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"]),Jx=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]&&Gx[t])&&(t==="set-cookie"?a[t]?a[t].push(n):a[t]=[n]:a[t]=a[t]?a[t]+", "+n:n)}),a},Zc=Symbol("internals");function Xo(o){return o&&String(o).trim().toLowerCase()}function yr(o){return o===!1||o==null?o:le.isArray(o)?o.map(yr):String(o)}function Kx(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 qx=o=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(o.trim());function Ws(o,a,t,n,i){if(le.isFunction(n))return n.call(this,a,t);if(i&&(a=t),!!le.isString(a)){if(le.isString(n))return a.indexOf(n)!==-1;if(le.isRegExp(n))return n.test(a)}}function Yx(o){return o.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(a,t,n)=>t.toUpperCase()+n)}function Qx(o,a){const t=le.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 la=class{constructor(a){a&&this.set(a)}set(a,t,n){const i=this;function r(l,d,c){const u=Xo(d);if(!u)throw new Error("header name must be a non-empty string");const f=le.findKey(i,u);(!f||i[f]===void 0||c===!0||c===void 0&&i[f]!==!1)&&(i[f||d]=yr(l))}const s=(l,d)=>le.forEach(l,(c,u)=>r(c,u,d));if(le.isPlainObject(a)||a instanceof this.constructor)s(a,t);else if(le.isString(a)&&(a=a.trim())&&!qx(a))s(Jx(a),t);else if(le.isObject(a)&&le.isIterable(a)){let l={},d,c;for(const u of a){if(!le.isArray(u))throw TypeError("Object iterator must return a key-value pair");l[c=u[0]]=(d=l[c])?le.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=Xo(a),a){const n=le.findKey(this,a);if(n){const i=this[n];if(!t)return i;if(t===!0)return Kx(i);if(le.isFunction(t))return t.call(this,i,n);if(le.isRegExp(t))return t.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(a,t){if(a=Xo(a),a){const n=le.findKey(this,a);return!!(n&&this[n]!==void 0&&(!t||Ws(this,this[n],n,t)))}return!1}delete(a,t){const n=this;let i=!1;function r(s){if(s=Xo(s),s){const l=le.findKey(n,s);l&&(!t||Ws(n,n[l],l,t))&&(delete n[l],i=!0)}}return le.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||Ws(this,this[r],r,a,!0))&&(delete this[r],i=!0)}return i}normalize(a){const t=this,n={};return le.forEach(this,(i,r)=>{const s=le.findKey(n,r);if(s){t[s]=yr(i),delete t[r];return}const l=a?Yx(r):String(r).trim();l!==r&&delete t[r],t[l]=yr(i),n[l]=!0}),this}concat(...a){return this.constructor.concat(this,...a)}toJSON(a){const t=Object.create(null);return le.forEach(this,(n,i)=>{n!=null&&n!==!1&&(t[i]=a&&le.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[Zc]=this[Zc]={accessors:{}}).accessors,i=this.prototype;function r(s){const l=Xo(s);n[l]||(Qx(i,s),n[l]=!0)}return le.isArray(a)?a.forEach(r):r(a),this}};la.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);le.reduceDescriptors(la.prototype,({value:o},a)=>{let t=a[0].toUpperCase()+a.slice(1);return{get:()=>o,set(n){this[t]=n}}});le.freezeMethods(la);function Hs(o,a){const t=this||Fi,n=a||t,i=la.from(n.headers);let r=n.data;return le.forEach(o,function(l){r=l.call(t,r,i.normalize(),a?a.status:void 0)}),i.normalize(),r}function kp(o){return!!(o&&o.__CANCEL__)}function Bo(o,a,t){Xe.call(this,o??"canceled",Xe.ERR_CANCELED,a,t),this.name="CanceledError"}le.inherits(Bo,Xe,{__CANCEL__:!0});function _p(o,a,t){const n=t.config.validateStatus;!t.status||!n||n(t.status)?o(t):a(new Xe("Request failed with status code "+t.status,[Xe.ERR_BAD_REQUEST,Xe.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function eS(o){const a=/^([-+\w]{1,25})(:?\/\/|:)/.exec(o);return a&&a[1]||""}function tS(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 f=r,m=0;for(;f!==i;)m+=t[f++],f=f%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(m*1e3/p):void 0}}function aS(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(),f=u-t;f>=n?s(c,u):(i=c,r||(r=setTimeout(()=>{r=null,s(i)},n-f)))},()=>i&&s(i)]}const Dr=(o,a,t=3)=>{let n=0;const i=tS(50,250);return aS(r=>{const s=r.loaded,l=r.lengthComputable?r.total:void 0,d=s-n,c=i(d),u=s<=l;n=s;const f={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(f)},t)},Xc=(o,a)=>{const t=o!=null;return[n=>a[0]({lengthComputable:t,total:o,loaded:n}),a[1]]},Gc=o=>(...a)=>le.asap(()=>o(...a)),nS=ea.hasStandardBrowserEnv?((o,a)=>t=>(t=new URL(t,ea.origin),o.protocol===t.protocol&&o.host===t.host&&(a||o.port===t.port)))(new URL(ea.origin),ea.navigator&&/(msie|trident)/i.test(ea.navigator.userAgent)):()=>!0,oS=ea.hasStandardBrowserEnv?{write(o,a,t,n,i,r){const s=[o+"="+encodeURIComponent(a)];le.isNumber(t)&&s.push("expires="+new Date(t).toGMTString()),le.isString(n)&&s.push("path="+n),le.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 iS(o){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(o)}function rS(o,a){return a?o.replace(/\/?\/$/,"")+"/"+a.replace(/^\/+/,""):o}function Ep(o,a,t){let n=!iS(a);return o&&(n||t==!1)?rS(o,a):a}const Jc=o=>o instanceof la?{...o}:o;function Zn(o,a){a=a||{};const t={};function n(c,u,f,m){return le.isPlainObject(c)&&le.isPlainObject(u)?le.merge.call({caseless:m},c,u):le.isPlainObject(u)?le.merge({},u):le.isArray(u)?u.slice():u}function i(c,u,f,m){if(le.isUndefined(u)){if(!le.isUndefined(c))return n(void 0,c,f,m)}else return n(c,u,f,m)}function r(c,u){if(!le.isUndefined(u))return n(void 0,u)}function s(c,u){if(le.isUndefined(u)){if(!le.isUndefined(c))return n(void 0,c)}else return n(void 0,u)}function l(c,u,f){if(f in a)return n(c,u);if(f 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,f)=>i(Jc(c),Jc(u),f,!0)};return le.forEach(Object.keys({...o,...a}),function(u){const f=d[u]||i,m=f(o[u],a[u],u);le.isUndefined(m)&&f!==l||(t[u]=m)}),t}const xp=o=>{const a=Zn({},o);let{data:t,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:r,headers:s,auth:l}=a;a.headers=s=la.from(s),a.url=bp(Ep(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(le.isFormData(t)){if(ea.hasStandardBrowserEnv||ea.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if((d=s.getContentType())!==!1){const[c,...u]=d?d.split(";").map(f=>f.trim()).filter(Boolean):[];s.setContentType([c||"multipart/form-data",...u].join("; "))}}if(ea.hasStandardBrowserEnv&&(n&&le.isFunction(n)&&(n=n(a)),n||n!==!1&&nS(a.url))){const c=i&&r&&oS.read(r);c&&s.set(i,c)}return a},sS=typeof XMLHttpRequest<"u",lS=sS&&function(o){return new Promise(function(t,n){const i=xp(o);let r=i.data;const s=la.from(i.headers).normalize();let{responseType:l,onUploadProgress:d,onDownloadProgress:c}=i,u,f,m,p,h;function v(){p&&p(),h&&h(),i.cancelToken&&i.cancelToken.unsubscribe(u),i.signal&&i.signal.removeEventListener("abort",u)}let w=new XMLHttpRequest;w.open(i.method.toUpperCase(),i.url,!0),w.timeout=i.timeout;function x(){if(!w)return;const _=la.from("getAllResponseHeaders"in w&&w.getAllResponseHeaders()),E={data:!l||l==="text"||l==="json"?w.responseText:w.response,status:w.status,statusText:w.statusText,headers:_,config:o,request:w};_p(function(N){t(N),v()},function(N){n(N),v()},E),w=null}"onloadend"in w?w.onloadend=x:w.onreadystatechange=function(){!w||w.readyState!==4||w.status===0&&!(w.responseURL&&w.responseURL.indexOf("file:")===0)||setTimeout(x)},w.onabort=function(){w&&(n(new Xe("Request aborted",Xe.ECONNABORTED,o,w)),w=null)},w.onerror=function(){n(new Xe("Network Error",Xe.ERR_NETWORK,o,w)),w=null},w.ontimeout=function(){let g=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const E=i.transitional||yp;i.timeoutErrorMessage&&(g=i.timeoutErrorMessage),n(new Xe(g,E.clarifyTimeoutError?Xe.ETIMEDOUT:Xe.ECONNABORTED,o,w)),w=null},r===void 0&&s.setContentType(null),"setRequestHeader"in w&&le.forEach(s.toJSON(),function(g,E){w.setRequestHeader(E,g)}),le.isUndefined(i.withCredentials)||(w.withCredentials=!!i.withCredentials),l&&l!=="json"&&(w.responseType=i.responseType),c&&([m,h]=Dr(c,!0),w.addEventListener("progress",m)),d&&w.upload&&([f,p]=Dr(d),w.upload.addEventListener("progress",f),w.upload.addEventListener("loadend",p)),(i.cancelToken||i.signal)&&(u=_=>{w&&(n(!_||_.type?new Bo(null,o,w):_),w.abort(),w=null)},i.cancelToken&&i.cancelToken.subscribe(u),i.signal&&(i.signal.aborted?u():i.signal.addEventListener("abort",u)));const T=eS(i.url);if(T&&ea.protocols.indexOf(T)===-1){n(new Xe("Unsupported protocol "+T+":",Xe.ERR_BAD_REQUEST,o));return}w.send(r||null)})},dS=(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 Xe?u:new Bo(u instanceof Error?u.message:u))}};let s=a&&setTimeout(()=>{s=null,r(new Xe(`timeout ${a} of ms exceeded`,Xe.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=()=>le.asap(l),d}},cS=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},uS=async function*(o,a){for await(const t of mS(o))yield*cS(t,a)},mS=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()}},Kc=(o,a,t,n)=>{const i=uS(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 f=u.byteLength;if(t){let m=r+=f;t(m)}d.enqueue(new Uint8Array(u))}catch(c){throw l(c),c}},cancel(d){return l(d),i.return()}},{highWaterMark:2})},us=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Sp=us&&typeof ReadableStream=="function",pS=us&&(typeof TextEncoder=="function"?(o=>a=>o.encode(a))(new TextEncoder):async o=>new Uint8Array(await new Response(o).arrayBuffer())),Cp=(o,...a)=>{try{return!!o(...a)}catch{return!1}},fS=Sp&&Cp(()=>{let o=!1;const a=new Request(ea.origin,{body:new ReadableStream,method:"POST",get duplex(){return o=!0,"half"}}).headers.has("Content-Type");return o&&!a}),qc=64*1024,Al=Sp&&Cp(()=>le.isReadableStream(new Response("").body)),Rr={stream:Al&&(o=>o.body)};us&&(o=>{["text","arrayBuffer","blob","formData","stream"].forEach(a=>{!Rr[a]&&(Rr[a]=le.isFunction(o[a])?t=>t[a]():(t,n)=>{throw new Xe(`Response type '${a}' is not supported`,Xe.ERR_NOT_SUPPORT,n)})})})(new Response);const hS=async o=>{if(o==null)return 0;if(le.isBlob(o))return o.size;if(le.isSpecCompliantForm(o))return(await new Request(ea.origin,{method:"POST",body:o}).arrayBuffer()).byteLength;if(le.isArrayBufferView(o)||le.isArrayBuffer(o))return o.byteLength;if(le.isURLSearchParams(o)&&(o=o+""),le.isString(o))return(await pS(o)).byteLength},vS=async(o,a)=>{const t=le.toFiniteNumber(o.getContentLength());return t??hS(a)},gS=us&&(async o=>{let{url:a,method:t,data:n,signal:i,cancelToken:r,timeout:s,onDownloadProgress:l,onUploadProgress:d,responseType:c,headers:u,withCredentials:f="same-origin",fetchOptions:m}=xp(o);c=c?(c+"").toLowerCase():"text";let p=dS([i,r&&r.toAbortSignal()],s),h;const v=p&&p.unsubscribe&&(()=>{p.unsubscribe()});let w;try{if(d&&fS&&t!=="get"&&t!=="head"&&(w=await vS(u,n))!==0){let E=new Request(a,{method:"POST",body:n,duplex:"half"}),S;if(le.isFormData(n)&&(S=E.headers.get("content-type"))&&u.setContentType(S),E.body){const[N,V]=Xc(w,Dr(Gc(d)));n=Kc(E.body,qc,N,V)}}le.isString(f)||(f=f?"include":"omit");const x="credentials"in Request.prototype;h=new Request(a,{...m,signal:p,method:t.toUpperCase(),headers:u.normalize().toJSON(),body:n,duplex:"half",credentials:x?f:void 0});let T=await fetch(h,m);const _=Al&&(c==="stream"||c==="response");if(Al&&(l||_&&v)){const E={};["status","statusText","headers"].forEach(A=>{E[A]=T[A]});const S=le.toFiniteNumber(T.headers.get("content-length")),[N,V]=l&&Xc(S,Dr(Gc(l),!0))||[];T=new Response(Kc(T.body,qc,N,()=>{V&&V(),v&&v()}),E)}c=c||"text";let g=await Rr[le.findKey(Rr,c)||"text"](T,o);return!_&&v&&v(),await new Promise((E,S)=>{_p(E,S,{data:g,headers:la.from(T.headers),status:T.status,statusText:T.statusText,config:o,request:h})})}catch(x){throw v&&v(),x&&x.name==="TypeError"&&/Load failed|fetch/i.test(x.message)?Object.assign(new Xe("Network Error",Xe.ERR_NETWORK,o,h),{cause:x.cause||x}):Xe.from(x,x&&x.code,o,h)}}),Ll={http:Mx,xhr:lS,fetch:gS};le.forEach(Ll,(o,a)=>{if(o){try{Object.defineProperty(o,"name",{value:a})}catch{}Object.defineProperty(o,"adapterName",{value:a})}});const Yc=o=>`- ${o}`,bS=o=>le.isFunction(o)||o===null||o===!1,Vp={getAdapter:o=>{o=le.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,!bS(t)&&(n=Ll[(s=String(t)).toLowerCase()],n===void 0))throw new Xe(`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(Yc).join(`
|
|
348
|
-
`):" "+Yc(r[0]):"as no adapter specified";throw new Xe("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return n},adapters:Ll};function Zs(o){if(o.cancelToken&&o.cancelToken.throwIfRequested(),o.signal&&o.signal.aborted)throw new Bo(null,o)}function Qc(o){return Zs(o),o.headers=la.from(o.headers),o.data=Hs.call(o,o.transformRequest),["post","put","patch"].indexOf(o.method)!==-1&&o.headers.setContentType("application/x-www-form-urlencoded",!1),Vp.getAdapter(o.adapter||Fi.adapter)(o).then(function(n){return Zs(o),n.data=Hs.call(o,o.transformResponse,n),n.headers=la.from(n.headers),n},function(n){return kp(n)||(Zs(o),n&&n.response&&(n.response.data=Hs.call(o,o.transformResponse,n.response),n.response.headers=la.from(n.response.headers))),Promise.reject(n)})}const Np="1.11.0",ms={};["object","boolean","number","function","string","symbol"].forEach((o,a)=>{ms[o]=function(n){return typeof n===o||"a"+(a<1?"n ":" ")+o}});const eu={};ms.transitional=function(a,t,n){function i(r,s){return"[Axios v"+Np+"] Transitional option '"+r+"'"+s+(n?". "+n:"")}return(r,s,l)=>{if(a===!1)throw new Xe(i(s," has been removed"+(t?" in "+t:"")),Xe.ERR_DEPRECATED);return t&&!eu[s]&&(eu[s]=!0),a?a(r,s,l):!0}};ms.spelling=function(a){return(t,n)=>!0};function yS(o,a,t){if(typeof o!="object")throw new Xe("options must be an object",Xe.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 Xe("option "+r+" must be "+d,Xe.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new Xe("Unknown option "+r,Xe.ERR_BAD_OPTION)}}const wr={assertOptions:yS,validators:ms},Oa=wr.validators;let zn=class{constructor(a){this.defaults=a||{},this.interceptors={request:new Hc,response:new Hc}}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=Zn(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;n!==void 0&&wr.assertOptions(n,{silentJSONParsing:Oa.transitional(Oa.boolean),forcedJSONParsing:Oa.transitional(Oa.boolean),clarifyTimeoutError:Oa.transitional(Oa.boolean)},!1),i!=null&&(le.isFunction(i)?t.paramsSerializer={serialize:i}:wr.assertOptions(i,{encode:Oa.function,serialize:Oa.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),wr.assertOptions(t,{baseUrl:Oa.spelling("baseURL"),withXsrfToken:Oa.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&le.merge(r.common,r[t.method]);r&&le.forEach(["delete","get","head","post","put","patch","common"],h=>{delete r[h]}),t.headers=la.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,f=0,m;if(!d){const h=[Qc.bind(this),void 0];for(h.unshift(...l),h.push(...c),m=h.length,u=Promise.resolve(t);f<m;)u=u.then(h[f++],h[f++]);return u}m=l.length;let p=t;for(f=0;f<m;){const h=l[f++],v=l[f++];try{p=h(p)}catch(w){v.call(this,w);break}}try{u=Qc.call(this,p)}catch(h){return Promise.reject(h)}for(f=0,m=c.length;f<m;)u=u.then(c[f++],c[f++]);return u}getUri(a){a=Zn(this.defaults,a);const t=Ep(a.baseURL,a.url,a.allowAbsoluteUrls);return bp(t,a.params,a.paramsSerializer)}};le.forEach(["delete","get","head","options"],function(a){zn.prototype[a]=function(t,n){return this.request(Zn(n||{},{method:a,url:t,data:(n||{}).data}))}});le.forEach(["post","put","patch"],function(a){function t(n){return function(r,s,l){return this.request(Zn(l||{},{method:a,headers:n?{"Content-Type":"multipart/form-data"}:{},url:r,data:s}))}}zn.prototype[a]=t(),zn.prototype[a+"Form"]=t(!0)});let wS=class Tp{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 Bo(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 Tp(function(i){a=i}),cancel:a}}};function kS(o){return function(t){return o.apply(null,t)}}function _S(o){return le.isObject(o)&&o.isAxiosError===!0}const Pl={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(Pl).forEach(([o,a])=>{Pl[a]=o});function Ip(o){const a=new zn(o),t=rp(zn.prototype.request,a);return le.extend(t,zn.prototype,a,{allOwnKeys:!0}),le.extend(t,a,null,{allOwnKeys:!0}),t.create=function(i){return Ip(Zn(o,i))},t}const Bt=Ip(Fi);Bt.Axios=zn;Bt.CanceledError=Bo;Bt.CancelToken=wS;Bt.isCancel=kp;Bt.VERSION=Np;Bt.toFormData=cs;Bt.AxiosError=Xe;Bt.Cancel=Bt.CanceledError;Bt.all=function(a){return Promise.all(a)};Bt.spread=kS;Bt.isAxiosError=_S;Bt.mergeConfig=Zn;Bt.AxiosHeaders=la;Bt.formToJSON=o=>wp(le.isHTMLForm(o)?new FormData(o):o);Bt.getAdapter=Vp.getAdapter;Bt.HttpStatusCode=Pl;Bt.default=Bt;const{Axios:iR,AxiosError:rR,CanceledError:sR,isCancel:lR,CancelToken:dR,VERSION:cR,all:uR,Cancel:mR,isAxiosError:pR,spread:fR,toFormData:hR,AxiosHeaders:vR,HttpStatusCode:gR,formToJSON:bR,getAdapter:yR,mergeConfig:wR}=Bt;class ps{constructor(a="/api/v1"){this.eventSource=null,this.progressCallbacks=new Map,this.api=Bt.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 ps;const ES={key:0,class:"mobile-layout"},xS={class:"mobile-toolbar"},SS={class:"mobile-toolbar-left"},CS=["aria-label"],VS={class:"mobile-toolbar-right"},NS=["disabled"],TS=["disabled"],IS={class:"preview-section"},BS={key:0,class:"mobile-export-overlay"},MS={class:"mobile-export-progress"},FS={class:"mobile-export-bar"},$S={class:"mobile-timeline-zoom"},DS={class:"mobile-edit-strip"},RS={class:"mobile-selection-summary"},AS={class:"mobile-selection-title"},LS={class:"mobile-selection-meta"},PS={class:"mobile-readout-row"},US=["disabled"],OS={class:"mobile-readout-grid"},zS={class:"mobile-readout-chip","data-testid":"mobile-playhead-readout"},jS={class:"mobile-readout-chip","data-testid":"mobile-clip-in-readout"},WS={class:"mobile-readout-chip","data-testid":"mobile-clip-out-readout"},HS={class:"mobile-readout-chip","data-testid":"mobile-duration-readout"},ZS=["disabled"],XS={class:"mobile-speed-strip"},GS={class:"mobile-speed-chips"},JS=["data-testid","onClick"],KS={class:"mobile-edit-actions"},qS=["disabled"],YS=["disabled"],QS=["disabled"],eC=["disabled"],tC=["disabled"],aC={class:"mobile-action-sheet-header"},nC={class:"mobile-action-sheet-title"},oC={class:"mobile-action-sheet-subtitle"},iC={class:"mobile-action-sheet-actions"},rC=["disabled"],sC=["disabled"],lC=["disabled"],dC=["disabled"],cC=["disabled"],uC={key:1,class:"desktop-layout"},mC={class:"desktop-main-row"},pC={class:"preview-panel"},fC={class:"fit-toggle"},hC={class:"editor-content"},vC={class:"editor-tabs"},gC={class:"tab-header"},bC=["onClick"],yC={class:"tab-content-area"},wC={class:"filter-controls"},kC={class:"text-controls"},_C={class:"transition-controls"},EC={class:"audio-controls"},xC={class:"adjustments-controls"},SC={key:1,class:"no-filter-selected"},CC={class:"export-controls"},VC={key:0,"data-testid":"video-export-status-completed"},NC={key:1,"data-testid":"video-export-status-message",class:"export-status-message"},TC={class:"desktop-timeline-row"},IC={class:"timeline-zoom"},BC=["value"],MC={class:"zoom-readout"},FC={key:0,class:"dev-editor-controls","data-testid":"video-editor-dev-controls"},$C={class:"dev-editor-row"},DC={class:"dev-editor-field"},RC={class:"dev-editor-field"},AC=["disabled"],LC=["disabled"],PC=["disabled"],UC={class:"dev-editor-row"},OC={class:"dev-editor-field dev-editor-field--wide"},zC=["value"],jC=["disabled"],WC=["disabled"],HC=["disabled"],ZC=["disabled"],XC=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 k=n.media.uuid??n.media.id;return typeof k=="string"&&k.trim()!==""?k.trim():void 0}),s=e.computed(()=>{const k=typeof n.mediaUuid=="string"?n.mediaUuid.trim():"";return k!==""?k: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 k=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},D=n.featureFlags;return D?{filters:typeof D.filters=="boolean"?D.filters:k.filters,adjustments:typeof D.adjustments=="boolean"?D.adjustments:k.adjustments,text:typeof D.text=="boolean"?D.text:k.text,transitions:typeof D.transitions=="boolean"?D.transitions:k.transitions,audio:typeof D.audio=="boolean"?D.audio:k.audio,export:typeof D.export=="boolean"?D.export:k.export}:k}),f=e.computed(()=>l.value?d.value:c.value),m=e.computed(()=>f.value==="filters"||w.value),p=e.computed(()=>f.value!=="filters"&&!w.value),h=e.ref(null),v=e.ref(null),w=e.ref(!1),x=e.computed(()=>l.value?h.value:v.value);function T(k){return k==="contain"||k==="cover"||k==="none"}function _(k){if(!(k!=null&&k.metadata))return null;const D=k.metadata.fit_mode;return T(D)?D:null}const g=e.shallowRef(null),E=e.ref(null),S=e.ref(_(n.initialRecipe)??"contain"),N=e.ref(null),V=e.ref(null),A=e.ref(null),j=e.ref(!1),C=new Map,$=e.ref([]),y=e.ref([]),R=e.ref([]),L=e.ref([]),U=e.ref(1),z=()=>{l.value=window.innerWidth<768},I=[{id:"filters",label:"Filters",icon:gn},{id:"adjustments",label:"Adjust",icon:Ah},{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:ko}],P=[{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(k=>u.value[k.id])),K=e.computed(()=>P.filter(k=>u.value[k.id])),ve=e.computed(()=>{var k,D;return((k=K.value[0])==null?void 0:k.id)??((D=Z.value[0])==null?void 0:D.id)??"filters"});e.watch(u,k=>{k[d.value]||(d.value=ve.value),k[c.value]||(c.value=ve.value)},{immediate:!0,deep:!0}),e.watch(ve,k=>{u.value[d.value]||(d.value=k),u.value[c.value]||(c.value=k)},{immediate:!0}),e.watch(u,k=>{k.export||(d.value==="export"&&(d.value=ve.value),c.value==="export"&&(c.value=ve.value))},{immediate:!0,deep:!0});const Ve=e.computed(()=>typeof window>"u"?!1:window.__MEDIABLES_EDITOR_DEV__===!0),ne=zu(),{currentFrame:ae,playheadPosition:F,timelineClips:B,totalDuration:O,hasChanges:X,isPlaying:oe,selectedClip:ce,zoomLevel:je,playbackSpeed:he,fps:ge,handleTrim:pe,handleSplit:we,handleClipSelect:ye,splitAtPlayhead:Ne,deleteSelectedClip:De,duplicateSelectedClip:Qe,setZoomLevel:et,moveClip:Lt,setFilters:kt,setTextOverlays:Ct,setAudioTracks:bt,saveDraft:rt,clearHasChanges:_t,resetChanges:be,generateRecipe:ke,zoomIn:Te,zoomOut:Ke,fitToWindow:Ge,togglePlayback:ze,setPlaying:Et,seekTo:ut,frameForward:Xt,frameBackward:Wt,skipToStart:ca,skipToEnd:ta,setPlaybackSpeed:ya,updateSourceDuration:Sa,undo:wa,redo:nn,canUndo:Q,canRedo:ue}=ep(s.value,n.initialRecipe,n.media),{videoCompatibleFilters:re,activeFilters:ie,selectedFilter:Se,previewFilter:Ae,previewFilterEffect:qe,applyFilter:ft,updateFilterParams:Vt,removeFilter:ht,clearAllFilters:vt,setActiveFilters:Ut}=np();function Mt(k){var ee,fe;const D=((ee=ce.value)==null?void 0:ee.id)??((fe=B.value[0])==null?void 0:fe.id);D&&(j.value=!0,typeof k=="object"&&k.id?ft(k.id):typeof k=="string"&&ft(k),kt(ie.value),g.value?g.value.setClipFilters(D,ie.value):C.set(D,[...ie.value]),ye(D),j.value=!1,Pa())}function Ft(){var D,ee;const k=((D=ce.value)==null?void 0:D.id)??((ee=B.value[0])==null?void 0:ee.id);k&&ye(k)}function on(k){const D=ie.value.find(ee=>ee.filterId===k);D&&ht(D.id)}const Fa=e.computed(()=>re.value.map(D=>{var fe;const ee=[];if(D.controls&&D.controls.length>0)for(const Ce of D.controls){const Ee=Ce.type;if(Ee==="button"||Ee==="text"||Ee==="range")continue;const xe={id:Ce.property||Ce.id,label:Ce.label||Ce.id,type:Ee,default:Ce.default??(Ee==="toggle"?!1:Ee==="color"?"#ffffff":0)};Ee==="slider"&&(xe.min=Ce.min??0,xe.max=Ce.max??1,xe.step=Ce.step??.01),Ee==="select"&&Ce.options&&(xe.options=Ce.options),ee.push(xe)}else if(D.paramRanges){const Ce=Object.entries(D.paramRanges);for(const[Ee,xe]of Ce){const ct=Ee.replace(/[-_]/g," ").replace(/\b\w/g,Bn=>Bn.toUpperCase()),fa=(fe=D.defaultParams)==null?void 0:fe[Ee],uo=(xe.min+xe.max)/2;ee.push({id:Ee,label:ct,min:xe.min,max:xe.max,step:xe.step??.01,default:typeof fa=="number"?fa:uo})}}return{id:D.id,name:D.name,category:D.category,params:ee}})),Ca=e.ref("0.00"),Va=e.ref("0.00"),ua=e.ref("");e.watch(Fa,k=>{if(k.length===0){ua.value="";return}k.some(ee=>ee.id===ua.value)||(ua.value=k[0].id)},{immediate:!0});const yt=e.ref(!1),wt=e.ref(0),ma=e.ref(!1),mt=e.ref(null),Ot=e.ref(null);let $a=null,H=!1;const G=e.computed(()=>{const k=new Map;return ie.value.forEach(D=>k.set(D.filterId,D)),k}),se=e.computed(()=>{var k,D;return ae.value?ae.value:((k=n.media)==null?void 0:k.thumbnail_url)||((D=n.media)==null?void 0:D.url)}),de=e.ref("");e.watch(()=>{var k,D;return{file:(k=n.media)==null?void 0:k.file,url:(D=n.media)==null?void 0:D.url}},(k,D,ee)=>{var Ce,Ee;const fe=de.value;ee(()=>{fe&&fe.startsWith("blob:")&&URL.revokeObjectURL(fe)}),(Ce=n.media)!=null&&Ce.file?de.value=URL.createObjectURL(n.media.file):(Ee=n.media)!=null&&Ee.url?de.value=n.media.url:de.value=""},{immediate:!0}),e.onUnmounted(()=>{de.value&&de.value.startsWith("blob:")&&URL.revokeObjectURL(de.value)});const _e=e.computed(()=>de.value),Le=Vm({forcePixiPreview:w,getPreviewRef:()=>x.value,getSourceUrl:()=>de.value,setPlaying:Et}),tt=e.computed(()=>{if(!n.media)return null;const{file:k,...D}=n.media;return{...D,url:de.value}}),He=e.computed(()=>{var D;const k=(D=n.media)==null?void 0:D.url;return!!(k&&/^https?:/i.test(k))}),Pe=e.computed(()=>ie.value),ot=e.computed(()=>F.value),st=e.computed(()=>!!ce.value&&F.value>0),Ze=e.computed(()=>!!ce.value&&B.value.length>1),Gt=e.computed(()=>!!ce.value),Nt=e.ref(!0),En=[.5,1,1.5,2],rn=e.computed(()=>{const k=new Set([0,oa.value]);for(const D of B.value)k.add(D.timelineStart),k.add(D.timelineEnd);return Array.from(k).filter(D=>Number.isFinite(D)).sort((D,ee)=>D-ee)}),gs=e.computed(()=>rn.value.some(k=>k<F.value-.001)),sn=e.computed(()=>rn.value.some(k=>k>F.value+.001)),Qn=e.ref(!1),xn=e.ref(null);function Na(k){if(!Number.isFinite(k)||k<0)return"0:00";const D=Math.floor(k/60),ee=Math.floor(k%60);return`${D}:${ee.toString().padStart(2,"0")}`}const $i=e.computed(()=>{var ee;const k=ce.value??B.value[0];if(!k)return"No clip selected";const D=(ee=k.label)==null?void 0:ee.trim();return D&&D.length>0?D:`Clip ${k.id.slice(-4)}`}),bs=e.computed(()=>{const k=ce.value??B.value[0];if(!k)return"Tap a clip to start editing";const D=Math.max(0,k.timelineEnd-k.timelineStart);return`${Na(k.timelineStart)} - ${Na(k.timelineEnd)} • ${D.toFixed(1)}s`});function Di(k){return!Number.isFinite(k)||k<0?"0.0s":k<60?`${k.toFixed(1)}s`:Na(k)}const ys=e.computed(()=>Na(F.value)),Mo=e.computed(()=>{const k=ce.value??B.value[0];return k?Na(k.sourceIn):"0:00"}),Ri=e.computed(()=>{const k=ce.value??B.value[0];return k?Na(k.sourceOut):"0:00"}),ws=e.computed(()=>{const k=ce.value??B.value[0];return k?Di(k.timelineEnd-k.timelineStart):"0.0s"}),Fo=e.computed(()=>xn.value===null?ce.value??B.value[0]??null:B.value.find(k=>k.id===xn.value)??null),ks=e.computed(()=>{var ee;const k=Fo.value;if(!k)return"Clip actions";const D=(ee=k.label)==null?void 0:ee.trim();return D&&D.length>0?D:`Clip ${k.id.slice(-4)}`}),_s=e.computed(()=>{const k=Fo.value;return k?`${Na(k.timelineStart)} - ${Na(k.timelineEnd)} • ${Di(k.timelineEnd-k.timelineStart)}`:"Choose an action"}),Sn=e.ref(0),oa=e.computed(()=>{try{const k=O.value??O;return k&&typeof k=="number"&&k>0?k:Sn.value}catch{return Sn.value}}),ln=e.ref(),$o=e.ref(),Do=e.ref(),dn=e.ref(),eo=e.ref(0),Ja=e.ref(!1);let Jt=null,ka=null;e.watch(oa,k=>{var ee;if(Ja.value||!k||k<=0)return;const D=eo.value||((ee=ln.value)==null?void 0:ee.clientWidth)||0;D>0&&(Ja.value=!0,Ge(D))}),e.watch(eo,k=>{if(Ja.value||!k||k<=0)return;oa.value>0&&(Ja.value=!0,Ge(k))}),e.watch(l,k=>{k||Aa()}),e.watch(()=>{var k;return(k=Fo.value)==null?void 0:k.id},k=>{Qn.value&&!k&&Aa()});function Ka(k){return Number.isFinite(k)?k.toFixed(2):"0.00"}function Ai(k){const D=Number(k);return Number.isFinite(D)?D:null}function Ht(k){k&&(Ca.value=Ka(k.sourceIn),Va.value=Ka(k.sourceOut))}e.watch(()=>{var k,D,ee;return[(k=ce.value)==null?void 0:k.id,(D=ce.value)==null?void 0:D.sourceIn,(ee=ce.value)==null?void 0:ee.sourceOut]},()=>{Ht(ce.value)},{immediate:!0});function cn(k){const D=ce.value;if(!D)return;const ee=1/30,fe=D.sourceMinIn??0,Ce=D.sourceMaxOut??oa.value,Ee=D.sourceIn+(F.value-D.timelineStart);if(k==="start"){const ct=Math.max(fe,Math.min(Ee,D.sourceOut-ee));Ca.value=Ka(ct);return}const xe=Math.max(D.sourceIn+ee,Math.min(Ee,Ce));Va.value=Ka(xe)}function Da(){const k=ce.value;if(!k)return;const D=Ai(Ca.value),ee=Ai(Va.value);if(D===null||ee===null)return;const fe=1/30,Ce=k.sourceMinIn??0,Ee=k.sourceMaxOut??oa.value,xe=Math.max(Ce,Math.min(D,Ee-fe)),ct=Math.max(xe+fe,Math.min(ee,Ee));pe(k.id,"start",xe),pe(k.id,"end",ct),Ca.value=Ka(xe),Va.value=Ka(ct),ce.value&&ut(ce.value.timelineStart)}function St(){ua.value.trim()!==""&&Mt(ua.value)}function qa(){var k;vt(),kt(ie.value),(k=ce.value)!=null&&k.id&&(g.value?g.value.setClipFilters(ce.value.id,ie.value):C.set(ce.value.id,[...ie.value])),Pa()}function to(k,D,ee){var Ce,Ee;const fe=ie.value.find(xe=>xe.filterId===k);fe?(fe.params={...fe.params,[D]:ee},kt(ie.value),g.value&&((Ce=ce.value)!=null&&Ce.id)?g.value.setClipFilters(ce.value.id,ie.value):(Ee=ce.value)!=null&&Ee.id&&C.set(ce.value.id,[...ie.value]),Pa(),Ft()):Ae.value&&Ae.value.filterId===k&&(Ae.value.params={...Ae.value.params||{},[D]:ee})}function Cn(k){ut(k)}function Ra(k){!k||!Number.isFinite(k.timestamp)||ut(k.timestamp)}function Ro(k){Et(k)}function ao(k){!Number.isFinite(k)||k<=0||(Sn.value=k,Sa(k))}function Aa(){Qn.value=!1,xn.value=null}function pa(k){l.value&&(xn.value=k,Qn.value=!0)}function Ao(k){var fe,Ce,Ee,xe;const D=((fe=ce.value)==null?void 0:fe.id)??((Ce=B.value[0])==null?void 0:Ce.id)??null;ye(k),(((Ee=ce.value)==null?void 0:Ee.id)??((xe=B.value[0])==null?void 0:xe.id)??null)!==D&&ne.selection()}function Li(k){Ao(k),pa(k)}function Vn(k){k&&ne.selection()}function no(){Nt.value=!Nt.value,ne.selection()}function La(){const k=rn.value.filter(ee=>ee<F.value-.001),D=k.length>0?k[k.length-1]:0;ut(D)}function Pi(){const k=rn.value.find(D=>D>F.value+.001);ut(k??oa.value)}function oo(){wa()}function io(){nn()}function un(){const k=B.value.length;Ne(),B.value.length>k&&(ne.success(),Aa())}function Lo(k){const D=B.value.length;we(k),B.value.length>D&&ne.success()}function Nn(){const k=B.value.length;Qe(),B.value.length>k&&(ne.selection(),Aa())}function ro(){const k=B.value.length;De(),B.value.length<k&&(ne.error(),Aa())}function Tn(k){const D=he.value;ya(k),he.value!==D&&ne.selection()}function so(k){return k instanceof HTMLElement?k.closest('input, textarea, select, button, [contenteditable="true"]')!==null:!1}function mn(k){if(l.value||so(k.target))return;const D=k.key.toLowerCase(),ee=k.metaKey||k.ctrlKey;if(k.code==="Space"){k.preventDefault(),ze();return}if(!ee&&D==="s"){k.preventDefault(),un();return}if(D==="arrowleft"){k.preventDefault(),Wt();return}if(D==="arrowright"){k.preventDefault(),Xt();return}if(D==="home"){k.preventDefault(),ca();return}if(D==="end"){k.preventDefault(),ta();return}if(!ee&&D==="["){k.preventDefault(),La();return}if(!ee&&D==="]"){k.preventDefault(),Pi();return}if(ee&&D==="z"&&k.shiftKey){k.preventDefault(),io();return}ee&&D==="z"&&(k.preventDefault(),oo())}function Ui(){var D;const k=eo.value||((D=ln.value)==null?void 0:D.clientWidth)||800;Ge(k)}function Po(k){Ja.value=!0,et(k)}function Md(){Ja.value=!0,Te()}function Fd(){Ja.value=!0,Ke()}function lo(k){const D=k.target,ee=Number(D.value);Po(ee)}function Uo(k){const D=Math.min(600,Math.max(10,je.value+k));Po(D)}function Oo(){ka==null||ka(),ka=null;const k=Do.value,D=dn.value;if(!l.value||!k||!D)return;const ee=()=>{Uo(-20)},fe=()=>{Uo(20)};k.addEventListener("click",ee),D.addEventListener("click",fe),ka=()=>{k.removeEventListener("click",ee),D.removeEventListener("click",fe)}}e.watch([l,Do,dn],()=>{Oo()},{flush:"post"});function Oi(k){var D;g.value=k,(D=g.value)!=null&&D.composition&&(N.value=new op(g.value.composition),V.value=new vi(g.value.composition),A.value=new ip(g.value.composition));try{C.size&&(C.forEach((ee,fe)=>{g.value.setClipFilters(fe,ee)}),C.clear(),g.value.composition.computeFrame())}catch{}}function zi(k){k!=null&&k.id&&qe(k.id)}function ji(k){Vt(k),Pa()}async function Wi(k){if(!N.value)return;const D=await N.value.addTextOverlay(k);$.value.push({id:D,...k})}async function Hi(k,D){if(!N.value)return;await N.value.updateTextOverlay(k,D);const ee=$.value.findIndex(fe=>fe.id===k);ee!==-1&&($.value[ee]={...$.value[ee],...D})}async function b(k){N.value&&(await N.value.removeTextOverlay(k),$.value=$.value.filter(D=>D.id!==k))}async function M(k){if(!V.value||L.value.length<2)return;const[D,ee]=L.value,fe=await V.value.applyTransition(D,ee,k);y.value.push({id:fe,...k,name:k.type})}function q(k){if(!V.value)return;const D=y.value[k];D&&(V.value.removeTransition(D.id),y.value.splice(k,1))}function me(k){}async function Me(k){if(!A.value)return;const D=await A.value.addAudioTrack(k);R.value.push({id:D,...k})}async function Fe(k,D){if(!A.value)return;const ee=R.value.findIndex(fe=>fe.id===k);ee!==-1&&(R.value[ee]={...R.value[ee],...D})}async function Ye(k){A.value&&(await A.value.removeAudioTrack(k),R.value=R.value.filter(D=>D.id!==k))}async function pt(k,D){if(!A.value)return;await A.value.updateVolume(k,D);const ee=R.value.find(fe=>fe.id===k);ee&&(ee.volume=D)}async function $t(k,D){if(!A.value)return;await A.value.muteTrack(k,D);const ee=R.value.find(fe=>fe.id===k);ee&&(ee.muted=D)}function aa(k){A.value&&(A.value.setMasterVolume(k),U.value=k)}function co(k){i("thumbnail-selected",k)}function pn(){$a!==null&&(clearInterval($a),$a=null)}function ff(k,D){return D?{...k,output:{...k.output,format:D.format,quality:D.quality}}:k}function zo(k){var D;return k.metadata||(k.metadata={created_at:new Date().toISOString(),editor_version:"2.0.0"}),k.metadata.fit_mode=S.value,(D=n.media)!=null&&D.url&&/^https?:/i.test(n.media.url)?k.metadata.source_url=n.media.url:delete k.metadata.source_url,k}function Tt(k,D,ee){return Math.min(ee,Math.max(D,k))}function Es(k,D){if(typeof k=="number"&&Number.isFinite(k))return k;if(typeof k=="string"){const ee=Number(k);if(Number.isFinite(ee))return ee}return D}function Kt(k,D,ee){for(const fe of D)if(fe in k)return Es(k[fe],ee);return ee}function hf(k){const D=typeof k.params=="object"&&k.params!==null?k.params:{};switch(k.filterId.trim().toLowerCase()){case"brightness":return[{type:"brightness",value:Tt(Kt(D,["value","brightness"],0),-1,1)}];case"contrast":return[{type:"contrast",value:Tt(Kt(D,["value","contrast"],1),.1,3)}];case"saturation":return[{type:"saturation",value:Tt(Kt(D,["value","saturation"],1),0,3)}];case"blur":case"gaussian-blur":case"kawase-blur":case"radial-blur":return[{type:"blur",value:Tt(Kt(D,["value","blur","radius"],0),0,25)}];case"sharpen":return[{type:"sharpen",value:Tt(Kt(D,["value","amount"],1),0,5)}];case"sepia":return[{type:"sepia",value:1}];case"grayscale":return[{type:"grayscale",value:1}];case"adjustment":{const fe=Tt(Kt(D,["brightness"],1)-1,-1,1),Ce=Tt(Kt(D,["contrast"],1),.1,3),Ee=Tt(Kt(D,["saturation"],1),0,3);return[{type:"brightness",value:fe},{type:"contrast",value:Ce},{type:"saturation",value:Ee}]}default:return[]}}function vf(k){const D=k.timeline[0],ee=Array.isArray(D==null?void 0:D.filters)?D.filters:[],fe=[];for(const Ee of ee)if(fe.push(...hf(Ee)),fe.length>=12)break;const Ce={...k,filters:fe.slice(0,12)};if(k.timeline.length===1&&D){const Ee=Math.max(0,Es(D.sourceIn,0)),xe=Es(D.sourceOut,Ee);xe>Ee&&(Ce.trim={start:Ee,end:xe})}return Ce}async function $d(k,D,ee){return Le.renderRecipeWithPixi(k,D,ee)}async function gf(k,D){var jo;pn(),H=!1,Le.resetClientExport(),Ot.value=null,mt.value=null,ma.value=!1,wt.value=0;const ee=zo(k??ke()),fe=Od(ee),Ce=Array.isArray(fe.filters)&&fe.filters.length>0,Ee=Cs(fe);if(!(X.value||Ce||Ee))return _t(),i("video-exported",null),null;const ct=fe.timeline[0],fa=ct?Math.max(0,ct.sourceIn):0,Bn=((ct==null?void 0:ct.sourceOut)??((jo=fe.source)==null?void 0:jo.duration)??oa.value)-fa,Ts=n.serverRenderEndpoint!=null&&n.clientExportThreshold>0&&Bn>n.clientExportThreshold;if(Ts){yt.value=!0;try{return await bf(fe),null}catch(qt){const ha=qt instanceof Error?qt.message:"Server render failed";throw mt.value=ha,i("server-render-failed",ha),qt}finally{yt.value=!1}}if(n.maxDuration>0&&Bn>n.maxDuration&&!Ts){const qt=`This video is too long for in-browser export (${Math.round(Bn)}s). Server rendering is not available. Try a shorter clip.`;return mt.value=qt,i("video-exported",null),null}yt.value=!0;try{const qt=await $d(fe,D,ha=>{H||(wt.value=ha)});return H?(mt.value="Export canceled.",wt.value=0,i("video-exported",null),null):(_t(),i("recipe-generated",fe),i("video-exported",qt),wt.value=100,ma.value=!0,qt)}catch(qt){if(H)return mt.value="Export canceled.",wt.value=0,i("video-exported",null),null;const ha=qt instanceof Error?qt.message:"Local WebGL export failed.";throw mt.value=ha,new Error(`Video export failed: ${ha}`)}finally{yt.value=!1}}function Zi(){return new ps(n.serverRenderEndpoint??"/api/v1")}async function bf(k){const D=Zi();mt.value="Starting server render...",wt.value=0;const ee=await D.createRenderJob({source_media_uuid:s.value,recipe:k});Ot.value=ee.id,i("server-render-started",ee.id),i("export-started",ee.id),mt.value="Rendering on server...";const fe=await D.pollRenderJob(ee.id,(Ee,xe)=>{wt.value=Ee,xe==="processing"&&(mt.value=`Server rendering: ${Ee}%`)},3e3,(n.maxDuration>0?n.maxDuration*3:1800)*1e3);wt.value=100,ma.value=!0,mt.value="Server render complete!",_t(),i("recipe-generated",k);const Ce={id:fe.id};typeof fe.output_media_id=="string"&&fe.output_media_id!==""&&(Ce.output_media_id=fe.output_media_id),i("server-render-completed",Ce)}async function Dd(){if(!yt.value)return;H=!0,w.value=!1,Le.cancelClientExport(),pn();const k=Ot.value;if(k)try{await Zi().cancelJob(k)}catch(D){const ee=D instanceof Error?D.message:"Failed to cancel export";mt.value=ee,yt.value=!1,Ot.value=null;return}yt.value=!1,wt.value=0,ma.value=!1,Ot.value=null,mt.value="Export canceled."}async function Rd(k){pn(),H=!1,Le.resetClientExport(),Ot.value=null,mt.value=null,ma.value=!1,yt.value=!0,wt.value=0;try{const D=zo(ff(ke(),k));i("recipe-generated",D);const ee=s.value.startsWith("temp-"),fe=D.timeline[0],Ce=Array.isArray(fe==null?void 0:fe.filters)?fe.filters:[],Ee=!0,xe=typeof window<"u"&&window.MEDIABLES_ALLOW_SERVER_EXPORT_FALLBACK===1||typeof localStorage<"u"&&localStorage.getItem("mediables.export.allowServerFallback")==="1";if(Ee)try{const ha=await $d(D,k,Bf=>{H||(wt.value=Bf)});if(H){mt.value="Export canceled.",yt.value=!1,wt.value=0;return}i("video-exported",ha);const jd=URL.createObjectURL(ha.file),Is=document.createElement("a");Is.href=jd,Is.download=`edited-video-${Date.now()}.mp4`,Is.click(),setTimeout(()=>URL.revokeObjectURL(jd),100),yt.value=!1,wt.value=100,ma.value=!0;return}catch(ha){if(H){mt.value="Export canceled.",yt.value=!1,wt.value=0;return}if(ee||!xe)throw ha;wt.value=0,mt.value="Local filter export failed, falling back to server render."}const ct={"360p":"low","480p":"low","720p":"medium","1080p":"high","1440p":"ultra","2160p":"ultra"},fa=(k==null?void 0:k.quality)??D.output.quality,uo=ct[fa]??"high",Bn={...vf(D),export:{format:(k==null?void 0:k.format)??D.output.format,quality:uo,resolution:fa,framerate:D.output.fps}},jo=await Zi().createJob({source_media_id:s.value,recipe:Bn}),qt=typeof jo.id=="string"?jo.id:null;if(!qt)throw new Error("Export failed: missing job id");Ot.value=qt,i("export-started",qt),Tf(qt)}catch(D){if(w.value=!1,Le.resetClientExport(),H){mt.value="Export canceled.",yt.value=!1,wt.value=0,Ot.value=null;return}try{const ee=zo(ke()),fe=new Blob([JSON.stringify(ee,null,2)],{type:"application/json"}),Ce=URL.createObjectURL(fe),Ee=document.createElement("a");Ee.href=Ce,Ee.download=`video-recipe-${Date.now()}.json`,Ee.click(),setTimeout(()=>URL.revokeObjectURL(Ce),100)}finally{yt.value=!1,wt.value=0,Ot.value=null,mt.value=D instanceof Error?D.message:"Export failed"}}}const xs=async k=>{await new Promise(D=>{window.setTimeout(D,k)})},Ss=k=>{if(!k||k.width<=0||k.height<=0)return null;try{return k.toDataURL("image/jpeg",.85)}catch{return null}},yf=k=>{if(!k||typeof k!="object")return null;const ee=k.pixiCanvas;if(ee&&typeof ee=="object"&&"value"in ee){const fe=ee.value;return fe instanceof HTMLCanvasElement?fe:null}return ee instanceof HTMLCanvasElement?ee:null},wf=k=>{if(!k||typeof k!="object")return null;const D=k.duration;if(typeof D=="number"&&Number.isFinite(D))return D;if(D&&typeof D=="object"&&"value"in D){const ee=D.value;if(typeof ee=="number"&&Number.isFinite(ee))return ee}return null},kf=k=>{if(!k||typeof k!="object")return null;const ee=k.videoElement;if(ee&&typeof ee=="object"&&"value"in ee){const fe=ee.value;return fe instanceof HTMLVideoElement?fe:null}return ee instanceof HTMLVideoElement?ee:null},Ad=k=>typeof k.params=="object"&&k.params!==null?k.params:{},_f=k=>{const D=[];for(const ee of k){const fe=Ad(ee),Ce=ee.filterId.trim().toLowerCase();if(Ce==="brightness"){const xe=(Tt(Kt(fe,["value","brightness"],0),-1,1)+1)*100;D.push(`brightness(${xe.toFixed(2)}%)`);continue}if(Ce==="contrast"){const Ee=Tt(Kt(fe,["value","contrast"],1),.1,4);D.push(`contrast(${(Ee*100).toFixed(2)}%)`);continue}if(Ce==="saturation"||Ce==="saturate"){const Ee=Tt(Kt(fe,["value","saturation"],1),0,4);D.push(`saturate(${(Ee*100).toFixed(2)}%)`);continue}if(Ce==="grayscale"){D.push("grayscale(100%)");continue}if(Ce==="sepia"){D.push("sepia(100%)");continue}if(Ce==="blur"||Ce==="gaussian-blur"||Ce==="kawase-blur"){const Ee=Tt(Kt(fe,["value","blur","radius"],0),0,30);Ee>.01&&D.push(`blur(${Ee.toFixed(2)}px)`);continue}if(Ce==="adjustment"){const Ee=Kt(fe,["brightness"],1),xe=Kt(fe,["contrast"],1),ct=Kt(fe,["saturation"],1);Math.abs(Ee-1)>.01&&D.push(`brightness(${(Tt(Ee,0,5)*100).toFixed(2)}%)`),Math.abs(xe-1)>.01&&D.push(`contrast(${(Tt(xe,.1,5)*100).toFixed(2)}%)`),Math.abs(ct-1)>.01&&D.push(`saturate(${(Tt(ct,0,5)*100).toFixed(2)}%)`);continue}if(Ce==="cinematic"){D.push("contrast(120%) brightness(95%) saturate(85%)");continue}if(Ce==="dramatic"){D.push("contrast(140%) brightness(90%) saturate(110%) sepia(10%)");continue}if(Ce==="dreamy"){D.push("blur(0.5px) brightness(105%) saturate(90%) contrast(95%)");continue}}return D.join(" ")},Ef=k=>{const D=k.find(Ce=>Ce.filterId.trim().toLowerCase()==="noise");if(!D)return 0;const ee=Ad(D),fe=Kt(ee,["noise","value","amount","intensity"],.2);return fe<=1?Tt(fe,0,1):Tt(fe/100,0,1)},xf=(k,D,ee,fe)=>{if(fe<=0)return;const Ce=k.getImageData(0,0,D,ee),Ee=255*fe;for(let xe=0;xe<Ce.data.length;xe+=4){const ct=(Math.random()*2-1)*Ee;Ce.data[xe]=Tt(Ce.data[xe]+ct,0,255),Ce.data[xe+1]=Tt(Ce.data[xe+1]+ct,0,255),Ce.data[xe+2]=Tt(Ce.data[xe+2]+ct,0,255)}k.putImageData(Ce,0,0)},Ld=async k=>{k.readyState>=2&&k.videoWidth>0&&k.videoHeight>0||await new Promise(D=>{let ee=!1,fe=0;const Ce=()=>{ee||(ee=!0,k.removeEventListener("loadedmetadata",Ee),k.removeEventListener("loadeddata",Ee),k.removeEventListener("canplay",Ee),window.clearTimeout(fe),D())},Ee=()=>{Ce()};k.addEventListener("loadedmetadata",Ee),k.addEventListener("loadeddata",Ee),k.addEventListener("canplay",Ee),fe=window.setTimeout(()=>Ce(),800),k.play().catch(()=>{})})},Sf=async(k,D)=>{await new Promise(ee=>{let fe=!1,Ce=0;const Ee=()=>{fe||(fe=!0,k.removeEventListener("seeked",xe),window.clearTimeout(Ce),ee())},xe=()=>{Ee()};if(Math.abs(k.currentTime-D)<.016){requestAnimationFrame(()=>Ee());return}k.addEventListener("seeked",xe),Ce=window.setTimeout(()=>Ee(),700),k.currentTime=D})},Pd=async(k,D)=>{await Ld(k);const ee=Math.floor(k.videoWidth),fe=Math.floor(k.videoHeight);if(ee<=0||fe<=0)return null;const Ce=Number.isFinite(k.duration)&&k.duration>0?k.duration:0,Ee=Ce>0?Tt(D,0,Ce):0;await Sf(k,Ee);const xe=document.createElement("canvas");xe.width=ee,xe.height=fe;const ct=xe.getContext("2d");if(!ct)return null;const fa=_f(ie.value);fa!==""&&(ct.filter=fa);try{ct.drawImage(k,0,0,ee,fe)}catch{return null}const uo=Ef(ie.value);return xf(ct,ee,fe,uo),Ss(xe)},Cf=async(k,D)=>{const ee=document.createElement("video");ee.src=k,ee.muted=!0,ee.playsInline=!0,ee.preload="auto",k.startsWith("blob:")||(ee.crossOrigin="anonymous");try{return await Ld(ee),await Pd(ee,D)}catch{return null}finally{ee.pause(),ee.removeAttribute("src"),ee.load()}},Vf=async k=>{const D=x.value,ee=Ss(yf(D));if(ee)return ee;if(D!=null&&D.captureFrameAt)for(let Ee=0;Ee<4;Ee+=1){const xe=wf(D);if(xe!==null&&xe<=0&&Ee<2){await xs(80);continue}const ct=await Promise.race([D.captureFrameAt(k),xs(450).then(()=>null)]),fa=Ss(ct);if(fa)return fa;await xs(80)}const fe=kf(D);if(fe){const Ee=await Pd(fe,k);if(Ee)return Ee}const Ce=_e.value.trim();if(Ce!==""){const Ee=await Cf(Ce,k);if(Ee)return Ee}return null},Ud=k=>k.map(D=>({...D,params:D.params&&typeof D.params=="object"?{...D.params}:D.params}));function Od(k){const D=Ud(ie.value);if(!Cs(k)&&D.length>0&&Array.isArray(k.timeline)&&k.timeline.length>0){const fe=k.timeline[0];fe&&(k.timeline=[{...fe,filters:D},...k.timeline.slice(1)])}return k}const Cs=k=>Array.isArray(k.timeline)?k.timeline.some(D=>Array.isArray(D.filters)&&D.filters.length>0):!1,Nf=k=>{if(!k||typeof k!="object")return null;const D=k.posterFrame;if(typeof D!="string")return null;const ee=D.trim();return ee!==""?ee:null};async function Vs(){const k=zo(Od(rt())),D=Ud(ie.value),ee=Cs(k)||D.length>0,fe=Nf(n.initialRecipe);if(ee){const Ce=F.value>0?F.value:.1;try{const Ee=await Vf(Ce);Ee?k.posterFrame=Ee:fe&&(k.posterFrame=fe)}catch{fe&&(k.posterFrame=fe)}}else delete k.posterFrame;return _t(),i("draft-saved",k),k}function zd(){be()&&(vt(),Pa())}async function Tf(k){pn();const D=Zi();$a=window.setInterval(async()=>{try{if(H){pn();return}const ee=await D.getJob(k),fe=Number(ee.progress??0);if(wt.value=Number.isFinite(fe)?fe:0,ee.status==="completed"||ee.status==="failed"||ee.status==="cancelled")if(pn(),yt.value=!1,Ot.value=null,ee.status==="completed")wt.value=100,ma.value=!0,mt.value=null;else{const Ce=ee.status==="cancelled"||typeof ee.error_message=="string"&&/cancel/i.test(ee.error_message);mt.value=Ce?"Export canceled.":typeof ee.error_message=="string"&&ee.error_message.trim()!==""?ee.error_message:"Export failed"}}catch(ee){pn(),yt.value=!1,Ot.value=null,mt.value=ee instanceof Error?ee.message:"Failed to check export progress"}},2e3)}function Ns(){const k=zo(ke());try{const D=k.timeline??[]}catch{}E.value=k}let In=null;function Pa(){In&&clearTimeout(In),In=setTimeout(()=>{Ns(),In=null},200)}e.watch(()=>B.value,Pa,{deep:!0}),e.watch(()=>ce.value,k=>{if(j.value||!k)return;const D=(k==null?void 0:k.filters)??[];Ut(D)},{immediate:!0}),e.watch(()=>ie.value,k=>{kt(k),Pa()},{deep:!0}),e.watch(()=>$.value,k=>{Ct(k),Pa()},{deep:!0}),e.watch(()=>R.value,k=>{const D=k.map(ee=>({...ee,source:typeof ee.source=="string"?ee.source:void 0}));bt(D),Pa()},{deep:!0}),e.watch(()=>F.value,Pa),a({saveDraft:Vs,exportForUpload:gf}),Ns(),e.onUnmounted(()=>{pn(),H=!0,Le.cancelClientExport(),In&&(clearTimeout(In),In=null),g.value&&(g.value.destroy(),g.value=null),N.value=null,V.value=null,A.value=null});function If(){Jt||!$o.value||(Jt=new t_({filters:Fa.value,callbacks:{onApplyFilter:k=>{Mt(k.id)},onRemoveFilter:k=>{on(k)},onUpdateParam:(k,D,ee)=>{to(k,D,ee)},onPreviewFilter:k=>{qe(k.id)}}}),Jt.mount($o.value),Jt.setActiveFilters(G.value))}e.watch(G,k=>{Jt==null||Jt.setActiveFilters(k)},{deep:!0}),e.watch(Fa,k=>{Jt==null||Jt.setFilters(k)});let fn=null;return e.onMounted(()=>{window.addEventListener("resize",z),window.addEventListener("keydown",mn);const k=()=>{!ln.value||fn||(fn=new ResizeObserver(D=>{D[0]&&(eo.value=Math.round(D[0].contentRect.width))}),fn.observe(ln.value))};k(),fn||e.nextTick(k),l.value&&(Oo(),ka||e.nextTick(Oo)),n.media&&Ns(),l.value&&e.nextTick(()=>{If()}),e.nextTick(()=>{const D=document.querySelector(".video-editor");D&&D.getBoundingClientRect();const ee=document.querySelector(".mobile-layout");ee&&ee.getBoundingClientRect()})}),e.onUnmounted(()=>{window.removeEventListener("resize",z),window.removeEventListener("keydown",mn),fn==null||fn.disconnect(),fn=null,ka==null||ka(),ka=null,Jt==null||Jt.destroy(),Jt=null}),(k,D)=>{var ee,fe,Ce,Ee;return e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-editor",{mobile:l.value}])},[l.value?(e.openBlock(),e.createElementBlock("div",ES,[e.createElementVNode("div",xS,[e.createElementVNode("div",SS,[e.createElementVNode("button",{class:e.normalizeClass(["mobile-toolbar-btn",{active:e.unref(oe)}]),onClick:D[0]||(D[0]=(...xe)=>e.unref(ze)&&e.unref(ze)(...xe)),"aria-label":e.unref(oe)?"Pause":"Play","data-testid":"btn-mobile-play"},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(oe)?e.unref(Zl):e.unref(Xl)},null,8,["icon"])],10,CS),e.createElementVNode("button",{class:"mobile-toolbar-btn",onClick:zd,"aria-label":"Reset all changes","data-testid":"btn-mobile-reset"},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Jn)},null,8,["icon"])])]),e.createElementVNode("div",VS,[e.createElementVNode("button",{class:"mobile-toolbar-btn mobile-toolbar-save",onClick:Vs,"aria-label":"Save","data-testid":"btn-mobile-save",disabled:!e.unref(X)},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(jr)},null,8,["icon"]),D[13]||(D[13]=e.createElementVNode("span",null,"Save",-1))],8,NS),e.createElementVNode("button",{class:"mobile-toolbar-btn",onClick:D[1]||(D[1]=xe=>Rd()),"aria-label":"Export","data-testid":"btn-mobile-export",disabled:yt.value||!e.unref(X)},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(ko)},null,8,["icon"])],8,TS),e.createElementVNode("button",{class:"mobile-toolbar-btn",onClick:D[2]||(D[2]=xe=>i("close")),"aria-label":"Close","data-testid":"btn-mobile-close"},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(jn)},null,8,["icon"])])])]),e.createElementVNode("div",IS,[e.withDirectives(e.createVNode(nl,{ref_key:"pixiPreviewMobileRef",ref:h,"aria-hidden":!m.value,class:"preview-host-child",source:_e.value,"fallback-duration":oa.value,filters:Pe.value,playhead:ot.value,"is-playing":e.unref(oe),"fit-mode":S.value,active:m.value,onPlayPause:e.unref(ze),onFrameUpdate:Ra,onDurationChange:ao},null,8,["aria-hidden","source","fallback-duration","filters","playhead","is-playing","fit-mode","active","onPlayPause"]),[[e.vShow,m.value]]),e.withDirectives(e.createVNode(yl,{"aria-hidden":!p.value,class:"preview-host-child","media-uuid":s.value,recipe:E.value,media:tt.value,"enable-engine":p.value&&He.value,"fit-mode":S.value,onTimeUpdate:Cn,onPlayStateChange:Ro,onDurationChange:ao,onEngineReady:Oi},null,8,["aria-hidden","media-uuid","recipe","media","enable-engine","fit-mode"]),[[e.vShow,p.value]]),yt.value?(e.openBlock(),e.createElementBlock("div",BS,[e.createElementVNode("div",MS,[e.createElementVNode("span",null,"Exporting "+e.toDisplayString(wt.value)+"%",1),e.createElementVNode("div",FS,[e.createElementVNode("div",{class:"mobile-export-bar-fill",style:e.normalizeStyle({width:wt.value+"%"})},null,4)]),e.createElementVNode("button",{class:"mobile-export-cancel",onClick:Dd},"Cancel")])])):e.createCommentVNode("",!0)]),e.createElementVNode("div",{ref_key:"timelineContainerRef",ref:ln,class:"timeline-section"},[e.createElementVNode("div",$S,[e.createElementVNode("button",{ref_key:"mobileZoomOutButtonRef",ref:Do,type:"button",class:"mobile-zoom-btn","aria-label":"Zoom out timeline","data-testid":"btn-timeline-zoom-out"},[...D[14]||(D[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:dn,type:"button",class:"mobile-zoom-btn","aria-label":"Zoom in timeline","data-testid":"btn-timeline-zoom-in"},[...D[15]||(D[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(wl,{playhead:e.unref(F),clips:e.unref(B),"selected-clip-id":((ee=e.unref(ce))==null?void 0:ee.id)??((fe=e.unref(B)[0])==null?void 0:fe.id)??null,duration:oa.value,fps:e.unref(ge),"zoom-level":e.unref(je),"snap-enabled":Nt.value,sensitivity:.25,"is-mobile":!0,"onUpdate:playhead":e.unref(ut),onTrim:e.unref(pe),onSplit:Lo,onClipSelect:Ao,onClipMove:e.unref(Lt),onClipLongPress:Li,onSnapStateChange:Vn},null,8,["playhead","clips","selected-clip-id","duration","fps","zoom-level","snap-enabled","onUpdate:playhead","onTrim","onClipMove"])],512),e.createElementVNode("div",DS,[e.createElementVNode("div",RS,[e.createElementVNode("span",AS,e.toDisplayString($i.value),1),e.createElementVNode("span",LS,e.toDisplayString(bs.value),1)]),e.createElementVNode("div",PS,[e.createElementVNode("button",{type:"button",class:"mobile-cut-nav-btn","data-testid":"btn-mobile-prev-cut","aria-label":"Jump to previous cut",disabled:!gs.value,onClick:La}," Prev Cut ",8,US),e.createElementVNode("div",OS,[e.createElementVNode("span",zS,"Playhead "+e.toDisplayString(ys.value),1),e.createElementVNode("span",jS,"In "+e.toDisplayString(Mo.value),1),e.createElementVNode("span",WS,"Out "+e.toDisplayString(Ri.value),1),e.createElementVNode("span",HS,"Duration "+e.toDisplayString(ws.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:!sn.value,onClick:Pi}," Next Cut ",8,ZS)]),e.createElementVNode("div",XS,[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["mobile-snap-toggle",{active:Nt.value}]),"data-testid":"btn-mobile-snap-toggle",onClick:no},e.toDisplayString(Nt.value?"Snap On":"Snap Off"),3),e.createElementVNode("div",GS,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(En,xe=>e.createElementVNode("button",{key:xe,type:"button",class:e.normalizeClass(["mobile-speed-chip",{active:e.unref(he)===xe}]),"data-testid":`btn-mobile-speed-${String(xe).replace(".","-")}`,onClick:ct=>Tn(xe)},e.toDisplayString(xe)+"x ",11,JS)),64))])]),e.createElementVNode("div",KS,[e.createElementVNode("button",{type:"button",class:"mobile-edit-btn","data-testid":"btn-mobile-undo","aria-label":"Undo",disabled:!e.unref(Q),onClick:oo}," Undo ",8,qS),e.createElementVNode("button",{type:"button",class:"mobile-edit-btn","data-testid":"btn-mobile-redo","aria-label":"Redo",disabled:!e.unref(ue),onClick:io}," Redo ",8,YS),e.createElementVNode("button",{type:"button",class:"mobile-edit-btn","data-testid":"btn-mobile-split","aria-label":"Split at playhead",disabled:!st.value,onClick:un}," Split ",8,QS),e.createElementVNode("button",{type:"button",class:"mobile-edit-btn","data-testid":"btn-mobile-duplicate","aria-label":"Duplicate selected clip",disabled:!Gt.value,onClick:Nn}," Duplicate ",8,eC),e.createElementVNode("button",{type:"button",class:"mobile-edit-btn mobile-edit-btn--danger","data-testid":"btn-mobile-delete","aria-label":"Delete selected clip",disabled:!Ze.value,onClick:ro}," Delete ",8,tC)])]),e.createElementVNode("div",{ref_key:"mobileControlsRef",ref:$o,class:"controls-section mobile-controls"},null,512),Qn.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"mobile-action-sheet-backdrop","data-testid":"video-mobile-action-sheet",onClick:Aa},[e.createElementVNode("div",{class:"mobile-action-sheet",onClick:D[3]||(D[3]=e.withModifiers(()=>{},["stop"]))},[D[16]||(D[16]=e.createElementVNode("div",{class:"mobile-action-sheet-handle"},null,-1)),e.createElementVNode("div",aC,[e.createElementVNode("span",nC,e.toDisplayString(ks.value),1),e.createElementVNode("span",oC,e.toDisplayString(_s.value),1)]),e.createElementVNode("div",iC,[e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-undo",disabled:!e.unref(Q),onClick:oo},"Undo",8,rC),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-redo",disabled:!e.unref(ue),onClick:io},"Redo",8,sC),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-split",disabled:!st.value,onClick:un},"Split",8,lC),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-duplicate",disabled:!Gt.value,onClick:Nn},"Duplicate",8,dC),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn mobile-action-sheet-btn--danger","data-testid":"btn-mobile-sheet-delete",disabled:!Ze.value,onClick:ro},"Delete",8,cC),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-close",onClick:Aa},"Close")])])])):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("div",uC,[e.createElementVNode("div",mC,[e.createElementVNode("div",pC,[e.createElementVNode("div",fC,[e.createElementVNode("label",null,[e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":D[4]||(D[4]=xe=>S.value=xe),"aria-label":"Fit mode","data-testid":"select-video-fit-mode"},[...D[17]||(D[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,S.value]])])]),e.withDirectives(e.createVNode(nl,{ref_key:"pixiPreviewDesktopRef",ref:v,"aria-hidden":!m.value,class:"preview-host-child",source:_e.value,"fallback-duration":oa.value,filters:Pe.value,playhead:ot.value,"is-playing":e.unref(oe),"fit-mode":S.value,active:m.value,onPlayPause:e.unref(ze),onFrameUpdate:Ra,onDurationChange:ao},null,8,["aria-hidden","source","fallback-duration","filters","playhead","is-playing","fit-mode","active","onPlayPause"]),[[e.vShow,m.value]]),e.withDirectives(e.createVNode(yl,{"aria-hidden":!p.value,class:"preview-host-child","media-uuid":s.value,recipe:E.value,media:tt.value,"enable-engine":p.value&&He.value,"fit-mode":S.value,onTimeUpdate:Cn,onPlayStateChange:Ro,onDurationChange:ao,onEngineReady:Oi},null,8,["aria-hidden","media-uuid","recipe","media","enable-engine","fit-mode"]),[[e.vShow,p.value]]),k.showThumbnailPicker?(e.openBlock(),e.createBlock(Mk,{key:0,"media-uuid":s.value,duration:oa.value,onSelect:co},null,8,["media-uuid","duration"])):e.createCommentVNode("",!0)]),e.createElementVNode("div",hC,[e.createElementVNode("div",vC,[e.createElementVNode("div",gC,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(K.value,xe=>(e.openBlock(),e.createElementBlock("button",{key:xe.id,class:e.normalizeClass(["tab-btn",{active:c.value===xe.id}]),onClick:ct=>c.value=xe.id},e.toDisplayString(xe.label),11,bC))),128))]),e.createElementVNode("div",yC,[e.withDirectives(e.createElementVNode("div",wC,[e.createVNode(_l,{filters:Fa.value,"active-filters":G.value,"thumbnail-url":se.value,onApplyFilter:Mt,onRemoveFilter:on,onUpdateParam:to,onPreviewFilter:zi},null,8,["filters","active-filters","thumbnail-url"])],512),[[e.vShow,c.value==="filters"]]),e.withDirectives(e.createElementVNode("div",kC,[e.createVNode(Sl,{overlays:$.value,onAddOverlay:Wi,onUpdateOverlay:Hi,onRemoveOverlay:b},null,8,["overlays"])],512),[[e.vShow,c.value==="text"]]),e.withDirectives(e.createElementVNode("div",_C,[e.createVNode(Cl,{"selected-clips":L.value,"applied-transitions":y.value,onApplyTransition:M,onRemoveTransition:q,onPreviewTransition:me},null,8,["selected-clips","applied-transitions"])],512),[[e.vShow,c.value==="transitions"]]),e.withDirectives(e.createElementVNode("div",EC,[e.createVNode(Vl,{"audio-layers":R.value,"master-volume":U.value,onAddTrack:Me,onUpdateTrack:Fe,onRemoveTrack:Ye,onUpdateVolume:pt,onToggleMute:$t,onUpdateMasterVolume:aa},null,8,["audio-layers","master-volume"])],512),[[e.vShow,c.value==="audio"]]),e.withDirectives(e.createElementVNode("div",xC,[e.unref(Se)?(e.openBlock(),e.createBlock(El,{key:0,filter:e.unref(Se),"current-frame":e.unref(ae),onUpdateParams:ji},null,8,["filter","current-frame"])):(e.openBlock(),e.createElementBlock("div",SC,[...D[18]||(D[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",CC,[e.createVNode(xl,{"can-export":e.unref(X),"is-exporting":yt.value,"export-progress":wt.value,onExport:Rd,onCancelExport:Dd,onSaveDraft:Vs,onReset:zd},null,8,["can-export","is-exporting","export-progress"]),ma.value?(e.openBlock(),e.createElementBlock("div",VC," Export complete ")):e.createCommentVNode("",!0),mt.value&&!ma.value?(e.openBlock(),e.createElementBlock("div",NC,e.toDisplayString(mt.value),1)):e.createCommentVNode("",!0)],512),[[e.vShow,c.value==="export"]])])])])]),e.createElementVNode("div",TC,[e.createElementVNode("div",{ref_key:"timelineContainerRef",ref:ln,class:"timeline-container"},[e.createElementVNode("div",IC,[e.createElementVNode("label",null,[D[19]||(D[19]=e.createTextVNode(" Zoom ",-1)),e.createElementVNode("input",{type:"range",min:"10",max:"600",value:e.unref(je),onInput:D[5]||(D[5]=xe=>lo(xe))},null,40,BC)]),e.createElementVNode("span",MC,e.toDisplayString(Math.round(e.unref(je)))+" px/s",1),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["desktop-snap-toggle",{active:Nt.value}]),"data-testid":"btn-desktop-snap-toggle",onClick:no},e.toDisplayString(Nt.value?"Snap On":"Snap Off"),3)]),e.createVNode(wl,{playhead:e.unref(F),clips:e.unref(B),"selected-clip-id":((Ce=e.unref(ce))==null?void 0:Ce.id)??((Ee=e.unref(B)[0])==null?void 0:Ee.id)??null,duration:oa.value,fps:e.unref(ge),"zoom-level":e.unref(je),"snap-enabled":Nt.value,sensitivity:.25,"onUpdate:playhead":e.unref(ut),onTrim:e.unref(pe),onSplit:Lo,onClipSelect:Ao,onClipMove:e.unref(Lt),onClipLongPress:Li,onSnapStateChange:Vn},null,8,["playhead","clips","selected-clip-id","duration","fps","zoom-level","snap-enabled","onUpdate:playhead","onTrim","onClipMove"]),e.createVNode(kl,{"selected-clip":e.unref(ce),"can-split":st.value,"can-delete":Ze.value,"is-playing":e.unref(oe),"zoom-level":e.unref(je),"playback-speed":e.unref(he),onSplit:un,onDelete:ro,onDuplicate:Nn,onZoomIn:Md,onZoomOut:Fd,onZoomChange:Po,onFitToWindow:Ui,onPlayPause:e.unref(ze),onFrameForward:e.unref(Xt),onFrameBackward:e.unref(Wt),onSkipToStart:e.unref(ca),onSkipToEnd:e.unref(ta),onSpeedChange:e.unref(ya)},null,8,["selected-clip","can-split","can-delete","is-playing","zoom-level","playback-speed","onPlayPause","onFrameForward","onFrameBackward","onSkipToStart","onSkipToEnd","onSpeedChange"]),Ve.value?(e.openBlock(),e.createElementBlock("div",FC,[e.createElementVNode("div",$C,[e.createElementVNode("label",DC,[D[20]||(D[20]=e.createElementVNode("span",null,"Trim start (s)",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":D[6]||(D[6]=xe=>Ca.value=xe),type:"number",step:"0.01",min:"0",inputmode:"decimal","data-testid":"video-dev-trim-start"},null,512),[[e.vModelText,Ca.value]])]),e.createElementVNode("label",RC,[D[21]||(D[21]=e.createElementVNode("span",null,"Trim end (s)",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":D[7]||(D[7]=xe=>Va.value=xe),type:"number",step:"0.01",min:"0",inputmode:"decimal","data-testid":"video-dev-trim-end"},null,512),[[e.vModelText,Va.value]])]),e.createElementVNode("button",{class:"dev-editor-button",type:"button","data-testid":"video-dev-trim-start-playhead",disabled:!e.unref(ce),onClick:D[8]||(D[8]=xe=>cn("start"))}," Start = Playhead ",8,AC),e.createElementVNode("button",{class:"dev-editor-button",type:"button","data-testid":"video-dev-trim-end-playhead",disabled:!e.unref(ce),onClick:D[9]||(D[9]=xe=>cn("end"))}," End = Playhead ",8,LC),e.createElementVNode("button",{class:"dev-editor-button dev-editor-button--primary",type:"button","data-testid":"video-dev-apply-trim",disabled:!e.unref(ce),onClick:Da}," Apply Trim ",8,PC)]),e.createElementVNode("div",UC,[e.createElementVNode("label",OC,[D[22]||(D[22]=e.createElementVNode("span",null,"Quick filter",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":D[10]||(D[10]=xe=>ua.value=xe),"data-testid":"video-dev-filter-select"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Fa.value,xe=>(e.openBlock(),e.createElementBlock("option",{key:xe.id,value:xe.id},e.toDisplayString(xe.name),9,zC))),128))],512),[[e.vModelSelect,ua.value]])]),e.createElementVNode("button",{class:"dev-editor-button dev-editor-button--primary",type:"button","data-testid":"video-dev-apply-filter",disabled:!e.unref(ce)||ua.value==="",onClick:St}," Apply Filter ",8,jC),e.createElementVNode("button",{class:"dev-editor-button",type:"button","data-testid":"video-dev-clear-filters",disabled:e.unref(ie).length===0,onClick:qa}," Clear Filters ",8,WC),e.createElementVNode("button",{class:"dev-editor-button dev-editor-button--primary",type:"button","data-testid":"btn-apply-noise-filter","aria-label":"Apply noise filter for QA testing",disabled:!e.unref(ce),onClick:D[11]||(D[11]=xe=>Mt("noise"))}," QA: Noise ",8,HC),e.createElementVNode("button",{class:"dev-editor-button dev-editor-button--primary",type:"button","data-testid":"btn-apply-grayscale-filter","aria-label":"Apply grayscale filter for QA testing",disabled:!e.unref(ce),onClick:D[12]||(D[12]=xe=>Mt("grayscale"))}," QA: Grayscale ",8,ZC)])])):e.createCommentVNode("",!0)],512)])]))],2)}}}),Bp=Be(XC,[["__scopeId","data-v-1bb4247b"]]),GC={key:0,class:"video-editor-v2-toolbar"},JC={class:"video-editor-v2-body"},KC={key:0,class:"video-editor-v2-assets","data-testid":"v2-assets-panel"},qC={class:"video-editor-v2-main"},YC={class:"video-editor-v2-canvas"},QC={key:1,class:"video-editor-v2-timeline"},eV=["aria-expanded"],tV=["aria-hidden","inert"],aV="(max-width: 900px)",nV=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(aV),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",GC,[e.renderSlot(c.$slots,"toolbar",{},void 0,!0)])):e.createCommentVNode("",!0),e.createElementVNode("div",JC,[!t.value&&c.$slots.assets?(e.openBlock(),e.createElementBlock("aside",KC,[e.renderSlot(c.$slots,"assets",{},void 0,!0)])):e.createCommentVNode("",!0),e.createElementVNode("div",qC,[e.createElementVNode("div",YC,[e.renderSlot(c.$slots,"canvas",{},void 0,!0)])])]),c.$slots.timeline?(e.openBlock(),e.createElementBlock("div",QC,[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,eV)),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,tV)],64)):e.createCommentVNode("",!0),t.value?e.renderSlot(c.$slots,"drawer",{key:3},void 0,!0):e.createCommentVNode("",!0)],2))}}),oV=Be(nV,[["__scopeId","data-v-ed83bde0"]]),iV=["aria-selected"],rV={class:"asset-rail-item__main"},sV={class:"asset-rail-item__type","data-testid":"asset-rail-item-type"},lV={class:"asset-rail-item__label","data-testid":"asset-rail-item-label"},dV={key:0,class:"asset-rail-item__details","data-testid":"asset-rail-item-details"},cV={class:"asset-rail-item__actions","aria-label":"Asset actions"},uV=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),f=c%60;return`${u}:${f.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",rV,[e.createElementVNode("span",sV,e.toDisplayString(c.source.type),1),e.createElementVNode("span",lV,e.toDisplayString(i.value),1),l.value.length>0?(e.openBlock(),e.createElementBlock("span",dV,e.toDisplayString(l.value.join(" / ")),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",cV,[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]=f=>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]=f=>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]=f=>d("remove"))}," - ")])],10,iV))}}),mV=Be(uV,[["__scopeId","data-v-3ba2fd25"]]),pV={class:"asset-rail__header"},fV={key:0,class:"asset-rail__list","data-testid":"asset-rail-list"},hV={key:1,class:"asset-rail__empty","data-testid":"asset-rail-empty"},vV=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=(f,m)=>{if(f==="add"){t("add",m);return}if(f==="replaceSelected"){t("replaceSelected",m);return}t("remove",m)},s=()=>{var f;(f=n.value)==null||f.click()},l=f=>{const m=f.target;if(!(m!=null&&m.files)||m.files.length===0)return;const p=Array.from(m.files);t("importFiles",p),m.value=""},d=f=>{f.preventDefault(),f.dataTransfer&&(f.dataTransfer.dropEffect="copy"),i.value=!0},c=()=>{i.value=!1},u=f=>{var p;f.preventDefault(),i.value=!1;const m=Array.from(((p=f.dataTransfer)==null?void 0:p.files)??[]);m.length!==0&&t("importFiles",m)};return(f,m)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["asset-rail",{"asset-rail--drag-over":i.value&&f.uploadsEnabled}]),"aria-label":"Assets","data-testid":"asset-rail",onDragover:d,onDragleave:c,onDrop:u},[e.createElementVNode("div",pV,[m[3]||(m[3]=e.createElementVNode("h2",{class:"asset-rail__title"},"Assets",-1)),f.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),f.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)]),f.sources.length>0?(e.openBlock(),e.createElementBlock("div",fV,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(f.sources,p=>(e.openBlock(),e.createBlock(mV,{key:p.id,source:p,selected:p.id===f.selectedSourceId,onAdd:m[0]||(m[0]=h=>r("add",h)),onReplaceSelected:m[1]||(m[1]=h=>r("replaceSelected",h)),onRemove:m[2]||(m[2]=h=>r("remove",h))},null,8,["source","selected"]))),128))])):(e.openBlock(),e.createElementBlock("p",hV,e.toDisplayString(f.uploadsEnabled?"Drop files here or click Upload to add media.":"No assets"),1))],34))}}),gV=Be(vV,[["__scopeId","data-v-3db665c6"]]),bV={class:"audio-mixer-panel__tracks","data-testid":"audio-mixer-tracks"},yV={key:0,class:"audio-mixer-panel__empty","data-testid":"audio-mixer-empty"},wV=["data-testid"],kV={class:"audio-mixer-strip__header"},_V={class:"audio-mixer-strip__identity"},EV={class:"audio-mixer-strip__kind"},xV=["data-testid"],SV=["data-testid"],CV=["data-testid"],VV={class:"audio-mixer-meter__rail","aria-hidden":"true"},NV={class:"audio-mixer-meter__value"},TV={class:"audio-mixer-strip__controls"},IV=["for"],BV=["id","min","max","value","data-testid","onInput"],MV={class:"audio-mixer-control__value"},FV={class:"audio-mixer-buttons"},$V=["aria-pressed","aria-label","data-testid","onClick"],DV=["aria-pressed","aria-label","data-testid","onClick"],RV=["for"],AV=["id","value","data-testid","onInput"],LV={class:"audio-mixer-control__value"},PV=["data-testid"],UV={key:0},OV={key:1},zV=["data-testid"],jV=["data-testid"],WV=["data-testid"],HV={class:"audio-mixer-routing__target"},ZV={class:"audio-mixer-strip__header"},XV={class:"audio-mixer-strip__identity"},GV={class:"audio-mixer-strip__name","data-testid":"audio-mixer-master-name"},JV={class:"audio-mixer-meter__rail","aria-hidden":"true"},KV={class:"audio-mixer-meter__value"},qV={class:"audio-mixer-strip__controls"},YV={key:0,class:"audio-mixer-control audio-mixer-control--fader",for:"audio-mixer-master-fader"},QV=["min","max","value"],eN={class:"audio-mixer-control__value"},tN={class:"audio-mixer-buttons"},aN=["aria-pressed","aria-label"],nN={key:1,class:"audio-mixer-effects","data-testid":"audio-mixer-master-effects"},oN=["data-testid"],iN=e.defineComponent({__name:"AudioMixerPanel",props:{state:{},deviceClass:{}},emits:["update"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>$_(t.deviceClass,t.state.capabilities)),r=e.computed(()=>t.deviceClass==="desktop"),s=e.computed(()=>[...t.state.tracks].sort((U,z)=>U.order-z.order)),l=e.computed(()=>{const U=new Map(D_(s.value,t.state.master.muted).map(z=>[z.trackId,z]));return s.value.map(z=>({track:z,effectiveState:U.get(z.id)??null}))}),d=e.computed(()=>i.value.canAdjustTrackFaders),c=e.computed(()=>i.value.canAdjustMasterFader),u=e.computed(()=>i.value.canMuteTracks),f=e.computed(()=>r.value&&i.value.canSoloTracks),m=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),w=U=>{if(!(U.target instanceof HTMLInputElement))return null;const z=Number(U.target.value);return Number.isFinite(z)?z:null},x=(U,z)=>{if(!d.value)return;const I=w(z);I!==null&&n("update",{type:"track-fader-db",trackId:U.id,valueDb:bi(I)})},T=U=>{u.value&&n("update",{type:"track-mute",trackId:U.id,muted:!U.controls.muted})},_=U=>{f.value&&n("update",{type:"track-solo",trackId:U.id,solo:!U.controls.solo})},g=(U,z)=>{if(!m.value)return;const I=w(z);I!==null&&n("update",{type:"track-pan",trackId:U.id,pan:Wm(I)})},E=U=>{if(!c.value)return;const z=w(U);z!==null&&n("update",{type:"master-fader-db",valueDb:bi(z)})},S=U=>{u.value&&n("update",{type:"master-mute",muted:!U.muted})},N=U=>{const z=Math.round(U*10)/10;return z>0?`+${z.toFixed(z%1===0?0:1)} dB`:`${z.toFixed(z%1===0?0:1)} dB`},V=U=>U===0?"C":`${U<0?"L":"R"} ${Math.round(Math.abs(U)*100)}`,A=U=>{if(U===void 0)return"";const z=Math.round(U*10)/10;return`${z.toFixed(z%1===0?0:1)}s`},j=U=>N(U),C=U=>{if(!Number.isFinite(U))return 0;const z=Math.min(Fr,Math.max(wn,U)),I=Fr-wn;return Math.round((z-wn)/I*100)},$=U=>U.slice(0,i.value.maxEffectSlots),y=U=>h.value&&$(U).length>0,R=U=>U.timeline.fadeIn!==void 0||U.timeline.fadeOut!==void 0,L=U=>U===null?"Unknown":U.mutedByMaster?"Master muted":U.mutedByTrack?"Muted":U.mutedBySolo?"Muted by solo":U.soloed?"Solo active":"Audible";return(U,z)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["audio-mixer-panel",`audio-mixer-panel--${U.deviceClass}`]),"data-testid":"audio-mixer-panel","aria-label":"Audio mixer"},[e.createElementVNode("div",bV,[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:P})=>(e.openBlock(),e.createElementBlock("article",{key:I.id,class:e.normalizeClass(["audio-mixer-strip",{"is-muted":(P==null?void 0:P.effectivelyMuted)===!0,"is-soloed":I.controls.solo}]),"data-testid":`audio-mixer-track-${I.id}`},[e.createElementVNode("header",kV,[e.createElementVNode("div",_V,[e.createElementVNode("span",EV,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,xV)]),e.createElementVNode("span",{class:e.normalizeClass(["audio-mixer-strip__status",{"is-active":(P==null?void 0:P.audible)===!0}]),"data-testid":`audio-mixer-track-status-${I.id}`},e.toDisplayString(L(P)),11,SV)]),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",VV,[e.createElementVNode("span",{class:"audio-mixer-meter__fill",style:e.normalizeStyle({width:`${C(I.controls.meter.peakDb)}%`})},null,4)]),e.createElementVNode("span",NV,e.toDisplayString(j(I.controls.meter.peakDb)),1)],10,CV)):e.createCommentVNode("",!0),e.createElementVNode("div",TV,[d.value?(e.openBlock(),e.createElementBlock("label",{key:0,class:"audio-mixer-control audio-mixer-control--fader",for:`audio-mixer-track-fader-${I.id}`},[z[2]||(z[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=>x(I,Z)},null,40,BV),e.createElementVNode("span",MV,e.toDisplayString(N(I.controls.fader.valueDb)),1)],8,IV)):e.createCommentVNode("",!0),e.createElementVNode("div",FV,[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=>T(I)}," M ",10,$V)):e.createCommentVNode("",!0),f.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=>_(I)}," S ",10,DV)):e.createCommentVNode("",!0)])]),m.value?(e.openBlock(),e.createElementBlock("label",{key:1,class:"audio-mixer-control audio-mixer-control--pan",for:`audio-mixer-track-pan-${I.id}`},[z[3]||(z[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=>g(I,Z)},null,40,AV),e.createElementVNode("span",LV,e.toDisplayString(V(I.controls.pan.value)),1)],8,RV)):e.createCommentVNode("",!0),R(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",UV," In "+e.toDisplayString(A(I.timeline.fadeIn)),1)):e.createCommentVNode("",!0),I.timeline.fadeOut!==void 0?(e.openBlock(),e.createElementBlock("span",OV," Out "+e.toDisplayString(A(I.timeline.fadeOut)),1)):e.createCommentVNode("",!0)],8,PV)):e.createCommentVNode("",!0),y(I.effectSlots)?(e.openBlock(),e.createElementBlock("div",{key:3,class:"audio-mixer-effects","data-testid":`audio-mixer-track-effects-${I.id}`},[z[4]||(z[4]=e.createElementVNode("span",{class:"audio-mixer-effects__label"},"FX",-1)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList($(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,jV))),128))],8,zV)):e.createCommentVNode("",!0),v.value?(e.openBlock(),e.createElementBlock("div",{key:4,class:"audio-mixer-routing","data-testid":`audio-mixer-track-routing-${I.id}`},[z[5]||(z[5]=e.createElementVNode("span",{class:"audio-mixer-routing__label"},"Route",-1)),e.createElementVNode("span",HV,e.toDisplayString(U.state.master.name),1)],8,WV)):e.createCommentVNode("",!0)],10,wV))),128))]),e.createElementVNode("article",{class:e.normalizeClass(["audio-mixer-strip audio-mixer-strip--master",{"is-muted":U.state.master.muted}]),"data-testid":"audio-mixer-master-strip"},[e.createElementVNode("header",ZV,[e.createElementVNode("div",XV,[z[6]||(z[6]=e.createElementVNode("span",{class:"audio-mixer-strip__kind"},"master",-1)),e.createElementVNode("h3",GV,e.toDisplayString(U.state.master.name),1)]),e.createElementVNode("span",{class:e.normalizeClass(["audio-mixer-strip__status",{"is-active":!U.state.master.muted}]),"data-testid":"audio-mixer-master-status"},e.toDisplayString(U.state.master.muted?"Muted":"Active"),3)]),p.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:e.normalizeClass(["audio-mixer-meter",{"is-clipping":U.state.master.meter.clipping}]),"data-testid":"audio-mixer-master-meter","aria-label":"Master meter"},[e.createElementVNode("span",JV,[e.createElementVNode("span",{class:"audio-mixer-meter__fill",style:e.normalizeStyle({width:`${C(U.state.master.meter.peakDb)}%`})},null,4)]),e.createElementVNode("span",KV,e.toDisplayString(j(U.state.master.meter.peakDb)),1)],2)):e.createCommentVNode("",!0),e.createElementVNode("div",qV,[c.value?(e.openBlock(),e.createElementBlock("label",YV,[z[7]||(z[7]=e.createElementVNode("span",{class:"audio-mixer-control__label"},"Level",-1)),e.createElementVNode("input",{id:"audio-mixer-master-fader",type:"range",class:"audio-mixer-control__range",min:U.state.master.fader.minDb,max:U.state.master.fader.maxDb,value:U.state.master.fader.valueDb,step:"0.5","data-testid":"audio-mixer-master-fader",onInput:z[0]||(z[0]=I=>E(I))},null,40,QV),e.createElementVNode("span",eN,e.toDisplayString(N(U.state.master.fader.valueDb)),1)])):e.createCommentVNode("",!0),e.createElementVNode("div",tN,[u.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:e.normalizeClass(["audio-mixer-button",{"is-active":U.state.master.muted}]),"aria-pressed":U.state.master.muted?"true":"false","aria-label":U.state.master.muted?`Unmute ${U.state.master.name}`:`Mute ${U.state.master.name}`,"data-testid":"audio-mixer-master-mute",onClick:z[1]||(z[1]=I=>S(U.state.master))}," M ",10,aN)):e.createCommentVNode("",!0)])]),y(U.state.master.effectSlots)?(e.openBlock(),e.createElementBlock("div",nN,[z[8]||(z[8]=e.createElementVNode("span",{class:"audio-mixer-effects__label"},"FX",-1)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList($(U.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,oN))),128))])):e.createCommentVNode("",!0)],2)],2))}}),tu=Be(iN,[["__scopeId","data-v-e5c785e8"]]),rN={class:"caption-srt-panel__header"},sN={class:"caption-srt-panel__title-group"},lN={class:"caption-srt-panel__title"},dN=["id"],cN={key:0,class:"caption-srt-panel__stats","data-testid":"caption-srt-desktop-stats"},uN={key:0,class:"caption-srt-panel__desktop-controls","data-testid":"caption-srt-desktop-controls"},mN={class:"caption-srt-panel__field"},pN={class:"caption-srt-panel__field"},fN=["for"],hN=["id","aria-describedby","aria-invalid"],vN=["id"],gN=["id"],bN={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"},wN={class:"caption-srt-panel__cue-time"},kN={class:"caption-srt-panel__cue-text"},_N={key:1,class:"caption-srt-panel__empty"},EN=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"),f=e.computed(()=>`${t.panelId}-textarea`),m=e.computed(()=>`${t.panelId}-helper`),p=e.computed(()=>`${t.panelId}-error`),h=e.computed(()=>`${t.panelId}-status`),v=e.computed(()=>{const y=[m.value,h.value];return r.value!==null&&y.push(p.value),y.join(" ")}),w=e.computed(()=>t.captionTrack!==null?t.captionTrack.segments:t.segments??[]),x=e.computed(()=>{try{return{text:Dc(w.value),errorMessage:null}}catch(y){return{text:"",errorMessage:j(y)}}}),T=e.computed(()=>w.value.length),_=e.computed(()=>w.value.reduce((y,R)=>Math.max(y,R.endTime),0)),g=e.computed(()=>w.value.slice(0,5));e.watch(()=>{var y,R;return[(y=t.captionTrack)==null?void 0:y.id,(R=t.captionTrack)==null?void 0:R.language,t.trackId]},([y,R,L])=>{l.value=y??L,d.value=R??""},{immediate:!0}),e.watch(x,y=>{if(y.errorMessage!==null){r.value=y.errorMessage;return}c.value||(i.value=y.text)},{immediate:!0});const E=()=>{c.value=!0,s.value=null,r.value!==null&&(r.value=null)},S=()=>{const y=i.value;if(r.value=null,s.value=null,y.trim()===""){r.value="Paste SRT text before importing captions.";return}try{const R=tE(y,{idPrefix:t.idPrefix}),L=gE(A(R)),U=Dc(L.segments);i.value=U,c.value=!1,s.value=`Imported ${C(L.segments.length)}.`,n("update:captionTrack",L),n("update:segments",L.segments),n("import",{track:L,segments:L.segments,sourceText:y})}catch(R){r.value=j(R)}},N=()=>{const y=x.value;if(r.value=y.errorMessage,y.errorMessage!==null){s.value=null;return}i.value=y.text,c.value=!1,s.value=y.text===""?"No captions to export.":`Exported ${C(T.value)}.`,n("export",y.text)},V=()=>{i.value="",c.value=!0,r.value=null,s.value="SRT text cleared.",n("clear")};function A(y){var U,z;const R={id:l.value.trim(),source:"srt-import",stylePreset:((U=t.captionTrack)==null?void 0:U.stylePreset)??"default",animation:((z=t.captionTrack)==null?void 0:z.animation)??"none",segments:y},L=d.value.trim();return L!==""&&(R.language=L),R}function j(y){return y instanceof kn||y instanceof Error?y.message:"Unable to process SRT captions."}function C(y){return y===1?"1 cue":`${y} cues`}function $(y){const R=Math.floor(y/60),L=Math.floor(y%60);return`${R}:${L.toString().padStart(2,"0")}`}return(y,R)=>(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",rN,[e.createElementVNode("div",sN,[e.createElementVNode("h2",lN,e.toDisplayString(y.title),1),e.createElementVNode("p",{id:m.value,class:"caption-srt-panel__helper"}," Paste SRT, import it as captions, or export the current caption track. ",8,dN)]),u.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",cN,[e.createElementVNode("span",null,e.toDisplayString(C(T.value)),1),e.createElementVNode("span",null,e.toDisplayString($(_.value)),1)]))]),u.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",uN,[e.createElementVNode("label",mN,[R[3]||(R[3]=e.createElementVNode("span",null,"Track ID",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":R[0]||(R[0]=L=>l.value=L),class:"caption-srt-panel__input",type:"text",autocomplete:"off","data-testid":"caption-srt-track-id"},null,512),[[e.vModelText,l.value]])]),e.createElementVNode("label",pN,[R[4]||(R[4]=e.createElementVNode("span",null,"Language",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":R[1]||(R[1]=L=>d.value=L),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:f.value},e.toDisplayString(y.textareaLabel),9,fN),e.withDirectives(e.createElementVNode("textarea",{id:f.value,"onUpdate:modelValue":R[2]||(R[2]=L=>i.value=L),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:E},null,42,hN),[[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,vN)):(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,gN)),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:S}," Import "),e.createElementVNode("button",{type:"button",class:"caption-srt-panel__button","data-testid":"caption-srt-export",onClick:N}," Export "),e.createElementVNode("button",{type:"button",class:"caption-srt-panel__button","data-testid":"caption-srt-clear",onClick:V}," Clear ")]),u.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",bN,[R[5]||(R[5]=e.createElementVNode("p",{class:"caption-srt-panel__cue-summary-title"},"Cue summary",-1)),g.value.length>0?(e.openBlock(),e.createElementBlock("ol",yN,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(g.value,L=>(e.openBlock(),e.createElementBlock("li",{key:L.id,class:"caption-srt-panel__cue"},[e.createElementVNode("span",wN,e.toDisplayString($(L.startTime))+"-"+e.toDisplayString($(L.endTime)),1),e.createElementVNode("span",kN,e.toDisplayString(L.text),1)]))),128))])):(e.openBlock(),e.createElementBlock("p",_N," No captions loaded. "))]))],2))}}),au=Be(EN,[["__scopeId","data-v-1d5fdb3b"]]),xN=["aria-label"],SN={class:"draft-recovery-banner__header"},CN={class:"draft-recovery-banner__heading"},VN={class:"draft-recovery-banner__title"},NN={class:"draft-recovery-banner__summary","data-testid":"draft-recovery-summary"},TN={key:0,class:"draft-recovery-banner__list","data-testid":"draft-recovery-list"},IN={class:"draft-recovery-banner__record-copy"},BN={class:"draft-recovery-banner__record-title","data-testid":"draft-recovery-record-title"},MN={class:"draft-recovery-banner__record-meta"},FN={"data-testid":"draft-recovery-record-updated"},$N={"data-testid":"draft-recovery-record-reason"},DN={class:"draft-recovery-banner__actions"},RN=["onClick"],AN=["onClick"],LN={key:1,class:"draft-recovery-banner__mobile-prompt","data-testid":"draft-recovery-mobile-prompt"},PN={class:"draft-recovery-banner__record-copy"},UN={class:"draft-recovery-banner__record-title","data-testid":"draft-recovery-record-title"},ON={class:"draft-recovery-banner__record-meta"},zN={"data-testid":"draft-recovery-record-updated"},jN={"data-testid":"draft-recovery-record-reason"},WN={class:"draft-recovery-banner__actions draft-recovery-banner__actions--mobile"},HN={key:2,class:"draft-recovery-banner__empty","data-testid":"draft-recovery-empty"},ZN=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 S={};return t.projectId!==void 0&&(S.projectId=t.projectId),t.savedAt!==void 0&&(S.savedAt=t.savedAt),t.maxAgeMs!==void 0&&(S.maxAgeMs=t.maxAgeMs),t.now!==void 0&&(S.now=t.now),S}),l=e.computed(()=>{const S=t.maxDesktopItems;return!Number.isFinite(S)||S<1?1:Math.floor(S)}),d=e.computed(()=>g_(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"),f=e.computed(()=>c.value.length>0),m=e.computed(()=>u.value?c.value[0]??null:null),p=e.computed(()=>u.value?"Unsaved video draft":"Unsaved video drafts"),h=e.computed(()=>f.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=S=>{var N;return((N=S.snapshot.metadata.title)==null?void 0:N.trim())||"Untitled video draft"},w=S=>{const N=S.snapshot.metadata.saveReason;return N===void 0?"Saved draft":i[N]},x=S=>{const N=new Date(S.snapshot.metadata.updatedAt);return Number.isFinite(N.getTime())?r.format(N):"Updated time unavailable"},T=S=>{n("restore",S)},_=S=>{S.length!==0&&n("dismiss",S)},g=S=>{_([S])},E=()=>{_(c.value)};return(S,N)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["draft-recovery-banner",{"draft-recovery-banner--mobile":u.value,"draft-recovery-banner--empty":!f.value}]),"data-testid":"draft-recovery-banner","aria-live":"polite","aria-label":p.value},[e.createElementVNode("header",SN,[e.createElementVNode("div",CN,[N[2]||(N[2]=e.createElementVNode("p",{class:"draft-recovery-banner__eyebrow"},"Draft recovery",-1)),e.createElementVNode("h2",VN,e.toDisplayString(p.value),1),e.createElementVNode("p",NN,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:E}," Dismiss all ")):e.createCommentVNode("",!0)]),!u.value&&f.value?(e.openBlock(),e.createElementBlock("ul",TN,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.value,V=>(e.openBlock(),e.createElementBlock("li",{key:V.key,class:"draft-recovery-banner__record","data-testid":"draft-recovery-record"},[e.createElementVNode("div",IN,[e.createElementVNode("h3",BN,e.toDisplayString(v(V)),1),e.createElementVNode("p",MN,[e.createElementVNode("span",FN,"Updated "+e.toDisplayString(x(V)),1),N[3]||(N[3]=e.createElementVNode("span",{"aria-hidden":"true"},"·",-1)),e.createElementVNode("span",$N,e.toDisplayString(w(V)),1)])]),e.createElementVNode("div",DN,[e.createElementVNode("button",{type:"button",class:"draft-recovery-banner__primary-action","data-testid":"draft-recovery-restore",onClick:A=>T(V)}," Restore ",8,RN),e.createElementVNode("button",{type:"button",class:"draft-recovery-banner__secondary-action","data-testid":"draft-recovery-dismiss",onClick:A=>g(V)}," Dismiss ",8,AN)])]))),128))])):m.value?(e.openBlock(),e.createElementBlock("article",LN,[e.createElementVNode("div",PN,[e.createElementVNode("h3",UN,e.toDisplayString(v(m.value)),1),e.createElementVNode("p",ON,[e.createElementVNode("span",zN,"Updated "+e.toDisplayString(x(m.value)),1),N[4]||(N[4]=e.createElementVNode("span",{"aria-hidden":"true"},"·",-1)),e.createElementVNode("span",jN,e.toDisplayString(w(m.value)),1)])]),e.createElementVNode("div",WN,[e.createElementVNode("button",{type:"button",class:"draft-recovery-banner__primary-action","data-testid":"draft-recovery-restore",onClick:N[0]||(N[0]=V=>T(m.value))}," Restore "),e.createElementVNode("button",{type:"button",class:"draft-recovery-banner__secondary-action","data-testid":"draft-recovery-dismiss",onClick:N[1]||(N[1]=V=>g(m.value))}," Dismiss ")])])):(e.openBlock(),e.createElementBlock("p",HN," No recoverable drafts "))],10,xN))}}),nu=Be(ZN,[["__scopeId","data-v-3ed3c273"]]),XN={class:"inspector-tabs",role:"tablist","aria-label":"Editor tools"},GN=["aria-selected","data-testid","onClick"],JN=["aria-labelledby"],KN={class:"inspector-placeholder","data-testid":"v2-inspector-placeholder"},qN=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",XN,[(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,GN))),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",KN,[e.createElementVNode("p",null,e.toDisplayString(s.activeTab)+" controls — coming soon",1)])],!0)],8,JN)],2))}}),YN=Be(qN,[["__scopeId","data-v-7f5b0e50"]]),QN={class:"keyframe-preset-panel__header"},eT={class:"keyframe-preset-panel__target","data-testid":"keyframe-preset-target"},tT={key:0,class:"keyframe-preset-panel__notice","data-testid":"keyframe-preset-invalid-duration"},aT={class:"keyframe-preset-panel__grid","data-testid":"keyframe-preset-buttons"},nT=["disabled","aria-disabled","data-testid","onClick"],oT={class:"keyframe-preset-panel__preset-label"},iT={class:"keyframe-preset-panel__preset-summary"},rT={key:1,class:"keyframe-preset-panel__compact-summary","data-testid":"keyframe-preset-mobile-summary"},sT={key:2,class:"keyframe-preset-panel__desktop-summary","data-testid":"keyframe-preset-desktop-summary"},lT={class:"keyframe-preset-panel__summary-list"},dT=["data-testid"],cT={key:0,class:"keyframe-preset-panel__summary-empty","data-testid":"keyframe-preset-summary-empty"},uT=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:S=>{const N=fE({duration:E(S)});return x("fade-in","Fade in",N,S)}},{id:"fade-out",label:"Fade out",target:"opacity",summary:"Opacity 100 -> 0%",create:S=>{const N=E(S),V=hE({startTime:S-N,duration:N});return x("fade-out","Fade out",V,S)}},{id:"push-in",label:"Push in",target:"scale",summary:"Scale 100 -> 108%",create:S=>{const N=vE({duration:S,fromScale:1,toScale:1.08,easing:"ease-out"});return x("push-in","Push in",N,S)}},{id:"push-out",label:"Push out",target:"scale",summary:"Scale 108 -> 100%",create:S=>_({id:"push-out",label:"Push out",target:"scale",duration:S,startValue:1.08,endValue:1,easing:"ease-in"})},{id:"pan-x-left",label:"Pan left",target:"x",summary:"X 55 -> 45%",create:S=>_({id:"pan-x-left",label:"Pan left",target:"x",duration:S,startValue:.55,endValue:.45,easing:"ease-in-out"})},{id:"pan-x-right",label:"Pan right",target:"x",summary:"X 45 -> 55%",create:S=>_({id:"pan-x-right",label:"Pan right",target:"x",duration:S,startValue:.45,endValue:.55,easing:"ease-in-out"})},{id:"pan-y-up",label:"Pan up",target:"y",summary:"Y 55 -> 45%",create:S=>_({id:"pan-y-up",label:"Pan up",target:"y",duration:S,startValue:.55,endValue:.45,easing:"ease-in-out"})},{id:"pan-y-down",label:"Pan down",target:"y",summary:"Y 45 -> 55%",create:S=>_({id:"pan-y-down",label:"Pan down",target:"y",duration:S,startValue:.45,endValue:.55,easing:"ease-in-out"})},{id:"audio-fade-in",label:"Audio fade in",target:"audioVolume",summary:"Volume 0 -> 100%",create:S=>_({id:"audio-fade-in",label:"Audio fade in",target:"audioVolume",duration:E(S),startValue:0,endValue:1,easing:"ease-out"})},{id:"audio-fade-out",label:"Audio fade out",target:"audioVolume",summary:"Volume 100 -> 0%",create:S=>{const N=E(S);return _({id:"audio-fade-out",label:"Audio fade out",target:"audioVolume",duration:N,startTime:S-N,startValue:1,endValue:0,easing:"ease-in"})}}],s=e.computed(()=>uE(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(S=>S.target===t.target)),u=e.computed(()=>d.value?c.value.map(S=>({definition:S,automation:S.create(t.duration)})):[]),f=e.computed(()=>i[t.target]),m=e.computed(()=>{const S=c.value.length,N=S===1?"preset":"presets";return d.value?`${S} ${N} - ${h(t.duration)} clip.`:`${S} ${N} available when duration is set.`}),p=S=>{if(!d.value)return;const N=S.create(t.duration);n("apply-preset",{presetId:N.id,target:N.target,keyframes:N.keyframes,automation:N})},h=S=>{const N=Math.round(S*100)/100;return`${N.toFixed(N%1===0?0:2)}s`},v=(S,N)=>S==="opacity"||S==="audioVolume"?`${Math.round(N*100)}%`:S==="scale"?`${Math.round(N*100)}%`:S==="x"||S==="y"?`${Math.round(N*100)}%`:`${Math.round(N*100)/100}`,w=S=>{const[N,V]=S.keyframes;return`${h(N.time)} ${v(S.target,N.value)} -> ${h(V.time)} ${v(S.target,V.value)}`};function x(S,N,V,A){return T({id:S,label:N,target:V.target,duration:A,keyframes:V.keyframes})}function T(S){const N=pE(S.keyframes,{target:S.target,minTime:0,maxTime:S.duration}),V=N[0],A=N[1];if(N.length!==2||V===void 0||A===void 0)throw new Error("Keyframe preset panel presets must generate exactly two keyframes.");return{id:S.id,label:S.label,target:S.target,editingMode:"preset-only",keyframes:[V,A]}}function _(S){const N=S.startTime??0,V=[g(`${S.id}:start`,S.target,N,S.startValue,"linear"),g(`${S.id}:end`,S.target,N+S.duration,S.endValue,S.easing)];return T({id:S.id,label:S.label,target:S.target,duration:N+S.duration,keyframes:V})}function g(S,N,V,A,j){return{id:S,target:N,time:V,value:A,easing:j}}function E(S){return Math.min(S,1)}return(S,N)=>(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",QN,[N[0]||(N[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",eT,e.toDisplayString(f.value),1)]),d.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("p",tT," Set a valid clip duration to apply automation presets. ")),e.createElementVNode("div",aT,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.value,V=>(e.openBlock(),e.createElementBlock("button",{key:V.id,type:"button",class:"keyframe-preset-panel__preset",disabled:!d.value,"aria-disabled":d.value?void 0:"true","data-testid":`keyframe-preset-button-${V.id}`,onClick:A=>p(V)},[e.createElementVNode("span",oT,e.toDisplayString(V.label),1),e.createElementVNode("span",iT,e.toDisplayString(V.summary),1)],8,nT))),128))]),l.value?(e.openBlock(),e.createElementBlock("p",rT,e.toDisplayString(m.value),1)):(e.openBlock(),e.createElementBlock("div",sT,[N[1]||(N[1]=e.createElementVNode("p",{class:"keyframe-preset-panel__summary-title"},"Generated keyframes",-1)),e.createElementVNode("ul",lT,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(u.value,V=>(e.openBlock(),e.createElementBlock("li",{key:V.definition.id,class:"keyframe-preset-panel__summary-row","data-testid":`keyframe-preset-summary-${V.definition.id}`},[e.createElementVNode("span",null,e.toDisplayString(V.definition.label),1),e.createElementVNode("span",null,e.toDisplayString(w(V.automation)),1)],8,dT))),128))]),u.value.length===0?(e.openBlock(),e.createElementBlock("p",cT," No generated keyframes until duration is valid. ")):e.createCommentVNode("",!0)]))],2))}}),ou=Be(uT,[["__scopeId","data-v-79615683"]]),mT={class:"mobile-clip-summary__main"},pT={class:"mobile-clip-summary__title","data-testid":"v2-mobile-clip-label"},fT={class:"mobile-clip-summary__stats","aria-label":"Selected clip timing"},hT={class:"mobile-clip-summary__stat"},vT={"data-testid":"v2-mobile-clip-start"},gT={class:"mobile-clip-summary__stat"},bT={"data-testid":"v2-mobile-clip-end"},yT={class:"mobile-clip-summary__stat"},wT={"data-testid":"v2-mobile-clip-duration"},kT={key:1,class:"mobile-clip-summary__empty","data-testid":"v2-mobile-no-clip"},_T=e.defineComponent({__name:"MobileClipSummary",props:{selectedClip:{}},emits:["open-actions"],setup(o,{emit:a}){const t=o,n=a,i=f=>f===void 0||!Number.isFinite(f)?null:f,r=e.computed(()=>{var f,m,p;return((m=(f=t.selectedClip)==null?void 0:f.label)==null?void 0:m.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 f=s.value,m=l.value;return f!==null&&m!==null?Math.max(0,m-f):t.selectedClip?i(t.selectedClip.duration):null}),c=f=>{if(f===null)return"--";const m=Math.round(f*100)/100;return`${m.toFixed(m%1===0?0:2)}s`},u=()=>{t.selectedClip&&n("open-actions",t.selectedClip.id)};return(f,m)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["mobile-clip-summary",{"mobile-clip-summary--empty":!f.selectedClip}]),"data-testid":"v2-mobile-clip-summary","aria-live":"polite"},[f.selectedClip?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("div",mT,[m[0]||(m[0]=e.createElementVNode("p",{class:"mobile-clip-summary__eyebrow"},"Selected clip",-1)),e.createElementVNode("h2",pT,e.toDisplayString(r.value),1)]),e.createElementVNode("dl",fT,[e.createElementVNode("div",hT,[m[1]||(m[1]=e.createElementVNode("dt",null,"Start",-1)),e.createElementVNode("dd",vT,e.toDisplayString(c(s.value)),1)]),e.createElementVNode("div",gT,[m[2]||(m[2]=e.createElementVNode("dt",null,"End",-1)),e.createElementVNode("dd",bT,e.toDisplayString(c(l.value)),1)]),e.createElementVNode("div",yT,[m[3]||(m[3]=e.createElementVNode("dt",null,"Duration",-1)),e.createElementVNode("dd",wT,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",kT," No clip selected "))],2))}}),ET=Be(_T,[["__scopeId","data-v-433c7812"]]),xT=["aria-label"],ST=["aria-pressed","data-testid","onClick"],CT={class:"mobile-tool-picker__label"},VT=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",CT,e.toDisplayString(d.label),1)],10,ST)),64))],8,xT))}}),NT=Be(VT,[["__scopeId","data-v-ec597c70"]]),TT=["aria-label","data-snap"],IT=["aria-expanded"],BT={class:"drawer-header"},MT={class:"drawer-body"},FT=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,f=null,m=0,p=0,h=0;const v=A=>{const j=h||(typeof window<"u"?window.innerHeight:600);switch(A){case"collapsed":return 80;case"half":return Math.round(j*.45);case"full":return Math.round(j*.85)}},w=(A,{animate:j=!0}={})=>{var y;if(!s.value)return;const C=d.value;d.value=A;const $=typeof window<"u"&&((y=window.matchMedia)==null?void 0:y.call(window,"(prefers-reduced-motion: reduce)").matches);s.value.style.transition=j&&!$?"height 0.25s cubic-bezier(0.33, 1, 0.68, 1)":"none",s.value.style.height=`${v(A)}px`,A!==C&&r("snap-change",A,C)},x=A=>{let j=n[0],C=1/0;for(const $ of n){const y=Math.abs(v($)-A);y<C&&(C=y,j=$)}return j},T=()=>{const A=n.indexOf(d.value);w(n[(A+1)%n.length])},_=A=>{if(u){u=!1,A.preventDefault();return}T()},g=A=>{var j,C,$;if(A.button===0){c=!0,u=!1,f=A.pointerId,m=A.clientY,p=((j=s.value)==null?void 0:j.offsetHeight)??0;try{($=(C=l.value)==null?void 0:C.setPointerCapture)==null||$.call(C,A.pointerId)}catch{}s.value&&(s.value.style.transition="none")}},E=A=>{if(!c||A.pointerId!==f)return;const j=A.clientY-m,C=p-j,$=v("collapsed"),y=v("full"),R=Math.max($,Math.min(y,C));s.value&&(s.value.style.height=`${R}px`),Math.abs(j)>4&&(u=!0),A.preventDefault()},S=A=>{var C,$,y;if(!c)return;c=!1;try{($=(C=l.value)==null?void 0:C.releasePointerCapture)==null||$.call(C,A.pointerId)}catch{}f=null;const j=((y=s.value)==null?void 0:y.offsetHeight)??0;w(x(j))},N=(A,j={})=>{n.includes(A)&&w(A,{animate:j.animate!==!1})},V=A=>{h=Math.max(0,Number(A)||0),w(d.value,{animate:!1})};return e.watch(()=>i.containerHeight,A=>{A>0&&V(A)}),e.onMounted(()=>{i.containerHeight>0&&(h=i.containerHeight),w(d.value,{animate:!1})}),e.onBeforeUnmount(()=>{c=!1,f=null}),a({snapTo:N,updateContainerHeight:V,snap:d}),(A,j)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"rootEl",ref:s,class:"video-editor-v2-drawer",role:"dialog","aria-label":A.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:_,onPointerdown:g,onPointermove:E,onPointerup:S,onPointercancel:S},[...j[0]||(j[0]=[e.createElementVNode("span",{class:"drawer-handle-grip","aria-hidden":"true"},null,-1)])],40,IT),e.createElementVNode("div",BT,[e.renderSlot(A.$slots,"header",{},void 0,!0)]),e.createElementVNode("div",MT,[e.renderSlot(A.$slots,"default",{},void 0,!0)])],8,TT))}}),$T=Be(FT,[["__scopeId","data-v-4ebedbf7"]]),DT=new Set(["INPUT","TEXTAREA","SELECT"]);function RT(o){return o instanceof HTMLElement?!!(DT.has(o.tagName)||o.isContentEditable):!1}function AT(o,a={}){const t=n=>{var l,d,c,u,f,m,p,h,v,w,x,T,_,g,E,S,N;if(a.enabled&&a.enabled()===!1||RT(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":(f=o.playPause)==null||f.call(o),n.preventDefault();return;case"ArrowLeft":r?(m=o.secondBackward)==null||m.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":(w=o.skipToStart)==null||w.call(o),n.preventDefault();return;case"End":(x=o.skipToEnd)==null||x.call(o),n.preventDefault();return;case"[":(T=o.prevClip)==null||T.call(o),n.preventDefault();return;case"]":(_=o.nextClip)==null||_.call(o),n.preventDefault();return;case"s":case"S":i||((g=o.splitAtPlayhead)==null||g.call(o),n.preventDefault());return;case"Delete":case"Backspace":r?(E=o.rippleDeleteSelected)==null||E.call(o):(S=o.deleteSelected)==null||S.call(o),n.preventDefault();return;case"?":(N=o.showShortcutsOverlay)==null||N.call(o),n.preventDefault();return}};e.onMounted(()=>{window.addEventListener("keydown",t)}),e.onBeforeUnmount(()=>{window.removeEventListener("keydown",t)})}const Mp=["video/mp4","video/webm","video/quicktime"],Fp=["image/png","image/jpeg","image/jpg","image/webp"],LT=["audio/mpeg","audio/mp3","audio/aac","audio/wav","audio/x-wav","audio/wave"],PT=new Set([...Mp,...Fp,...LT]),UT=2*1024*1024*1024,OT=60*60;function iu(o,a){const t=o.type.toLowerCase();return PT.has(t)?o.size>UT?{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>OT?{ok:!1,reason:"duration_exceeded",message:`Clip is too long (${Math.round(a)}s). Limit is 1 hour.`}:{ok:!0,kind:Mp.includes(t)?"video":Fp.includes(t)?"image":"audio"}:{ok:!1,reason:"unsupported_mime",message:`Unsupported file type: ${t||"unknown"}.`}}const zT="mediables-asset-blobs",za="blobs",jT=1;class WT{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(zT,jT);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(za)||i.createObjectStore(za)},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(za,"readwrite").objectStore(za).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(za,"readonly").objectStore(za).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(za,"readwrite").objectStore(za).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(za,"readwrite").objectStore(za).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error??new Error("Failed to clear cache."))}})}}let Xs=null;function HT(){return Xs===null&&(Xs=new WT),Xs}class ZT{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 XT(){return`asset-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function GT(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 JT(o){const a=e.reactive(new Map),t=o.blobCache??KT();async function n(u,f){try{await t.put(u,f)}catch{}}async function i(u){try{await t.delete(u)}catch{}}async function r(u,f,m){var p,h,v;try{f.status="uploading",f.uploadProgress=0,a.set(f.assetId,f);const w=await o.uploader.upload({file:u},({assetId:x,progress:T,status:_})=>{if(x!==f.assetId)return;const g=a.get(x);g&&(g.uploadProgress=T,g.status=_,a.set(x,g))});return a.set(f.assetId,w),w.status==="ready"?(i(f.assetId),(p=o.onReady)==null||p.call(o,w)):w.status==="failed"&&((h=o.onFailure)==null||h.call(o,w)),{ok:!0,record:w}}catch(w){const x=w instanceof Error?w.message:"Upload failed.",T={...f,status:"failed",failureMessage:x};return a.set(f.assetId,T),(v=o.onFailure)==null||v.call(o,T),{ok:!1,reason:"upload",message:x}}}const s=o.probeTimeoutMs??1500;async function l(u){const f=await GT(u,s),m=iu(u,f.durationSeconds);if(!m.ok)return{ok:!1,reason:"preflight",message:m.message};const p=XT(),h={assetId:p,filename:u.name,mime:u.type,sizeBytes:u.size,status:"local-selected"};return f.durationSeconds!==void 0&&(h.durationSeconds=f.durationSeconds),f.width!==void 0&&(h.width=f.width),f.height!==void 0&&(h.height=f.height),a.set(p,h),await n(p,u),r(u,h)}async function d(u){const f=a.get(u);if(!f)return{ok:!1,reason:"unknown",message:"Unknown asset."};const m=await t.get(u);if(!m)return{ok:!1,reason:"unknown",message:"Original file is no longer cached."};const p=m instanceof File?m:new File([m],f.filename,{type:f.mime}),h=iu(p,f.durationSeconds);return h.ok?r(p,f):{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 KT(){return typeof indexedDB<"u"?HT():new ZT}const qT={class:"v2-toolbar-group"},YT=["aria-label"],QT=["disabled"],e4={class:"v2-toolbar-group"},t4={class:"v2-toolbar-fit"},a4=["disabled"],n4=["aria-label","title","disabled"],o4={class:"v2-assets"},i4={key:0,class:"v2-asset-rail-status","data-testid":"v2-asset-rail-status",role:"status"},r4={class:"v2-preview-host"},s4={class:"v2-timeline-topbar"},l4={class:"v2-timeline-heading"},d4={class:"v2-timeline-meta","data-testid":"v2-timeline-meta"},c4={class:"v2-timeline-zoom"},u4=["value"],m4={class:"v2-timeline-zoom-readout"},p4={key:0,class:"v2-timeline-track-actions"},f4={key:0,class:"v2-timeline-track-target"},h4=["value"],v4=["value"],g4=["aria-pressed"],b4={key:0,class:"v2-editor-status","data-testid":"v2-editor-status",role:"status","aria-live":"polite"},y4={key:1,class:"v2-timeline-empty","data-testid":"v2-timeline-empty"},w4={key:1,class:"v2-empty-state"},k4={key:0,"data-testid":"v2-export-status-completed",class:"v2-export-status"},_4={key:1,class:"v2-export-status","data-testid":"v2-export-status-message"},E4={key:1,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-look"},x4={class:"v2-mobile-panel-section"},S4={class:"v2-mobile-panel-section v2-mobile-panel-section--compact"},C4={key:1,class:"v2-empty-state"},V4={key:2,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-trim"},N4={key:3,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-text"},T4={key:4,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-audio"},I4={key:5,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-export"},B4={key:0,class:"v2-export-status"},M4={key:1,class:"v2-export-status"},F4={key:6,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-more"},$4={class:"v2-mobile-secondary-controls"},D4={class:"v2-mobile-secondary-field"},R4=["aria-pressed"],A4=["disabled"],L4=["disabled"],P4={key:0,class:"v2-mobile-secondary-details","data-testid":"v2-mobile-transitions"},U4={class:"v2-mobile-secondary-details","data-testid":"v2-mobile-keyframes"},O4={class:"v2-shortcuts-overlay__panel"},z4={class:"v2-shortcuts-overlay__header"},j4=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 zi,ji,Wi,Hi;const n=o,i=t,r=e.computed(()=>{var q;const b=typeof n.mediaUuid=="string"?n.mediaUuid.trim():"";if(b!=="")return b;const M=(q=n.media)==null?void 0:q.uuid;return typeof M=="string"&&M.trim()!==""?M.trim():`temp-${Date.now()}`}),s=ep(r.value,n.initialRecipe,n.media),l=np(),d=e.ref("filters"),c=e.ref("look"),u=e.ref(null),f=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}),m=e.computed(()=>{const b=n.featureFlags??{},M=["filters","adjustments","text","transitions","audio","export"],q={filters:"Filters",adjustments:"Adjust",text:"Text",transitions:"Transitions",audio:"Audio",export:"Export"};return M.map(me=>({id:me,label:q[me],enabled:typeof b[me]=="boolean"?b[me]:f.value[me]}))}),p=b=>m.value.some(M=>M.id===b&&M.enabled),h={look:"filters",text:"text",audio:"audio",export:"export"},v=e.computed(()=>{var b;return((b=n.featureFlags)==null?void 0:b.transitions)===!0});e.watch(c,b=>{var M,q;if(b!=="trim"&&b!=="more"){const me=h[b];p(me)&&(d.value=me)}(q=(M=u.value)==null?void 0:M.snapTo)==null||q.call(M,"full"),e.nextTick(()=>{var Fe;if(typeof document>"u")return;const me=document.querySelector(`[data-testid="v2-mobile-panel-${b}"]`);if(!me||!(me instanceof HTMLElement))return;const Me=typeof window<"u"&&((Fe=window.matchMedia)==null?void 0:Fe.call(window,"(prefers-reduced-motion: reduce)").matches);me.scrollIntoView({block:"start",behavior:Me?"auto":"smooth"})})});const w=e.ref(!1),x=e.computed(()=>d.value),T=e.computed(()=>x.value==="filters"||w.value),_=e.computed(()=>x.value!=="filters"&&!w.value),g=e.ref(null),E=e.computed(()=>g.value),S=["contain","cover","none"],N=b=>typeof b=="string"&&S.includes(b),V=b=>{var q;const M=(q=b==null?void 0:b.metadata)==null?void 0:q.fit_mode;return N(M)?M:null},A=e.ref(V(n.initialRecipe)??"contain"),j=e.ref("");e.watch(()=>{var b,M;return{file:(b=n.media)==null?void 0:b.file,url:(M=n.media)==null?void 0:M.url}},(b,M,q)=>{var Me,Fe;const me=j.value;q(()=>{me&&me.startsWith("blob:")&&URL.revokeObjectURL(me)}),(Me=n.media)!=null&&Me.file?j.value=URL.createObjectURL(n.media.file):(Fe=n.media)!=null&&Fe.url?j.value=n.media.url:j.value=""},{immediate:!0});const C=e.computed(()=>j.value),$=e.computed(()=>l.activeFilters.value),y=e.computed(()=>s.playheadPosition.value),R=Vm({forcePixiPreview:w,getPreviewRef:()=>E.value,getSourceUrl:()=>j.value,setPlaying:s.setPlaying}),L=e.computed(()=>{if(!n.media)return null;const{file:b,...M}=n.media;return{...M,url:j.value}}),U=e.computed(()=>{var M;const b=(M=n.media)==null?void 0:M.url;return!!(b&&/^https?:/i.test(b))}),z=e.ref(0),I=e.computed(()=>{var M;if(s.totalDuration.value>0)return s.totalDuration.value;if(z.value>0)return z.value;const b=Number((M=n.media)==null?void 0:M.duration);return Number.isFinite(b)&&b>0?b:0}),P=b=>{!Number.isFinite(b)||b<=0||(z.value=b,s.updateSourceDuration(b))},Z=b=>{b&&typeof b.time=="number"&&Number.isFinite(b.time)&&s.seekTo(b.time)},K=b=>{Number.isFinite(b)&&s.seekTo(b)},ve=b=>{s.setPlaying(b)},Ve=e.computed(()=>l.videoCompatibleFilters.value.map(M=>{var me;const q=[];if(M.controls&&M.controls.length>0)for(const Me of M.controls){const Fe=Me.type;if(Fe==="button"||Fe==="text"||Fe==="range")continue;const Ye={id:Me.property||Me.id,label:Me.label||Me.id,type:Fe,default:Me.default??(Fe==="toggle"?!1:Fe==="color"?"#ffffff":0)};Fe==="slider"&&(Ye.min=Me.min??0,Ye.max=Me.max??1,Ye.step=Me.step??.01),Fe==="select"&&Me.options&&(Ye.options=Me.options),q.push(Ye)}else if(M.paramRanges){const Me=Object.entries(M.paramRanges);for(const[Fe,Ye]of Me){const pt=Fe.replace(/[-_]/g," ").replace(/\b\w/g,co=>co.toUpperCase()),$t=(me=M.defaultParams)==null?void 0:me[Fe],aa=(Ye.min+Ye.max)/2;q.push({id:Fe,label:pt,min:Ye.min,max:Ye.max,step:Ye.step??.01,default:typeof $t=="number"?$t:aa})}}return{id:M.id,name:M.name,category:M.category,params:q}})),ne=e.computed(()=>{const b=new Map;return l.activeFilters.value.forEach(M=>b.set(M.filterId,M)),b}),ae=e.computed(()=>{if(s.currentFrame.value)return s.currentFrame.value;const b=n.media;return(b==null?void 0:b.thumbnail_url)??(b==null?void 0:b.url)}),F=e.shallowRef(null),B=e.ref(null),O=e.ref(null),X=e.ref(null),oe=e.ref(!1),ce=new Map,je=(b,M)=>{const q={id:b.id??`text-overlay-recipe-${M}`,text:b.content};return b.fontFamily!==void 0&&(q.fontFamily=b.fontFamily),b.fontSize!==void 0&&(q.fontSize=b.fontSize),b.fontWeight!==void 0&&(q.fontWeight=b.fontWeight),b.color!==void 0&&(q.color=b.color),b.position!==void 0&&(q.position=b.position),b.startTime!==void 0&&(q.startTime=b.startTime),b.duration!==void 0&&(q.duration=b.duration),b.animation!==void 0&&(q.animation=b.animation),b.textAlign!==void 0&&(q.textAlign=b.textAlign),b.textBaseline!==void 0&&(q.textBaseline=b.textBaseline),q},he=b=>{const M={id:b.id,content:b.text};return b.fontFamily!==void 0&&(M.fontFamily=b.fontFamily),b.fontSize!==void 0&&(M.fontSize=b.fontSize),b.fontWeight!==void 0&&(M.fontWeight=b.fontWeight),b.color!==void 0&&(M.color=b.color),b.position!==void 0&&(M.position=b.position),b.startTime!==void 0&&(M.startTime=b.startTime),b.duration!==void 0&&(M.duration=b.duration),b.animation!==void 0&&(M.animation=b.animation),b.textAlign!==void 0&&(M.textAlign=b.textAlign),b.textBaseline!==void 0&&(M.textBaseline=b.textBaseline),M},ge=(b,M)=>{const q={id:b.id??`audio-track-recipe-${M}`,source:b.source};return b.volume!==void 0&&(q.volume=b.volume),b.startTime!==void 0&&(q.startTime=b.startTime),b.duration!==void 0&&(q.duration=b.duration),b.fadeIn!==void 0&&(q.fadeIn=b.fadeIn),b.fadeOut!==void 0&&(q.fadeOut=b.fadeOut),b.loop!==void 0&&(q.loop=b.loop),b.name!==void 0&&(q.name=b.name),q},pe=b=>{if(typeof b.source!="string")return null;const M={id:b.id,source:b.source};return b.volume!==void 0&&(M.volume=b.volume),b.startTime!==void 0&&(M.startTime=b.startTime),b.duration!==void 0&&(M.duration=b.duration),b.fadeIn!==void 0&&(M.fadeIn=b.fadeIn),b.fadeOut!==void 0&&(M.fadeOut=b.fadeOut),b.loop!==void 0&&(M.loop=b.loop),b.name!==void 0&&(M.name=b.name),M},we=b=>{const M={id:b.id,source:typeof b.source=="string"?b.source:""};return b.volume!==void 0&&(M.volume=b.volume),b.startTime!==void 0&&(M.startTime=b.startTime),b.duration!==void 0&&(M.duration=b.duration),b.fadeIn!==void 0&&(M.fadeIn=b.fadeIn),b.fadeOut!==void 0&&(M.fadeOut=b.fadeOut),b.loop!==void 0&&(M.loop=b.loop),b.name!==void 0&&(M.name=b.name),b.muted!==void 0&&(M.muted=b.muted),b.solo!==void 0&&(M.solo=b.solo),b.pan!==void 0&&(M.pan=b.pan),b.faderDb!==void 0&&(M.faderDb=b.faderDb),M},ye=b=>({...b,segments:b.segments.map(M=>{const q={...M};return M.words&&(q.words=M.words.map(me=>({...me}))),q})}),Ne=e.ref((((zi=n.initialRecipe)==null?void 0:zi.textOverlays)??[]).map(je)),De=b=>{switch(b){case"crossfade":return"cross-fade";case"zoom":return"zoom-in";case"cut":return"fade";default:return b}},Qe=b=>{switch(b){case"ease-in":return"easeIn";case"ease-out":return"easeOut";case"ease-in-out":return"easeInOut";case"linear":return"linear"}},et=b=>{switch(b){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 b}},Lt=b=>{switch(b){case"easeIn":return"ease-in";case"easeOut":return"ease-out";case"easeInOut":return"ease-in-out";case"linear":default:return"linear"}},kt=b=>({id:b.id,type:De(b.type),duration:b.duration,easing:Qe(b.easing),name:b.type,fromClipId:b.fromClipId,toClipId:b.toClipId,cutTime:b.cutTime??0}),Ct=b=>({id:b.id,type:et(b.type),fromClipId:b.fromClipId,toClipId:b.toClipId,duration:b.duration,easing:Lt(b.easing),cutTime:b.cutTime}),bt=e.ref((((ji=n.initialRecipe)==null?void 0:ji.transitions)??[]).map(kt)),rt=e.ref((((Wi=n.initialRecipe)==null?void 0:Wi.audioTracks)??[]).map(ge)),_t=e.ref(1),be=e.ref(!1),ke=e.ref((((Hi=n.initialRecipe)==null?void 0:Hi.captionTracks)??[]).map(ye)),Te=e.ref([]),Ke=e.ref(null),Ge=e.computed(()=>r.value),ze=e.computed(()=>Te.value),Et=e.computed(()=>ke.value[0]??null),ut=e.computed(()=>{const b=s.selectedClip.value??s.timelineClips.value[0];return b?Math.max(0,b.timelineEnd-b.timelineStart):I.value}),Xt=e.computed(()=>R_(rt.value.map(we),{master:{volume:_t.value,muted:be.value}})),Wt=e.computed(()=>{const b=[...s.timelineClips.value].sort((Ye,pt)=>Ye.timelineStart-pt.timelineStart),M=s.selectedClip.value??b[0];if(!M)return[];const q=b.findIndex(Ye=>Ye.id===M.id);if(q===-1)return[];const me=Ye=>(Ye.trackId??null)===(M.trackId??null),Me=b.slice(q+1).find(me);if(Me)return[M,Me];const Fe=[...b.slice(0,q)].reverse().find(me);return Fe?[Fe,M]:[]}),ca=b=>{F.value=b,b!=null&&b.composition&&(O.value=new op(b.composition),X.value=new ip(b.composition));try{ce.size&&F.value&&(ce.forEach((M,q)=>{F.value.setClipFilters(q,M)}),ce.clear(),F.value.composition.computeFrame())}catch{}},ta=b=>{F.value?F.value.setClipFilters(b,l.activeFilters.value):ce.set(b,[...l.activeFilters.value])},ya=b=>{var q,me;const M=((q=s.selectedClip.value)==null?void 0:q.id)??((me=s.timelineClips.value[0])==null?void 0:me.id);M&&(oe.value=!0,typeof b=="object"&&b!==null&&"id"in b?l.applyFilter(b.id):typeof b=="string"&&l.applyFilter(b),s.setFilters(l.activeFilters.value),ta(M),s.handleClipSelect(M),oe.value=!1,Pe())},Sa=b=>{var me,Me;const M=l.activeFilters.value.find(Fe=>Fe.filterId===b);M&&l.removeFilter(M.id),s.setFilters(l.activeFilters.value);const q=((me=s.selectedClip.value)==null?void 0:me.id)??((Me=s.timelineClips.value[0])==null?void 0:Me.id);q&&ta(q),Pe()},wa=(b,M,q)=>{var Fe,Ye;const me=l.activeFilters.value.find(pt=>pt.filterId===b);if(me){me.params={...me.params??{},[M]:q},s.setFilters(l.activeFilters.value);const pt=((Fe=s.selectedClip.value)==null?void 0:Fe.id)??((Ye=s.timelineClips.value[0])==null?void 0:Ye.id);pt&&ta(pt),Pe();return}const Me=l.previewFilter.value;Me&&Me.filterId===b&&(Me.params={...Me.params??{},[M]:q})},nn=b=>{b&&typeof b.id=="string"&&b.id!==""&&l.previewFilterEffect(b.id)},Q=b=>{l.updateFilterParams(b),s.setFilters(l.activeFilters.value),Pe()},ue=async b=>{if(!O.value)return;const M=await O.value.addTextOverlay(b);Ne.value.push({id:M,...b})},re=async(b,M)=>{if(!O.value)return;await O.value.updateTextOverlay(b,M);const q=Ne.value.findIndex(me=>me.id===b);q!==-1&&(Ne.value[q]={...Ne.value[q],...M})},ie=async b=>{O.value&&(await O.value.removeTextOverlay(b),Ne.value=Ne.value.filter(M=>M.id!==b))},Se=async b=>{const[M,q]=Wt.value;if(!M||!q)return;const me={id:`transition-${M.id}-${q.id}-${Date.now()}`,...b,name:b.type,fromClipId:M.id,toClipId:q.id,cutTime:M.timelineEnd};bt.value.push(me),s.setTransitions(bt.value.map(Ct)),Pe()},Ae=b=>{bt.value[b]&&(bt.value.splice(b,1),s.setTransitions(bt.value.map(Ct)),Pe())},qe=b=>{},ft=async b=>{if(!X.value)return;const M=await X.value.addAudioTrack(b);rt.value.push({id:M,...b});const q=typeof b.source=="string"?b.source:b.source instanceof File?URL.createObjectURL(b.source):null;if(!q)return;const me={id:`audio-source-${M}`,type:"url",url:q,duration:typeof b.duration=="number"&&b.duration>0?b.duration:0,width:0,height:0};typeof b.name=="string"&&(me.filename=b.name),s.registerMediaSource(me);const Me=s.appendAudioSourceToTimeline(me.id);if(!Me.ok){Ze.value=Me.message;return}Ze.value=`Audio added to ${Me.value.trackId??"timeline"}.`,Pe()},Vt=async(b,M)=>{if(!X.value)return;await X.value.updateAudioTrack(b,M);const q=rt.value.findIndex(me=>me.id===b);q!==-1&&(rt.value[q]={...rt.value[q],...M})},ht=async b=>{X.value&&(await X.value.removeAudioTrack(b),rt.value=rt.value.filter(M=>M.id!==b))},vt=async(b,M)=>{if(!X.value)return;await X.value.updateVolume(b,M);const q=rt.value.find(me=>me.id===b);q&&(q.volume=M)},Ut=async(b,M)=>{if(!X.value)return;await X.value.muteTrack(b,M);const q=rt.value.find(me=>me.id===b);q&&(q.muted=M)},Mt=b=>{X.value&&(X.value.setMasterVolume(b),_t.value=b)},Ft=(b,M)=>{const q=rt.value.findIndex(Me=>Me.id===b);if(q===-1)return null;const me={...rt.value[q],...M};return rt.value[q]=me,me},on=b=>{switch(b.type){case"track-fader-db":{const M=Bl(b.valueDb);Ft(b.trackId,{faderDb:b.valueDb,volume:M}),X.value&&X.value.updateVolume(b.trackId,M);break}case"track-mute":Ft(b.trackId,{muted:b.muted}),X.value&&X.value.muteTrack(b.trackId,b.muted);break;case"track-solo":Ft(b.trackId,{solo:b.solo});break;case"track-pan":Ft(b.trackId,{pan:b.pan});break;case"master-fader-db":{_t.value=Bl(b.valueDb),X.value&&X.value.setMasterVolume(be.value?0:_t.value);break}case"master-mute":be.value=b.muted,X.value&&X.value.setMasterVolume(be.value?0:_t.value);break}},Fa=b=>{ke.value=[ye(b.track)],s.setCaptionTracks(ke.value),Pe()},Ca=b=>{ke.value=[ye(b)],s.setCaptionTracks(ke.value),Pe()},Va=()=>{ke.value=[],s.setCaptionTracks([]),Pe()},ua=b=>{const M=s.selectedClip.value??s.timelineClips.value[0];if(!M)return;const me=[...(M.keyframes??[]).filter(Me=>Me.target!==b.target),...b.keyframes].sort((Me,Fe)=>{const Ye=Me.time-Fe.time;return Ye===0?Me.id.localeCompare(Fe.id):Ye});s.setClipKeyframes(M.id,me),Pe()},yt=b=>{var M;return b.metadata||(b.metadata={created_at:new Date().toISOString(),editor_version:"2.0.0"}),b.metadata.fit_mode=A.value,(M=n.media)!=null&&M.url&&/^https?:/i.test(n.media.url)?b.metadata.source_url=n.media.url:delete b.metadata.source_url,b.captionTracks=ke.value.map(ye),b},wt=(b,M)=>M?{...b,output:{...b.output,format:M.format,quality:M.quality,codec:M.codec??b.output.codec,fps:M.fps??b.output.fps,...typeof M.bitrate=="number"?{bitrate:M.bitrate}:{}}}:b,ma=b=>b.map(M=>({...M,params:M.params&&typeof M.params=="object"?{...M.params}:M.params})),mt=b=>b.timeline.some(M=>Array.isArray(M.filters)&&M.filters.length>0),Ot=b=>{const M=ma(l.activeFilters.value);if(!mt(b)&&M.length>0&&b.timeline.length>0){const me=b.timeline[0];me&&(b.timeline=[{...me,filters:M},...b.timeline.slice(1)])}return b},$a=()=>{const b=Ot(yt(s.saveDraft()));try{localStorage.setItem(`video-draft-${r.value}`,JSON.stringify(b))}catch{}return se(b,"manual",!0),b},H=()=>typeof localStorage>"u"?null:{getItem:b=>localStorage.getItem(b),setItem:(b,M)=>{localStorage.setItem(b,M)},removeItem:b=>{localStorage.removeItem(b)},listKeys:b=>{const M=[];for(let q=0;q<localStorage.length;q+=1){const me=localStorage.key(q);me!=null&&me.startsWith(b)&&M.push(me)}return M}},G=async()=>{const b=H();if(b===null){Te.value=[];return}Te.value=await Tc(b)},se=async(b,M,q)=>{var aa,co;const me=H();if(me===null)return;const Me=new Date().toISOString(),Fe={projectId:Ge.value,sourceMediaUuid:r.value,durationSeconds:I.value,editorVersion:((aa=b.metadata)==null?void 0:aa.editor_version)??"2.0.0",saveReason:M,now:Me};((co=b.metadata)==null?void 0:co.title)!==void 0&&(Fe.title=b.metadata.title);const Ye=c_(Nm(b),Fe);await b_(me,Ye);const pt=await Tc(me),$t=f_(pt,{maxCount:5,projectId:Ge.value,now:Me});await Ic(me,$t.removed),Te.value=[...$t.retained],q&&(Ke.value=Me)},de=b=>b.snapshot.metadata.payloadKind==="project"?i_(b.snapshot.payload):b.snapshot.payload,_e=b=>{const M=de(b);s.loadRecipe(M),Ne.value=(M.textOverlays??[]).map(je),rt.value=(M.audioTracks??[]).map(ge),ke.value=(M.captionTracks??[]).map(ye),bt.value=(M.transitions??[]).map(kt);const q=V(M);q!==null&&(A.value=q),tt()},Le=b=>{const M=H();Te.value=Te.value.filter(q=>!b.some(me=>me.key===q.key)),M!==null&&Ic(M,b)},tt=()=>{B.value=yt(s.generateRecipe())};let He=null;const Pe=()=>{He&&clearTimeout(He),He=setTimeout(()=>{tt(),He=null},200)};if(e.watch(()=>s.timelineClips.value,Pe,{deep:!0}),e.watch(()=>s.selectedClip.value,b=>{if(oe.value||!b)return;const M=(b==null?void 0:b.filters)??[];l.setActiveFilters(M)},{immediate:!0}),e.watch(()=>l.activeFilters.value,b=>{s.setFilters(b),Pe()},{deep:!0}),e.watch(()=>Ne.value,b=>{s.setTextOverlays(b.map(he)),Pe()},{deep:!0}),e.watch(()=>rt.value,b=>{const M=b.map(pe).filter(q=>q!==null);s.setAudioTracks(M),Pe()},{deep:!0}),e.watch(()=>ke.value,b=>{s.setCaptionTracks(b.map(ye)),Pe()},{deep:!0}),Ne.value.length>0&&s.setTextOverlays(Ne.value.map(he)),rt.value.length>0){const b=rt.value.map(pe).filter(M=>M!==null);s.setAudioTracks(b)}ke.value.length>0&&s.setCaptionTracks(ke.value.map(ye)),e.watch(()=>s.playheadPosition.value,Pe),tt();const ot=e.ref(!0),st=e.ref(null),Ze=e.ref(null);let Gt=null;e.watch(Ze,b=>{Gt!==null&&(clearTimeout(Gt),Gt=null),!(b===null||b==="")&&(Gt=setTimeout(()=>{Ze.value=null},4e3))});const Nt=e.ref(null),En=e.computed(()=>s.tracks.value),rn=e.computed(()=>s.mediaSources.value),gs=e.computed(()=>{var b,M;return((b=s.selectedClip.value)==null?void 0:b.sourceRefId)??((M=rn.value[0])==null?void 0:M.id)}),sn=e.computed(()=>En.value.filter(b=>b.locked!==!0&&b.type==="video")),Qn=e.computed(()=>Nt.value?En.value.find(b=>b.id===Nt.value)??null:null),xn=e.computed(()=>!!s.selectedClip.value&&s.playheadPosition.value>0),Na=e.computed(()=>!!s.selectedClip.value),$i=e.computed(()=>s.timelineClips.value.length>0&&s.hasChanges.value),bs=e.computed(()=>s.selectedClip.value??s.timelineClips.value[0]??null),Di=b=>{const M=Number.isFinite(b)&&b>0?Math.round(b):0,q=Math.floor(M/60),me=M%60;return`${q}:${me.toString().padStart(2,"0")}`},ys=e.computed(()=>{const b=s.timelineClips.value.length,M=En.value.length,q=b===1?"1 clip":`${b} clips`,me=M===1?"1 track":`${M} tracks`;return`${q} / ${me} / ${Di(I.value)}`});e.watch(()=>En.value.map(b=>`${b.id}:${b.locked===!0?"locked":"open"}`).join("|"),()=>{var b;Nt.value&&sn.value.some(M=>M.id===Nt.value)||(Nt.value=((b=sn.value[0])==null?void 0:b.id)??null)},{immediate:!0}),e.watch(()=>{var b;return(b=s.selectedClip.value)==null?void 0:b.trackId},b=>{b&&sn.value.some(M=>M.id===b)&&(Nt.value=b)},{immediate:!0});const Mo=b=>{const M=rn.value.find(q=>q.id===b);return M?M.filename??M.mediaUuid??M.url??M.id:"Asset"},Ri=n.assetUploader?JT({uploader:n.assetUploader,onReady:b=>{if(!b.mediaUrl&&!b.mediaUuid)return;const M={id:`imported-${b.assetId}`,type:b.mediaUuid?"media":"url",filename:b.filename,mimeType:b.mime,duration:b.durationSeconds??0,width:b.width??0,height:b.height??0};b.mediaUuid!==void 0&&(M.mediaUuid=b.mediaUuid),b.mediaUrl!==void 0&&(M.url=b.mediaUrl),s.registerMediaSource(M),Ze.value=`${b.filename} ready.`},onFailure:b=>{Ze.value=b.failureMessage??`Upload of ${b.filename} failed.`}}):null,ws=async b=>{if(!Ri){Ze.value="Asset import is not configured for this editor host.";return}for(const M of b){const q=await Ri.importFile(M);q.ok||(Ze.value=q.message)}},Fo=b=>{var Me;const M=s.appendMediaSourceToTimeline(b,Nt.value);if(!M.ok){st.value=M.message;return}const q=M.value;q.trackId&&(Nt.value=q.trackId),s.handleClipSelect(q.id);const me=((Me=Qn.value)==null?void 0:Me.name)??"timeline";st.value=`${Mo(b)} added to ${me}.`,Pe()},ks=b=>{if(!s.replaceSelectedClipSource(b)){st.value="Select a clip before replacing its source.";return}st.value=`${Mo(b)} replaced the selected clip.`,Pe()},_s=b=>{const M=Mo(b);if(!s.removeMediaSource(b)){st.value="Remove timeline clips before deleting this asset.";return}st.value=`${M} removed.`,Pe()},Sn=(b="video")=>{const M=s.addTimelineTrack(b);Nt.value=M.id,st.value=`${M.name} added. New assets will be placed on that track.`,Pe()},oa=b=>{const M=b.target;M&&(Nt.value=M.value||null)},ln=b=>{var q;s.handleClipSelect(b);const M=(q=s.selectedClip.value)==null?void 0:q.trackId;M&&sn.value.some(me=>me.id===M)&&(Nt.value=M)},$o=(b,M,q)=>{const me=s.moveClip(b,M,q);if(!me.ok){Ze.value=me.message;return}Pe()},Do=b=>{const M=s.deleteClip(b);if(!M.ok){Ze.value=M.message;return}Ze.value="Clip deleted.",Pe()},dn=(b,M)=>{M(b)&&Pe()},eo=(b,M)=>{const q=s.renameTimelineTrack(b,M);if(!q.ok){Ze.value=q.message;return}Ze.value=`Track renamed to "${M}".`,Pe()},Ja=b=>{const M=s.deleteTimelineTrack(b);if(!M.ok){Ze.value=M.message;return}Nt.value===b&&(Nt.value=null),Ze.value="Track deleted.",Pe()},Jt=(b,M)=>{const q=s.reorderTimelineTrack(b,M);if(!q.ok){Ze.value=q.message;return}Ze.value=`Track moved ${M}.`,Pe()},ka=b=>{ot.value=b},Ka=()=>{ot.value=!ot.value},Ai=b=>{const M=b.target;if(!M)return;const q=Number(M.value);Number.isFinite(q)&&s.setZoomLevel(q)},Ht=e.ref(!1),cn=e.ref(0),Da=e.ref(!1),St=e.ref(null),qa=e.ref(null),to=e.ref("preparing");let Cn=null,Ra=!1;const Ro={preparing:"Preparing export...",rendering:"Rendering frames...","encoding-video":"Encoding video...","encoding-audio":"Encoding audio...",muxing:"Muxing output...",storing:"Storing export...",complete:"Export complete"},ao=b=>typeof b=="string"&&b in Ro,Aa=(b,M)=>{to.value=b,St.value=typeof M=="string"&&M.trim()!==""?M.trim():Ro[b]},pa=(b,M,q)=>{const me=Number.isFinite(b)?Math.max(0,Math.min(100,b)):0;cn.value=me,M&&Aa(M,q)},Ao=b=>{if(ao(b.phase))return b.phase;switch(b.status){case"pending":return"preparing";case"processing":return"rendering";case"completed":return"complete";default:return to.value}},Li=b=>typeof b.progress_message=="string"&&b.progress_message.trim()!==""?b.progress_message.trim():void 0,Vn=(b,M,q={allowClient:!0})=>{if(!Number.isFinite(M)||M<=0||b.timeline.length===0)return{route:"unsupported",exportDuration:M,message:"Export unavailable: the recipe has no renderable duration."};if(n.maxDuration>0&&M>n.maxDuration)return{route:"unsupported",exportDuration:M,message:`Export unavailable: duration exceeds the ${n.maxDuration}s limit.`};if(q.allowClient&&n.clientExportThreshold>0&&M<=n.clientExportThreshold)return{route:"client",exportDuration:M};const Me=!!n.serverRenderEndpoint,Fe=r.value.startsWith("temp-");return Me&&!Fe?{route:"server-render",exportDuration:M}:{route:"recipe-download",exportDuration:M,message:Fe?"Local media — downloaded recipe.json. Client-side PIXI export is unavailable on this device.":"No server render endpoint configured — downloaded recipe.json."}},no=()=>new ps(n.serverRenderEndpoint??"/api/v1"),La=()=>{Cn!==null&&(clearInterval(Cn),Cn=null)},Pi=b=>{La();const M=no();Cn=setInterval(async()=>{if(Ra){La();return}try{const q=await M.getJob(b),me=Number(q.progress??0);if(pa(me,Ao(q),Li(q)),i("server-render-progress",cn.value),q.status==="completed"||q.status==="failed"||q.status==="cancelled")if(La(),Ht.value=!1,qa.value=null,q.status==="completed"){pa(100,"complete"),Da.value=!0,St.value=null;const Me=typeof q.output_media_id=="string"?q.output_media_id:void 0,Fe={id:b};Me!==void 0&&(Fe.output_media_id=Me),i("server-render-completed",Fe)}else{const Me=q.status==="cancelled"||typeof q.error_message=="string"&&/cancel/i.test(q.error_message),Fe=Me?"Export canceled.":typeof q.error_message=="string"&&q.error_message.trim()!==""?q.error_message:"Export failed";St.value=Fe,Me||i("server-render-failed",Fe)}}catch(q){La(),Ht.value=!1,qa.value=null;const me=q instanceof Error?q.message:"Failed to check export progress";St.value=me,i("server-render-failed",me)}},2e3)},oo=b=>{const M=new Blob([JSON.stringify(b,null,2)],{type:"application/json"}),q=URL.createObjectURL(M),me=document.createElement("a");me.href=q,me.download=`video-recipe-${Date.now()}.json`,me.click(),setTimeout(()=>URL.revokeObjectURL(q),100)},io=()=>{La(),Ra=!1,R.resetClientExport(),qa.value=null,St.value=null,Da.value=!1,cn.value=0,to.value="preparing"},un=async b=>{pa(0,"preparing");const q=await no().createRenderJob({source_media_uuid:r.value,recipe:b}),me=typeof q.id=="string"?q.id:null;if(!me)throw new Error("Export failed: missing job id");qa.value=me,i("export-started",me),i("server-render-started",me),pa(1,"rendering"),Pi(me)},Lo=async(b,M)=>{if(!await R.canExportClientSide())return null;const q=await R.renderRecipeWithPixi(b,M,me=>{Ra||pa(me,"rendering")});return Ra?(St.value="Export canceled.",pa(0),i("video-exported",null),null):(s.clearHasChanges(),i("recipe-generated",b),i("video-exported",q),pa(100,"complete"),Da.value=!0,q)},Nn=async b=>{io(),Ht.value=!0,Aa("preparing");try{const M=yt(Ot(wt(s.generateRecipe(),b)));se(M,"before-export",!1),i("recipe-generated",M);const q=Nc(M,I.value),me=Vn(M,q);if(me.route==="unsupported"){Ht.value=!1,St.value=me.message??"Export unavailable.",i("server-render-failed",St.value);return}if(me.route==="client"){const Fe=await Lo(M,b);if(Fe!==null){const Ye=URL.createObjectURL(Fe.file),pt=document.createElement("a");pt.href=Ye,pt.download=`edited-video-${Date.now()}.mp4`,pt.click(),setTimeout(()=>URL.revokeObjectURL(Ye),100),Ht.value=!1;return}}const Me=me.route==="client"?Vn(M,q,{allowClient:!1}):me;if(Me.route==="unsupported"){Ht.value=!1,St.value=Me.message??"Export unavailable.",i("server-render-failed",St.value);return}if(Me.route==="recipe-download"){oo(M),Ht.value=!1,pa(100,"complete"),Da.value=!0,St.value=Me.message??"Downloaded recipe.json.";return}await un(M)}catch(M){const q=yt(s.generateRecipe());oo(q);const me=M instanceof Error?M.message:"Export failed";Ht.value=!1,pa(0),qa.value=null,St.value=me,i("server-render-failed",me)}},ro=async()=>{Ra=!0,w.value=!1,R.cancelClientExport();const b=qa.value;if(La(),Ht.value=!1,pa(0),St.value="Export canceled.",qa.value=null,b&&n.serverRenderEndpoint)try{await no().cancelJob(b)}catch{}},Tn=()=>{s.togglePlayback()},so=()=>{s.resetChanges()},mn=()=>{const b=$a();i("draft-saved",b)},Ui=()=>{Nn()},Po=()=>{i("close")};a({saveDraft:async()=>{const b=$a();return i("draft-saved",b),b},exportForUpload:async b=>{io();const M=yt(b??s.generateRecipe()),q=Ot(M),me=Array.isArray(q.filters)&&q.filters.length>0,Me=mt(q);if(!(s.hasChanges.value||me||Me))return s.clearHasChanges(),i("video-exported",null),null;const Ye=Nc(q,I.value),pt=Vn(q,Ye);if(pt.route==="unsupported"){const $t=pt.message??"Export unavailable.";throw St.value=$t,new Error(`Video export failed: ${$t}`)}if(pt.route==="server-render")return Ht.value=!0,await un(q),null;Ht.value=!0;try{if(pt.route==="client"){const aa=await Lo(q);if(aa!==null)return aa}const $t=pt.route==="client"?Vn(q,Ye,{allowClient:!1}):pt;if($t.route==="server-render")return await un(q),null;if($t.route==="unsupported"){const aa=$t.message??"Export unavailable.";throw St.value=aa,new Error(`Video export failed: ${aa}`)}return St.value=$t.message??"Export unavailable for upload.",i("video-exported",null),null}catch($t){if(Ra)return St.value="Export canceled.",pa(0),i("video-exported",null),null;const aa=$t instanceof Error?$t.message:"Local WebGL export failed.";throw St.value=aa,new Error(`Video export failed: ${aa}`)}finally{Ht.value=!1}}});const lo=e.ref(!1),Uo=b=>{var Fe,Ye;const M=[...s.timelineClips.value].sort((pt,$t)=>pt.timelineStart-$t.timelineStart);if(M.length===0)return;const q=s.selectedClip.value;if(!q){s.handleClipSelect(((Fe=M[0])==null?void 0:Fe.id)??null);return}const me=M.findIndex(pt=>pt.id===q.id);if(me===-1){s.handleClipSelect(((Ye=M[0])==null?void 0:Ye.id)??null);return}const Me=b==="next"?M[Math.min(me+1,M.length-1)]:M[Math.max(me-1,0)];Me&&s.handleClipSelect(Me.id)},Oo=()=>{s.seekTo(Math.min(s.totalDuration.value,s.playheadPosition.value+1))},Oi=()=>{s.seekTo(Math.max(0,s.playheadPosition.value-1))};return AT({playPause:Tn,frameForward:s.frameForward,frameBackward:s.frameBackward,secondForward:Oo,secondBackward:Oi,skipToStart:s.skipToStart,skipToEnd:s.skipToEnd,prevClip:()=>Uo("prev"),nextClip:()=>Uo("next"),splitAtPlayhead:s.splitAtPlayhead,deleteSelected:()=>{const b=s.deleteSelectedClip();b.ok?Ze.value="Clip deleted.":Ze.value=b.message},rippleDeleteSelected:()=>{s.rippleDeleteSelectedClip()?Ze.value="Clip removed and gap closed.":Ze.value="Nothing to ripple-delete."},undo:s.undo,redo:s.redo,save:mn,exportNow:()=>{if(s.timelineClips.value.length===0){Ze.value="Add media to export.";return}Ui()},showShortcutsOverlay:()=>{lo.value=!0}}),e.onMounted(()=>{document.documentElement.setAttribute("data-video-editor-version","v2"),G()}),e.onBeforeUnmount(()=>{document.documentElement.getAttribute("data-video-editor-version")==="v2"&&document.documentElement.removeAttribute("data-video-editor-version")}),e.onUnmounted(()=>{La(),Ra=!0,R.cancelClientExport(),He&&(clearTimeout(He),He=null),F.value&&(F.value.destroy(),F.value=null),O.value=null,X.value=null}),(b,M)=>(e.openBlock(),e.createElementBlock(e.Fragment,null,[e.createVNode(oV,{"data-testid":"video-editor-v2"},{toolbar:e.withCtx(()=>[e.createElementVNode("div",qT,[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:Tn},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(s).isPlaying.value?e.unref(Zl):e.unref(Xl),"aria-hidden":"true"},null,8,["icon"])],10,YT),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:so},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Jn),"aria-hidden":"true"},null,8,["icon"])],8,QT)]),M[20]||(M[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",e4,[e.createElementVNode("label",t4,[M[18]||(M[18]=e.createElementVNode("span",{class:"sr-only"},"Fit mode",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":M[0]||(M[0]=q=>A.value=q),"aria-label":"Fit mode","data-testid":"v2-select-fit-mode"},[...M[17]||(M[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,A.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:mn},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(jr),"aria-hidden":"true"},null,8,["icon"]),M[19]||(M[19]=e.createElementVNode("span",{class:"v2-toolbar-btn-label"},"Save",-1))],8,a4),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:Ht.value||e.unref(s).timelineClips.value.length===0,onClick:Ui},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(ko),"aria-hidden":"true"},null,8,["icon"])],8,n4),e.createElementVNode("button",{type:"button",class:"v2-toolbar-btn","data-testid":"v2-btn-close","aria-label":"Close editor",onClick:Po},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(jn),"aria-hidden":"true"},null,8,["icon"])])])]),assets:e.withCtx(()=>[e.createElementVNode("div",o4,[e.createVNode(gV,{sources:rn.value,"selected-source-id":gs.value,"uploads-enabled":!!b.assetUploader,onAdd:Fo,onReplaceSelected:ks,onRemove:_s,onImportFiles:ws},null,8,["sources","selected-source-id","uploads-enabled"]),st.value?(e.openBlock(),e.createElementBlock("p",i4,e.toDisplayString(st.value),1)):e.createCommentVNode("",!0)])]),canvas:e.withCtx(()=>[e.createElementVNode("div",r4,[e.withDirectives(e.createVNode(nl,{ref_key:"pixiPreviewRef",ref:g,class:"v2-preview-child","aria-hidden":!T.value,source:C.value,"fallback-duration":I.value,filters:$.value,playhead:y.value,"is-playing":e.unref(s).isPlaying.value,"fit-mode":A.value,active:T.value,onPlayPause:Tn,onFrameUpdate:Z,onDurationChange:P},null,8,["aria-hidden","source","fallback-duration","filters","playhead","is-playing","fit-mode","active"]),[[e.vShow,T.value]]),e.withDirectives(e.createVNode(yl,{class:"v2-preview-child","aria-hidden":!_.value,"media-uuid":r.value,recipe:B.value,media:L.value,"enable-engine":_.value&&U.value,"fit-mode":A.value,onTimeUpdate:K,onPlayStateChange:ve,onDurationChange:P,onEngineReady:ca},null,8,["aria-hidden","media-uuid","recipe","media","enable-engine","fit-mode"]),[[e.vShow,_.value]])])]),timeline:e.withCtx(({isMobile:q})=>{var me,Me;return[e.createElementVNode("div",{class:e.normalizeClass(["v2-timeline",{"is-mobile":!!q}])},[e.createElementVNode("div",s4,[e.createElementVNode("div",l4,[M[21]||(M[21]=e.createElementVNode("span",{class:"v2-timeline-title","data-testid":"v2-timeline-title"},"Timeline",-1)),e.createElementVNode("span",d4,e.toDisplayString(ys.value),1)]),e.createElementVNode("label",c4,[M[22]||(M[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:Ai},null,40,u4),e.createElementVNode("span",m4,e.toDisplayString(Math.round(e.unref(s).zoomLevel.value))+" px/s",1)]),q?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",p4,[e.createElementVNode("button",{type:"button",class:"v2-toolbar-btn v2-toolbar-btn--ghost","data-testid":"v2-btn-add-track",onClick:M[1]||(M[1]=Fe=>Sn("video"))},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(cr)},null,8,["icon"]),M[23]||(M[23]=e.createTextVNode(" Add Track ",-1))]),sn.value.length>0?(e.openBlock(),e.createElementBlock("label",f4,[M[24]||(M[24]=e.createElementVNode("span",null,"Place clips in",-1)),e.createElementVNode("select",{value:Nt.value??"","data-testid":"v2-select-target-track","aria-label":"Target track for added assets",onChange:oa},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(sn.value,Fe=>(e.openBlock(),e.createElementBlock("option",{key:Fe.id,value:Fe.id},e.toDisplayString(Fe.name),9,v4))),128))],40,h4)])):e.createCommentVNode("",!0)])),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["v2-toolbar-btn v2-toolbar-btn--ghost",{"is-active":ot.value}]),"data-testid":"v2-btn-snap-toggle","aria-pressed":ot.value?"true":"false",onClick:Ka},e.toDisplayString(ot.value?"Snap On":"Snap Off"),11,g4)]),Ze.value?(e.openBlock(),e.createElementBlock("p",b4,e.toDisplayString(Ze.value),1)):e.createCommentVNode("",!0),e.unref(s).timelineClips.value.length===0?(e.openBlock(),e.createElementBlock("div",y4,[...M[25]||(M[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(wl,{key:2,playhead:e.unref(s).playheadPosition.value,clips:e.unref(s).timelineClips.value,tracks:En.value,"selected-clip-id":((me=e.unref(s).selectedClip.value)==null?void 0:me.id)??((Me=e.unref(s).timelineClips.value[0])==null?void 0:Me.id)??null,duration:I.value,fps:e.unref(s).fps.value,"is-mobile":!!q,"zoom-level":e.unref(s).zoomLevel.value,"snap-enabled":ot.value,sensitivity:.25,"onUpdate:playhead":M[2]||(M[2]=Fe=>e.unref(s).seekTo(Fe)),onTrim:M[3]||(M[3]=(Fe,Ye,pt)=>e.unref(s).handleTrim(Fe,Ye,pt)),onSplit:M[4]||(M[4]=Fe=>e.unref(s).handleSplit(Fe)),onClipSelect:ln,onClipDelete:Do,onClipMove:$o,onSnapStateChange:ka,onToggleLock:M[5]||(M[5]=Fe=>dn(Fe,e.unref(s).toggleTrackLock)),onToggleHidden:M[6]||(M[6]=Fe=>dn(Fe,e.unref(s).toggleTrackHidden)),onToggleMuted:M[7]||(M[7]=Fe=>dn(Fe,e.unref(s).toggleTrackMuted)),onToggleSolo:M[8]||(M[8]=Fe=>dn(Fe,e.unref(s).toggleTrackSolo)),onRenameTrack:eo,onDeleteTrack:Ja,onReorderTrack:Jt},null,8,["playhead","clips","tracks","selected-clip-id","duration","fps","is-mobile","zoom-level","snap-enabled"])),e.createVNode(kl,{"selected-clip":e.unref(s).selectedClip.value,"can-split":xn.value,"can-delete":Na.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":!!q,"show-add-track":!!q,onSplit:e.unref(s).splitAtPlayhead,onDelete:e.unref(s).deleteSelectedClip,onAddTrack:M[9]||(M[9]=Fe=>Sn("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:Tn,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(nu,{key:0,class:"v2-draft-recovery",records:ze.value,surface:"desktop","project-id":Ge.value,"saved-at":Ke.value,onRestore:_e,onDismiss:Le},null,8,["records","project-id","saved-at"])):e.createCommentVNode("",!0),e.createVNode(YN,{"active-tab":d.value,"onUpdate:activeTab":M[10]||(M[10]=q=>d.value=q),tabs:m.value},{filters:e.withCtx(()=>[e.createVNode(_l,{filters:Ve.value,"active-filters":ne.value,"thumbnail-url":ae.value,onApplyFilter:ya,onRemoveFilter:Sa,onUpdateParam:wa,onPreviewFilter:nn},null,8,["filters","active-filters","thumbnail-url"])]),adjustments:e.withCtx(()=>[e.unref(l).selectedFilter.value?(e.openBlock(),e.createBlock(El,{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",w4,[...M[26]||(M[26]=[e.createElementVNode("p",null,"Select a filter from the Filters tab to adjust its parameters.",-1)])])),e.createVNode(ou,{class:"v2-keyframe-panel",duration:ut.value,target:"all","device-class":"desktop",onApplyPreset:ua},null,8,["duration"])]),text:e.withCtx(()=>[e.createVNode(Sl,{overlays:Ne.value,onAddOverlay:ue,onUpdateOverlay:re,onRemoveOverlay:ie},null,8,["overlays"]),e.createVNode(au,{class:"v2-caption-panel","caption-track":Et.value,layout:"desktop",onImport:Fa,"onUpdate:captionTrack":Ca,onClear:Va},null,8,["caption-track"])]),transitions:e.withCtx(()=>[e.createVNode(Cl,{"selected-clips":Wt.value,"applied-transitions":bt.value,onApplyTransition:Se,onRemoveTransition:Ae,onPreviewTransition:qe},null,8,["selected-clips","applied-transitions"])]),audio:e.withCtx(()=>[e.createVNode(Vl,{"audio-layers":rt.value,"master-volume":_t.value,onAddTrack:ft,onUpdateTrack:Vt,onRemoveTrack:ht,onUpdateVolume:vt,onToggleMute:Ut,onUpdateMasterVolume:Mt},null,8,["audio-layers","master-volume"]),e.createVNode(tu,{class:"v2-audio-mixer",state:Xt.value,"device-class":"desktop",onUpdate:on},null,8,["state"])]),export:e.withCtx(()=>[e.createVNode(xl,{"can-export":$i.value,"is-exporting":Ht.value,"export-progress":cn.value,onExport:Nn,onCancelExport:ro,onSaveDraft:mn,onReset:so},null,8,["can-export","is-exporting","export-progress"]),Da.value?(e.openBlock(),e.createElementBlock("div",k4," Export complete ")):e.createCommentVNode("",!0),St.value&&!Da.value?(e.openBlock(),e.createElementBlock("div",_4,e.toDisplayString(St.value),1)):e.createCommentVNode("",!0)]),_:1},8,["active-tab","tabs"])]),drawer:e.withCtx(()=>[e.createVNode($T,{ref_key:"mobileDrawerRef",ref:u,"initial-snap":"half","aria-label":"Video editor controls"},{default:e.withCtx(()=>[ze.value.length>0?(e.openBlock(),e.createBlock(nu,{key:0,class:"v2-draft-recovery",records:ze.value,surface:"mobile","project-id":Ge.value,"saved-at":Ke.value,onRestore:_e,onDismiss:Le},null,8,["records","project-id","saved-at"])):e.createCommentVNode("",!0),e.createVNode(ET,{"selected-clip":bs.value,onOpenActions:M[11]||(M[11]=q=>c.value="trim")},null,8,["selected-clip"]),e.createVNode(NT,{modelValue:c.value,"onUpdate:modelValue":M[12]||(M[12]=q=>c.value=q)},null,8,["modelValue"]),c.value==="look"?(e.openBlock(),e.createElementBlock("section",E4,[e.createElementVNode("div",x4,[e.createVNode(_l,{filters:Ve.value,"active-filters":ne.value,"thumbnail-url":ae.value,onApplyFilter:ya,onRemoveFilter:Sa,onUpdateParam:wa,onPreviewFilter:nn},null,8,["filters","active-filters","thumbnail-url"])]),e.createElementVNode("div",S4,[e.unref(l).selectedFilter.value?(e.openBlock(),e.createBlock(El,{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",C4,[...M[27]||(M[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",V4,[e.createVNode(kl,{"selected-clip":e.unref(s).selectedClip.value,"can-split":xn.value,"can-delete":Na.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:M[13]||(M[13]=q=>Sn("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:Tn,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",N4,[e.createVNode(Sl,{overlays:Ne.value,onAddOverlay:ue,onUpdateOverlay:re,onRemoveOverlay:ie},null,8,["overlays"]),e.createVNode(au,{"caption-track":Et.value,layout:"mobile",onImport:Fa,"onUpdate:captionTrack":Ca,onClear:Va},null,8,["caption-track"])])):c.value==="audio"?(e.openBlock(),e.createElementBlock("section",T4,[e.createVNode(Vl,{"audio-layers":rt.value,"master-volume":_t.value,onAddTrack:ft,onUpdateTrack:Vt,onRemoveTrack:ht,onUpdateVolume:vt,onToggleMute:Ut,onUpdateMasterVolume:Mt},null,8,["audio-layers","master-volume"]),e.createVNode(tu,{state:Xt.value,"device-class":"mobile",onUpdate:on},null,8,["state"])])):c.value==="export"?(e.openBlock(),e.createElementBlock("section",I4,[e.createVNode(xl,{"can-export":$i.value,"is-exporting":Ht.value,"export-progress":cn.value,"is-mobile":"",onExport:Nn,onCancelExport:ro,onSaveDraft:mn,onReset:so},null,8,["can-export","is-exporting","export-progress"]),Da.value?(e.openBlock(),e.createElementBlock("div",B4,"Export complete")):e.createCommentVNode("",!0),St.value&&!Da.value?(e.openBlock(),e.createElementBlock("div",M4,e.toDisplayString(St.value),1)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("section",F4,[e.createElementVNode("div",$4,[e.createElementVNode("label",D4,[M[29]||(M[29]=e.createElementVNode("span",null,"Fit",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":M[14]||(M[14]=q=>A.value=q),"aria-label":"Mobile fit mode"},[...M[28]||(M[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,A.value]])]),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["v2-mobile-secondary-button",{"is-active":ot.value}]),"aria-pressed":ot.value?"true":"false","data-testid":"v2-mobile-btn-snap-toggle",onClick:Ka},e.toDisplayString(ot.value?"Snap On":"Snap Off"),11,R4),e.createElementVNode("button",{type:"button",class:"v2-mobile-secondary-button","data-testid":"v2-mobile-btn-reset",disabled:!e.unref(s).hasChanges.value,onClick:so}," Reset ",8,A4),e.createElementVNode("button",{type:"button",class:"v2-mobile-secondary-button","data-testid":"v2-mobile-btn-save",disabled:!e.unref(s).hasChanges.value,onClick:mn}," Save ",8,L4)]),v.value?(e.openBlock(),e.createElementBlock("details",P4,[M[30]||(M[30]=e.createElementVNode("summary",null,"Transitions",-1)),e.createVNode(Cl,{"selected-clips":Wt.value,"applied-transitions":bt.value,onApplyTransition:Se,onRemoveTransition:Ae,onPreviewTransition:qe},null,8,["selected-clips","applied-transitions"])])):e.createCommentVNode("",!0),e.createElementVNode("details",U4,[M[31]||(M[31]=e.createElementVNode("summary",null,"Keyframe presets",-1)),e.createVNode(ou,{duration:ut.value,target:"all","device-class":"mobile",onApplyPreset:ua},null,8,["duration"])])]))]),_:1},512)]),_:1}),lo.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:M[16]||(M[16]=e.withModifiers(q=>lo.value=!1,["self"]))},[e.createElementVNode("div",O4,[e.createElementVNode("div",z4,[M[32]||(M[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:M[15]||(M[15]=q=>lo.value=!1)},"×")]),M[33]||(M[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))}}),W4=Be(j4,[["__scopeId","data-v-aa4426a6"]]),Ba=o=>o===null||typeof o!="object"||Array.isArray(o)?null:o,lt=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},H4=(o,a)=>{if(a===null)return;const t=Ba(o.source)??{},n=lt(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=Ba(r[0]);if(d!==null){const c=lt(d.sourceIn)??0,u=lt(d.sourceOut)??lt(d.end)??lt(d.timelineEnd);if(c===0&&u!==null&&u>0&&u<=1){d.sourceOut=a;const m=lt(d.end);m!==null&&m>0&&m<=1&&(d.end=a);const p=lt(d.timelineEnd);p!==null&&p>0&&p<=1&&(d.timelineEnd=a)}}}const s=lt(o.trimEnd)??lt(o.trim_end);s!==null&&s>0&&s<=1&&(o.trimEnd=a);const l=Ba(o.trim);if(l!==null){const d=lt(l.end);d!==null&&d>0&&d<=1&&(l.end=a,o.trim=l)}},Z4=(o,a)=>{if(!o)return!1;const t=Ba(o);if(t===null)return!1;const n=Ba(t.trim),i=Ba(t.source),s=lt(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=lt(t.trimStart)??lt(t.trim_start)??lt(n==null?void 0:n.start),f=lt(t.trimEnd)??lt(t.trim_end)??lt(n==null?void 0:n.end);if(u!==null&&u>0&&(c=!0),f!==null&&s!==void 0&&f<s&&(c=!0),!c&&Array.isArray(o.timeline)&&o.timeline.length===1){const p=o.timeline[0];if(p){const h=lt(p.sourceIn),v=lt(p.sourceOut);h!==null&&h>0&&(c=!0),v!==null&&s!==void 0&&v<s&&(c=!0)}}let m=!1;if(Array.isArray(o.timeline)&&o.timeline.length===1){const p=o.timeline[0];if(p){const h=lt(p.speed);m=h!==null&&h!==1}}return l||d||c||m},$p=o=>{if(!o)return!1;const a=Ba(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 m,p;const t=JSON.parse(JSON.stringify(o)),n=Array.isArray(t.timeline)?t.timeline:[],i=n.length>0?Ba(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=lt(i.sourceIn),v=lt(i.sourceOut);h!==null&&t.trimStart===void 0&&(t.trimStart=h),v!==null&&t.trimEnd===void 0&&(t.trimEnd=v)}const l=Ba(t.trim);if(t.trimStart===void 0){const h=lt(l==null?void 0:l.start);h!==null&&(t.trimStart=h)}if(t.trimEnd===void 0){const h=lt(l==null?void 0:l.end);h!==null&&(t.trimEnd=h)}const d=Ba(t.source),c=lt(t.width)??lt(d==null?void 0:d.original_width)??lt((m=a.exportMeta)==null?void 0:m.width);c!==null&&(t.width=c);const u=lt(t.height)??lt(d==null?void 0:d.original_height)??lt((p=a.exportMeta)==null?void 0:p.height);u!==null&&(t.height=u);const f=Ba(t.output);return t.fps=lt(t.fps)??lt(f==null?void 0:f.fps)??30,H4(t,a.mediaDuration??null),t},G4={key:0},J4=["data-testid"],K4={class:"ve-mobile-header"},q4=["data-testid"],Y4={class:"ve-mobile-title"},Q4=["data-testid","disabled"],e3={key:1,class:"ve-mobile-spacer","aria-hidden":"true"},t3={class:"ve-body"},a3=["data-testid"],n3=["aria-label"],o3={class:"ve-header"},i3={class:"ve-title"},r3=["data-testid"],s3={class:"ve-body"},l3={class:"ve-footer"},d3=["data-testid"],c3=["data-testid","disabled"],u3=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(()=>f.value?n.savingText:n.confirmText),u=e.ref(typeof window<"u"?window.innerWidth<768:!1),f=e.ref(!1),m=e.ref(!1),p=e.ref(null),h=`temp-${Date.now()}`,v=e.computed(()=>{var I;const z=(I=n.featureFlags)==null?void 0:I.export;return typeof z=="boolean"?z:n.workflowMode==="full"}),w=e.computed(()=>{if(n.editorVersion==="v1"||n.editorVersion==="v2")return n.editorVersion;if(typeof window>"u")return"v2";try{const z=new URLSearchParams(window.location.search),I=z.get("editor")??z.get("video-editor");if(I==="v1")return"v1";if(I==="v2")return"v2"}catch{}return"v2"}),x=e.computed(()=>w.value==="v2"?W4:Bp),T=e.computed(()=>typeof n.mediaUuid=="string"&&n.mediaUuid.trim()!==""?n.mediaUuid.trim():n.media&&n.media.uuid.trim()!==""?n.media.uuid.trim():h),_=e.computed(()=>{const z={showThumbnailPicker:n.showThumbnailPicker,workflowMode:n.workflowMode,clientExportThreshold:n.clientExportThreshold,maxDuration:n.maxDuration,serverRenderEndpoint:n.serverRenderEndpoint};return n.featureFlags!==void 0&&(z.featureFlags=n.featureFlags),n.initialRecipe!==void 0&&(z.initialRecipe=n.initialRecipe),n.media!==void 0&&(z.media=n.media),z}),g=()=>{u.value=window.innerWidth<768};e.onMounted(()=>{window.addEventListener("resize",g)}),e.onUnmounted(()=>{window.removeEventListener("resize",g)}),e.onErrorCaptured(()=>(m.value=!0,!1));const E=z=>{const I=Array.isArray(z.timeline)?z.timeline:[];if(I.length===0)return 0;let P=0;for(const Z of I){const K=Number(Z.sourceIn),ve=Number(Z.sourceOut),Ve=Number(Z.speed??1),ne=Number.isFinite(Ve)&&Ve>0?Ve:1;if(Number.isFinite(K)&&Number.isFinite(ve)&&ve>K){P+=(ve-K)/ne;continue}const ae=Number(Z.timelineStart),F=Number(Z.timelineEnd);Number.isFinite(ae)&&Number.isFinite(F)&&F>ae&&(P+=F-ae)}return P},S=(z,I,P)=>{let Z=null;const K=new Promise((ve,Ve)=>{Z=setTimeout(()=>Ve(new Error(`${P} timed out after ${I}ms`)),I)});return Promise.race([z,K]).finally(()=>{Z!==null&&clearTimeout(Z)})},N=()=>{var K;const P=(K=n.media)==null?void 0:K.duration;if(typeof P!="number"||!Number.isFinite(P)||P<=0)return 12e3;const Z=Math.round(P*1e3);return Math.min(45e3,Math.max(12e3,Z))},V=()=>{i("close"),i("update:open",!1)},A=()=>{f.value=!1,V()},j=z=>{i("recipe-generated",z)},C=z=>{i("export-started",z),i("save-started",z)},$=z=>{i("video-exported",z)},y=z=>{i("thumbnail-selected",z)},R=(z,I,P)=>{i("save-recipe",z);const Z={recipe:z,exportPayload:I};P!==void 0&&(Z.toastDescription=P),i("save-complete",Z),V()},L=z=>{f.value||(i("draft-saved",z),R(z,null))},U=async()=>{var z;if(!f.value){if(m.value||p.value===null){i("save-error",{code:"save-failed",message:"Unable to save video edits. Please try again."}),V();return}f.value=!0;try{const I=await S(p.value.saveDraft(),N(),"saveDraft");let P=null,Z=!1,K;const ve=E(I),Ve=ve>0?ve:((z=n.media)==null?void 0:z.duration)??0;if(v.value&&Ve>0&&Ve<=n.clientExportThreshold&&typeof p.value.exportForUpload=="function"){Z=!0;const ae=Math.min(9e4,Math.max(15e3,n.clientExportThreshold*2e3));try{P=await S(p.value.exportForUpload(I),ae,"exportForUpload")}catch{P=null}}if($p(I)&&P===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&&P===null&&(K="Video edits saved. Final render will happen when you share."),R(I,P,K)}catch{i("save-error",{code:"save-failed",message:"Unable to save video edits. Please try again."}),V()}finally{f.value=!1}}};return a({saveDraft:U}),(z,I)=>(e.openBlock(),e.createBlock(e.Teleport,{to:"body"},[s.value?(e.openBlock(),e.createElementBlock("div",G4,[u.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"ve-fullscreen","data-testid":r.value},[e.createElementVNode("header",K4,[e.createElementVNode("button",{class:"ve-mobile-action",type:"button","data-testid":`${r.value}-close-button`,onClick:A},e.toDisplayString(d.value),9,q4),e.createElementVNode("h2",Y4,e.toDisplayString(z.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:f.value,onClick:U},e.toDisplayString(c.value),9,Q4)):(e.openBlock(),e.createElementBlock("span",e3))]),e.createElementVNode("section",t3,[(e.openBlock(),e.createBlock(e.resolveDynamicComponent(x.value),e.mergeProps({ref_key:"videoEditorRef",ref:p,"media-uuid":T.value,"data-editor-version":w.value},_.value,{onClose:A,onDraftSaved:L,onExportStarted:C,onRecipeGenerated:j,onThumbnailSelected:y,onVideoExported:$}),null,16,["media-uuid","data-editor-version"]))])],8,J4)):(e.openBlock(),e.createElementBlock("div",{key:1,class:"ve-overlay","data-testid":r.value,onClick:e.withModifiers(A,["self"])},[e.createElementVNode("div",{class:"ve-dialog",role:"dialog","aria-label":z.title,"aria-modal":"true"},[e.createElementVNode("header",o3,[e.createElementVNode("h2",i3,e.toDisplayString(z.title),1),e.createElementVNode("button",{class:"ve-close",type:"button","data-testid":`${r.value}-close-button`,"aria-label":"Close",onClick:A}," ✕ ",8,r3)]),e.createElementVNode("section",s3,[(e.openBlock(),e.createBlock(e.resolveDynamicComponent(x.value),e.mergeProps({ref_key:"videoEditorRef",ref:p,"media-uuid":T.value,"data-editor-version":w.value},_.value,{onClose:A,onDraftSaved:L,onExportStarted:C,onRecipeGenerated:j,onThumbnailSelected:y,onVideoExported:$}),null,16,["media-uuid","data-editor-version"]))]),e.createElementVNode("footer",l3,[e.renderSlot(z.$slots,"footer",{close:A,isSaving:f.value,save:U},()=>[e.createElementVNode("button",{class:"ve-btn",type:"button","data-testid":`${r.value}-cancel-button`,onClick:A},e.toDisplayString(d.value),9,d3),l.value?(e.openBlock(),e.createElementBlock("button",{key:0,class:"ve-btn ve-btn--primary",type:"button","data-testid":`${r.value}-confirm-button`,disabled:f.value,onClick:U},e.toDisplayString(c.value),9,c3)):e.createCommentVNode("",!0)],!0)])],8,n3)],8,a3))])):e.createCommentVNode("",!0)]))}}),m3=Be(u3,[["__scopeId","data-v-3cc6e078"]]),p3={class:"video-editor-modal"},f3={class:"video-preview-container"},h3=["src"],v3={class:"video-overlay-controls"},g3=["aria-label"],b3={class:"time-display"},y3={class:"timeline-container"},w3={class:"clip-name"},k3={class:"timeline-time-labels"},_3={class:"tool-tabs"},E3=["onClick"],x3={class:"tool-panel"},S3={key:0,class:"trim-panel"},C3={class:"trim-controls"},V3={key:1,class:"filters-panel"},N3={class:"filter-grid"},T3=["onClick"],I3={key:2,class:"text-panel"},B3={key:3,class:"transitions-panel"},M3={class:"transition-grid"},F3=["onClick"],$3={class:"action-buttons"},D3=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),f=e.ref(0),m=e.ref(null),p=e.ref("trim"),h=e.ref(null),v=e.ref(""),w=[{id:"trim",label:"Trim",icon:Er},{id:"filters",label:"Filters",icon:Vh},{id:"text",label:"Text",icon:Uu},{id:"transitions",label:"Transitions",icon:Dh}],x=[{id:"none",name:"None"},{id:"grayscale",name:"Grayscale"},{id:"sepia",name:"Sepia"},{id:"blur",name:"Blur"},{id:"brightness",name:"Brightness"},{id:"contrast",name:"Contrast"}],T=[{id:"fade",name:"Fade"},{id:"slide",name:"Slide"},{id:"zoom",name:"Zoom"},{id:"wipe",name:"Wipe"}],_=e.ref();e.onMounted(()=>{var I,P;(I=t.media)!=null&&I.url?r.value=t.media.url:(P=t.media)!=null&&P.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 g(){i.value&&(d.value=i.value.duration,f.value=d.value)}function E(){i.value&&(l.value=i.value.currentTime)}function S(){s.value=!1}function N(){i.value&&(s.value?(i.value.pause(),s.value=!1):(i.value.play(),s.value=!0))}function V(I){if(!I||isNaN(I))return"00:00";const P=Math.floor(I/60),Z=Math.floor(I%60);return`${P.toString().padStart(2,"0")}:${Z.toString().padStart(2,"0")}`}function A(I){if(!i.value||!_.value)return;const P=_.value.getBoundingClientRect(),ve=(I.clientX-P.left)/P.width*d.value;i.value.currentTime=Math.max(0,Math.min(ve,d.value))}function j(){u.value=l.value}function C(){f.value=l.value}function $(){u.value=0,f.value=d.value}function y(I){m.value=I;const P=K=>{if(!m.value||!_.value)return;const ve=_.value.getBoundingClientRect(),ae=(K.clientX-ve.left)/ve.width*d.value;m.value==="start"?u.value=Math.max(0,Math.min(ae,f.value-1)):f.value=Math.max(u.value+1,Math.min(ae,d.value))},Z=()=>{m.value=null,document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",Z)};document.addEventListener("mousemove",P),document.addEventListener("mouseup",Z)}function R(I){if(h.value=I,!i.value)return;const P={none:"none",grayscale:"grayscale(100%)",sepia:"sepia(100%)",blur:"blur(5px)",brightness:"brightness(150%)",contrast:"contrast(150%)"};i.value.style.filter=P[I]||"none"}function L(){}function U(I){}function z(){const I={timeline:[{id:c.value,url:r.value,startTime:0,endTime:d.value,sourceIn:u.value,sourceOut:f.value,track:0}],filters:h.value?[{type:h.value}]:[],textOverlays:v.value?[{content:v.value}]:[],duration:f.value-u.value};n("save",I)}return(I,P)=>(e.openBlock(),e.createElementBlock("div",p3,[e.createElementVNode("div",f3,[e.createElementVNode("video",{ref_key:"videoElement",ref:i,class:"video-preview",src:r.value,onLoadedmetadata:g,onTimeupdate:E,onEnded:S,controls:""},null,40,h3),e.createElementVNode("div",v3,[e.createElementVNode("button",{class:"play-pause-btn",onClick:N,"aria-label":s.value?"Pause":"Play"},[e.createVNode(e.unref(W.IonIcon),{icon:s.value?e.unref(Ph):e.unref(jh)},null,8,["icon"])],8,g3),e.createElementVNode("div",b3,e.toDisplayString(V(l.value))+" / "+e.toDisplayString(V(d.value)),1)])]),e.createElementVNode("div",y3,[e.createElementVNode("div",{class:"timeline-track",onClick:A,ref_key:"timelineTrack",ref:_},[e.createElementVNode("div",{class:"timeline-clip",style:e.normalizeStyle({left:`${u.value/d.value*100}%`,right:`${100-f.value/d.value*100}%`})},[e.createElementVNode("span",w3,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:P[0]||(P[0]=Z=>y("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:`${f.value/d.value*100}%`}),onMousedown:P[1]||(P[1]=Z=>y("end"))},null,36)):e.createCommentVNode("",!0)],512),e.createElementVNode("div",k3,[e.createElementVNode("span",null,e.toDisplayString(V(0)),1),e.createElementVNode("span",null,e.toDisplayString(V(d.value)),1)])]),e.createElementVNode("div",_3,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(w,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(W.IonIcon),{icon:Z.icon},null,8,["icon"]),e.createTextVNode(" "+e.toDisplayString(Z.label),1)],10,E3)),64))]),e.createElementVNode("div",x3,[p.value==="trim"?(e.openBlock(),e.createElementBlock("div",S3,[P[7]||(P[7]=e.createElementVNode("h3",null,"Trim Video",-1)),P[8]||(P[8]=e.createElementVNode("p",null,"Click and drag on the timeline to set trim points",-1)),e.createElementVNode("div",C3,[e.createElementVNode("button",{class:"btn-trim",onClick:j},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(qd)},null,8,["icon"]),P[4]||(P[4]=e.createTextVNode(" Set Start ",-1))]),e.createElementVNode("button",{class:"btn-trim",onClick:C},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(qd)},null,8,["icon"]),P[5]||(P[5]=e.createTextVNode(" Set End ",-1))]),e.createElementVNode("button",{class:"btn-trim",onClick:$},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(jn)},null,8,["icon"]),P[6]||(P[6]=e.createTextVNode(" Clear ",-1))])])])):p.value==="filters"?(e.openBlock(),e.createElementBlock("div",V3,[P[9]||(P[9]=e.createElementVNode("h3",null,"Filters",-1)),e.createElementVNode("div",N3,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(x,Z=>e.createElementVNode("button",{key:Z.id,class:e.normalizeClass(["filter-option",{active:h.value===Z.id}]),onClick:K=>R(Z.id)},e.toDisplayString(Z.name),11,T3)),64))])])):p.value==="text"?(e.openBlock(),e.createElementBlock("div",I3,[P[10]||(P[10]=e.createElementVNode("h3",null,"Text Overlay",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":P[2]||(P[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:L},"Add Text")])):p.value==="transitions"?(e.openBlock(),e.createElementBlock("div",B3,[P[11]||(P[11]=e.createElementVNode("h3",null,"Transitions",-1)),e.createElementVNode("div",M3,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(T,Z=>e.createElementVNode("button",{key:Z.id,class:"transition-option",onClick:K=>(Z.id,void 0)},e.toDisplayString(Z.name),9,F3)),64))])])):e.createCommentVNode("",!0)]),e.createElementVNode("div",$3,[e.createElementVNode("button",{class:"btn-cancel",onClick:P[3]||(P[3]=Z=>I.$emit("cancel"))},"CANCEL"),e.createElementVNode("button",{class:"btn-save",onClick:z},"SAVE")])]))}}),R3=Be(D3,[["__scopeId","data-v-b933f33b"]]),A3={class:"time-label"},L3=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),f=d%(l*5)===0;s.push({time:d,position:c,label:u,major:f})}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",A3,e.toDisplayString(d.label),1),e.createElementVNode("div",{class:e.normalizeClass(["time-tick",{major:d.major}])},null,2)],4))),128))],4))}}),P3=Be(L3,[["__scopeId","data-v-0ef9c910"]]),U3=["data-track-index"],O3={class:"track-header"},z3={class:"track-label"},j3={class:"track-controls"},W3=["data-testid","aria-label"],H3=["data-testid","onMousedown","onClick"],Z3={class:"clip-content"},X3={class:"clip-name"},G3={key:0,class:"clip-thumbnail"},J3=["src","alt"],K3=["onMousedown","aria-label"],q3=["onMousedown","aria-label"],Y3=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(w){const x=w.timelineEnd-w.timelineStart,T=w.timelineStart/t.duration*100,_=x/t.duration*100;return{left:`${T}%`,width:`${_}%`,backgroundColor:u(w)}}function u(w){const x=["#4A90E2","#7ED321","#F5A623","#BD10E0","#9013FE","#50E3C2","#B8E986","#F8E71C"],T=parseInt(w.id.replace(/\D/g,""))%x.length;return x[T]}function f(w){return w.label?w.label:w.url?(w.url.split("/").pop()||"Clip").split(".")[0]:`Clip ${w.id.slice(-4)}`}function m(w){i.value=w.id,n("clip-select",w.id)}function p(){r.value=!r.value}function h(w,x){if(l.value)return;s.value=!0;const T=x.clientX,_=w.timelineStart,g=S=>{if(!s.value)return;const N=S.clientX-T,V=parseFloat(d.value.width),A=N/(t.zoom*100)*(t.duration/V),j=Math.max(0,_+A);n("clip-move",w.id,j)},E=()=>{s.value=!1,document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",E)};document.addEventListener("mousemove",g),document.addEventListener("mouseup",E)}function v(w,x,T){l.value=x;const _=T.clientX,g=w.sourceIn,E=w.sourceOut,S=V=>{if(!l.value)return;const A=V.clientX-_,j=parseFloat(d.value.width),C=A/(t.zoom*100)*(t.duration/j);if(l.value==="start"){const $=Math.max(0,g+C);n("clip-trim",w.id,$,E)}else{const $=Math.max(g+1,E+C);n("clip-trim",w.id,g,$)}},N=()=>{l.value=null,document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",N)};document.addEventListener("mousemove",S),document.addEventListener("mouseup",N)}return(w,x)=>(e.openBlock(),e.createElementBlock("div",{class:"video-track","data-track-index":w.trackIndex},[e.createElementVNode("div",O3,[e.createElementVNode("span",z3,"Track "+e.toDisplayString(w.trackIndex+1),1),e.createElementVNode("div",j3,[w.clips.length>0?(e.openBlock(),e.createElementBlock("button",{key:0,class:"track-btn","data-testid":`btn-mute-track-${w.trackIndex}`,"aria-label":`${r.value?"Unmute":"Mute"} track ${w.trackIndex+1}`,onClick:p},[e.createVNode(e.unref(W.IonIcon),{icon:r.value?e.unref(nv):e.unref(tv)},null,8,["icon"])],8,W3)):e.createCommentVNode("",!0)])]),e.createElementVNode("div",{class:"track-timeline",style:e.normalizeStyle(d.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(w.clips,T=>(e.openBlock(),e.createElementBlock("div",{key:T.id,class:e.normalizeClass(["timeline-clip",{selected:T.id===i.value}]),style:e.normalizeStyle(c(T)),"data-testid":`clip-${T.id}`,onMousedown:_=>h(T,_),onClick:_=>m(T)},[e.createElementVNode("div",Z3,[e.createElementVNode("span",X3,e.toDisplayString(f(T)),1),T.thumbnail?(e.openBlock(),e.createElementBlock("div",G3,[e.createElementVNode("img",{src:T.thumbnail,alt:f(T)},null,8,J3)])):e.createCommentVNode("",!0)]),e.createElementVNode("div",{class:"trim-handle trim-start",onMousedown:e.withModifiers(_=>v(T,"start",_),["stop"]),"aria-label":`Trim start of ${f(T)}`},null,40,K3),e.createElementVNode("div",{class:"trim-handle trim-end",onMousedown:e.withModifiers(_=>v(T,"end",_),["stop"]),"aria-label":`Trim end of ${f(T)}`},null,40,q3)],46,H3))),128))],4)],8,U3))}}),Q3=Be(Y3,[["__scopeId","data-v-48e480d2"]]),eI={class:"video-timeline"},tI={class:"timeline-tracks"},aI=["aria-label","aria-valuenow","aria-valuemax"],nI={class:"timeline-controls"},oI={class:"zoom-level"},iI=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 _=Math.max(0,...t.clips.map(g=>g.track||0));return Array(_+1).fill(null)}),c=e.computed(()=>`${t.currentTime/t.duration*100}%`);function u(_){return t.clips.filter(g=>(g.track||0)===_)}function f(_){const g=Math.floor(_/60),E=Math.floor(_%60);return`${g}:${E.toString().padStart(2,"0")}`}function m(_,g){n("clip-move",_,g)}function p(_,g,E){n("clip-trim",_,g,E)}function h(_){r.value=_}function v(){i.value=Math.min(i.value*1.2,5)}function w(){i.value=Math.max(i.value/1.2,.5)}function x(){s.value=!0;const _=E=>{if(!s.value||!l.value)return;const S=l.value.getBoundingClientRect(),A=Math.max(0,Math.min(E.clientX-S.left,S.width))/S.width*t.duration;n("seek",A)},g=()=>{s.value=!1,document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",g)};document.addEventListener("mousemove",_),document.addEventListener("mouseup",g)}function T(_){let g=t.currentTime;switch(_.key){case"ArrowLeft":g=Math.max(0,t.currentTime-1);break;case"ArrowRight":g=Math.min(t.duration,t.currentTime+1);break;case"Home":g=0;break;case"End":g=t.duration;break;default:return}_.preventDefault(),n("seek",g)}return e.onMounted(()=>{l.value=document.querySelector(".video-timeline")}),e.onUnmounted(()=>{}),(_,g)=>(e.openBlock(),e.createElementBlock("div",eI,[e.createVNode(P3,{duration:_.duration,zoom:i.value},null,8,["duration","zoom"]),e.createElementVNode("div",tI,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(d.value,(E,S)=>(e.openBlock(),e.createBlock(Q3,{key:`track-${S}`,"data-testid":`track-${S}`,clips:u(S),"track-index":S,zoom:i.value,duration:_.duration,onClipMove:m,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:x,"data-testid":"playhead","aria-label":`Playhead at ${f(_.currentTime)}`,role:"slider","aria-valuenow":_.currentTime,"aria-valuemax":_.duration,tabindex:"0",onKeydown:T},null,44,aI),e.createElementVNode("div",nI,[e.createElementVNode("button",{"data-testid":"btn-zoom-in","aria-label":"Zoom in",onClick:v},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Wl)},null,8,["icon"])]),e.createElementVNode("span",oI,e.toDisplayString(Math.round(i.value*100))+"%",1),e.createElementVNode("button",{"data-testid":"btn-zoom-out","aria-label":"Zoom out",onClick:w},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Jh)},null,8,["icon"])])])]))}}),rI=Be(iI,[["__scopeId","data-v-001df415"]]),sI={class:"video-filters-panel"},lI={class:"filter-controls"},dI=["for"],cI={class:"filter-slider-group"},uI=["id","onUpdate:modelValue","min","max","step","data-testid","aria-label","aria-valuenow","aria-valuemin","aria-valuemax","onInput"],mI={class:"filter-value"},pI={class:"filter-actions"},fI={key:0,class:"filter-presets"},hI={class:"preset-list"},vI=["data-testid","aria-label","onClick"],gI=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((m,p)=>(m[p.type]=p.default,m),{})),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(m,p){switch(m){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(m){return["brightness","contrast","saturation","hue","blur","sharpen","sepia","grayscale"].includes(m)}function d(m){if(!l(m))return;const p={id:`filter-${m}`,filterId:m,params:{value:i[m]},intensity:1};t("filter-change",p)}function c(){n.forEach(m=>{i[m.type]=m.default,d(m.type)})}function u(){const m=prompt("Enter preset name:");if(!m)return;const p={id:`custom-${Date.now()}`,name:m,values:{...i}};r.value.push(p)}function f(m){Object.entries(m.values).forEach(([p,h])=>{i[p]=h,d(p)})}return(m,p)=>(e.openBlock(),e.createElementBlock("div",sI,[p[3]||(p[3]=e.createElementVNode("h3",null,"Video Filters",-1)),e.createElementVNode("div",lI,[(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,dI),e.createElementVNode("div",cI,[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,uI),[[e.vModelText,i[h.type],void 0,{number:!0}]]),e.createElementVNode("span",mI,e.toDisplayString(s(h.type,i[h.type])),1)])])),64))]),e.createElementVNode("div",pI,[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(W.IonIcon),{icon:e.unref(Jn)},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(W.IonIcon),{icon:e.unref(jr)},null,8,["icon"]),p[1]||(p[1]=e.createTextVNode(" Save as Preset ",-1))])]),r.value.length>0?(e.openBlock(),e.createElementBlock("div",fI,[p[2]||(p[2]=e.createElementVNode("h4",null,"Presets",-1)),e.createElementVNode("div",hI,[(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=>f(h)},e.toDisplayString(h.name),9,vI))),128))])])):e.createCommentVNode("",!0)]))}}),bI=Be(gI,[["__scopeId","data-v-5ad2ac63"]]),yI={class:"video-text-panel"},wI={class:"text-input-group"},kI={class:"text-options"},_I={class:"option-row"},EI={class:"option-row"},xI={class:"option-row"},SI={class:"option-row"},CI={class:"checkbox-label"},VI={class:"option-row"},NI={class:"text-overlay-list"},TI={key:0,class:"empty-state"},II=["data-testid"],BI={class:"overlay-preview"},MI={class:"overlay-controls"},FI=["data-testid","aria-label","onClick"],$I=["data-testid","aria-label","onClick"],DI=["data-testid","aria-label","onClick"],RI=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(f=>f.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",yI,[u[17]||(u[17]=e.createElementVNode("h3",null,"Text Overlays",-1)),e.createElementVNode("div",wI,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":u[0]||(u[0]=f=>i.text=f),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(W.IonIcon),{icon:e.unref(Wl)},null,8,["icon"]),u[7]||(u[7]=e.createTextVNode(" Add ",-1))])]),e.createElementVNode("div",kI,[e.createElementVNode("div",_I,[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]=f=>i.fontFamily=f),"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",EI,[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]=f=>i.fontSize=f),type:"number",min:"10",max:"200","data-testid":"input-font-size"},null,512),[[e.vModelText,i.fontSize,void 0,{number:!0}]])]),e.createElementVNode("div",xI,[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]=f=>i.color=f),type:"color","data-testid":"input-text-color"},null,512),[[e.vModelText,i.color]])]),e.createElementVNode("div",SI,[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]=f=>i.backgroundColor=f),type:"color","data-testid":"input-bg-color"},null,512),[[e.vModelText,i.backgroundColor]]),e.createElementVNode("label",CI,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":u[5]||(u[5]=f=>i.hasBackground=f),type:"checkbox","data-testid":"checkbox-bg"},null,512),[[e.vModelCheckbox,i.hasBackground]]),u[12]||(u[12]=e.createTextVNode(" Enable ",-1))])]),e.createElementVNode("div",VI,[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]=f=>i.animation=f),"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",NI,[u[16]||(u[16]=e.createElementVNode("h4",null,"Active Overlays",-1)),n.value.length===0?(e.openBlock(),e.createElementBlock("div",TI," No text overlays added yet ")):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.value,(f,m)=>(e.openBlock(),e.createElementBlock("div",{key:f.id,class:"text-overlay-item","data-testid":`overlay-${m}`},[e.createElementVNode("div",BI,[e.createElementVNode("span",{style:e.normalizeStyle({fontFamily:f.fontFamily,fontSize:`${Math.min(f.fontSize/4,16)}px`,color:f.color})},e.toDisplayString(f.text),5)]),e.createElementVNode("div",MI,[e.createElementVNode("button",{class:"edit-btn","data-testid":`btn-edit-${m}`,"aria-label":`Edit overlay: ${f.text}`,onClick:p=>l(f)},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Th)},null,8,["icon"])],8,FI),e.createElementVNode("button",{class:"duplicate-btn","data-testid":`btn-duplicate-${m}`,"aria-label":`Duplicate overlay: ${f.text}`,onClick:p=>d(f)},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(al)},null,8,["icon"])],8,$I),e.createElementVNode("button",{class:"remove-btn","data-testid":`btn-remove-${m}`,"aria-label":`Remove overlay: ${f.text}`,onClick:p=>s(f.id)},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(xr)},null,8,["icon"])],8,DI)])],8,II))),128))])]))}}),AI=Be(RI,[["__scopeId","data-v-4d240e1e"]]),LI={class:"video-tools-panel"},PI={class:"tool-tabs"},UI=["data-testid","aria-label","aria-selected","onClick"],OI={class:"tool-content"},zI={key:0,class:"trim-panel",role:"tabpanel","aria-label":"Trim controls"},jI={class:"trim-actions"},WI={key:3,class:"transitions-panel",role:"tabpanel","aria-label":"Transition controls"},HI={class:"transition-types"},ZI=["data-testid","aria-label","onClick"],XI={class:"transition-preview"},GI=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:Er},{id:"filters",name:"Filters",icon:gn},{id:"text",name:"Text",icon:Uu},{id:"transitions",name:"Transitions",icon:ec}],t=[{id:"fade",name:"Fade",icon:$s},{id:"slide-left",name:"Slide Left",icon:_h},{id:"slide-right",name:"Slide Right",icon:Eh},{id:"dissolve",name:"Dissolve",icon:$s},{id:"wipe",name:"Wipe",icon:ec},{id:"zoom",name:"Zoom",icon:$s}];return(n,i)=>(e.openBlock(),e.createElementBlock("div",LI,[e.createElementVNode("div",PI,[(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(W.IonIcon),{icon:r.icon},null,8,["icon"]),e.createTextVNode(" "+e.toDisplayString(r.name),1)],10,UI)),64))]),e.createElementVNode("div",OI,[n.activeTool==="trim"?(e.openBlock(),e.createElementBlock("div",zI,[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",jI,[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(W.IonIcon),{icon:e.unref(Yd)},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(W.IonIcon),{icon:e.unref(Yd)},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(W.IonIcon),{icon:e.unref(jn)},null,8,["icon"]),i[7]||(i[7]=e.createTextVNode(" Clear ",-1))])])])):e.createCommentVNode("",!0),n.activeTool==="filters"?(e.openBlock(),e.createBlock(bI,{key:1,onFilterChange:i[3]||(i[3]=r=>n.$emit("filter-change",r))})):e.createCommentVNode("",!0),n.activeTool==="text"?(e.openBlock(),e.createBlock(AI,{key:2,onTextAdd:i[4]||(i[4]=r=>n.$emit("text-add",r))})):e.createCommentVNode("",!0),n.activeTool==="transitions"?(e.openBlock(),e.createElementBlock("div",WI,[i[10]||(i[10]=e.createElementVNode("h3",null,"Transitions",-1)),e.createElementVNode("div",HI,[(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(W.IonIcon),{icon:r.icon},null,8,["icon"])]),e.createElementVNode("span",null,e.toDisplayString(r.name),1)],8,ZI)),64))])])):e.createCommentVNode("",!0)])]))}}),JI=Be(GI,[["__scopeId","data-v-fc135306"]]),KI={class:"video-export-panel"},qI={class:"export-presets"},YI=["value"],QI={key:0,class:"preset-details"},eB={class:"detail-row"},tB={class:"detail-row"},aB={class:"detail-row"},nB={class:"advanced-options"},oB={class:"options-content"},iB={class:"option-group"},rB={class:"option-group"},sB={class:"option-group"},lB=["disabled"],dB={key:1,class:"export-progress"},cB={class:"progress-message"},uB={class:"progress-bar"},mB=["aria-valuenow"],pB={class:"progress-percentage"},fB=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",KI,[u[14]||(u[14]=e.createElementVNode("h3",null,"Export Video",-1)),e.createElementVNode("div",qI,[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]=f=>i.value=f),"data-testid":"preset-select","aria-label":"Select export preset"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.presets,f=>(e.openBlock(),e.createElementBlock("option",{key:f.id,value:f.id},e.toDisplayString(f.name),9,YI))),128))],512),[[e.vModelSelect,i.value]])]),s.value?(e.openBlock(),e.createElementBlock("div",QI,[e.createElementVNode("div",eB,[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",tB,[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",aB,[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",nB,[u[12]||(u[12]=e.createElementVNode("summary",null,"Advanced Options",-1)),e.createElementVNode("div",oB,[e.createElementVNode("div",iB,[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]=f=>r.quality=f),"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",rB,[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]=f=>r.bitrate=f),type:"number",min:"1",max:"50","data-testid":"bitrate-input"},null,512),[[e.vModelText,r.bitrate,void 0,{number:!0}]])]),e.createElementVNode("div",sB,[e.createElementVNode("label",null,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":u[3]||(u[3]=f=>r.includeAudio=f),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(W.IonSpinner),{key:0,name:"crescent"})):(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(ko)},null,8,["icon"]),u[13]||(u[13]=e.createTextVNode(" Export Video ",-1))],64))],8,lB),c.isExporting?(e.openBlock(),e.createElementBlock("div",dB,[e.createElementVNode("div",cB,e.toDisplayString(l.value),1),e.createElementVNode("div",uB,[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,mB)]),e.createElementVNode("div",pB,e.toDisplayString(c.exportProgress)+"% ",1)])):e.createCommentVNode("",!0)]))}}),hB=Be(fB,[["__scopeId","data-v-5caf8fe6"]]),vB=["data-testid"],gB={class:"progress-header"},bB={class:"file-info"},yB={class:"file-details"},wB={class:"file-name"},kB={class:"file-meta"},_B={class:"file-size"},EB={key:0,class:"separator"},xB={key:1,class:"upload-speed"},SB={key:2,class:"separator"},CB={key:3,class:"time-remaining"},VB={class:"progress-actions"},NB={key:0,class:"status-icon completed","data-testid":"video-upload-status-completed"},TB={key:1,class:"status-icon error","data-testid":"video-upload-status-error"},IB={key:2,class:"status-icon processing","data-testid":"video-upload-status-processing",role:"status","aria-label":"Processing video"},BB=["aria-valuenow","aria-label"],MB={class:"progress-bar"},FB={class:"progress-percent"},$B={key:1,class:"error-message","data-testid":"video-upload-error"},DB={key:2,class:"thumbnail-preview","data-testid":"video-upload-thumbnail"},RB=["src","alt"],AB={key:0,class:"video-duration"},LB=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(()=>Ou),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 m=a.upload.timeRemaining;if(m<60)return`${Math.round(m)}s`;const p=Math.floor(m/60);return p<60?`${p}m ${Math.round(m%60)}s`:`${Math.floor(p/60)}h ${p%60}m`}),l=e.computed(()=>{var m;return a.upload.status==="completed"&&((m=a.upload.media)!=null&&m.thumbnail_url)?a.upload.media.thumbnail_url:null}),d=e.computed(()=>{var m;return(m=a.upload.media)==null?void 0:m.duration});function c(m){if(m===0)return"0 B";const p=["B","KB","MB","GB","TB"],h=1024,v=Math.floor(Math.log(m)/Math.log(h));return`${(m/Math.pow(h,v)).toFixed(1)} ${p[v]}`}function u(m){if(m===0)return"0 B/s";const p=["B/s","KB/s","MB/s","GB/s"],h=1024,v=Math.floor(Math.log(m)/Math.log(h));return`${(m/Math.pow(h,v)).toFixed(1)} ${p[v]}`}function f(m){const p=Math.floor(m/3600),h=Math.floor(m%3600/60),v=Math.floor(m%60);return p>0?`${p}:${h.toString().padStart(2,"0")}:${v.toString().padStart(2,"0")}`:`${h}:${v.toString().padStart(2,"0")}`}return(m,p)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["upload-progress-item",t.value]),"data-testid":`video-upload-progress-${m.upload.id}`},[e.createElementVNode("div",gB,[e.createElementVNode("div",bB,[e.createVNode(e.unref(W.IonIcon),{icon:n.value,class:"file-icon","aria-hidden":"true"},null,8,["icon"]),e.createElementVNode("div",yB,[e.createElementVNode("h4",wB,e.toDisplayString(m.upload.filename),1),e.createElementVNode("p",kB,[e.createElementVNode("span",_B,e.toDisplayString(c(m.upload.bytesTotal||0)),1),m.upload.status==="uploading"?(e.openBlock(),e.createElementBlock("span",EB,"•")):e.createCommentVNode("",!0),m.upload.status==="uploading"?(e.openBlock(),e.createElementBlock("span",xB,e.toDisplayString(u(m.upload.uploadSpeed||0)),1)):e.createCommentVNode("",!0),s.value?(e.openBlock(),e.createElementBlock("span",SB,"•")):e.createCommentVNode("",!0),s.value?(e.openBlock(),e.createElementBlock("span",CB,e.toDisplayString(s.value)+" remaining ",1)):e.createCommentVNode("",!0)])])]),e.createElementVNode("div",VB,[m.upload.status==="completed"?(e.openBlock(),e.createElementBlock("div",NB,[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Ru)},null,8,["icon"])])):m.upload.status==="error"?(e.openBlock(),e.createElementBlock("div",TB,[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(kh),"aria-hidden":"true"},null,8,["icon"])])):m.upload.status==="processing"?(e.openBlock(),e.createElementBlock("div",IB,[e.createVNode(e.unref(W.IonSpinner),{name:"crescent"})])):e.createCommentVNode("",!0),m.upload.status==="uploading"?(e.openBlock(),e.createBlock(e.unref(W.IonButton),{key:3,fill:"clear",size:"small",onClick:p[0]||(p[0]=h=>m.$emit("cancel")),"data-testid":"btn-cancel-video-upload","aria-label":"Cancel upload"},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(jn),slot:"icon-only"},null,8,["icon"])]),_:1})):m.upload.status==="error"?(e.openBlock(),e.createBlock(e.unref(W.IonButton),{key:4,fill:"clear",size:"small",onClick:p[1]||(p[1]=h=>m.$emit("retry")),"data-testid":"btn-retry-video-upload","aria-label":"Retry upload"},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Jn),slot:"icon-only"},null,8,["icon"])]),_:1})):m.upload.status==="completed"?(e.openBlock(),e.createBlock(e.unref(W.IonButton),{key:5,fill:"clear",size:"small",onClick:p[2]||(p[2]=h=>m.$emit("remove")),"data-testid":"btn-remove-video-upload","aria-label":"Remove from list"},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(jn),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":m.upload.status==="processing"?"Processing progress":"Upload progress"},[e.createElementVNode("div",MB,[e.createElementVNode("div",{class:e.normalizeClass(["progress-fill",{indeterminate:m.upload.status==="processing"}]),style:e.normalizeStyle({width:r.value+"%"})},null,6)]),e.createElementVNode("span",FB,e.toDisplayString(Math.round(r.value))+"%",1)],8,BB)):e.createCommentVNode("",!0),m.upload.error?(e.openBlock(),e.createElementBlock("div",$B,[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(ov)},null,8,["icon"]),e.createElementVNode("span",null,e.toDisplayString(m.upload.error),1)])):e.createCommentVNode("",!0),l.value?(e.openBlock(),e.createElementBlock("div",DB,[e.createElementVNode("img",{src:l.value,alt:m.upload.filename},null,8,RB),d.value?(e.openBlock(),e.createElementBlock("div",AB,e.toDisplayString(f(d.value)),1)):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)],10,vB))}}),PB=Be(LB,[["__scopeId","data-v-9eacbf91"]]),Gs=4,UB=500,OB=new Set([408,425,429,500,502,503,504,520,521,522,523,524,525]);function fs(o){return typeof o=="object"&&o!==null}function ru(o){return fs(o)?typeof o.upload_url=="string"&&typeof o.upload_id=="string"&&typeof o.media_uuid=="string"&&typeof o.expires_at=="string":!1}function zB(o){if(ru(o))return o;if(fs(o)&&ru(o.data))return o.data;throw new Error("Invalid upload response from backend")}function su(o){return fs(o)?typeof o.uuid=="string"&&typeof o.processing_status=="string":!1}function jB(o){if(su(o))return o;if(fs(o)&&su(o.data))return o.data;throw new Error("Invalid media response from backend")}function ar(o){return o?{...o}:{}}function lu(o,a="PUT"){return typeof o.method=="string"&&o.method.trim()!==""?o.method.trim().toUpperCase():a}function WB(o){return o.resumable===!0?!0:/tusupload/i.test(o.upload_url)}function HB(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 ZB(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} ${HB(i)}`).join(",")}function nr(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 XB(o,a){return o instanceof Error?o:new Error(a)}function GB(o){if(!(o instanceof Error))return!1;const a=o.message.toLowerCase();return a.includes("failed to fetch")||a.includes("networkerror")||a.includes("network request failed")||a.includes("err_ssl_")}function du(o){const a=Math.max(0,o-1),t=UB*Math.pow(2,a);return Math.min(5e3,t)}function cu(o){return new Promise(a=>{window.setTimeout(a,o)})}async function uu(o,a){for(let t=1;t<=Gs;t+=1)try{const n=await a();if(n.ok||!OB.has(n.status)||t>=Gs)return n;await cu(du(t))}catch(n){if(!GB(n)||t>=Gs)throw n;await cu(du(t))}throw new Error(`${o} failed after retry attempts`)}function JB(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 C=Array.from(a.value.values());return C.length===0?0:C.reduce((y,R)=>y+R.progress,0)/C.length});function c(C){n.value=C}function u(){}async function f(C){var y;const $=C.filter(R=>m(R));if($.length!==0&&((y=o.onFilesSelected)==null||y.call(o,$),o.autoUpload!==!1))for(const R of $)await p(R)}function m(C){return!(o.maxFileSize&&C.size>o.maxFileSize||o.allowedFormats&&o.allowedFormats.length>0&&!o.allowedFormats.includes(C.type))}async function p(C){var R,L,U;const $=j(C);if(a.value.has($)){const z=a.value.get($);if((z==null?void 0:z.status)==="uploading")return}const y={id:$,file:C,filename:C.name,progress:0,status:"pending",startedAt:new Date,bytesTotal:C.size,bytesUploaded:0};a.value.set(y.id,y),t.value.add(y.id);try{y.status="uploading",(R=o.onUploadStart)==null||R.call(o,y);const z=await h(C);o.resumable===!0||z.resumable===!0?await w(y,z):await v(y,z),y.status="processing",y.progress=100;const P=await E(z.media_uuid);y.status="completed",y.media=P,(L=o.onUploadComplete)==null||L.call(o,P)}catch(z){if(y.status!=="cancelled"){const I=XB(z,"Upload failed");y.status="error",y.error=I.message,(U=o.onUploadError)==null||U.call(o,I,y)}}finally{t.value.delete(y.id),i.delete(y.id),r.delete(y.id)}}async function h(C){if(!n.value)throw new Error("API client not configured");const $={collection:o.collection||"videos",filename:C.name,size:C.size,mime_type:C.type,...o.ownerUuid!==void 0?{ownerUuid:o.ownerUuid}:{},...o.ownerType!==void 0?{ownerType:o.ownerType}:{}},y=await n.value.post("/api/v1/video/upload",$);return zB(y)}async function v(C,$){const y=new XMLHttpRequest,R=lu($),L=ar($.headers);return new Promise((U,z)=>{y.upload.addEventListener("progress",I=>{var P;I.lengthComputable&&(nr(C,I.loaded),(P=o.onUploadProgress)==null||P.call(o,C))}),y.addEventListener("load",()=>{i.delete(C.id),y.status>=200&&y.status<300?U():z(new Error(`Upload failed with status ${y.status}`))}),y.addEventListener("error",()=>{i.delete(C.id),z(new Error("Upload failed"))}),y.addEventListener("abort",()=>{i.delete(C.id),z(new Error("Upload cancelled"))}),y.open(R,$.upload_url),Object.entries(L).forEach(([I,P])=>{y.setRequestHeader(I,P)}),!Object.keys(L).some(I=>I.toLowerCase()==="content-type")&&C.file.type&&y.setRequestHeader("Content-Type",C.file.type),i.set(C.id,y),y.send(C.file)})}async function w(C,$){var z;if(WB($)){await x(C,$);return}const y=o.chunkSize||5*1024*1024,R=T(C.file,y),L=new AbortController;r.set(C.id,L);const U=await g($.upload_id);U&&(R.forEach(I=>{I.end<=U.bytesUploaded&&(I.uploaded=!0)}),nr(C,U.bytesUploaded));for(const I of R)I.uploaded||(await _(C,$,I,L),nr(C,I.end),(z=o.onUploadProgress)==null||z.call(o,C))}async function x(C,$){var Z;const y=new AbortController;r.set(C.id,y);const R={...ar($.headers),"Tus-Resumable":"1.0.0","Upload-Length":String(C.file.size),"Upload-Metadata":ZB(C,$)},L=await uu("Resumable upload initialization",()=>fetch($.upload_url,{method:"POST",headers:R,signal:y.signal}));if(!L.ok)throw new Error(`Failed to initialize resumable upload: ${L.status}`);const U=L.headers.get("Location");if(!U)throw new Error("Resumable upload endpoint did not return upload location");const z=new URL(U,$.upload_url).toString(),I=o.chunkSize||5*1024*1024;let P=0;for(;P<C.file.size;){const K=Math.min(P+I,C.file.size),ve=C.file.slice(P,K),Ve={...ar($.headers),"Tus-Resumable":"1.0.0","Upload-Offset":String(P),"Content-Type":"application/offset+octet-stream"},ne=await uu("Resumable chunk upload",()=>fetch(z,{method:"PATCH",headers:Ve,body:ve,signal:y.signal}));if(ne.status===409){const F=Number(ne.headers.get("Upload-Offset")??"-1");if(Number.isFinite(F)&&F>=0){P=F;continue}}if(!ne.ok)throw new Error(`Resumable chunk upload failed: ${ne.status}`);const ae=Number(ne.headers.get("Upload-Offset")??String(K));P=Number.isFinite(ae)&&ae>P?ae:K,nr(C,P),(Z=o.onUploadProgress)==null||Z.call(o,C)}}function T(C,$){const y=[];let R=0,L=0;for(;R<C.size;){const U=Math.min(R+$,C.size);y.push({start:R,end:U,blob:C.slice(R,U),index:L,uploaded:!1}),R=U,L++}return y}async function _(C,$,y,R){const L={...ar($.headers),"Content-Range":`bytes ${y.start}-${y.end-1}/${C.file.size}`,"Content-Type":C.file.type||"application/octet-stream"},U=await fetch($.upload_url,{method:lu($),headers:L,body:y.blob,signal:R.signal});if(!U.ok)throw new Error(`Chunk upload failed: ${U.status}`);y.uploaded=!0}async function g(C){return null}async function E(C){if(!n.value)throw new Error("API client not configured");const $=60;let y=0;for(;y<$;){const R=await n.value.get(`/api/v1/video/${C}`),L=jB(R),U=String(L.processing_status);if(U==="ready")return L;if(U==="failed"||U==="error")throw new Error("Video processing failed");await new Promise(z=>{window.setTimeout(z,5e3)}),y++}throw new Error("Video processing timeout")}function S(C){const $=a.value.get(C);if(!$)return;const y=i.get(C);y&&(y.abort(),i.delete(C));const R=r.get(C);R&&(R.abort(),r.delete(C)),$.status="cancelled",$.error="Upload cancelled",t.value.delete(C)}async function N(C){const $=a.value.get(C);$&&($.status="pending",$.error="",$.progress=0,$.bytesUploaded=0,await p($.file))}function V(C){a.value.delete(C),t.value.delete(C),i.delete(C),r.delete(C)}function A(){Array.from(a.value.entries()).forEach(([C,$])=>{$.status==="completed"&&a.value.delete(C)})}function j(C){return`${C.name}-${C.size}-${Date.now()}`}return{uploads:l,isUploading:s,totalProgress:d,openFilePicker:u,handleFileSelect:f,validateFile:m,startUpload:p,cancelUpload:S,retryUpload:N,removeUpload:V,clearCompleted:A,setApiClient:c}}const KB=["accept","multiple"],qB={key:0,class:"upload-trigger","data-testid":"video-uploader-trigger"},YB=["onKeydown"],QB={key:1,class:"upload-list","data-testid":"video-upload-list"},eM={class:"drag-content"},tM=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:f,setApiClient:m}=JB({collection:t.collection,...t.ownerUuid!==void 0?{ownerUuid:t.ownerUuid}:{},...t.ownerType!==void 0?{ownerType:t.ownerType}:{},maxFileSize:t.maxFileSize,...t.maxDuration!==void 0?{maxDuration:t.maxDuration}:{},allowedFormats:t.allowedFormats,autoUpload:t.autoUpload,resumable:t.resumable,onUploadStart:g=>n("upload-start",g),onUploadProgress:g=>n("upload-progress",g),onUploadComplete:g=>n("upload-complete",g),onUploadError:(g,E)=>n("upload-error",g,E),onFilesSelected:g=>n("files-selected",g)});t.apiClient&&m(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 w(g){const E=g.target,S=Array.from(E.files||[]);S.length>0&&(d(S),E.value="")}function x(g){var N;g.preventDefault(),r.value=!1;const S=Array.from(((N=g.dataTransfer)==null?void 0:N.files)||[]).filter(V=>V.type.startsWith("video/"));S.length>0&&d(S)}function T(g){var E;g.preventDefault(),(E=g.dataTransfer)!=null&&E.types.includes("Files")&&(r.value=!0)}function _(g){g.target.closest(".video-uploader")||(r.value=!1)}return e.onMounted(()=>{document.addEventListener("dragover",T),document.addEventListener("dragleave",_),document.addEventListener("drop",g=>g.preventDefault())}),e.onUnmounted(()=>{document.removeEventListener("dragover",T),document.removeEventListener("dragleave",_),document.removeEventListener("drop",g=>g.preventDefault())}),(g,E)=>(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:g.multiple,onChange:w,"data-testid":"video-uploader-input","aria-label":"Select video files to upload",hidden:""},null,40,KB),!e.unref(l)||h.value?(e.openBlock(),e.createElementBlock("div",qB,[e.renderSlot(g.$slots,"trigger",{open:v},()=>[e.createElementVNode("div",{class:"default-upload-area","data-testid":"video-uploader-area",role:"button",tabindex:"0","aria-label":"Click to select video for upload",onClick:v,onKeydown:[e.withKeys(v,["enter"]),e.withKeys(e.withModifiers(v,["prevent"]),["space"])]},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Ou),class:"upload-icon","aria-hidden":"true"},null,8,["icon"]),e.createElementVNode("h3",null,e.toDisplayString(g.label),1),e.createElementVNode("p",null,e.toDisplayString(g.description),1),e.createVNode(e.unref(W.IonButton),{size:"small","data-testid":"btn-select-video","aria-label":"Select video file"},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Wl),slot:"start","aria-hidden":"true"},null,8,["icon"]),E[2]||(E[2]=e.createTextVNode(" Select Video ",-1))]),_:1})],40,YB)],!0)])):e.createCommentVNode("",!0),e.unref(s).length>0?(e.openBlock(),e.createElementBlock("div",QB,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(s),S=>(e.openBlock(),e.createBlock(PB,{key:S.id,upload:S,onCancel:N=>e.unref(c)(S.id),onRetry:N=>e.unref(u)(S.id),onRemove:N=>e.unref(f)(S.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:x,onDragover:E[0]||(E[0]=e.withModifiers(()=>{},["prevent"])),onDragleave:E[1]||(E[1]=S=>r.value=!1)},[e.createElementVNode("div",eM,[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(ko),"aria-hidden":"true"},null,8,["icon"]),E[3]||(E[3]=e.createElementVNode("p",null,"Drop video files here",-1))])],32)):e.createCommentVNode("",!0)],2))}}),aM=Be(tM,[["__scopeId","data-v-ea7587f7"]]),nM=["aria-valuenow","aria-valuemax","aria-label"],oM={class:"progress-bar"},iM={class:"time-display","data-testid":"video-time-display"},rM={class:"current-time"},sM={class:"duration"},lM={class:"control-buttons"},dM={class:"controls-left"},cM=["aria-label"],uM={class:"controls-center"},mM={key:0,class:"volume-controls"},pM=["aria-label"],fM=["value"],hM={class:"controls-right"},vM={key:0,class:"quality-selector"},gM=["aria-expanded"],bM={class:"quality-label"},yM={key:0,class:"quality-menu","data-testid":"video-quality-menu",role:"menu"},wM=["data-testid","aria-label","onClick"],kM=["aria-label"],_M=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=W.isPlatform("mobile"),d="pictureInPictureEnabled"in document,c=e.computed(()=>({width:`${t.currentTime/t.duration*100}%`})),u=e.computed(()=>({left:`${t.currentTime/t.duration*100}%`})),f=e.computed(()=>{if(!t.buffered||t.buffered.length===0)return{width:"0%"};for(let g=0;g<t.buffered.length;g++){const E=t.buffered.start(g),S=t.buffered.end(g);if(t.currentTime>=E&&t.currentTime<=S)return{width:`${S/t.duration*100}%`}}return t.buffered.length>0?{width:`${t.buffered.end(0)/t.duration*100}%`}:{width:"0%"}}),m=e.computed(()=>t.muted||t.volume===0?av:t.volume<33?Qh:t.volume<66?ev:Yh);let p=null;function h(){i.value=!0,v()}function v(){p&&clearTimeout(p),t.playing&&!l&&(p=setTimeout(()=>{i.value=!1},3e3))}function w(g){if(!s.value||t.isLive)return;const E=s.value.getBoundingClientRect(),N=(g.clientX-E.left)/E.width*t.duration;n("seek",Math.max(0,Math.min(N,t.duration)))}function x(g){const E=g.target;n("setVolume",parseInt(E.value))}function T(g){n("selectQuality",g),r.value=!1}function _(g){if(!isFinite(g))return"0:00";const E=Math.floor(g/3600),S=Math.floor(g%3600/60),N=Math.floor(g%60);return E>0?`${E}:${S.toString().padStart(2,"0")}:${N.toString().padStart(2,"0")}`:`${S}:${N.toString().padStart(2,"0")}`}return e.onMounted(()=>{document.addEventListener("mousemove",h),v()}),e.onUnmounted(()=>{document.removeEventListener("mousemove",h),p&&clearTimeout(p)}),(g,E)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-controls",{"controls-visible":i.value}]),"data-testid":"video-controls"},[e.createElementVNode("div",{class:"progress-container","data-testid":"video-progress-bar",role:"slider","aria-valuenow":Math.round(g.currentTime),"aria-valuemin":"0","aria-valuemax":Math.round(g.duration),"aria-label":g.isLive?"Live stream":"Video progress",tabindex:"0",onClick:w},[e.createElementVNode("div",oM,[e.createElementVNode("div",{class:"progress-buffered",style:e.normalizeStyle(f.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",iM,[e.createElementVNode("span",rM,e.toDisplayString(_(g.currentTime)),1),E[7]||(E[7]=e.createElementVNode("span",{class:"separator"},"/",-1)),e.createElementVNode("span",sM,e.toDisplayString(g.isLive?"LIVE":_(g.duration)),1)])],8,nM),e.createElementVNode("div",lM,[e.createElementVNode("div",dM,[e.createElementVNode("button",{class:"control-btn play-pause","data-testid":"btn-video-play-pause",onClick:E[0]||(E[0]=S=>g.$emit("play-pause")),"aria-label":g.playing?"Pause":"Play"},[e.createVNode(e.unref(W.IonIcon),{icon:g.playing?e.unref(Lh):e.unref(Uh),"aria-hidden":"true"},null,8,["icon"])],8,cM),g.isLive?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("button",{key:0,class:"control-btn skip-backward","data-testid":"btn-video-skip-backward",onClick:E[1]||(E[1]=S=>g.$emit("skip-backward")),"aria-label":"Skip backward 10 seconds"},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Oh),"aria-hidden":"true"},null,8,["icon"]),E[8]||(E[8]=e.createElementVNode("span",{class:"skip-label"},"10",-1))])),g.isLive?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("button",{key:1,class:"control-btn skip-forward","data-testid":"btn-video-skip-forward",onClick:E[2]||(E[2]=S=>g.$emit("skip-forward")),"aria-label":"Skip forward 10 seconds"},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Wh),"aria-hidden":"true"},null,8,["icon"]),E[9]||(E[9]=e.createElementVNode("span",{class:"skip-label"},"10",-1))]))]),e.createElementVNode("div",uM,[e.unref(l)?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",mM,[e.createElementVNode("button",{class:"control-btn mute-btn","data-testid":"btn-video-mute",onClick:E[3]||(E[3]=S=>g.$emit("toggleMute")),"aria-label":g.muted?"Unmute":"Mute"},[e.createVNode(e.unref(W.IonIcon),{icon:m.value,"aria-hidden":"true"},null,8,["icon"])],8,pM),e.createElementVNode("input",{type:"range",class:"volume-slider","data-testid":"slider-video-volume",min:"0",max:"100",value:g.muted?0:g.volume,onInput:x,"aria-label":"Volume"},null,40,fM)]))]),e.createElementVNode("div",hM,[g.qualityLevels.length>1?(e.openBlock(),e.createElementBlock("div",vM,[e.createElementVNode("button",{class:"control-btn quality-btn","data-testid":"btn-video-quality",onClick:E[4]||(E[4]=S=>r.value=!r.value),"aria-label":"Quality settings","aria-expanded":r.value},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Kh),"aria-hidden":"true"},null,8,["icon"]),e.createElementVNode("span",bM,e.toDisplayString(g.currentQuality),1)],8,gM),r.value?(e.openBlock(),e.createElementBlock("div",yM,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(g.qualityLevels,S=>(e.openBlock(),e.createElementBlock("button",{key:S.label,class:e.normalizeClass(["quality-option",{active:S.label===g.currentQuality}]),"data-testid":`btn-video-quality-${S.label}`,"aria-label":`Set quality to ${S.label}`,role:"menuitem",onClick:N=>T(S)},e.toDisplayString(S.label),11,wM))),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:E[5]||(E[5]=S=>g.$emit("togglePiP")),"aria-label":"Picture in Picture"},[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(qh),"aria-hidden":"true"},null,8,["icon"])])):e.createCommentVNode("",!0),e.createElementVNode("button",{class:"control-btn fullscreen-btn","data-testid":"btn-video-fullscreen",onClick:E[6]||(E[6]=S=>g.$emit("toggleFullscreen")),"aria-label":g.fullscreen?"Exit fullscreen":"Enter fullscreen"},[e.createVNode(e.unref(W.IonIcon),{icon:g.fullscreen?e.unref(Nh):e.unref(Bh),"aria-hidden":"true"},null,8,["icon"])],8,kM)])])],2))}}),EM=Be(_M,[["__scopeId","data-v-2ae77c13"]]);function xM(o={}){var ve,Ve,ne;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),f=e.ref(!1),m=e.ref(null),p=e.ref("idle"),h=e.ref(o.playbackUrl||((ve=o.media)==null?void 0:ve.playback_url)||((Ve=o.media)==null?void 0:Ve.url)||""),v=e.ref(null),w=e.ref(o.isLive||!1),x=e.ref(null),T=e.ref(null);function _(ae){T.value=ae}if((ne=o.media)!=null&&ne.token_expires_at){const ae=new Date(o.media.token_expires_at);v.value=Number.isNaN(ae.getTime())?null:ae}async function g(){var F;const ae=w.value?t.value:a.value;if(ae)try{await ae.play(),n.value=!0,p.value=w.value?"live":"playing",(F=o.onPlay)==null||F.call(o)}catch{m.value="Failed to play video",p.value="error"}}function E(){var F;const ae=w.value?t.value:a.value;ae&&(ae.pause(),n.value=!1,p.value="paused",(F=o.onPause)==null||F.call(o))}function S(){n.value?E():g()}function N(ae){const F=w.value?t.value:a.value;if(!F||w.value)return;const B=Number.isFinite(F.duration)?F.duration:ae;F.currentTime=Math.max(0,Math.min(ae,B)),i.value=F.currentTime}function V(ae=10){const F=a.value;!F||w.value||N(F.currentTime+ae)}function A(ae=10){const F=a.value;!F||w.value||N(F.currentTime-ae)}function j(){const ae=w.value?t.value:a.value;ae&&(ae.muted=!ae.muted,l.value=ae.muted)}function C(ae){const F=w.value?t.value:a.value;if(!F)return;const B=Math.max(0,Math.min(100,ae));F.volume=B/100,s.value=B,B>0&&F.muted&&(F.muted=!1,l.value=!1)}function $(ae){const F=a.value;!F||w.value||(F.playbackRate=ae,u.value=ae)}async function y(){const ae=document.querySelector(".video-player-container");if(ae)try{document.fullscreenElement?(await document.exitFullscreen(),d.value=!1):(await ae.requestFullscreen(),d.value=!0)}catch{}}async function R(){const ae=w.value?t.value:a.value;if(ae)try{document.pictureInPictureElement?await document.exitPictureInPicture():document.pictureInPictureEnabled&&await ae.requestPictureInPicture()}catch{}}async function L(){var F;m.value=null,p.value="loading",(F=o.media)!=null&&F.provider&&o.media.provider!=="local"&&await U();const ae=w.value?t.value:a.value;ae&&(ae.load(),await g())}async function U(){if(!(!T.value||!o.media))try{f.value=!0;const ae=await T.value.get(`/api/v1/video/${o.media.uuid}/playback`);h.value=ae.playback_url,v.value=new Date(ae.token_expires_at);const F=w.value?t.value:a.value;if(F&&F.src!==h.value){const B=!F.paused,O=F.currentTime;F.src=h.value,w.value||(F.currentTime=O),B&&await g()}}catch{m.value="Failed to refresh playback token",p.value="error"}finally{f.value=!1}}async function z(ae){if(t.value){if(t.value.canPlayType("application/vnd.apple.mpegurl")){t.value.src=ae;return}try{t.value.src=ae}catch{m.value="Live streaming not supported in this browser",p.value="error"}}}function I(){x.value&&(x.value.destroy(),x.value=null)}function P(){var F;const ae=w.value?t.value:a.value;ae&&(i.value=ae.currentTime,r.value=ae.duration,(F=o.onTimeUpdate)==null||F.call(o,ae.currentTime))}const Z=e.computed(()=>{if(!c.value||c.value.length===0||!r.value)return 0;for(let ae=0;ae<c.value.length;ae++){const F=c.value.start(ae),B=c.value.end(ae);if(i.value>=F&&i.value<=B)return B/r.value*100}return 0});function K(){if(!v.value)return!1;const ae=new Date;return v.value.getTime()-ae.getTime()<5*60*1e3}return e.watch([a,t],([ae,F])=>{const B=w.value?F:ae;B&&(B.addEventListener("timeupdate",P),B.addEventListener("loadedmetadata",()=>{r.value=B.duration,p.value="ready"}),B.addEventListener("progress",()=>{c.value=B.buffered}),B.addEventListener("ended",()=>{var O;n.value=!1,p.value="ended",(O=o.onEnded)==null||O.call(o)}),B.addEventListener("error",O=>{var X;p.value="error",(X=o.onError)==null||X.call(o,"Video playback error")}),B.volume=s.value/100,B.muted=l.value)}),e.onUnmounted(()=>{I();const ae=w.value?t.value:a.value;ae&&ae.removeEventListener("timeupdate",P)}),{videoEl:a,liveVideoEl:t,playing:n,currentTime:i,duration:r,volume:s,muted:l,isFullscreen:d,bufferedRanges:c,bufferedPercent:Z,playbackRate:u,isLoading:f,error:m,status:p,currentPlaybackUrl:h,tokenExpiresAt:v,play:g,pause:E,togglePlayPause:S,seek:N,skipForward:V,skipBackward:A,toggleMute:j,setVolume:C,setPlaybackRate:$,toggleFullscreen:y,togglePiP:R,retry:L,refreshToken:U,setupLiveStream:z,setApiClient:_,shouldRefreshToken:K}}const SM=["src","poster","controls","autoplay","muted","loop","preload"],CM={key:1,ref:"livePlayerEl",class:"live-player"},VM=["controls","muted"],NM={key:0,class:"live-indicator","data-testid":"video-live-indicator","aria-label":"Live stream"},TM={key:2,class:"video-loading","data-testid":"video-loading",role:"status","aria-label":"Loading video"},IM={key:3,class:"video-error","data-testid":"video-error",role:"alert"},BM={key:5,class:"gesture-zones","data-testid":"video-gesture-zones"},MM=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:f,bufferedRanges:m,isLoading:p,error:h,status:v,currentPlaybackUrl:w,tokenExpiresAt:x,play:T,pause:_,seek:g,toggleMute:E,setVolume:S,toggleFullscreen:N,togglePlayPause:V,skipForward:A,skipBackward:j,retry:C,refreshToken:$,setApiClient:y,shouldRefreshToken:R,setupLiveStream:L}=xM({...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 U(){await $()}const z=e.computed(()=>{const X=["video-player-container"];return t.className&&X.push(t.className),f.value&&X.push("fullscreen"),t.isLive&&X.push("is-live"),s.value&&X.push("is-playing"),p.value&&X.push("is-loading"),X}),I=e.computed(()=>{var X,oe;if(t.poster)return t.poster;if((X=t.media)!=null&&X.poster_url)return t.media.poster_url;if((oe=t.media)!=null&&oe.thumbnail_url)return t.media.thumbnail_url});function P(X){const oe=X.target;n("loadedmetadata",{duration:oe.duration,width:oe.videoWidth,height:oe.videoHeight})}function Z(X){const oe=X.target;l.value=oe.currentTime,n("timeupdate",oe.currentTime)}function K(){s.value=!0,n("play")}function ve(){s.value=!1,n("pause")}function Ve(){s.value=!1,n("ended")}function ne(X){const oe=X.target;let ce="Failed to load video";if(oe.error)switch(oe.error.code){case oe.error.MEDIA_ERR_ABORTED:ce="Video playback aborted";break;case oe.error.MEDIA_ERR_NETWORK:ce="Network error while loading video";break;case oe.error.MEDIA_ERR_DECODE:ce="Video decoding error";break;case oe.error.MEDIA_ERR_SRC_NOT_SUPPORTED:ce="Video format not supported";break}h.value=ce,n("error",ce)}function ae(X){const oe=X.target;m.value=oe.buffered,n("progress",oe.buffered)}function F(){p.value=!0}function B(){p.value=!1}e.watch(()=>t.apiClient,X=>{X&&y(X)},{immediate:!0}),e.watch(()=>t.playbackUrl,X=>{typeof X=="string"&&X.length>0&&(w.value=X)},{immediate:!0}),e.watch(()=>{var X;return(X=t.media)==null?void 0:X.token_expires_at},X=>{if(!X){x.value=null;return}const oe=new Date(X);x.value=Number.isNaN(oe.getTime())?null:oe},{immediate:!0}),e.watch(()=>{var X;return(X=t.media)==null?void 0:X.playback_url},async(X,oe)=>{if(t.playbackUrl||!X||X===oe)return;const ce=i.value;if(!ce||t.isLive){w.value=X;return}const je=!ce.paused,he=ce.currentTime;w.value=X,await e.nextTick();try{ce.currentTime=he}catch{}je&&await T()},{immediate:!0});let O=null;return e.watch(()=>t.isLive,async X=>{var ce;if(!X)return;const oe=t.playbackUrl||((ce=t.media)==null?void 0:ce.playback_url)||"";oe&&await L(oe)},{immediate:!0}),e.onMounted(()=>{var X;(X=t.media)!=null&&X.provider&&t.media.provider!=="local"&&(O=setInterval(()=>{R()&&U()},3e4)),W.isPlatform("mobile")&&t.showCustomControls}),e.onUnmounted(()=>{O&&clearInterval(O)}),(X,oe)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-player-container",z.value]),"data-testid":"video-player"},[X.isLive?(e.openBlock(),e.createElementBlock("div",CM,[e.createElementVNode("video",{ref_key:"liveVideoEl",ref:r,controls:X.controls&&!X.showCustomControls,autoplay:!0,muted:e.unref(u),onPlay:K,onPause:ve,onError:ne,playsinline:"",class:"video-element","data-testid":"video-element"},null,40,VM),e.unref(v)==="live"?(e.openBlock(),e.createElementBlock("div",NM,[...oe[3]||(oe[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(w),poster:I.value,controls:X.controls&&!X.showCustomControls,autoplay:X.autoplay,muted:e.unref(u),loop:X.loop,preload:X.preload,onLoadedmetadata:P,onTimeupdate:Z,onPlay:K,onPause:ve,onEnded:Ve,onError:ne,onProgress:ae,onWaiting:F,onCanplay:B,playsinline:"",class:"video-element","data-testid":"video-element"},null,40,SM)),e.unref(p)?(e.openBlock(),e.createElementBlock("div",TM,[e.createVNode(e.unref(W.IonSpinner),{name:"crescent"})])):e.createCommentVNode("",!0),e.unref(h)?(e.openBlock(),e.createElementBlock("div",IM,[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Hl),"aria-hidden":"true"},null,8,["icon"]),e.createElementVNode("p",null,e.toDisplayString(e.unref(h)),1),e.createVNode(e.unref(W.IonButton),{size:"small",onClick:e.unref(C),"data-testid":"btn-video-retry","aria-label":"Retry loading video"},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{icon:e.unref(Jn),slot:"start","aria-hidden":"true"},null,8,["icon"]),oe[4]||(oe[4]=e.createTextVNode(" Retry ",-1))]),_:1},8,["onClick"])])):e.createCommentVNode("",!0),X.showCustomControls&&!e.unref(h)?(e.openBlock(),e.createBlock(EM,{key:4,playing:e.unref(s),currentTime:e.unref(l),duration:e.unref(d),buffered:e.unref(m),volume:e.unref(c),muted:e.unref(u),fullscreen:e.unref(f),isLive:X.isLive,onPlay:e.unref(T),onPause:e.unref(_),onSeek:e.unref(g),onToggleMute:e.unref(E),onSetVolume:e.unref(S),onToggleFullscreen:e.unref(N),class:"custom-controls"},null,8,["playing","currentTime","duration","buffered","volume","muted","fullscreen","isLive","onPlay","onPause","onSeek","onToggleMute","onSetVolume","onToggleFullscreen"])):e.createCommentVNode("",!0),X.enableGestures&&!e.unref(h)?(e.openBlock(),e.createElementBlock("div",BM,[e.createElementVNode("div",{class:"gesture-left","data-testid":"video-gesture-skip-back","aria-label":"Double tap to skip backward",onDblclick:oe[0]||(oe[0]=(...ce)=>e.unref(j)&&e.unref(j)(...ce))},null,32),e.createElementVNode("div",{class:"gesture-center","data-testid":"video-gesture-play-pause","aria-label":"Tap to play or pause",onClick:oe[1]||(oe[1]=(...ce)=>e.unref(V)&&e.unref(V)(...ce))}),e.createElementVNode("div",{class:"gesture-right","data-testid":"video-gesture-skip-forward","aria-label":"Double tap to skip forward",onDblclick:oe[2]||(oe[2]=(...ce)=>e.unref(A)&&e.unref(A)(...ce))},null,32)])):e.createCommentVNode("",!0)],2))}}),Dp=Be(MM,[["__scopeId","data-v-b8db4951"]]),FM=zr.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(L=>L.status==="live")),d=e.computed(()=>r.value.filter(L=>L.processing_status==="processing"));function c(L){o.value.set(L.uuid,L)}function u(L,U){const z=o.value.get(L);z&&o.value.set(L,{...z,...U})}function f(L){o.value.delete(L)}function m(L){return o.value.get(L)}function p(L){a.value.set(L.id,L)}function h(L,U){const z=a.value.get(L);z&&a.value.set(L,{...z,...U})}function v(L,U){const z=a.value.get(L);z&&a.value.set(L,{...z,status:U.status,viewer_count:U.viewer_count,peak_viewers:U.peak_viewers})}function w(L){a.value.delete(L)}function x(L){return a.value.get(L)}function T(L){return s.value.find(U=>U.media_uuid===L)}function _(L){t.value.set(L.id,L)}function g(L,U){const z=t.value.get(L);z&&t.value.set(L,{...z,...U})}function E(L){t.value.delete(L)}function S(L){return t.value.get(L)}function N(L){return Array.from(t.value.values()).filter(U=>U.media_uuid===L)}function V(L){n.value=L}function A(L){n.value&&(n.value={...n.value,...L})}function j(){n.value=null}function C(L){i.value=L}function $(){o.value.clear(),a.value.clear(),t.value.clear(),n.value=null,i.value=!1}function y(L){o.value.clear(),L.forEach(U=>{o.value.set(U.uuid,U)})}function R(L){a.value.clear(),L.forEach(U=>{a.value.set(U.id,U)})}return{videos:o,liveStreams:a,exportJobs:t,currentEditorState:n,isProcessing:i,allVideos:r,allLiveStreams:s,activeLiveStreams:l,processingVideos:d,setVideo:c,updateVideo:u,removeVideo:f,getVideo:m,setLiveStream:p,updateLiveStream:h,updateLiveStreamStats:v,removeLiveStream:w,getLiveStream:x,getLiveStreamByMedia:T,addExportJob:_,updateExportJob:g,removeExportJob:E,getExportJob:S,getExportJobsByMedia:N,setEditorState:V,updateEditorState:A,clearEditorState:j,setProcessing:C,clearAll:$,loadVideos:y,loadLiveStreams:R}});let Rn=null;function $M(o){Rn=o}const or={post:async(o,a)=>{if(!Rn)throw new Error("HTTP client not configured");return await Rn(`/api/v1/video${o}`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json"}})},get:async o=>{if(!Rn)throw new Error("HTTP client not configured");return await Rn(`/api/v1/video${o}`)},delete:async o=>{if(!Rn)throw new Error("HTTP client not configured");return await Rn(`/api/v1/video${o}`,{method:"DELETE"})}};function ir(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 Js(o,a){return o instanceof Error&&o.message?o.message:a}function DM(o){const a=FM(),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),f=e.ref(0);let m;const p=e.computed(()=>c.value?Math.floor((new Date().getTime()-c.value.getTime())/1e3):0),h=e.computed(()=>{var j;if(!((j=t.value)!=null&&j.playback_url))return null;const A=new URL(t.value.playback_url);return A.searchParams.set("live","true"),n.value&&A.searchParams.set("latency","low"),A.toString()}),v=e.computed(()=>{var A;return((A=t.value)==null?void 0:A.status)==="live"}),w=e.computed(()=>{var A;return((A=t.value)==null?void 0:A.status)==="idle"}),x=e.computed(()=>{var A;return((A=t.value)==null?void 0:A.status)==="ended"});async function T(A={}){s.value=!0,d.value=null;try{const j=await or.post("/live",{title:r.value||A.title||"Live Stream",low_latency:A.low_latency??n.value,auto_record:A.auto_record??i.value,...A}),C=ir(j);return t.value=C,a.setLiveStream(C),S(),C}catch(j){throw d.value=Js(j,"Failed to create stream"),j instanceof Error?j:new Error(d.value)}finally{s.value=!1}}async function _(){if(!t.value)throw new Error("No active stream");l.value=!0,d.value=null;try{const A=await or.post(`/live/${t.value.id}/end`),j=ir(A,t.value);return t.value=j,a.setLiveStream(j),N(),j}catch(A){throw d.value=Js(A,"Failed to end stream"),A instanceof Error?A:new Error(d.value)}finally{l.value=!1}}async function g(){if(t.value)try{const A=await or.get(`/live/${t.value.id}`),j=ir(A,t.value);u.value=j.viewer_count,f.value=j.peak_viewers,t.value=j;const C={status:j.status,viewer_count:j.viewer_count,peak_viewers:j.peak_viewers};j.started_at&&(C.started_at=j.started_at),j.ended_at&&(C.ended_at=j.ended_at),a.updateLiveStreamStats(j.id,C),j.status==="live"&&!c.value&&j.started_at&&(c.value=new Date(j.started_at)),j.status==="ended"&&N()}catch{}}async function E(A){try{const j=await or.get(`/live/${A}`),C=ir(j,t.value);return{rtmp_url:C.rtmp_url,stream_key:C.stream_key,playback_url:C.playback_url||""}}catch(j){throw d.value=Js(j,"Failed to get stream credentials"),j instanceof Error?j:new Error(d.value)}}function S(A=5e3){N(),m=window.setInterval(()=>{g()},A)}function N(){m!==void 0&&(clearInterval(m),m=void 0)}async function V(){if(!o)return;const A=a.getLiveStreamByMedia(o);A&&(t.value=A,u.value=A.viewer_count,f.value=A.peak_viewers,A.status==="live"&&(S(),A.started_at&&(c.value=new Date(A.started_at))))}return o&&V(),e.onUnmounted(()=>{N()}),{stream:t,lowLatency:n,autoRecord:i,streamTitle:r,isCreating:s,isEnding:l,error:d,streamDuration:p,viewerCount:u,peakViewers:f,playbackUrl:h,isLive:v,isIdle:w,hasEnded:x,createStream:T,endStream:_,refreshStreamStatus:g,getStreamCredentials:E,startStatusPolling:S,stopStatusPolling:N}}const RM={class:"stream-status"},AM={class:"flex items-center justify-between"},LM={class:"flex items-center gap-3"},PM={key:0,class:"flex items-center"},UM={key:2,class:"text-sm text-gray-600"},OM={key:0,class:"flex items-center gap-2"},zM={class:"text-sm font-medium text-gray-700"},jM={key:0,class:"text-xs text-gray-500"},WM=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",RM,[e.createElementVNode("div",AM,[e.createElementVNode("div",LM,[r.status==="live"?(e.openBlock(),e.createElementBlock("div",PM,[...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",UM,e.toDisplayString(i.value),1)):e.createCommentVNode("",!0)]),r.viewers!==void 0?(e.openBlock(),e.createElementBlock("div",OM,[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",zM,e.toDisplayString(r.viewers)+" "+e.toDisplayString(r.viewers===1?"viewer":"viewers"),1),r.peakViewers>r.viewers?(e.openBlock(),e.createElementBlock("span",jM," (Peak: "+e.toDisplayString(r.peakViewers)+") ",1)):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)])]))}}),HM=Be(WM,[["__scopeId","data-v-1d09c19f"]]),ZM={class:"stream-credentials"},XM={class:"space-y-3"},GM={class:"credential-field"},JM={class:"flex gap-2"},KM=["value"],qM={class:"credential-field"},YM={class:"flex gap-2"},QM=["value","type"],e5=["aria-label"],t5={key:0,class:"w-4 h-4 text-gray-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},a5={key:1,class:"w-4 h-4 text-gray-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},n5={key:0,class:"mt-2 text-sm text-green-600"},o5=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",ZM,[u[8]||(u[8]=e.createElementVNode("h4",{class:"text-sm font-medium text-gray-700 mb-3"},"Stream Settings",-1)),e.createElementVNode("div",XM,[e.createElementVNode("div",GM,[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",JM,[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,KM),e.createElementVNode("button",{onClick:u[0]||(u[0]=f=>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",qM,[u[7]||(u[7]=e.createElementVNode("label",{class:"block text-xs font-medium text-gray-500 mb-1"},"Stream Key",-1)),e.createElementVNode("div",YM,[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,QM),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",a5,[...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",t5,[...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,e5),e.createElementVNode("button",{onClick:u[1]||(u[1]=f=>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",n5,e.toDisplayString(r.value)+" copied to clipboard! ",1)):e.createCommentVNode("",!0)]),_:1})]))}}),i5=Be(o5,[["__scopeId","data-v-306d92f6"]]),r5={class:"live-stream-manager","data-testid":"live-stream-manager"},s5={key:0,class:"stream-setup"},l5={class:"space-y-4"},d5={class:"flex items-center justify-between p-4 bg-gray-50 rounded-lg"},c5={class:"flex items-center justify-between p-4 bg-gray-50 rounded-lg"},u5=["disabled"],m5={key:0},p5={key:1,class:"flex items-center justify-center"},f5={key:1,class:"stream-active space-y-6"},h5={key:1,class:"video-preview"},v5={key:2,class:"analytics-panel"},g5={class:"grid grid-cols-2 gap-4"},b5={class:"bg-gray-50 p-3 rounded"},y5={class:"text-2xl font-bold text-gray-900"},w5={class:"bg-gray-50 p-3 rounded"},k5={class:"text-2xl font-bold text-gray-900"},_5={class:"stream-controls flex gap-3"},E5=["disabled"],x5={key:0},S5={key:1},C5={key:2,class:"mt-4 p-4 bg-red-50 border border-red-200 rounded-lg"},V5={class:"text-red-600 text-sm"},N5=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&&$M(t.httpClient);const{stream:i,lowLatency:r,autoRecord:s,streamTitle:l,isCreating:d,isEnding:c,error:u,createStream:f,endStream:m,streamDuration:p,playbackUrl:h,refreshStreamStatus:v}=DM(t.mediaUuid),w=e.ref(!1);async function x(){var S;try{const N=await f({title:l.value,low_latency:r.value,auto_record:s.value});n("stream-created",N),(S=t.onStreamCreated)==null||S.call(t,N)}catch(N){n("error",N)}}async function T(){var S;try{const N=await m();n("stream-ended",N),(S=t.onStreamEnded)==null||S.call(t,N)}catch(N){n("error",N)}}function _(){i.value=null,l.value="",w.value=!1,u.value=null}async function g(S,N){try{await navigator.clipboard.writeText(S)}catch{}}let E;return e.onMounted(()=>{var S;((S=i.value)==null?void 0:S.status)==="live"&&(E=window.setInterval(()=>{v()},5e3))}),e.onUnmounted(()=>{E&&clearInterval(E)}),(S,N)=>(e.openBlock(),e.createElementBlock("div",r5,[e.unref(i)?(e.openBlock(),e.createElementBlock("div",f5,[e.createVNode(HM,{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(i5,{key:0,"rtmp-url":e.unref(i).rtmp_url,"stream-key":e.unref(i).stream_key,onCopy:g},null,8,["rtmp-url","stream-key"])):e.createCommentVNode("",!0),e.unref(h)?(e.openBlock(),e.createElementBlock("div",h5,[N[9]||(N[9]=e.createElementVNode("h4",{class:"text-sm font-medium text-gray-700 mb-2"},"Live Preview",-1)),e.createVNode(Dp,{"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",v5,[N[12]||(N[12]=e.createElementVNode("h4",{class:"text-sm font-medium text-gray-700 mb-3"},"Live Analytics",-1)),e.createElementVNode("div",g5,[e.createElementVNode("div",b5,[e.createElementVNode("div",y5,e.toDisplayString(e.unref(i).viewer_count),1),N[10]||(N[10]=e.createElementVNode("div",{class:"text-xs text-gray-500"},"Current Viewers",-1))]),e.createElementVNode("div",w5,[e.createElementVNode("div",k5,e.toDisplayString(e.unref(i).peak_viewers),1),N[11]||(N[11]=e.createElementVNode("div",{class:"text-xs text-gray-500"},"Peak Viewers",-1))])])])):e.createCommentVNode("",!0),e.createElementVNode("div",_5,[e.unref(i).status==="idle"?(e.openBlock(),e.createElementBlock("button",{key:0,onClick:N[3]||(N[3]=V=>w.value=!w.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(w.value?"Hide":"Show")+" Credentials ",1)):e.createCommentVNode("",!0),e.unref(i).status==="live"?(e.openBlock(),e.createElementBlock("button",{key:1,onClick:T,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",S5,"Ending...")):(e.openBlock(),e.createElementBlock("span",x5,"End Stream"))],8,E5)):e.createCommentVNode("",!0),e.unref(i).status==="ended"?(e.openBlock(),e.createElementBlock("button",{key:2,onClick:_,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",s5,[N[8]||(N[8]=e.createElementVNode("h3",{class:"text-lg font-semibold mb-4"},"Start Live Stream",-1)),e.createElementVNode("div",l5,[e.createElementVNode("div",d5,[N[4]||(N[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":N[0]||(N[0]=V=>e.isRef(r)?r.value=V: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",c5,[N[5]||(N[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":N[1]||(N[1]=V=>e.isRef(s)?s.value=V: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,[N[6]||(N[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":N[2]||(N[2]=V=>e.isRef(l)?l.value=V: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:x,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",p5,[...N[7]||(N[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",m5,"Create Stream"))],8,u5)])])),e.unref(u)?(e.openBlock(),e.createElementBlock("div",C5,[e.createElementVNode("p",V5,e.toDisplayString(e.unref(u)),1)])):e.createCommentVNode("",!0)]))}}),T5=Be(N5,[["__scopeId","data-v-26291f6f"]]),I5={class:"album-tree-node"},B5=["data-album-id","draggable","aria-selected","aria-expanded"],M5={key:1,class:"album-node__chevron-placeholder"},F5={key:2,"data-testid":"media-count",class:"album-node__count"},$5={key:0,class:"album-tree-node__children",role:"group"},D5=16,R5=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*D5}px`),c=e.computed(()=>{var _;return((_=t.dragState)==null?void 0:_.draggedAlbumId)===t.album.id}),u=e.computed(()=>{var _;return((_=t.dragState)==null?void 0:_.dropTargetId)===t.album.id}),f=e.computed(()=>{var _;return(_=t.dragState)!=null&&_.draggedAlbumId?t.dragState.draggedAlbumId===t.album.id:!1}),m=e.computed(()=>{const _=["album-node"];return r.value&&_.push("album-node--selected"),s.value&&_.push("album-node--focused"),t.compact&&_.push("album-node--compact"),c.value&&_.push("album-node--dragging"),u.value&&_.push("album-node--drop-target"),f.value&&_.push("album-node--invalid-drop"),_});function p(){n("select",t.album)}function h(_){_.stopPropagation(),n("toggle-expand",t.album.id)}function v(_){t.draggable&&(_.dataTransfer&&(_.dataTransfer.setData("text/plain",t.album.id),_.dataTransfer.effectAllowed="move"),n("drag-start",t.album.id))}function w(_){t.draggable&&(_.preventDefault(),_.dataTransfer&&(_.dataTransfer.dropEffect="move"),n("drag-over",t.album.id))}function x(){n("drag-leave",t.album.id)}function T(_){t.draggable&&(_.preventDefault(),n("drop",t.album.id))}return(_,g)=>{var S;const E=e.resolveComponent("AlbumTreeNode",!0);return e.openBlock(),e.createElementBlock("div",I5,[e.createElementVNode("div",{"data-testid":"album-node","data-album-id":_.album.id,class:e.normalizeClass(m.value),style:e.normalizeStyle({paddingLeft:d.value}),draggable:_.draggable,role:"treeitem","aria-selected":r.value,"aria-expanded":l.value?i.value:void 0,onDragstart:v,onDragover:w,onDragleave:x,onDrop:T},[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(W.IonIcon),{icon:i.value?e.unref(Sh):e.unref(Ch)},null,8,["icon"])])):(e.openBlock(),e.createElementBlock("span",M5)),e.createVNode(e.unref(W.IonIcon),{icon:e.unref($h),class:"album-node__icon"},null,8,["icon"]),e.createElementVNode("span",{"data-testid":"album-name",class:"album-node__name",onClick:p},e.toDisplayString(_.album.name),1),_.showMediaCount?(e.openBlock(),e.createElementBlock("span",F5,e.toDisplayString(_.album.media_count),1)):e.createCommentVNode("",!0)],46,B5),i.value&&((S=_.album.children)!=null&&S.length)?(e.openBlock(),e.createElementBlock("div",$5,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(_.album.children,N=>(e.openBlock(),e.createBlock(E,{key:N.id,album:N,depth:_.depth+1,"selected-id":_.selectedId,"expanded-ids":_.expandedIds,"focused-id":_.focusedId,draggable:_.draggable,"show-media-count":_.showMediaCount,compact:_.compact,onSelect:g[0]||(g[0]=V=>n("select",V)),onToggleExpand:g[1]||(g[1]=V=>n("toggle-expand",V))},null,8,["album","depth","selected-id","expanded-ids","focused-id","draggable","show-media-count","compact"]))),128))])):e.createCommentVNode("",!0)])}}}),A5=Be(R5,[["__scopeId","data-v-76be65a6"]]),hs=zr.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 g=new Map;return o.value.forEach(E=>g.set(E.id,E)),g}),s=e.computed(()=>o.value.filter(g=>g.parent_id===null));async function l(g){t.value=!0,n.value=null;try{const E=(g==null?void 0:g.parent_id)??null,S=E?`/api/v1/albums?parent_id=${E}`:"/api/v1/albums?parent_id=null",N=await fetch(S);if(!N.ok)throw new Error("Failed to fetch albums");((await N.json()).data||[]).forEach(j=>{const C=o.value.findIndex($=>$.id===j.id);C>=0?o.value[C]=j:o.value.push(j)}),E!==null&&i.value.add(E)}catch(E){n.value=E instanceof Error?E.message:"Unknown error"}finally{t.value=!1}}async function d(g){t.value=!0,n.value=null;try{const E=await fetch(`/api/v1/albums/${g}`);if(!E.ok)throw new Error("Failed to fetch album");const N=(await E.json()).data,V=o.value.findIndex(A=>A.id===N.id);return V>=0?o.value[V]=N:o.value.push(N),N}catch(E){throw n.value=E instanceof Error?E.message:"Unknown error",E}finally{t.value=!1}}async function c(g){t.value=!0,n.value=null;try{const E=await fetch(`/api/v1/albums/${g}/media`);if(!E.ok)throw new Error("Failed to fetch album media");const N=(await E.json()).data||[];return a.value.set(g,N),N}catch(E){throw n.value=E instanceof Error?E.message:"Unknown error",E}finally{t.value=!1}}async function u(g,E){t.value=!0,n.value=null;try{if(!(await fetch(`/api/v1/albums/${g}/media/reorder`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({media_ids:E})})).ok)throw new Error("Failed to reorder album media");const N=a.value.get(g)||[],V=E.map(A=>N.find(j=>j.uuid===A)).filter(A=>A!==void 0);a.value.set(g,V)}catch(S){throw n.value=S instanceof Error?S.message:"Unknown error",S}finally{t.value=!1}}async function f(g){t.value=!0,n.value=null;try{const E=await fetch("/api/v1/albums",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(g)});if(!E.ok)throw new Error("Failed to create album");const N=(await E.json()).data;return o.value.push(N),N}catch(E){throw n.value=E instanceof Error?E.message:"Unknown error",E}finally{t.value=!1}}async function m(g,E){t.value=!0,n.value=null;try{const S=await fetch(`/api/v1/albums/${g}`,{method:"PATCH",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(E)});if(!S.ok)throw new Error("Failed to update album");const V=(await S.json()).data,A=o.value.findIndex(j=>j.id===V.id);return A>=0&&(o.value[A]=V),V}catch(S){throw n.value=S instanceof Error?S.message:"Unknown error",S}finally{t.value=!1}}async function p(g){t.value=!0,n.value=null;try{if(!(await fetch(`/api/v1/albums/${g}`,{method:"DELETE",headers:{"Content-Type":"application/json"},credentials:"include"})).ok)throw new Error("Failed to delete album");const S=o.value.findIndex(N=>N.id===g);S>=0&&o.value.splice(S,1),a.value.delete(g)}catch(E){throw n.value=E instanceof Error?E.message:"Unknown error",E}finally{t.value=!1}}function h(g){return o.value.filter(E=>E.parent_id===g)}function v(g){return i.value.has(g)}function w(g){return a.value.get(g)||[]}async function x(g,E){const S=o.value.findIndex(V=>V.id===g);if(S<0)return;const N=o.value[S];o.value[S]={...N,parent_id:E};try{if(!(await fetch(`/api/v1/albums/${g}/move`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({parent_id:E})})).ok)throw new Error("Failed to move album")}catch(V){throw o.value[S]=N,n.value=V instanceof Error?V.message:"Unknown error",V instanceof Error?V:new Error("Failed to move album")}}function T(g){o.value=g}function _(){o.value=[],a.value.clear(),t.value=!1,n.value=null,i.value.clear()}return{albums:o,albumMedia:a,loading:t,error:n,childrenLoadedById:i,albumsById:r,rootAlbums:s,fetchAlbums:l,fetchAlbum:d,fetchAlbumMedia:c,reorderAlbumMedia:u,createAlbum:f,updateAlbum:m,deleteAlbum:p,getChildrenOf:h,childrenLoaded:v,getAlbumMedia:w,moveAlbum:x,setAlbums:T,reset:_}});function Rp(){const o=hs(),{albums:a,albumsById:t,rootAlbums:n,loading:i,error:r}=zr.storeToRefs(o);async function s(u){await o.fetchAlbums(u)}function l(u){return o.getChildrenOf(u)}function d(u){return o.childrenLoaded(u)}async function c(u,f){await o.moveAlbum(u,f)}return{albums:a,albumsById:t,rootAlbums:n,loading:i,error:r,fetchAlbums:s,getChildrenOf:l,childrenLoaded:d,moveAlbum:c}}function Ap(o){const{childrenByParentId:a,onMove:t}=o,n=e.ref({isDragging:!1,draggedAlbumId:null,dropTargetId:null,dropPosition:null});function i(f,m){if(f===m)return!0;const p=new Set,h=[f];for(;h.length>0;){const v=h.shift();if(!v||p.has(v))continue;p.add(v);const w=a.get(v)||[];for(const x of w){if(x===m)return!0;h.push(x)}}return!1}function r(f,m){return f===m?!1:m===null?!0:!i(f,m)}function s(f){n.value={isDragging:!0,draggedAlbumId:f,dropTargetId:null,dropPosition:null}}function l(){n.value={isDragging:!1,draggedAlbumId:null,dropTargetId:null,dropPosition:null}}function d(f){n.value.dropTargetId=f}function c(){n.value.dropTargetId=null,n.value.dropPosition=null}async function u(){const{draggedAlbumId:f,dropTargetId:m}=n.value;if(!f){l();return}if(!r(f,m)){l();return}try{await t(f,m)}finally{l()}}return{dragState:n,isDescendant:i,canDropOn:r,startDrag:s,endDrag:l,setDropTarget:d,clearDropTarget:c,executeDrop:u}}const L5={key:0,"data-testid":"loading-spinner",class:"album-tree__loading"},P5={key:1,"data-testid":"error-state",class:"album-tree__error"},U5={key:2,"data-testid":"empty-state",class:"album-tree__empty"},O5={key:3,class:"album-tree__content",role:"group"},z5=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}},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),{albums:d,rootAlbums:c,loading:u,error:f,fetchAlbums:m,getChildrenOf:p,childrenLoaded:h,moveAlbum:v}=Rp(),w=e.shallowRef(new Set(n.expandedIds)),x=e.ref(n.modelValue??null),T=e.ref(null),_=new Map,g=new Map;function E(F){_.clear(),g.clear();for(const B of F){_.set(B.id,B);const O=B.parent_id??null,X=g.get(O)??[];X.push(B.id),g.set(O,X)}}e.watch(d,F=>{E(F)},{immediate:!0});const{dragState:S,canDropOn:N,startDrag:V,endDrag:A,setDropTarget:j,clearDropTarget:C,executeDrop:$}=Ap({childrenByParentId:g,onMove:async(F,B)=>{await v(F,B),i("album-moved",{albumId:F,newParentId:B})}});e.watch(()=>n.modelValue,F=>{x.value=F??null}),e.watch(()=>n.expandedIds,F=>{w.value=new Set(F)}),e.onMounted(async()=>{await m({parent_id:null})});const y=e.computed(()=>c.value.map(F=>R(F)));function R(F){if(!w.value.has(F.id))return F;const B=p(F.id);return{...F,children:B.map(O=>R(O))}}const L=e.computed(()=>{const F=[];function B(O){var X;for(const oe of O)F.push(oe),w.value.has(oe.id)&&((X=oe.children)!=null&&X.length)&&B(oe.children)}return B(y.value),F});function U(F){var X;if(!L.value.length)return;const B=T.value?L.value.findIndex(oe=>oe.id===T.value):-1,O=B>=0?L.value[B]:null;switch(F.key){case"ArrowDown":F.preventDefault(),B<L.value.length-1?T.value=L.value[B+1].id:B===-1&&L.value.length>0&&(T.value=L.value[0].id);break;case"ArrowUp":F.preventDefault(),B>0&&(T.value=L.value[B-1].id);break;case"ArrowRight":F.preventDefault(),O&&(O.children_count>0&&!w.value.has(O.id)?z(O.id):w.value.has(O.id)&&((X=O.children)!=null&&X.length)&&(T.value=O.children[0].id));break;case"ArrowLeft":F.preventDefault(),O&&(w.value.has(O.id)&&O.children_count>0?z(O.id):O.parent_id&&(T.value=O.parent_id));break;case"Enter":case" ":F.preventDefault(),O&&I(O);break;case"Home":F.preventDefault(),L.value.length>0&&(T.value=L.value[0].id);break;case"End":F.preventDefault(),L.value.length>0&&(T.value=L.value[L.value.length-1].id);break}}async function z(F){w.value.has(F)?(w.value.delete(F),i("album-collapsed",F)):(h(F)||await m({parent_id:F}),w.value.add(F),i("album-expanded",F))}function I(F){x.value=F.id,i("update:modelValue",F.id),i("album-selected",F)}function P(F){n.draggable&&V(F)}function Z(F){var O;if(!n.draggable)return;const B=(O=S.value)==null?void 0:O.draggedAlbumId;B&&(j(F),N(B,F))}function K(){n.draggable&&C()}async function ve(F){n.draggable&&(j(F),await $())}function Ve(F){n.draggable&&(F.preventDefault(),j(null))}async function ne(F){n.draggable&&(F.preventDefault(),j(null),await $())}function ae(){A()}return a({focusedId:T}),(F,B)=>(e.openBlock(),e.createElementBlock("div",{class:"album-tree","data-testid":"album-tree",tabindex:"0",role:"tree","aria-label":"Album tree",onKeydown:U,onDragover:Ve,onDrop:ne,onDragend:ae},[e.unref(u)?(e.openBlock(),e.createElementBlock("div",L5,[e.createVNode(e.unref(W.IonSpinner),{name:"crescent"})])):e.unref(f)?(e.openBlock(),e.createElementBlock("div",P5,[e.createElementVNode("p",null,e.toDisplayString(e.unref(f)),1)])):e.unref(c).length?(e.openBlock(),e.createElementBlock("div",O5,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(y.value,O=>(e.openBlock(),e.createBlock(A5,{key:O.id,album:O,depth:0,"selected-id":x.value,"expanded-ids":w.value,"focused-id":T.value,draggable:r.value,"drag-state":r.value?e.unref(S):null,"show-media-count":s.value,compact:l.value,onSelect:I,onToggleExpand:z,onDragStart:P,onDragOver:Z,onDragLeave:K,onDrop:ve},null,8,["album","selected-id","expanded-ids","focused-id","draggable","drag-state","show-media-count","compact"]))),128))])):(e.openBlock(),e.createElementBlock("div",U5,[B[0]||(B[0]=e.createElementVNode("p",null,"No albums yet",-1)),e.renderSlot(F.$slots,"empty-action",{},void 0,!0)]))],32))}}),Lp=Be(z5,[["__scopeId","data-v-ae3dea7a"]]),j5=300,W5=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<j5){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 f(){n("close")}function m(){n("close")}return(p,h)=>(e.openBlock(),e.createBlock(e.unref(W.IonModal),{"is-open":p.isOpen,class:"album-browser-modal",onDidDismiss:m},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonHeader),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonToolbar),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonTitle),null,{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(p.title),1)]),_:1}),e.createVNode(e.unref(W.IonButtons),{slot:"end"},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonButton),{"data-testid":"cancel-button",onClick:f},{default:e.withCtx(()=>[...h[1]||(h[1]=[e.createTextVNode(" Cancel ",-1)])]),_:1})]),_:1})]),_:1})]),_:1}),e.createVNode(e.unref(W.IonContent),{class:"album-browser-content"},{default:e.withCtx(()=>[e.createVNode(Lp,{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(W.IonFooter),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonToolbar),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonButtons),{slot:"end"},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonButton),{fill:"clear",onClick:f},{default:e.withCtx(()=>[...h[2]||(h[2]=[e.createTextVNode(" Cancel ",-1)])]),_:1}),e.createVNode(e.unref(W.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"]))}}),Pp=Be(W5,[["__scopeId","data-v-21676ec1"]]),H5={class:"ion-padding-start text-sm"},Z5={class:"ion-padding-start text-sm"},X5={key:1},G5={key:1,class:"album-manager-inline rounded-lg border border-gray-200 bg-white p-4"},J5={class:"flex items-center justify-between gap-3 pb-3"},K5={class:"text-base font-semibold text-gray-900"},q5={class:"ion-padding-start text-sm"},Y5={class:"ion-padding-start text-sm"},Q5={class:"flex justify-between pt-2"},eF={key:1},Go=255,Jo=1e3,tF=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=hs(),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),f=e.ref(!1),m=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>Go?`Name must be ${Go} characters or less`:null:"Name is required":null),w=e.computed(()=>c.value.description&&d.value.description.length>Jo?`Description must be ${Jo} characters or less`:null),x=e.computed(()=>{const U=d.value.name.trim().length>0,z=d.value.name.length<=Go,I=d.value.description.length<=Jo;return U&&z&&I&&!p.value}),T=e.computed(()=>{var U;return((U=u.value)==null?void 0:U.name)??"None (Root)"}),_=e.computed(()=>m.value?m.value.children_count===0&&m.value.media_count===0:!1),g=e.computed(()=>m.value?m.value.children_count>0?"Cannot delete album with child albums. Move or delete children first.":m.value.media_count>0?"Cannot delete album with media. Remove media first.":`Are you sure you want to delete "${m.value.name}"? This action cannot be undone.`:"");e.onMounted(async()=>{t.albumId&&await E()});async function E(){if(t.albumId)try{const U=await i.fetchAlbum(t.albumId);m.value=U,d.value={name:U.name,description:U.description??"",parent_id:U.parent_id},U.parent_id&&(u.value={id:U.parent_id,name:"Parent Album"})}catch(U){n("error",U)}}function S(){c.value.name=!0}function N(){c.value.description=!0}function V(){f.value=!0}function A(U){u.value={id:U.id,name:U.name},d.value.parent_id=U.id,f.value=!1}function j(){f.value=!1}function C(){n("close")}function $(){n("close")}async function y(){if(c.value.name=!0,c.value.description=!0,!(!x.value||p.value)){p.value=!0;try{const U={name:d.value.name.trim(),description:d.value.description.trim(),parent_id:d.value.parent_id};if(r.value&&t.albumId){const z=await i.updateAlbum(t.albumId,U);n("updated",z)}else{const z=await i.createAlbum(U);n("created",z)}n("close")}catch(U){n("error",U)}finally{p.value=!1}}}function R(){_.value&&(h.value=!0)}async function L(U){var I;if((((I=U.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(P){n("error",P)}finally{p.value=!1,h.value=!1}}}return(U,z)=>(e.openBlock(),e.createElementBlock(e.Fragment,null,[U.mode==="modal"?(e.openBlock(),e.createBlock(e.unref(W.IonModal),{key:0,"is-open":U.isOpen,class:"album-manager-modal",onDidDismiss:$},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonHeader),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonToolbar),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonTitle),null,{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(s.value),1)]),_:1}),e.createVNode(e.unref(W.IonButtons),{slot:"end"},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonButton),{"data-testid":"cancel-btn",fill:"clear",onClick:C},{default:e.withCtx(()=>[...z[4]||(z[4]=[e.createTextVNode(" Cancel ",-1)])]),_:1})]),_:1})]),_:1})]),_:1}),e.createVNode(e.unref(W.IonContent),{class:"album-manager-content"},{default:e.withCtx(()=>[e.createElementVNode("form",{"data-testid":"album-form",class:"p-4 space-y-3",onSubmit:e.withModifiers(y,["prevent"])},[e.createVNode(e.unref(W.IonItem),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonLabel),{position:"stacked"},{default:e.withCtx(()=>[...z[5]||(z[5]=[e.createTextVNode("Name *",-1)])]),_:1}),e.createVNode(e.unref(W.IonInput),{modelValue:d.value.name,"onUpdate:modelValue":z[0]||(z[0]=I=>d.value.name=I),"data-testid":"name-input",maxlength:Go,onIonBlur:S},null,8,["modelValue"])]),_:1}),v.value?(e.openBlock(),e.createBlock(e.unref(W.IonText),{key:0,color:"danger","data-testid":"name-error"},{default:e.withCtx(()=>[e.createElementVNode("p",H5,e.toDisplayString(v.value),1)]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(W.IonItem),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonLabel),{position:"stacked"},{default:e.withCtx(()=>[...z[6]||(z[6]=[e.createTextVNode("Description",-1)])]),_:1}),e.createVNode(e.unref(W.IonTextarea),{modelValue:d.value.description,"onUpdate:modelValue":z[1]||(z[1]=I=>d.value.description=I),"data-testid":"description-input",maxlength:Jo,onIonBlur:N},null,8,["modelValue"])]),_:1}),w.value?(e.openBlock(),e.createBlock(e.unref(W.IonText),{key:1,color:"danger","data-testid":"description-error"},{default:e.withCtx(()=>[e.createElementVNode("p",Z5,e.toDisplayString(w.value),1)]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(W.IonItem),{button:"","data-testid":"parent-selector",onClick:V},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonLabel),null,{default:e.withCtx(()=>[...z[7]||(z[7]=[e.createTextVNode("Parent Album",-1)])]),_:1}),e.createVNode(e.unref(W.IonNote),{slot:"end","data-testid":"parent-name"},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(T.value),1)]),_:1})]),_:1})],32)]),_:1}),e.createVNode(e.unref(W.IonFooter),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonToolbar),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonButtons),{slot:"start"},{default:e.withCtx(()=>[r.value?(e.openBlock(),e.createBlock(e.unref(W.IonButton),{key:0,"data-testid":"delete-btn",color:"danger",disabled:!_.value,title:_.value?void 0:g.value,onClick:R},{default:e.withCtx(()=>[...z[8]||(z[8]=[e.createTextVNode(" Delete ",-1)])]),_:1},8,["disabled","title"])):e.createCommentVNode("",!0)]),_:1}),e.createVNode(e.unref(W.IonButtons),{slot:"end"},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonButton),{"data-testid":"submit-btn",type:"submit",color:"primary",disabled:!x.value,onClick:y},{default:e.withCtx(()=>[p.value?(e.openBlock(),e.createBlock(e.unref(W.IonSpinner),{key:0,"data-testid":"loading-spinner",name:"crescent"})):(e.openBlock(),e.createElementBlock("span",X5,e.toDisplayString(l.value),1))]),_:1},8,["disabled"])]),_:1})]),_:1})]),_:1})]),_:1},8,["is-open"])):(e.openBlock(),e.createElementBlock("div",G5,[e.createElementVNode("div",J5,[e.createElementVNode("h2",K5,e.toDisplayString(s.value),1),e.createVNode(e.unref(W.IonButton),{"data-testid":"cancel-btn",fill:"clear",onClick:C},{default:e.withCtx(()=>[...z[9]||(z[9]=[e.createTextVNode(" Cancel ",-1)])]),_:1})]),e.createElementVNode("form",{"data-testid":"album-form",class:"space-y-3",onSubmit:e.withModifiers(y,["prevent"])},[e.createVNode(e.unref(W.IonItem),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonLabel),{position:"stacked"},{default:e.withCtx(()=>[...z[10]||(z[10]=[e.createTextVNode("Name *",-1)])]),_:1}),e.createVNode(e.unref(W.IonInput),{modelValue:d.value.name,"onUpdate:modelValue":z[2]||(z[2]=I=>d.value.name=I),"data-testid":"name-input",maxlength:Go,onIonBlur:S},null,8,["modelValue"])]),_:1}),v.value?(e.openBlock(),e.createBlock(e.unref(W.IonText),{key:0,color:"danger","data-testid":"name-error"},{default:e.withCtx(()=>[e.createElementVNode("p",q5,e.toDisplayString(v.value),1)]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(W.IonItem),null,{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonLabel),{position:"stacked"},{default:e.withCtx(()=>[...z[11]||(z[11]=[e.createTextVNode("Description",-1)])]),_:1}),e.createVNode(e.unref(W.IonTextarea),{modelValue:d.value.description,"onUpdate:modelValue":z[3]||(z[3]=I=>d.value.description=I),"data-testid":"description-input",maxlength:Jo,onIonBlur:N},null,8,["modelValue"])]),_:1}),w.value?(e.openBlock(),e.createBlock(e.unref(W.IonText),{key:1,color:"danger","data-testid":"description-error"},{default:e.withCtx(()=>[e.createElementVNode("p",Y5,e.toDisplayString(w.value),1)]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(W.IonItem),{button:"","data-testid":"parent-selector",onClick:V},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonLabel),null,{default:e.withCtx(()=>[...z[12]||(z[12]=[e.createTextVNode("Parent Album",-1)])]),_:1}),e.createVNode(e.unref(W.IonNote),{slot:"end","data-testid":"parent-name"},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(T.value),1)]),_:1})]),_:1}),e.createElementVNode("div",Q5,[e.createElementVNode("div",null,[r.value?(e.openBlock(),e.createBlock(e.unref(W.IonButton),{key:0,"data-testid":"delete-btn",color:"danger",fill:"outline",disabled:!_.value,title:_.value?void 0:g.value,onClick:R},{default:e.withCtx(()=>[...z[13]||(z[13]=[e.createTextVNode(" Delete ",-1)])]),_:1},8,["disabled","title"])):e.createCommentVNode("",!0)]),e.createVNode(e.unref(W.IonButton),{"data-testid":"submit-btn",type:"submit",color:"primary",disabled:!x.value,onClick:y},{default:e.withCtx(()=>[p.value?(e.openBlock(),e.createBlock(e.unref(W.IonSpinner),{key:0,"data-testid":"loading-spinner",name:"crescent"})):(e.openBlock(),e.createElementBlock("span",eF,e.toDisplayString(l.value),1))]),_:1},8,["disabled"])])],32)])),e.createVNode(Pp,{"is-open":f.value,"selected-album-id":d.value.parent_id,title:"Select Parent Album",onClose:j,onConfirm:A},null,8,["is-open","selected-album-id"]),e.createVNode(e.unref(W.IonAlert),{"is-open":h.value,header:"Delete Album?",message:g.value,buttons:[{text:"Cancel",role:"cancel"},{text:"Delete",role:"confirm",cssClass:"alert-button-danger"}],onDidDismiss:L},null,8,["is-open","message"])],64))}}),aF=Be(tF,[["__scopeId","data-v-22083f3a"]]),nF={class:"album-media-grid"},oF={class:"aspect-square"},iF={key:1,"data-testid":"empty-state",class:"flex flex-col items-center justify-center py-12 gap-4"},rF={class:"text-gray-500"},sF=["data-media-id","draggable","onDragstart","onDragover","onDrop","onMouseenter"],lF={key:0,"data-testid":"drop-indicator",class:"absolute inset-0 border-2 border-primary rounded-lg pointer-events-none z-30"},dF={key:1,class:"absolute top-2 right-2 z-20 opacity-0 group-hover:opacity-100 transition-opacity cursor-grab"},cF={class:"aspect-square relative"},uF=["src","alt"],mF={key:0,class:"absolute inset-0 bg-black/50 flex items-center justify-center gap-2 transition-opacity"},pF=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=hs(),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),f=e.computed(()=>!u.value&&r.value.length===0),m=e.computed(()=>{const $=t.columns;return["grid","gap-4",`grid-cols-${$.mobile??2}`,`sm:grid-cols-${$.sm??3}`,`md:grid-cols-${$.md??4}`,`lg:grid-cols-${$.lg??5}`,`xl:grid-cols-${$.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 $=await i.fetchAlbumMedia(t.albumId);r.value=$}catch{r.value=[]}finally{s.value=!1}}function v($){return t.selectedItems.includes($)}function w($){n("toggle-select",$);const y=v($.uuid)?t.selectedItems.filter(R=>R!==$.uuid):[...t.selectedItems,$.uuid];n("selection-change",y)}function x($){if($.conversions&&typeof $.conversions=="object"){const y=$.conversions.thumb;if(typeof y=="string")return y}return $.original_url}function T($){l.value=$}function _(){l.value=null}function g($){n("preview",$)}function E($){n("edit",$)}function S($){n("detach",$.uuid)}function N(){n("add")}function V($,y){t.reorderable&&(d.value=y,$.dataTransfer&&($.dataTransfer.effectAllowed="move",$.dataTransfer.setData("text/plain",String(y))))}function A($,y){!t.reorderable||d.value===null||($.preventDefault(),c.value=y)}function j($,y){if(!t.reorderable||d.value===null)return;$.preventDefault();const R=d.value;if(R!==y){const L=[...r.value],[U]=L.splice(R,1);L.splice(y,0,U),r.value=L;const z=L.map(I=>I.uuid);n("reorder",z),i.reorderAlbumMedia(t.albumId,z).catch(()=>{h()})}d.value=null,c.value=null}function C(){d.value=null,c.value=null}return($,y)=>(e.openBlock(),e.createElementBlock("div",nF,[u.value?(e.openBlock(),e.createElementBlock("div",{key:0,"data-testid":"loading-grid",class:e.normalizeClass(m.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(p.value,R=>(e.openBlock(),e.createBlock(e.unref(W.IonCard),{key:R,class:"m-0"},{default:e.withCtx(()=>[e.createElementVNode("div",oF,[e.createVNode(e.unref(W.IonSkeletonText),{animated:"",class:"w-full h-full skeleton"})])]),_:1}))),128))],2)):f.value?(e.openBlock(),e.createElementBlock("div",iF,[e.createVNode(e.unref(W.IonIcon),{name:"images-outline",class:"text-6xl text-gray-400"}),e.createElementVNode("p",rF,e.toDisplayString($.emptyText),1),e.createVNode(e.unref(W.IonButton),{"data-testid":"add-media-btn",onClick:N},{default:e.withCtx(()=>[...y[0]||(y[0]=[e.createTextVNode(" Add Media ",-1)])]),_:1})])):(e.openBlock(),e.createElementBlock("div",{key:2,"data-testid":"media-grid",class:e.normalizeClass(m.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.value,(R,L)=>(e.openBlock(),e.createElementBlock("div",{key:R.uuid,"data-media-id":R.uuid,class:e.normalizeClass(["media-item relative group",{"opacity-50":d.value===L,"ring-2 ring-primary":c.value===L&&d.value!==L}]),draggable:$.reorderable,onDragstart:U=>V(U,L),onDragover:U=>A(U,L),onDrop:U=>j(U,L),onDragend:C,onMouseenter:U=>T(R.uuid),onMouseleave:_},[c.value===L&&d.value!==L&&$.reorderable?(e.openBlock(),e.createElementBlock("div",lF)):e.createCommentVNode("",!0),$.reorderable?(e.openBlock(),e.createElementBlock("div",dF,[e.createVNode(e.unref(W.IonIcon),{name:"reorder-three-outline",class:"text-white drop-shadow-md"})])):e.createCommentVNode("",!0),$.selectionMode?(e.openBlock(),e.createBlock(e.unref(W.IonCheckbox),{key:2,"data-testid":"media-checkbox",checked:v(R.uuid),class:"absolute top-2 left-2 z-20",onIonChange:U=>w(R)},null,8,["checked","onIonChange"])):e.createCommentVNode("",!0),e.createVNode(e.unref(W.IonCard),{class:"m-0 overflow-hidden"},{default:e.withCtx(()=>[e.createElementVNode("div",cF,[e.createElementVNode("img",{src:x(R),alt:R.file_name,class:"w-full h-full object-cover"},null,8,uF),$.showActions&&l.value===R.uuid?(e.openBlock(),e.createElementBlock("div",mF,[e.createVNode(e.unref(W.IonButton),{"data-testid":"action-preview",fill:"clear",size:"small",color:"light",onClick:U=>g(R)},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{slot:"icon-only",name:"eye-outline"})]),_:1},8,["onClick"]),e.createVNode(e.unref(W.IonButton),{"data-testid":"action-edit",fill:"clear",size:"small",color:"light",onClick:U=>E(R)},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{slot:"icon-only",name:"create-outline"})]),_:1},8,["onClick"]),e.createVNode(e.unref(W.IonButton),{"data-testid":"action-detach",fill:"clear",size:"small",color:"danger",onClick:U=>S(R)},{default:e.withCtx(()=>[e.createVNode(e.unref(W.IonIcon),{slot:"icon-only",name:"close-circle-outline"})]),_:1},8,["onClick"])])):e.createCommentVNode("",!0)])]),_:2},1024)],42,sF))),128)),e.createElementVNode("div",{class:"aspect-square border-2 border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center gap-2 cursor-pointer hover:border-primary hover:bg-gray-50 transition-colors","data-testid":"add-more-card",onClick:N},[e.createVNode(e.unref(W.IonIcon),{name:"add-circle-outline",class:"text-4xl text-gray-400"}),y[1]||(y[1]=e.createElementVNode("span",{class:"text-sm text-gray-500"},"Add Media",-1))])],2))]))}}),fF=Be(pF,[["__scopeId","data-v-d84b796a"]]),hF={key:0,class:"media-album-inline-create","data-testid":"media-album-inline-create"},vF={class:"media-album-inline-create__field"},gF={class:"media-album-inline-create__field"},bF=["value"],yF={key:1,class:"media-album-inline-create__autocomplete"},wF={class:"media-album-inline-create__autocomplete-input-wrap"},kF={key:0,class:"media-album-inline-create__autocomplete-list"},_F=["onMousedown"],EF={key:1,class:"media-album-inline-create__autocomplete-empty"},xF={class:"media-album-inline-create__actions"},SF=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 w=s.value.toLowerCase();return t.albums.filter(x=>x.name.toLowerCase().includes(w))}),u=e.computed(()=>{if(r.value==="")return"";const w=t.albums.find(x=>x.id===r.value);return(w==null?void 0:w.name)??""}),f=w=>{r.value=w.id,s.value=w.name,l.value=!1},m=()=>{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(w,x)=>w.open?(e.openBlock(),e.createElementBlock("section",hF,[x[7]||(x[7]=e.createElementVNode("h4",{class:"media-album-inline-create__heading"}," New album ",-1)),e.createElementVNode("label",vF,[e.createElementVNode("span",null,e.toDisplayString(w.nameLabel),1),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":x[0]||(x[0]=T=>i.value=T),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",gF,[x[6]||(x[6]=e.createElementVNode("span",null,"Parent album (optional)",-1)),d.value?(e.openBlock(),e.createElementBlock("div",yF,[e.createElementVNode("div",wF,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":x[2]||(x[2]=T=>s.value=T),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(m,["prevent"])},[...x[5]||(x[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",kF,[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(m,["prevent"])}," None ",32)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.value,T=>(e.openBlock(),e.createElementBlock("li",{key:T.id,class:e.normalizeClass(["media-album-inline-create__autocomplete-option",{"is-selected":T.id===r.value}]),onMousedown:e.withModifiers(_=>f(T),["prevent"])},e.toDisplayString(T.name),43,_F))),128)),c.value.length===0?(e.openBlock(),e.createElementBlock("li",EF," No albums match ")):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)])):e.withDirectives((e.openBlock(),e.createElementBlock("select",{key:0,"onUpdate:modelValue":x[1]||(x[1]=T=>r.value=T),class:"media-album-inline-create__input","data-testid":"select-media-album-parent"},[x[4]||(x[4]=e.createElementVNode("option",{value:""}," None ",-1)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(w.albums,T=>(e.openBlock(),e.createElementBlock("option",{key:T.id,value:T.id},e.toDisplayString(T.name),9,bF))),128))],512)),[[e.vModelSelect,r.value]])]),e.createElementVNode("div",xF,[e.createElementVNode("button",{type:"button",class:"media-album-inline-create__button","data-testid":"btn-media-album-cancel",onClick:x[3]||(x[3]=T=>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)}}),Up=Be(SF,[["__scopeId","data-v-a85162fe"]]),CF={class:"media-album-unavailable-state","data-testid":"media-album-unavailable-state"},VF=e.defineComponent({__name:"MediaAlbumUnavailableState",props:{title:{default:"Album unavailable"},body:{default:"You no longer have access to this album."},actionLabel:{default:"Go to library"}},emits:["goToLibrary"],setup(o,{emit:a}){const t=a;return(n,i)=>(e.openBlock(),e.createElementBlock("section",CF,[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)]))}}),Op=Be(VF,[["__scopeId","data-v-04620e64"]]);/*!
|
|
350
|
-
* tabbable 6.2.0
|
|
351
|
-
* @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE
|
|
352
|
-
*/var zp=["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])"],Ar=zp.join(","),jp=typeof Element>"u",Xn=jp?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,Lr=!jp&&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},Pr=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},NF=function(a){var t,n=a==null||(t=a.getAttribute)===null||t===void 0?void 0:t.call(a,"contenteditable");return n===""||n==="true"},Wp=function(a,t,n){if(Pr(a))return[];var i=Array.prototype.slice.apply(a.querySelectorAll(Ar));return t&&Xn.call(a,Ar)&&i.unshift(a),i=i.filter(n),i},Hp=function o(a,t,n){for(var i=[],r=Array.from(a);r.length;){var s=r.shift();if(!Pr(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=Xn.call(s,Ar);u&&n.filter(s)&&(t||!a.includes(s))&&i.push(s);var f=s.shadowRoot||typeof n.getShadowRoot=="function"&&n.getShadowRoot(s),m=!Pr(f,!1)&&(!n.shadowRootFilter||n.shadowRootFilter(s));if(f&&m){var p=o(f===!0?s.children:f.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},Zp=function(a){return!isNaN(parseInt(a.getAttribute("tabindex"),10))},Ln=function(a){if(!a)throw new Error("No node provided");return a.tabIndex<0&&(/^(AUDIO|VIDEO|DETAILS)$/.test(a.tagName)||NF(a))&&!Zp(a)?0:a.tabIndex},TF=function(a,t){var n=Ln(a);return n<0&&t&&!Zp(a)?0:n},IF=function(a,t){return a.tabIndex===t.tabIndex?a.documentOrder-t.documentOrder:a.tabIndex-t.tabIndex},Xp=function(a){return a.tagName==="INPUT"},BF=function(a){return Xp(a)&&a.type==="hidden"},MF=function(a){var t=a.tagName==="DETAILS"&&Array.prototype.slice.apply(a.children).some(function(n){return n.tagName==="SUMMARY"});return t},FF=function(a,t){for(var n=0;n<a.length;n++)if(a[n].checked&&a[n].form===t)return a[n]},$F=function(a){if(!a.name)return!0;var t=a.form||Lr(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=FF(i,a.form);return!r||r===a},DF=function(a){return Xp(a)&&a.type==="radio"},RF=function(a){return DF(a)&&!$F(a)},AF=function(a){var t,n=a&&Lr(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,f;n=Lr(i),i=(c=n)===null||c===void 0?void 0:c.host,r=!!((u=i)!==null&&u!==void 0&&(f=u.ownerDocument)!==null&&f!==void 0&&f.contains(i))}}return r},mu=function(a){var t=a.getBoundingClientRect(),n=t.width,i=t.height;return n===0&&i===0},LF=function(a,t){var n=t.displayCheck,i=t.getShadowRoot;if(getComputedStyle(a).visibility==="hidden")return!0;var r=Xn.call(a,"details>summary:first-of-type"),s=r?a.parentElement:a;if(Xn.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=Lr(a);if(d&&!d.shadowRoot&&i(d)===!0)return mu(a);a.assignedSlot?a=a.assignedSlot:!d&&c!==a.ownerDocument?a=c.host:a=d}a=l}if(AF(a))return!a.getClientRects().length;if(n!=="legacy-full")return!0}else if(n==="non-zero-area")return mu(a);return!1},PF=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 Xn.call(t,"fieldset[disabled] *")?!0:!i.contains(a)}return!0}t=t.parentElement}return!1},Ur=function(a,t){return!(t.disabled||Pr(t)||BF(t)||LF(t,a)||MF(t)||PF(t))},Ul=function(a,t){return!(RF(t)||Ln(t)<0||!Ur(a,t))},UF=function(a){var t=parseInt(a.getAttribute("tabindex"),10);return!!(isNaN(t)||t>=0)},OF=function o(a){var t=[],n=[];return a.forEach(function(i,r){var s=!!i.scopeParent,l=s?i.scopeParent:i,d=TF(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(IF).reduce(function(i,r){return r.isScope?i.push.apply(i,r.content):i.push(r.content),i},[]).concat(t)},zF=function(a,t){t=t||{};var n;return t.getShadowRoot?n=Hp([a],t.includeContainer,{filter:Ul.bind(null,t),flatten:!1,getShadowRoot:t.getShadowRoot,shadowRootFilter:UF}):n=Wp(a,t.includeContainer,Ul.bind(null,t)),OF(n)},jF=function(a,t){t=t||{};var n;return t.getShadowRoot?n=Hp([a],t.includeContainer,{filter:Ur.bind(null,t),flatten:!0,getShadowRoot:t.getShadowRoot}):n=Wp(a,t.includeContainer,Ur.bind(null,t)),n},po=function(a,t){if(t=t||{},!a)throw new Error("No node provided");return Xn.call(a,Ar)===!1?!1:Ul(t,a)},WF=zp.concat("iframe").join(","),Ks=function(a,t){if(t=t||{},!a)throw new Error("No node provided");return Xn.call(a,WF)===!1?!1:Ur(t,a)};/*!
|
|
353
|
-
* focus-trap 7.6.5
|
|
354
|
-
* @license MIT, https://github.com/focus-trap/focus-trap/blob/master/LICENSE
|
|
355
|
-
*/function Ol(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 HF(o){if(Array.isArray(o))return Ol(o)}function ZF(o,a,t){return(a=qF(a))in o?Object.defineProperty(o,a,{value:t,enumerable:!0,configurable:!0,writable:!0}):o[a]=t,o}function XF(o){if(typeof Symbol<"u"&&o[Symbol.iterator]!=null||o["@@iterator"]!=null)return Array.from(o)}function GF(){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 pu(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 fu(o){for(var a=1;a<arguments.length;a++){var t=arguments[a]!=null?arguments[a]:{};a%2?pu(Object(t),!0).forEach(function(n){ZF(o,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(t)):pu(Object(t)).forEach(function(n){Object.defineProperty(o,n,Object.getOwnPropertyDescriptor(t,n))})}return o}function JF(o){return HF(o)||XF(o)||YF(o)||GF()}function KF(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 qF(o){var a=KF(o,"string");return typeof a=="symbol"?a:a+""}function YF(o,a){if(o){if(typeof o=="string")return Ol(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)?Ol(o,a):void 0}}var hu={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)}},QF=function(a){return a.tagName&&a.tagName.toLowerCase()==="input"&&typeof a.select=="function"},e8=function(a){return(a==null?void 0:a.key)==="Escape"||(a==null?void 0:a.key)==="Esc"||(a==null?void 0:a.keyCode)===27},mi=function(a){return(a==null?void 0:a.key)==="Tab"||(a==null?void 0:a.keyCode)===9},t8=function(a){return mi(a)&&!a.shiftKey},a8=function(a){return mi(a)&&a.shiftKey},vu=function(a){return setTimeout(a,0)},Ko=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},rr=function(a){return a.target.shadowRoot&&typeof a.composedPath=="function"?a.composedPath()[0]:a.target},n8=[],o8=function(a,t){var n=(t==null?void 0:t.document)||document,i=(t==null?void 0:t.trapStack)||n8,r=fu({returnFocusOnDeactivate:!0,escapeDeactivates:!0,delayInitialFocus:!0,isKeyForward:t8,isKeyBackward:a8},t),s={containers:[],containerGroups:[],tabbableGroups:[],nodeFocusedBeforeActivation:null,mostRecentlyFocusedNode:null,active:!1,paused:!1,manuallyPaused:!1,delayInitialFocusTimer:void 0,recentNavEvent:void 0},l,d=function(y,R,L){return y&&y[R]!==void 0?y[R]:r[L||R]},c=function(y,R){var L=typeof(R==null?void 0:R.composedPath)=="function"?R.composedPath():void 0;return s.containerGroups.findIndex(function(U){var z=U.container,I=U.tabbableNodes;return z.contains(y)||(L==null?void 0:L.includes(z))||I.find(function(P){return P===y})})},u=function(y){var R=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},L=R.hasFallback,U=L===void 0?!1:L,z=R.params,I=z===void 0?[]:z,P=r[y];if(typeof P=="function"&&(P=P.apply(void 0,JF(I))),P===!0&&(P=void 0),!P){if(P===void 0||P===!1)return P;throw new Error("`".concat(y,"` was specified but was not a node, or did not return a node"))}var Z=P;if(typeof P=="string"){try{Z=n.querySelector(P)}catch(K){throw new Error("`".concat(y,'` appears to be an invalid selector; error="').concat(K.message,'"'))}if(!Z&&!U)throw new Error("`".concat(y,"` as selector refers to no known node"))}return Z},f=function(){var y=u("initialFocus",{hasFallback:!0});if(y===!1)return!1;if(y===void 0||y&&!Ks(y,r.tabbableOptions))if(c(n.activeElement)>=0)y=n.activeElement;else{var R=s.tabbableGroups[0],L=R&&R.firstTabbableNode;y=L||u("fallbackFocus")}else y===null&&(y=u("fallbackFocus"));if(!y)throw new Error("Your focus-trap needs to have at least one focusable element");return y},m=function(){if(s.containerGroups=s.containers.map(function(y){var R=zF(y,r.tabbableOptions),L=jF(y,r.tabbableOptions),U=R.length>0?R[0]:void 0,z=R.length>0?R[R.length-1]:void 0,I=L.find(function(K){return po(K)}),P=L.slice().reverse().find(function(K){return po(K)}),Z=!!R.find(function(K){return Ln(K)>0});return{container:y,tabbableNodes:R,focusableNodes:L,posTabIndexesFound:Z,firstTabbableNode:U,lastTabbableNode:z,firstDomTabbableNode:I,lastDomTabbableNode:P,nextTabbableNode:function(ve){var Ve=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,ne=R.indexOf(ve);return ne<0?Ve?L.slice(L.indexOf(ve)+1).find(function(ae){return po(ae)}):L.slice(0,L.indexOf(ve)).reverse().find(function(ae){return po(ae)}):R[ne+(Ve?1:-1)]}}}),s.tabbableGroups=s.containerGroups.filter(function(y){return y.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(y){return y.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(y){var R=y.activeElement;if(R)return R.shadowRoot&&R.shadowRoot.activeElement!==null?p(R.shadowRoot):R},h=function(y){if(y!==!1&&y!==p(document)){if(!y||!y.focus){h(f());return}y.focus({preventScroll:!!r.preventScroll}),s.mostRecentlyFocusedNode=y,QF(y)&&y.select()}},v=function(y){var R=u("setReturnFocus",{params:[y]});return R||(R===!1?!1:y)},w=function(y){var R=y.target,L=y.event,U=y.isBackward,z=U===void 0?!1:U;R=R||rr(L),m();var I=null;if(s.tabbableGroups.length>0){var P=c(R,L),Z=P>=0?s.containerGroups[P]:void 0;if(P<0)z?I=s.tabbableGroups[s.tabbableGroups.length-1].lastTabbableNode:I=s.tabbableGroups[0].firstTabbableNode;else if(z){var K=s.tabbableGroups.findIndex(function(B){var O=B.firstTabbableNode;return R===O});if(K<0&&(Z.container===R||Ks(R,r.tabbableOptions)&&!po(R,r.tabbableOptions)&&!Z.nextTabbableNode(R,!1))&&(K=P),K>=0){var ve=K===0?s.tabbableGroups.length-1:K-1,Ve=s.tabbableGroups[ve];I=Ln(R)>=0?Ve.lastTabbableNode:Ve.lastDomTabbableNode}else mi(L)||(I=Z.nextTabbableNode(R,!1))}else{var ne=s.tabbableGroups.findIndex(function(B){var O=B.lastTabbableNode;return R===O});if(ne<0&&(Z.container===R||Ks(R,r.tabbableOptions)&&!po(R,r.tabbableOptions)&&!Z.nextTabbableNode(R))&&(ne=P),ne>=0){var ae=ne===s.tabbableGroups.length-1?0:ne+1,F=s.tabbableGroups[ae];I=Ln(R)>=0?F.firstTabbableNode:F.firstDomTabbableNode}else mi(L)||(I=Z.nextTabbableNode(R))}}else I=u("fallbackFocus");return I},x=function(y){var R=rr(y);if(!(c(R,y)>=0)){if(Ko(r.clickOutsideDeactivates,y)){l.deactivate({returnFocus:r.returnFocusOnDeactivate});return}Ko(r.allowOutsideClick,y)||y.preventDefault()}},T=function(y){var R=rr(y),L=c(R,y)>=0;if(L||R instanceof Document)L&&(s.mostRecentlyFocusedNode=R);else{y.stopImmediatePropagation();var U,z=!0;if(s.mostRecentlyFocusedNode)if(Ln(s.mostRecentlyFocusedNode)>0){var I=c(s.mostRecentlyFocusedNode),P=s.containerGroups[I].tabbableNodes;if(P.length>0){var Z=P.findIndex(function(K){return K===s.mostRecentlyFocusedNode});Z>=0&&(r.isKeyForward(s.recentNavEvent)?Z+1<P.length&&(U=P[Z+1],z=!1):Z-1>=0&&(U=P[Z-1],z=!1))}}else s.containerGroups.some(function(K){return K.tabbableNodes.some(function(ve){return Ln(ve)>0})})||(z=!1);else z=!1;z&&(U=w({target:s.mostRecentlyFocusedNode,isBackward:r.isKeyBackward(s.recentNavEvent)})),h(U||s.mostRecentlyFocusedNode||f())}s.recentNavEvent=void 0},_=function(y){var R=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;s.recentNavEvent=y;var L=w({event:y,isBackward:R});L&&(mi(y)&&y.preventDefault(),h(L))},g=function(y){(r.isKeyForward(y)||r.isKeyBackward(y))&&_(y,r.isKeyBackward(y))},E=function(y){e8(y)&&Ko(r.escapeDeactivates,y)!==!1&&(y.preventDefault(),l.deactivate())},S=function(y){var R=rr(y);c(R,y)>=0||Ko(r.clickOutsideDeactivates,y)||Ko(r.allowOutsideClick,y)||(y.preventDefault(),y.stopImmediatePropagation())},N=function(){if(s.active)return hu.activateTrap(i,l),s.delayInitialFocusTimer=r.delayInitialFocus?vu(function(){h(f())}):h(f()),n.addEventListener("focusin",T,!0),n.addEventListener("mousedown",x,{capture:!0,passive:!1}),n.addEventListener("touchstart",x,{capture:!0,passive:!1}),n.addEventListener("click",S,{capture:!0,passive:!1}),n.addEventListener("keydown",g,{capture:!0,passive:!1}),n.addEventListener("keydown",E),l},V=function(){if(s.active)return n.removeEventListener("focusin",T,!0),n.removeEventListener("mousedown",x,!0),n.removeEventListener("touchstart",x,!0),n.removeEventListener("click",S,!0),n.removeEventListener("keydown",g,!0),n.removeEventListener("keydown",E),l},A=function(y){var R=y.some(function(L){var U=Array.from(L.removedNodes);return U.some(function(z){return z===s.mostRecentlyFocusedNode})});R&&h(f())},j=typeof window<"u"&&"MutationObserver"in window?new MutationObserver(A):void 0,C=function(){j&&(j.disconnect(),s.active&&!s.paused&&s.containers.map(function(y){j.observe(y,{subtree:!0,childList:!0})}))};return l={get active(){return s.active},get paused(){return s.paused},activate:function(y){if(s.active)return this;var R=d(y,"onActivate"),L=d(y,"onPostActivate"),U=d(y,"checkCanFocusTrap");U||m(),s.active=!0,s.paused=!1,s.nodeFocusedBeforeActivation=p(n),R==null||R();var z=function(){U&&m(),N(),C(),L==null||L()};return U?(U(s.containers.concat()).then(z,z),this):(z(),this)},deactivate:function(y){if(!s.active)return this;var R=fu({onDeactivate:r.onDeactivate,onPostDeactivate:r.onPostDeactivate,checkCanReturnFocus:r.checkCanReturnFocus},y);clearTimeout(s.delayInitialFocusTimer),s.delayInitialFocusTimer=void 0,V(),s.active=!1,s.paused=!1,C(),hu.deactivateTrap(i,l);var L=d(R,"onDeactivate"),U=d(R,"onPostDeactivate"),z=d(R,"checkCanReturnFocus"),I=d(R,"returnFocus","returnFocusOnDeactivate");L==null||L();var P=function(){vu(function(){I&&h(v(s.nodeFocusedBeforeActivation)),U==null||U()})};return I&&z?(z(v(s.nodeFocusedBeforeActivation)).then(P,P),this):(P(),this)},pause:function(y){return s.active?(s.manuallyPaused=!0,this._setPausedState(!0,y)):this},unpause:function(y){return s.active?(s.manuallyPaused=!1,i[i.length-1]!==this?this:this._setPausedState(!1,y)):this},updateContainerElements:function(y){var R=[].concat(y).filter(Boolean);return s.containers=R.map(function(L){return typeof L=="string"?n.querySelector(L):L}),s.active&&m(),C(),this}},Object.defineProperties(l,{_isManuallyPaused:{value:function(){return s.manuallyPaused}},_setPausedState:{value:function(y,R){if(s.paused===y)return this;if(s.paused=y,y){var L=d(R,"onPause"),U=d(R,"onPostPause");L==null||L(),V(),C(),U==null||U()}else{var z=d(R,"onUnpause"),I=d(R,"onPostUnpause");z==null||z(),m(),N(),C(),I==null||I()}return this}}}),l.updateContainerElements(a),l};const i8=["aria-labelledby"],r8={class:"media-preview-sheet__header"},s8=["id"],l8=["aria-label"],d8=["src","alt"],c8=["src"],u8={class:"media-preview-sheet__actions"},m8=["disabled","aria-label"],p8=["aria-label","aria-pressed"],f8=["disabled","aria-label"],h8=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 E;return((E=t.media)==null?void 0:E.mime_type.startsWith("image/"))===!0}),u=e.computed(()=>t.media?t.media.preview_url??t.media.original_url:""),f=e.computed(()=>t.media?`Preview ${t.media.file_name}`:"Media preview"),m=e.computed(()=>t.media?`Close preview of ${t.media.file_name}`:"Close preview"),p=e.computed(()=>t.canGoPrevious?"Previous media":"No previous media"),h=e.computed(()=>t.canGoNext?"Next media":"No next media"),v=e.computed(()=>{const E=t.selected?t.deselectLabel:t.selectLabel;return t.media?t.selected?`${t.deselectLabel} ${t.media.file_name}`:`${t.selectLabel} ${t.media.file_name}`:E}),w=e.computed(()=>t.selected?t.deselectLabel:t.selectLabel),x=()=>{t.media&&n("toggleSelect",t.media)},T=E=>{if(E.key==="Escape"){E.preventDefault(),n("close");return}if(E.key==="ArrowLeft"&&t.canGoPrevious){E.preventDefault(),n("previous");return}E.key==="ArrowRight"&&t.canGoNext&&(E.preventDefault(),n("next"))},_=()=>{if(l){try{l.deactivate({returnFocus:!1})}catch{}l=null}},g=()=>{const E=d;d=null,E&&typeof E.focus=="function"&&e.nextTick(()=>{E.focus()})};return e.watch(()=>t.open&&t.media!==null,async E=>{var S;if(E){d=document.activeElement instanceof HTMLElement?document.activeElement:null,await e.nextTick();const N=r.value;if(N)try{l=o8(N,{initialFocus:()=>s.value??N,escapeDeactivates:!1,clickOutsideDeactivates:!1,returnFocusOnDeactivate:!1,allowOutsideClick:!0}),l.activate()}catch{(S=s.value)==null||S.focus()}}else _(),g()},{immediate:!0}),e.onBeforeUnmount(()=>{_()}),(E,S)=>E.open&&E.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",r8,[e.createElementVNode("strong",{id:e.unref(i),"data-testid":"media-preview-sheet-title"},e.toDisplayString(f.value),9,s8),e.createElementVNode("button",{ref_key:"closeButtonRef",ref:s,type:"button",class:"media-preview-sheet__close","aria-label":m.value,"data-testid":"btn-media-preview-close",onClick:S[0]||(S[0]=N=>n("close"))},e.toDisplayString(E.closeLabel),9,l8)]),c.value?(e.openBlock(),e.createElementBlock("img",{key:0,class:"media-preview-sheet__image",src:u.value,alt:E.media.file_name},null,8,d8)):(e.openBlock(),e.createElementBlock("video",{key:1,class:"media-preview-sheet__video",src:u.value,controls:""},null,8,c8)),e.createElementVNode("div",u8,[e.createElementVNode("button",{type:"button",class:"media-preview-sheet__nav",disabled:!E.canGoPrevious,"aria-label":p.value,"data-testid":"btn-media-preview-previous",onClick:S[1]||(S[1]=N=>n("previous"))},e.toDisplayString(E.previousLabel),9,m8),e.createElementVNode("button",{type:"button",class:"media-preview-sheet__select","aria-label":v.value,"aria-pressed":E.selected,"data-testid":"btn-media-preview-select",onClick:x},e.toDisplayString(w.value),9,p8),e.createElementVNode("button",{type:"button",class:"media-preview-sheet__nav",disabled:!E.canGoNext,"aria-label":h.value,"data-testid":"btn-media-preview-next",onClick:S[2]||(S[2]=N=>n("next"))},e.toDisplayString(E.nextLabel),9,f8)])],40,i8)):e.createCommentVNode("",!0)}}),Gp=Be(h8,[["__scopeId","data-v-0ca8008b"]]),v8={key:0,class:"media-album-grid","data-testid":"media-source-sheet"},g8={class:"media-album-grid__items"},b8={class:"media-album-grid__card-name"},y8={class:"media-album-grid__card-name"},w8=["data-testid","onClick"],k8={class:"media-album-grid__card-name"},_8={key:0,class:"media-album-grid__card-meta"},E8={key:0,class:"media-album-grid__empty"},x8=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",v8,[e.createElementVNode("div",g8,[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",b8,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",y8,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",k8,e.toDisplayString(r.name),1),r.mediaCount!==void 0?(e.openBlock(),e.createElementBlock("span",_8,e.toDisplayString(r.mediaCount)+" item"+e.toDisplayString(r.mediaCount===1?"":"s"),1)):e.createCommentVNode("",!0)],10,w8))),128))]),n.albums.length===0?(e.openBlock(),e.createElementBlock("p",E8," No albums yet. ")):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)}}),Jp=Be(x8,[["__scopeId","data-v-129f67b1"]]),S8={key:0,class:"media-upload-sheet","data-testid":"media-upload-sheet"},C8={class:"media-upload-sheet__dropzone-text"},V8={key:0,class:"media-upload-sheet__dropzone-helper","data-testid":"text-media-upload-sheet-helper"},N8={class:"media-upload-sheet__sr-only"},T8=["accept","aria-label"],I8=["aria-label"],B8={class:"media-upload-sheet__queue-info"},M8={class:"media-upload-sheet__queue-status"},F8=["aria-valuenow","aria-label","data-testid"],$8=["aria-label"],D8=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=m=>{var h;return t.progressAriaLabel!==void 0?t.progressAriaLabel(m):`Uploading ${((h=m.file)==null?void 0:h.name)??"file"}`},s=m=>{const p=Number.isFinite(m.progress)?m.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=m=>{const p=m.target;!(p instanceof HTMLInputElement)||p.files===null||(n("filesSelected",Array.from(p.files)),p.value="")},c=m=>{m.preventDefault(),i.value=!0},u=()=>{i.value=!1},f=m=>{var p;m.preventDefault(),i.value=!1,(p=m.dataTransfer)!=null&&p.files&&m.dataTransfer.files.length>0&&n("filesSelected",Array.from(m.dataTransfer.files))};return(m,p)=>m.open?(e.openBlock(),e.createElementBlock("section",S8,[e.createElementVNode("label",{class:e.normalizeClass(["media-upload-sheet__dropzone",{"is-drag-over":i.value}]),onDragover:c,onDragleave:u,onDrop:f},[p[1]||(p[1]=e.createStaticVNode('<div class="media-upload-sheet__dropzone-icon" data-v-89997025><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-89997025><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" data-v-89997025></path><polyline points="17 8 12 3 7 8" data-v-89997025></polyline><line x1="12" y1="3" x2="12" y2="15" data-v-89997025></line></svg></div>',1)),e.createElementVNode("span",C8,e.toDisplayString(m.dropzoneLabel),1),m.dropzoneHelperText?(e.openBlock(),e.createElementBlock("span",V8,e.toDisplayString(m.dropzoneHelperText),1)):e.createCommentVNode("",!0),e.createElementVNode("span",N8,e.toDisplayString(m.fileInputLabel),1),e.createElementVNode("input",{type:"file",accept:m.accept,multiple:"",class:"media-upload-sheet__file-input","data-testid":"input-media-upload-sheet","aria-label":m.fileInputLabel,onChange:d},null,40,T8)],34),m.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(m.queue,h=>(e.openBlock(),e.createElementBlock("li",{key:h.id,class:"media-upload-sheet__queue-item"},[e.createElementVNode("div",B8,[e.createElementVNode("strong",null,e.toDisplayString(h.file.name),1),e.createElementVNode("span",M8,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,F8)]))),128))],8,I8)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",class:"media-upload-sheet__close-btn","aria-label":m.closeButtonAriaLabel,"data-testid":"btn-close-upload-sheet",onClick:p[0]||(p[0]=h=>n("close"))},e.toDisplayString(m.closeButtonLabel),9,$8)])):e.createCommentVNode("",!0)}}),Kp=Be(D8,[["__scopeId","data-v-89997025"]]),R8=["aria-label","aria-pressed","data-testid"],A8=["src","alt"],L8={key:1,class:"media-thumbnail-cell__video"},P8={class:"media-thumbnail-cell__video-name"},U8={key:2,class:"media-thumbnail-cell__selected-badge"},O8={key:3,class:"media-thumbnail-cell__status-badge"},z8=["aria-label"],j8=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,f)=>(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,A8)):(e.openBlock(),e.createElementBlock("div",L8,[f[0]||(f[0]=e.createElementVNode("span",{class:"media-thumbnail-cell__video-label"},"Video",-1)),e.createElementVNode("span",P8,e.toDisplayString(u.media.file_name),1)])),u.selected?(e.openBlock(),e.createElementBlock("span",U8," Selected ")):e.createCommentVNode("",!0),s.value!==null?(e.openBlock(),e.createElementBlock("span",O8,e.toDisplayString(s.value),1)):e.createCommentVNode("",!0)],8,R8),e.createElementVNode("button",{type:"button",class:"media-thumbnail-cell__preview-button","aria-label":`Preview ${u.media.file_name}`,onClick:c}," Preview ",8,z8)],2))}}),qp=Be(j8,[["__scopeId","data-v-edd4f0ad"]]),W8={class:"virtual-media-grid"},H8={key:0,class:"virtual-media-grid__state","data-testid":"media-grid-loading"},Z8={key:1,class:"virtual-media-grid__state","data-testid":"media-grid-empty"},X8={key:2,class:"virtual-media-grid__items"},G8=["disabled"],J8=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",W8,[r.loading&&r.items.length===0?(e.openBlock(),e.createElementBlock("div",H8,e.toDisplayString(r.loadingMessage),1)):r.items.length===0?(e.openBlock(),e.createElementBlock("div",Z8,e.toDisplayString(r.emptyMessage),1)):(e.openBlock(),e.createElementBlock("div",X8,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.items,l=>{var d,c;return e.openBlock(),e.createBlock(qp,{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,G8)):e.createCommentVNode("",!0)]))}}),Yp=Be(J8,[["__scopeId","data-v-34667f65"]]);function Or(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 Qp(o){var t;const a=o.split(".");return a.length>1?`.${(t=a.pop())==null?void 0:t.toLowerCase()}`:""}function kd(o){return o.type.startsWith("image/")}async function ef(o){return kd(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 tf(o,a){const t=[];if(a.maxFileSize&&o.size>a.maxFileSize&&t.push({field:"size",message:`File exceeds maximum size of ${Or(a.maxFileSize)}`,code:"MAX_FILE_SIZE"}),a.minFileSize&&o.size<a.minFileSize&&t.push({field:"size",message:`File is smaller than minimum size of ${Or(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=Qp(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(kd(o)&&(a.maxDimensions||a.minDimensions)){const n=await ef(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 tf(d,a.value)}async function i(d){const c=new Map;return await Promise.all(d.map(async u=>{const f=await n(u);c.set(u,f)})),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 K8(){return`upload-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function q8(o){if(o.type.startsWith("image/"))return URL.createObjectURL(o)}function Ed(o){const{adapter:a,maxConcurrent:t=3,rules:n,collection:i,onUploadStart:r,onUploadProgress:s,onUploadComplete:l,onUploadError:d,onQueueComplete:c,postUpload:u}=o,f=e.ref(new Map),m=e.ref(new Set),p=n?{rules:n}:{},{validateFile:h}=_d(p);async function v(){if(m.value.size>=t)return;const $=Array.from(f.value.entries()).find(([L,U])=>U.status==="pending"&&!m.value.has(L));if(!$){Array.from(f.value.values()).every(U=>U.status==="completed"||U.status==="error")&&f.value.size>0&&(c==null||c());return}const[y,R]=$;await w(y,R)}async function w($,y){m.value.add($),y.status="uploading",y.abortController=new AbortController,f.value.set($,{...y}),r==null||r(y);try{const R={onProgress:U=>{y.progress=U,f.value.set($,{...y}),s==null||s(y)},signal:y.abortController.signal};i&&(R.collection=i);const L=await a.upload(y.file,R);u&&(y.status="attaching",f.value.set($,{...y}),s==null||s(y),await u(y,L.media,a)),y.status="completed",y.progress=100,y.media=L.media,f.value.set($,{...y}),l==null||l(y,L.media)}catch(R){R.name==="AbortError"?f.value.delete($):(y.status="error",y.error=R.message,f.value.set($,{...y}),d==null||d(y,R))}finally{m.value.delete($),delete y.abortController,v()}}async function x($){var L;const y=Array.from($),R=[];for(const U of y){const z=await h(U),I=K8(),P=q8(U),Z={id:I,file:U,progress:0,status:z.valid?"pending":"error"};!z.valid&&((L=z.errors[0])!=null&&L.message)&&(Z.error=z.errors[0].message),P&&(Z.previewUrl=P),f.value.set(I,Z);const K={media:null,clientId:I,name:U.name,order:0,upload:Z,errors:z.errors};R.push(K)}for(let U=0;U<t;U++)v();return R}function T($){const y=f.value.get($);y&&(y.abortController&&y.abortController.abort(),y.previewUrl&&URL.revokeObjectURL(y.previewUrl),f.value.delete($),m.value.delete($),v())}async function _($){const y=f.value.get($);!y||y.status!=="error"||(y.status="pending",y.progress=0,delete y.error,f.value.set($,{...y}),v())}function g(){for(const[$,y]of f.value.entries())(y.status==="completed"||y.status==="error")&&(y.previewUrl&&URL.revokeObjectURL(y.previewUrl),f.value.delete($))}function E(){for(const $ of f.value.values())$.abortController&&$.abortController.abort(),$.previewUrl&&URL.revokeObjectURL($.previewUrl);f.value.clear(),m.value.clear()}function S($){return f.value.get($)}const N=e.computed(()=>m.value.size>0),V=e.computed(()=>m.value.size),A=e.computed(()=>Array.from(f.value.values()).filter($=>$.status==="pending").length),j=e.computed(()=>f.value.size===0?!0:Array.from(f.value.values()).every($=>$.status==="completed"||$.status==="error")),C=e.computed(()=>Array.from(f.value.values()));return{uploads:f,isUploading:N,activeCount:V,pendingCount:A,isComplete:j,addFiles:x,cancelUpload:T,retryUpload:_,clearCompleted:g,clearAll:E,getUpload:S,uploadsArray:C}}function Gn(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function wi(o){return typeof o=="string"?o:null}function gu(o){return typeof o=="number"?o:null}function Y8(o){return typeof o=="boolean"?o:null}function af(o){return Gn(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 Q8(o){return!Gn(o)||typeof o.id!="string"||typeof o.status!="string"?null:o.status==="ready"?af(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 e6(o){return Gn(o)?{next_cursor:wi(o.next_cursor),previous_cursor:wi(o.previous_cursor),has_more:Y8(o.has_more)??!1,per_page:gu(o.per_page),count:gu(o.count)}:null}function bu(o){const a=Gn(o)?o:{},t=Array.isArray(a.data)?a.data.filter(af):[],n=Gn(a.meta)?a.meta:{},i=e6(n.pagination),r=(i==null?void 0:i.next_cursor)??wi(n.next_cursor)??wi(n.cursor),s=(i==null?void 0:i.has_more)??n.has_more===!0,l=Array.isArray(a.hydrated)?a.hydrated.map(Q8).filter(c=>c!==null):[],d={cursor:r,has_more:s};return i!==null&&(d.pagination=i),{data:t,meta:d,hydrated:l}}function yu(o,a,t,n,i){const r={view:o.scope==="album"?{scope:"album",album_id:o.albumId}:{scope:"library"},per_page:t,sort:a.sort??"newest"};return a.query&&a.query.trim()!==""&&(r.query=a.query.trim()),a.kinds&&a.kinds.length>0&&(r.kinds=a.kinds),n!==null&&(r.cursor=n),i&&i.length>0&&(r.hydrate_ids=i),r}function wu(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 t6(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 a6(o){var a;return o instanceof Error?((a=o.response)==null?void 0:a.data)??null:null}function n6(o){if(!Gn(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 o6(o){var r;const a=a6(o),t=Gn(a)?a:null,n=((r=wi(t==null?void 0:t.message))==null?void 0:r.trim())??null,i=n6(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 ku(o,a){const t=o6(a),n=t6(a);return{code:n===403?"permission_denied":o,message:t,retriable:n!==403,cause:a}}function xd(o){const a=o.perPage??40,t=e.ref([]),n=e.ref([]),i=e.ref(null),r=e.ref(!1),s=e.ref(!1),l=e.ref(!1),d=e.ref(!1),c=e.ref(null);let u=null,f=0;const m=async v=>{f+=1;const w=f;u==null||u.abort();const x=new AbortController;u=x,v?l.value=!0:s.value=!0,c.value=null,d.value=!1;try{const T=await o.httpClient.get("/v1/media/library",{params:yu(o.view.value,o.filters.value,a,v?i.value:null),signal:x.signal});if(w!==f)return;const _=bu(T);t.value=v?wu([...t.value,..._.data]):_.data,n.value=_.hydrated,i.value=_.meta.cursor,r.value=_.meta.has_more}catch(T){if(x.signal.aborted||w!==f)return;const _=ku(v?"load_more_failed":"query_failed",T);c.value=_,d.value=_.code==="permission_denied",v||(t.value=[],i.value=null,r.value=!1)}finally{w===f&&(s.value=!1,l.value=!1)}};return{items:t,hydrated:n,cursor:i,hasMore:r,loading:s,loadingMore:l,permissionDenied:d,error:c,loadInitial:async()=>{i.value=null,await m(!1)},loadMore:async()=>{!r.value||l.value||await m(!0)},refresh:async()=>{i.value=null,await m(!1)},hydrateSelection:async v=>{if(v.length===0)return n.value=[],[];try{const w=await o.httpClient.get("/v1/media/library",{params:yu(o.view.value,o.filters.value,1,null,v)}),x=bu(w);return n.value=x.hydrated,x.hydrated}catch(w){return c.value=ku("hydration_failed",w),[]}},prepend:v=>{t.value=wu([v,...t.value])}}}const i6="mediables.media-library.";function r6(o){return!o||o.key.trim()===""?null:`${i6}${o.key}`}function qs(){return typeof window>"u"||typeof window.sessionStorage>"u"?null:window.sessionStorage}function s6(o,a){const t=Date.parse(o);return Number.isFinite(t)?Date.now()-t>a*60*1e3:!0}function nf(o){const a=r6(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=qs();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"||s6(u.savedAt,t))return l.removeItem(a),null;const f={selectedIds:Array.isArray(u.selectedIds)?u.selectedIds.filter(m=>typeof m=="string"&&m.trim()!==""):[]};return((o==null?void 0:o.restoreView)??!0)&&u.view&&(f.view=u.view),u.filters&&(f.filters=u.filters),f},save:l=>{if(a===null)return;const d=qs();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=qs();l==null||l.removeItem(a)},sessionId:n}}function of(o){const a=e.ref(o);return{state:a,transition:n=>{a.value=n}}}function rf(o){return{emitMetric:(t,n)=>{const i={name:t,timestamp:new Date().toISOString()};n!==void 0&&(i.payload=n),o==null||o(i)}}}function yo(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function l6(o){const a=yo(o)?o:{};return(Array.isArray(a.data)?a.data:yo(a.data)&&Array.isArray(a.data.data)?a.data.data:Array.isArray(o)?o:[]).map(n=>{if(!yo(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 d6(o){const a=yo(o)?o:{},t=yo(a.data)?a.data:yo(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 c6(o){return o==="ready"||o==="uploading"||o==="failed"}function sr(o,a="ready"){return{id:o.uuid,media:o,status:a,countsTowardMax:c6(a)}}function u6(o,a){return o.scope==="library"?!0:a.type==="album"&&a.albumId===o.albumId}function m6(o,a){return o.scope==="library"?a.type==="library"||a.type==="album":a.type==="album"&&a.albumId===o.albumId}function Ys(o){return{code:"configuration_error",message:o,retriable:!1}}function p6(o){return typeof o!="string"||o.length===0?"document":o.startsWith("image/")?"image":o.startsWith("video/")?"video":o.startsWith("audio/")?"audio":"document"}function f6(o,a){return a.length===0||o===null?!0:a.includes(p6(o.mime_type))}function sf(o){var ae,F,B;const a=o.selectionMode??"multiple",t=o.maxSelection,n=o.uploadBehavior??"adapter",i=e.ref(o.initialView??{scope:"library"}),r=((ae=o.initialFilters)==null?void 0:ae.kinds)??(o.allowedMediaKinds&&o.allowedMediaKinds.length>0?[...o.allowedMediaKinds]:void 0),s=e.ref({sort:((F=o.initialFilters)==null?void 0:F.sort)??"newest",...(B=o.initialFilters)!=null&&B.query?{query:o.initialFilters.query}:{},...r?{kinds:r}:{}}),l=o.allowedMediaKinds?[...o.allowedMediaKinds]:[],d=e.ref([]),c=e.ref([]),u=e.ref(null),f=e.ref(null),m=nf(o.sessionPolicy),{emitMetric:p}=rf(o.telemetry),h=of("idle"),v=xd({httpClient:o.deps.httpClient,view:i,filters:s}),w=e.computed(()=>c.value.map(O=>O.id)),x=e.computed(()=>{const O=u.value;return O===null?null:v.items.value[O]??null}),T=e.computed(()=>o.uploadTarget??{type:"library"}),_=Ed({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:O=>O.original_url,getThumbnailUrl:O=>O.thumbnail_url??O.preview_url??O.original_url},postUpload:async(O,X,oe)=>{const ce=T.value;ce.type!=="album"||!ce.albumId||await oe.attach(X.uuid,{modelType:"album",modelId:ce.albumId})},onUploadComplete:(O,X)=>{const oe=T.value;u6(i.value,oe)&&v.prepend(X),o.autoSelectUploaded&&m6(i.value,oe)&&A(X),p("upload-complete",{mediaId:X.uuid,targetType:oe.type,targetAlbumId:oe.albumId})},onUploadError:(O,X)=>{f.value={code:"upload_failed",message:X.message,retriable:!0,cause:X}}}),g=e.computed(()=>_.isUploading.value),E=()=>{m.save({selectedIds:[...w.value],view:i.value,filters:s.value})},S=async O=>{const X=await v.hydrateSelection(O);c.value=X.map(oe=>oe.status==="ready"&&oe.media?sr(oe.media):{id:oe.id,media:null,status:oe.status,countsTowardMax:!1})},N=e.computed(()=>c.value.filter(O=>O.countsTowardMax).length),V=()=>a==="single"||t===void 0?!0:N.value<t,A=O=>{if(c.value.findIndex(oe=>oe.id===O.uuid)>=0){a==="multiple"?c.value=c.value.filter(oe=>oe.id!==O.uuid):c.value=[sr(O)],E();return}if(!V()){f.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=[sr(O)]:c.value=[...c.value,sr(O)],f.value=null,E()},j=async()=>{var X;h.transition("restoring");const O=m.restore();if(O===null){h.transition("ready");return}O.view&&(i.value=O.view),O.filters&&(s.value={sort:O.filters.sort??"newest",...O.filters.query?{query:O.filters.query}:{},...O.filters.kinds?{kinds:O.filters.kinds}:{}}),await v.loadInitial(),(((X=o.sessionPolicy)==null?void 0:X.restoreSelection)??!0)&&await S(O.selectedIds),h.transition("ready")};e.watch(()=>v.error.value,O=>{O!==null&&(f.value=O,h.transition("error"))});const C=async()=>{f.value=null,h.transition("idle"),await j(),v.items.value.length===0&&!v.loading.value&&!v.permissionDenied.value&&await v.loadInitial();const O=o.defaultSelectedIds??[];c.value.length===0&&O.length>0&&await S(O),h.transition("ready")},$=async(O,X="user")=>{const oe=i.value;i.value=O,X==="user"&&o.preserveSelectionOnViewChange===!1&&(c.value=[]),p("view-change",{from:oe.scope,to:O.scope,reason:X}),await v.loadInitial(),E()},y=async()=>{const O=await o.deps.httpClient.get("/v1/albums");d.value=l6(O)},R=async(O,X)=>{try{const oe={name:O,visibility:"private"};X&&X.trim()!==""&&(oe.parent_id=X);const ce=await o.deps.httpClient.post("/v1/albums",oe),je=d6(ce);return je===null?Ys("Album creation response was invalid."):(d.value=[je,...d.value.filter(he=>he.id!==je.id)],await $({scope:"album",albumId:je.id,albumName:je.name},"inline-album-created"),je)}catch(oe){const ce={code:"album_create_failed",message:oe instanceof Error?oe.message:"Album creation failed.",retriable:!0,cause:oe};return f.value=ce,ce}},L=async O=>{if(!o.enableUpload){f.value=Ys("Uploads are not enabled for this picker.");return}if(n!=="delegate"){if(!o.deps.uploadAdapter){f.value=Ys("Uploads require a configured upload adapter.");return}await _.addFiles(O)}},U=()=>{var oe;if(l.length>0&&c.value.find(je=>je.media!==null&&!f6(je.media,l))){const he={code:"selection_invalid",message:`Selected media is not allowed here. Choose one of: ${l.join(", ")}.`,retriable:!0};return f.value=he,he}const O=((oe=o.validateSelection)==null?void 0:oe.call(o,c.value))??null;if(O!==null){const ce={code:"selection_invalid",message:O,retriable:!0};return f.value=ce,ce}if(c.value.filter(ce=>ce.status==="ready"&&ce.media!==null).length===0){const ce={code:"selection_invalid",message:"Select at least one available media item.",retriable:!0};return f.value=ce,ce}return{orderedIds:w.value,items:[...c.value],view:i.value,filters:s.value,dirty:!0,sessionId:m.sessionId}},z=O=>{const X=v.items.value.findIndex(oe=>oe.uuid===O.uuid);u.value=X>=0?X:null},I=()=>{u.value=null},P=()=>{u.value===null||u.value<=0||(u.value-=1)},Z=()=>{u.value===null||u.value>=v.items.value.length-1||(u.value+=1)},K=O=>{c.value=c.value.filter(X=>X.id!==O),E()},ve=async()=>{await v.refresh()},Ve=async O=>{s.value={...s.value,...O&&O.trim()!==""?{query:O.trim()}:{}},(!O||O.trim()==="")&&delete s.value.query,await v.loadInitial(),E()},ne=async()=>{await $({scope:"library"},"permission-unavailable")};return{view:i,filters:s,albums:d,selectedItems:c,orderedIds:w,queryItems:v.items,cursor:v.cursor,hasMore:v.hasMore,loading:v.loading,loadingMore:v.loadingMore,permissionDenied:v.permissionDenied,error:f,uploadQueue:_.uploadsArray,isUploading:g,previewIndex:u,previewItem:x,initialize:C,refresh:ve,loadMore:v.loadMore,setQuery:Ve,setView:$,toggleSelection:A,removeSelected:K,confirmSelection:U,openPreview:z,closePreview:I,showPreviousPreview:P,showNextPreview:Z,loadAlbums:y,createAlbum:R,addUploadFiles:L,goToLibrary:ne,sessionId:m.sessionId}}const h6=["data-testid"],v6={class:"mlp-location-bar"},g6={class:"mlp-location-bar__left"},b6={class:"mlp-location-bar__label"},y6={class:"mlp-tabs","data-testid":"media-picker-tabs"},w6={key:0,class:"mlp-search-row"},k6=["placeholder"],_6={key:2,class:"mlp-overlay-panel"},E6={key:0,class:"mlp-error","data-testid":"media-picker-error"},x6={key:5,class:"mlp-bottom-bar"},S6={key:0,class:"mlp-bottom-bar__selection"},C6={class:"mlp-bottom-bar__count"},V6={class:"mlp-bottom-bar__thumbs"},N6=["src","alt"],T6={key:1,class:"mlp-bottom-bar__thumb-placeholder"},I6=["aria-label","onClick"],B6={class:"mlp-bottom-bar__actions"},M6=e.defineComponent({__name:"MediaLibraryPicker",props:{deps:{},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","view-change","error","metric","request-upload-files"],setup(o,{expose:a,emit:t}){const n=o,i=t,r=e.computed(()=>{var P,Z,K,ve,Ve,ne,ae,F,B,O,X,oe,ce,je,he,ge,pe,we,ye,Ne,De,Qe,et,Lt,kt,Ct,bt,rt,_t,be,ke,Te;return{title:((P=n.labels)==null?void 0:P.title)??"Media library",searchPlaceholder:((Z=n.labels)==null?void 0:Z.searchPlaceholder)??"Search your media",viewLibrary:((K=n.labels)==null?void 0:K.viewLibrary)??"Library",browseAlbums:((ve=n.labels)==null?void 0:ve.browseAlbums)??"Albums",createAlbum:((Ve=n.labels)==null?void 0:Ve.createAlbum)??"Create album",createAlbumNameLabel:((ne=n.labels)==null?void 0:ne.createAlbumNameLabel)??"Album name",emptyLibrary:((ae=n.labels)==null?void 0:ae.emptyLibrary)??"No media found in your library.",emptyAlbum:((F=n.labels)==null?void 0:F.emptyAlbum)??"No media found in this album.",networkError:((B=n.labels)==null?void 0:B.networkError)??"Unable to load media right now.",retry:((O=n.labels)==null?void 0:O.retry)??"Retry",selectedCount:((X=n.labels)==null?void 0:X.selectedCount)??(Ke=>`${Ke} selected`),confirmAction:((oe=n.labels)==null?void 0:oe.confirmAction)??"Attach selected",cancel:((ce=n.labels)==null?void 0:ce.cancel)??"Cancel",dismiss:((je=n.labels)==null?void 0:je.dismiss)??"Remove",uploadLabel:((he=n.labels)==null?void 0:he.uploadLabel)??"Upload",albumUnavailableTitle:((ge=n.labels)==null?void 0:ge.albumUnavailableTitle)??"Album unavailable",albumUnavailableBody:((pe=n.labels)==null?void 0:pe.albumUnavailableBody)??"You no longer have access to this album.",goToLibrary:((we=n.labels)==null?void 0:we.goToLibrary)??"Go to library",allMediaTab:((ye=n.labels)==null?void 0:ye.allMediaTab)??"All Media",loadingMedia:((Ne=n.labels)==null?void 0:Ne.loadingMedia)??"Loading media…",loadMore:((De=n.labels)==null?void 0:De.loadMore)??"Load more",loadingMore:((Qe=n.labels)==null?void 0:Qe.loadingMore)??"Loading…",uploadDropzone:((et=n.labels)==null?void 0:et.uploadDropzone)??"Drop files here or browse",uploadDropzoneHelper:((Lt=n.labels)==null?void 0:Lt.uploadDropzoneHelper)??"",uploadDone:((kt=n.labels)==null?void 0:kt.uploadDone)??"Done",uploadDoneAria:((Ct=n.labels)==null?void 0:Ct.uploadDoneAria)??"Close upload panel",uploadFileInputLabel:((bt=n.labels)==null?void 0:bt.uploadFileInputLabel)??"Choose media files",previewClose:((rt=n.labels)==null?void 0:rt.previewClose)??"Close preview",previewPrevious:((_t=n.labels)==null?void 0:_t.previewPrevious)??"Previous media",previewNext:((be=n.labels)==null?void 0:be.previewNext)??"Next media",previewSelect:((ke=n.labels)==null?void 0:ke.previewSelect)??"Select media",previewDeselect:((Te=n.labels)==null?void 0:Te.previewDeselect)??"Deselect media"}}),s={deps:n.deps,selectionMode:n.selectionMode,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:P=>{var Z;(Z=n.telemetry)==null||Z.call(n,P),i("metric",P)}},l=sf(s),d=e.ref(n.initialFilters.query??""),c=e.ref(n.enableUpload?"upload":"media"),u=e.ref(!1),f=JSON.stringify(n.modelValue.length>0?n.modelValue:n.defaultSelectedIds);let m=null;const p=e.computed(()=>JSON.stringify(l.orderedIds.value)!==f),h=e.computed(()=>l.view.value.scope==="album"?r.value.emptyAlbum:r.value.emptyLibrary),v=e.computed(()=>r.value.selectedCount(l.selectedItems.value.length)),w=e.computed(()=>l.view.value.scope==="album"?l.view.value.albumName??"Album":r.value.viewLibrary),x=e.computed(()=>l.view.value.scope==="album"),T=()=>{m!==null&&(window.clearTimeout(m),m=null)},_=()=>{i("update:modelValue",[...l.orderedIds.value]),i("selection-change",{orderedIds:[...l.orderedIds.value],items:[...l.selectedItems.value],dirty:p.value})},g=P=>{P!==null&&i("error",P)},E=P=>typeof P.code=="string",S=P=>typeof P=="object"&&P!==null&&"code"in P&&typeof P.code=="string",N=()=>{const P=l.confirmSelection();if(E(P)){g(P);return}i("confirm",{...P,dirty:p.value})},V=(P="user")=>{i("cancel",{dirty:p.value,reason:P,sessionId:l.sessionId})},A=async()=>{c.value="albums",await l.loadAlbums()},j=async()=>{await l.goToLibrary(),c.value="albums",await l.loadAlbums()},C=P=>{l.setView({scope:"album",albumId:P.id,albumName:P.name}),c.value="media"},$=async(P,Z)=>{const K=l.view.value,ve=await l.createAlbum(P,Z);if(S(ve)){g(ve);return}u.value=!1,c.value="media",i("view-change",{from:K,to:{scope:"album",albumId:ve.id,albumName:ve.name},reason:"inline-album-created",restoredFromSession:!1})},y=async P=>{if(n.uploadBehavior==="delegate"){i("request-upload-files",{files:[...P],view:l.view.value,filters:l.filters.value,sessionId:l.sessionId});return}await l.addUploadFiles(P)};function R(P){var Z;return P?P.thumbnail_url??((Z=P.conversion_urls)==null?void 0:Z.thumb)??P.preview_url??P.original_url??P.url??null:null}function L(P){return P!=null&&P.mime_type?P.mime_type.startsWith("image/"):!1}e.watch(()=>d.value,P=>{T(),m=window.setTimeout(()=>{l.setQuery(P)},250)}),e.watch(()=>l.selectedItems.value,()=>{_()},{deep:!0}),e.watch(()=>l.error.value,P=>{g(P)}),e.watch(()=>n.enableUpload,P=>{!P&&c.value==="upload"&&(c.value="media")}),e.onMounted(()=>{l.initialize()}),e.onBeforeUnmount(()=>{T()}),a({refresh:l.refresh});function U(P){if(P==="albums"){A();return}if(P==="upload"&&!n.enableUpload){c.value="media";return}c.value=P}const z=e.computed(()=>({activeTab:c.value,setActiveTab:U,enableUpload:n.enableUpload,labels:{uploadLabel:r.value.uploadLabel,allMediaTab:r.value.allMediaTab,browseAlbums:r.value.browseAlbums}})),I=e.computed(()=>({query:d.value,setQuery:P=>{d.value=P},placeholder:r.value.searchPlaceholder}));return(P,Z)=>(e.openBlock(),e.createElementBlock("section",{class:"media-library-picker","data-testid":P.testIdPrefix},[e.createElementVNode("header",v6,[e.createElementVNode("div",g6,[x.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:j},[...Z[8]||(Z[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",b6,e.toDisplayString(w.value),1)])]),e.renderSlot(P.$slots,"tabs",e.normalizeProps(e.guardReactiveProps(z.value)),()=>[e.createElementVNode("nav",y6,[P.enableUpload?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:e.normalizeClass(["mlp-tabs__tab",{"is-active":c.value==="upload"}]),"data-testid":"tab-media-picker-upload",onClick:Z[0]||(Z[0]=K=>c.value="upload")},e.toDisplayString(r.value.uploadLabel),3)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["mlp-tabs__tab",{"is-active":c.value==="media"}]),"data-testid":"tab-media-picker-all",onClick:Z[1]||(Z[1]=K=>c.value="media")},e.toDisplayString(r.value.allMediaTab),3),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["mlp-tabs__tab",{"is-active":c.value==="albums"}]),"data-testid":"tab-media-picker-albums",onClick:A},e.toDisplayString(r.value.browseAlbums),3)])],!0),c.value==="media"||c.value==="albums"?(e.openBlock(),e.createElementBlock("div",w6,[e.renderSlot(P.$slots,"search",e.normalizeProps(e.guardReactiveProps(I.value)),()=>[Z[9]||(Z[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":Z[2]||(Z[2]=K=>d.value=K),class:"mlp-search-row__input",type:"search",placeholder:r.value.searchPlaceholder,"data-testid":"input-media-picker-search"},null,8,k6),[[e.vModelText,d.value]])],!0)])):e.createCommentVNode("",!0),P.enableUpload&&c.value==="upload"?(e.openBlock(),e.createBlock(Kp,{key:1,open:!0,queue:e.unref(l).uploadQueue.value,accept:P.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:Z[3]||(Z[3]=K=>c.value="media"),onFilesSelected:y},null,8,["queue","accept","upload-label","dropzone-label","dropzone-helper-text","file-input-label","close-button-label","close-button-aria-label"])):e.createCommentVNode("",!0),u.value?(e.openBlock(),e.createElementBlock("div",_6,[e.createVNode(Up,{open:u.value,"name-label":r.value.createAlbumNameLabel,albums:e.unref(l).albums.value,onCancel:Z[4]||(Z[4]=K=>u.value=!1),onCreate:$},null,8,["open","name-label","albums"])])):e.createCommentVNode("",!0),e.unref(l).permissionDenied.value&&e.unref(l).view.value.scope==="album"?(e.openBlock(),e.createBlock(Op,{key:3,title:r.value.albumUnavailableTitle,body:r.value.albumUnavailableBody,"action-label":r.value.goToLibrary,onGoToLibrary:e.unref(l).goToLibrary},null,8,["title","body","action-label","onGoToLibrary"])):e.createCommentVNode("",!0),!e.unref(l).permissionDenied.value||e.unref(l).view.value.scope!=="album"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:4},[e.unref(l).error.value?(e.openBlock(),e.createElementBlock("div",E6,[e.createElementVNode("p",null,e.toDisplayString(e.unref(l).error.value.message||r.value.networkError),1),e.createElementVNode("button",{type:"button",class:"mlp-error__retry",onClick:Z[5]||(Z[5]=(...K)=>e.unref(l).refresh&&e.unref(l).refresh(...K))},e.toDisplayString(r.value.retry),1)])):e.createCommentVNode("",!0),c.value==="media"?(e.openBlock(),e.createBlock(Yp,{key:1,items:e.unref(l).queryItems.value,"selected-items":e.unref(l).selectedItems.value,loading:e.unref(l).loading.value,"loading-more":e.unref(l).loadingMore.value,"has-more":e.unref(l).hasMore.value,"empty-message":h.value,"loading-message":r.value.loadingMedia,"load-more-label":r.value.loadMore,"loading-more-label":r.value.loadingMore,"test-id-prefix":`${P.testIdPrefix}-item`,onToggle:e.unref(l).toggleSelection,onPreview:e.unref(l).openPreview,onLoadMore:e.unref(l).loadMore},null,8,["items","selected-items","loading","loading-more","has-more","empty-message","loading-message","load-more-label","loading-more-label","test-id-prefix","onToggle","onPreview","onLoadMore"])):c.value==="albums"?(e.openBlock(),e.createBlock(Jp,{key:2,open:!0,"current-view":e.unref(l).view.value,albums:e.unref(l).albums.value,"view-library-label":r.value.viewLibrary,"browse-albums-label":r.value.browseAlbums,"create-album-label":r.value.createAlbum,"enable-album-creation":P.enableAlbumCreation,onSelectLibrary:j,onSelectAlbum:C,onCreateAlbum:Z[6]||(Z[6]=K=>u.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),P.showFooter?(e.openBlock(),e.createElementBlock("footer",x6,[e.unref(l).selectedItems.value.length>0?(e.openBlock(),e.createElementBlock("div",S6,[e.createElementVNode("span",C6,e.toDisplayString(v.value),1),e.createElementVNode("div",V6,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(l).selectedItems.value,K=>{var ve,Ve,ne;return e.openBlock(),e.createElementBlock("div",{key:K.id,class:"mlp-bottom-bar__thumb-item"},[L(K.media)&&R(K.media)?(e.openBlock(),e.createElementBlock("img",{key:0,src:R(K.media),alt:((ve=K.media)==null?void 0:ve.alt_text)??((Ve=K.media)==null?void 0:Ve.file_name)??"Selected",class:"mlp-bottom-bar__thumb-img"},null,8,N6)):(e.openBlock(),e.createElementBlock("div",T6,[...Z[10]||(Z[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} ${((ne=K.media)==null?void 0:ne.file_name)??K.id}`,"data-testid":"btn-media-picker-remove-selected",onClick:ae=>e.unref(l).removeSelected(K.id)},[...Z[11]||(Z[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,I6)])}),128))])])):e.createCommentVNode("",!0),e.createElementVNode("div",B6,[e.createElementVNode("button",{type:"button",class:"mlp-bottom-bar__cancel","data-testid":"btn-media-picker-cancel",onClick:Z[7]||(Z[7]=K=>V())},e.toDisplayString(r.value.cancel),1),e.createElementVNode("button",{type:"button",class:"mlp-bottom-bar__confirm","data-testid":"btn-media-picker-confirm",onClick:N},e.toDisplayString(r.value.confirmAction),1)])])):e.createCommentVNode("",!0),P.enablePreview?(e.openBlock(),e.createBlock(Gp,{key:6,open:e.unref(l).previewItem.value!==null,media:e.unref(l).previewItem.value,"can-go-previous":e.unref(l).previewIndex.value!==null&&e.unref(l).previewIndex.value>0,"can-go-next":e.unref(l).previewIndex.value!==null&&e.unref(l).previewIndex.value<e.unref(l).queryItems.value.length-1,selected:e.unref(l).previewItem.value!==null&&e.unref(l).orderedIds.value.includes(e.unref(l).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(l).closePreview,onPrevious:e.unref(l).showPreviousPreview,onNext:e.unref(l).showNextPreview,onToggleSelect:e.unref(l).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,h6))}}),lf=Be(M6,[["__scopeId","data-v-68a73e25"]]),F6={key:0,class:"media-library-picker-modal","data-testid":"media-library-picker-modal"},$6={class:"media-library-picker-modal__panel"},D6=e.defineComponent({__name:"MediaLibraryPickerModal",props:{deps:{},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",F6,[e.createElementVNode("button",{type:"button",class:"media-library-picker-modal__backdrop","aria-label":"Close media picker",onClick:i}),e.createElementVNode("div",$6,[e.createVNode(lf,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)}}),R6=Be(D6,[["__scopeId","data-v-a92e8703"]]),A6={key:0,class:"media-selection-tray","data-testid":"media-selection-tray"},L6={class:"media-selection-tray__header"},P6={class:"media-selection-tray__title"},U6={class:"media-selection-tray__items"},O6={class:"media-selection-tray__item-preview"},z6=["src","alt"],j6={key:1,class:"media-selection-tray__file-icon"},W6={class:"media-selection-tray__item-copy"},H6=["aria-label","onClick"],Z6=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",A6,[e.createElementVNode("header",L6,[e.createElementVNode("h3",P6,e.toDisplayString(r.selectedCountLabel),1)]),e.createElementVNode("div",U6,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.items,l=>{var d,c,u,f;return e.openBlock(),e.createElementBlock("article",{key:l.id,class:"media-selection-tray__item"},[e.createElementVNode("div",O6,[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,z6)):(e.openBlock(),e.createElementBlock("div",j6,[...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",W6,[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} ${((f=l.media)==null?void 0:f.file_name)??l.id}`,onClick:m=>t("remove",l.id)},e.toDisplayString(r.dismissLabel),9,H6)])}),128))])])):e.createCommentVNode("",!0)}}),X6=Be(Z6,[["__scopeId","data-v-f2a3d69d"]]);function Sd(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=T=>{if(r.value++,d.value=null,i.value=null,t.value=!1,T!=null&&typeof T=="object"&&!(T instanceof Blob)&&("image"in T||"state"in T||"sessionKey"in T)){const _=T;n.value=_.image??null,l.value=_.state??null,s.value=_.sessionKey??r.value}else n.value=T??null,l.value=null,s.value=r.value;a.value=!0},f=()=>{a.value=!1,n.value=null,i.value=null,d.value=null,t.value=!1,l.value=null},m=async T=>{try{return t.value=!0,i.value=T,o.onSave&&await o.onSave(T),f(),T}catch(_){const g=_;throw d.value=g,o.onError&&o.onError(g),g}finally{t.value=!1}},p=()=>{o.onCancel&&o.onCancel(),f()},h=T=>{d.value=T,o.onError&&o.onError(T)},v=()=>{d.value=null},w=()=>i.value,x=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:x,open:u,close:f,handleSave:m,handleCancel:p,handleError:h,clearError:v,getEditedImage:w}}let Qs=null;function G6(o){return Qs||(Qs=Sd(o)),Qs}function J6(o){return a=>new Promise((t,n)=>{Sd({...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 Cd(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 zl(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 Vd(o){if(o){const t={};o.apiBaseUrl!==void 0&&(t.apiBaseUrl=o.apiBaseUrl),o.isAdmin!==void 0&&(t.isAdmin=o.isAdmin),wo(t)}return{name:"mediables",async upload(t,n){const r=await va().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 va().attachMedia(n.modelType,String(n.modelId),[t],n.collection||"images")},async attachMany(t,n){await va().attachMedia(n.modelType,String(n.modelId),t,n.collection||"images")},async detach(t,n){await va().detachMedia(n.modelType,String(n.modelId),t,n.collection||"images")},async reorder(t,n){await va().reorderMedia(t.modelType,String(t.modelId),n,t.collection||"images")},async fetchModelMedia(t){return await va().fetchModelMedia(t.modelType,String(t.modelId),t.collection||"images")},getUrl(t,n){return va().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 va().deleteMedia(t)},async update(t,n){const r=await va().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),wo(n)}}}let kr=null;function K6(){return kr||(kr=Vd()),kr}function q6(){kr=null}const Y6={apiBaseUrl:"/media-library-pro"};function lr(){var o;return typeof document>"u"?null:((o=document.querySelector('meta[name="csrf-token"]'))==null?void 0:o.getAttribute("content"))||null}function el(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 Nd(o){const a={...Y6,...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||lr();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 m=await c.json().catch(()=>({message:"Upload failed"}));throw new Error(m.message||`HTTP ${c.status}`)}const u=await c.json(),f=el(u);return i!=null&&i.onProgress&&i.onProgress(100),{media:f,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||lr();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(el)}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||lr();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||lr();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 el(d)},configure(n){Object.assign(a,n)}}}let _r=null;function Q6(){return _r||(_r=Nd()),_r}function e$(){_r=null}function df(o,a){switch(o){case"mediables":return Vd(a);case"spatie":return Nd(a);default:throw new Error(`Unknown adapter: ${o}`)}}function cf(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(T,_,g){a&&("dataTransfer"in T&&T.dataTransfer&&(T.dataTransfer.effectAllowed="move",T.dataTransfer.setData("text/plain",String(g))),c=T.target,c&&c.classList.add(r),l.value={isDragging:!0,dragIndex:g,dropIndex:g,draggedItem:_},d.value=!0,n==null||n(_,g))}function f(T,_){var g;if(!(!a||!l.value.isDragging)&&(T.preventDefault(),l.value.dropIndex!==_)){const E=document.querySelector(`.${s}`);E==null||E.classList.remove(s);const S=(g=T.target)==null?void 0:g.closest("[data-index]");S==null||S.classList.add(s),l.value.dropIndex=_}}function m(){if(!l.value.isDragging)return;const{dragIndex:T,dropIndex:_,draggedItem:g}=l.value;c&&c.classList.remove(r);const E=document.querySelector(`.${s}`);E==null||E.classList.remove(s),T!==null&&_!==null&&T!==_&&g&&(t==null||t({fromIndex:T,toIndex:_,item:g})),h(),i==null||i()}function p(){c&&c.classList.remove(r);const T=document.querySelector(`.${s}`);T==null||T.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(T,_,g){const E=[...T],[S]=E.splice(_,1);return E.splice(g,0,S),E.map((N,V)=>({...N,order:V}))}function w(T,_){return{draggable:a,"data-index":_,onDragstart:g=>u(g,T,_),onDragover:g=>f(g,_),onDragend:()=>m(),onDrop:g=>{g.preventDefault(),m()}}}function x(T){T.key==="Escape"&&l.value.isDragging&&p()}return e.onMounted(()=>{document.addEventListener("keydown",x)}),e.onUnmounted(()=>{document.removeEventListener("keydown",x),p()}),{dragState:l,isDragging:d,startDrag:u,handleDragOver:f,endDrag:m,cancelDrag:p,reorderItems:v,getDragProps:w}}function vs(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:f="mediables",adapter:m,maxConcurrentUploads:p=3,onChange:h,onUpload:v,onUploadComplete:w,onUploadError:x,onRemove:T,onReorder:_,onError:g,onReadyToSubmitChange:E}=o,S={maxItems:r,maxFileSize:s,acceptedMimeTypes:l,...u},N=m||df(f),V=e.ref([]),A=e.ref(!1),j=e.ref([]);function C(pe){if(pe.length===0)return[];const we=pe[0];return"media"in we&&"clientId"in we?pe:zl(pe)}V.value=C(a);const{acceptString:$,canAddFiles:y}=_d({rules:S}),R=Ed({adapter:N,maxConcurrent:p,rules:S,collection:i,onUploadStart:pe=>{v==null||v(pe)},onUploadComplete:(pe,we)=>{const ye=V.value.findIndex(Ne=>Ne.clientId===pe.id);ye!==-1&&(V.value[ye]={...V.value[ye],media:we,name:we.name||we.file_name,upload:{...pe,status:"completed"}}),w==null||w(we)},onUploadError:(pe,we)=>{const ye=V.value.findIndex(Ne=>Ne.clientId===pe.id);ye!==-1&&(V.value[ye]={...V.value[ye],upload:{...pe,status:"error",error:we.message},errors:[{field:"upload",message:we.message,code:"UPLOAD_ERROR"}]}),x==null||x({file:pe.file,message:we.message})},onQueueComplete:()=>{h==null||h(V.value)}}),{dragState:L,getDragProps:U,reorderItems:z}=cf({enabled:d&&!c,onReorder:pe=>{V.value=z(V.value,pe.fromIndex,pe.toIndex),_==null||_(V.value),h==null||h(V.value)}}),I=e.computed(()=>R.isUploading.value),P=e.computed(()=>!R.isUploading.value&&R.pendingCount.value===0),Z=e.computed(()=>r?V.value.length>=r:!1),K=e.computed(()=>Cd(V.value)),ve=e.computed(()=>V.value.length),Ve=e.computed(()=>r?Math.max(0,r-V.value.length):1/0);e.watch(P,pe=>{E==null||E(pe)});function ne(pe){V.value=C(pe),h==null||h(V.value)}async function ae(pe){if(c)return;const we=Array.from(pe);if(!y(we.length,V.value.length)){const Qe={field:"count",message:`Maximum ${r} files allowed`,code:"MAX_ITEMS"};j.value=[Qe],g==null||g([Qe]);return}const ye=await R.addFiles(we),Ne=V.value.length,De=ye.map((Qe,et)=>({...Qe,order:Ne+et}));V.value=[...V.value,...De],h==null||h(V.value)}function F(pe){c||(pe.upload&&(pe.upload.status==="uploading"||pe.upload.status==="pending")&&R.cancelUpload(pe.clientId),V.value=V.value.filter(we=>we.clientId!==pe.clientId),V.value=V.value.map((we,ye)=>({...we,order:ye})),T==null||T(pe),h==null||h(V.value))}function B(pe){const we=V.value.find(ye=>ye.clientId===pe);we&&F(we)}function O(){c||(R.clearAll(),V.value=[],h==null||h(V.value))}function X(pe,we){c||!d||(V.value=z(V.value,pe,we),_==null||_(V.value),h==null||h(V.value))}function oe(pe,we){if(c)return;const ye=V.value.findIndex(Ne=>Ne.clientId===pe);ye!==-1&&(V.value[ye]={...V.value[ye],...we},h==null||h(V.value))}function ce(pe){R.cancelUpload(pe),B(pe)}async function je(pe){await R.retryUpload(pe)}async function he(){if(!t||!n)throw new Error("modelType and modelId are required for save()");const pe={modelType:t,modelId:n,collection:i},we=V.value.filter(ye=>ye.media&&!ye.markedForRemoval).map(ye=>ye.media.uuid);A.value=!0;try{await N.attachMany(we,pe),await N.reorder(pe,we)}finally{A.value=!1}}async function ge(){if(!t||!n)throw new Error("modelType and modelId are required for load()");const pe={modelType:t,modelId:n,collection:i};A.value=!0;try{const we=await N.fetchModelMedia(pe);V.value=zl(we),h==null||h(V.value)}finally{A.value=!1}}return e.onMounted(()=>{t&&n&&a.length===0&&ge().catch(console.error)}),e.onUnmounted(()=>{R.clearAll()}),{items:V,setItems:ne,addFiles:ae,removeItem:F,removeItemById:B,clearAll:O,reorderItems:X,updateItem:oe,cancelUpload:ce,retryUpload:je,save:he,load:ge,isLoading:A,isUploading:I,isReadyToSubmit:P,isAtMaxItems:Z,errors:j,dragState:L,getDragProps:U,adapter:N,formValues:K,acceptString:$,count:ve,remainingSlots:Ve}}const t$=["aria-disabled"],a$=["accept","multiple","disabled"],n$={class:"media-dropzone__content"},o$={class:"media-dropzone__title"},i$={class:"media-dropzone__subtitle"},r$=["disabled"],s$={key:0,class:"media-dropzone__helper"},l$=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: ${Or(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 f(v){var x;if(v.preventDefault(),i.value=!1,t.disabled)return;const w=(x=v.dataTransfer)==null?void 0:x.files;w&&w.length>0&&n("files",w)}function m(){var v;t.disabled||(v=r.value)==null||v.click()}function p(v){const w=v.target,x=w.files;x&&x.length>0&&n("files",x),w.value=""}function h(v){(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),m())}return(v,w)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(s.value),role:"button",tabindex:"0","aria-disabled":v.disabled,"aria-label":"Upload files",onClick:m,onKeydown:h,onDragenter:d,onDragleave:c,onDragover:u,onDrop:f},[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,a$),e.createElementVNode("div",n$,[e.renderSlot(v.$slots,"icon",{},()=>[w[0]||(w[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",o$,[e.renderSlot(v.$slots,"title",{},()=>[e.createTextVNode(e.toDisplayString(v.title),1)],!0)]),e.createElementVNode("p",i$,[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(m,["stop"])},[e.renderSlot(v.$slots,"button",{},()=>[e.createTextVNode(e.toDisplayString(v.buttonText),1)],!0)],8,r$),l.value?(e.openBlock(),e.createElementBlock("p",s$,e.toDisplayString(l.value),1)):e.createCommentVNode("",!0)])],42,t$))}}),Td=Be(l$,[["__scopeId","data-v-b1366c1e"]]),d$=["data-index"],c$={key:0,class:"media-item__drag-handle","aria-label":"Drag to reorder",role:"button",tabindex:"0"},u$={class:"media-item__thumbnail"},m$=["src","alt"],p$={key:1,class:"media-item__file-icon"},f$={key:2,class:"media-item__progress-overlay"},h$={class:"media-item__progress-text"},v$={key:3,class:"media-item__processing-overlay"},g$={key:4,class:"media-item__error-overlay"},b$={class:"media-item__info"},y$=["title"],w$={key:0,class:"media-item__size"},k$={key:1,class:"media-item__error-message"},_$={class:"media-item__actions"},E$=["disabled"],x$=["disabled"],S$=["disabled"],C$=["disabled"],V$=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 _;return(_=t.item.upload)!=null&&_.previewUrl?t.item.upload.previewUrl:t.item.media?t.adapter.getThumbnailUrl(t.item.media):null}),s=e.computed(()=>{var _,g,E;return((_=t.item.upload)==null?void 0:_.status)==="uploading"||((g=t.item.upload)==null?void 0:g.status)==="pending"||((E=t.item.upload)==null?void 0:E.status)==="queued"}),l=e.computed(()=>{var _;return((_=t.item.upload)==null?void 0:_.status)==="processing"}),d=e.computed(()=>{var _;return((_=t.item.upload)==null?void 0:_.status)==="error"||t.item.errors&&t.item.errors.length>0}),c=e.computed(()=>{var _;return(_=t.item.upload)!=null&&_.error?t.item.upload.error:t.item.errors&&t.item.errors.length>0?t.item.errors[0].message:null}),u=e.computed(()=>{var _;return((_=t.item.upload)==null?void 0:_.progress)||0}),f=e.computed(()=>{var _;return t.item.name||((_=t.item.media)==null?void 0:_.file_name)||"Unknown file"}),m=e.computed(()=>{var N,V;const _=((N=t.item.media)==null?void 0:N.size)||((V=t.item.upload)==null?void 0:V.file.size);if(!_)return"";const g=1024,E=["Bytes","KB","MB","GB"],S=Math.floor(Math.log(_)/Math.log(g));return parseFloat((_/Math.pow(g,S)).toFixed(2))+" "+E[S]}),p=e.computed(()=>{var g,E;const _=((g=t.item.media)==null?void 0:g.mime_type)||((E=t.item.upload)==null?void 0:E.file.type);return _==null?void 0:_.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 w(){t.disabled||n("edit",t.item)}function x(){t.disabled||n("retry",t.item)}function T(){t.disabled||n("cancel",t.item)}return(_,g)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(h.value),"data-index":_.index,onMouseenter:g[0]||(g[0]=E=>i.value=!0),onMouseleave:g[1]||(g[1]=E=>i.value=!1)},[_.sortable&&!_.disabled?(e.openBlock(),e.createElementBlock("div",c$,[...g[2]||(g[2]=[e.createStaticVNode('<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" data-v-ff81c9ec><circle cx="9" cy="5" r="1" data-v-ff81c9ec></circle><circle cx="9" cy="12" r="1" data-v-ff81c9ec></circle><circle cx="9" cy="19" r="1" data-v-ff81c9ec></circle><circle cx="15" cy="5" r="1" data-v-ff81c9ec></circle><circle cx="15" cy="12" r="1" data-v-ff81c9ec></circle><circle cx="15" cy="19" r="1" data-v-ff81c9ec></circle></svg>',1)])])):e.createCommentVNode("",!0),e.createElementVNode("div",u$,[r.value&&p.value?(e.openBlock(),e.createElementBlock("img",{key:0,src:r.value,alt:f.value,class:"media-item__image"},null,8,m$)):(e.openBlock(),e.createElementBlock("div",p$,[...g[3]||(g[3]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.createElementVNode("polyline",{points:"14 2 14 8 20 8"})],-1)])])),s.value?(e.openBlock(),e.createElementBlock("div",f$,[e.createElementVNode("div",{class:"media-item__progress-bar",style:e.normalizeStyle({width:`${u.value}%`})},null,4),e.createElementVNode("span",h$,e.toDisplayString(u.value)+"%",1)])):e.createCommentVNode("",!0),l.value?(e.openBlock(),e.createElementBlock("div",v$,[...g[4]||(g[4]=[e.createElementVNode("div",{class:"media-item__spinner","aria-label":"Processing"},null,-1)])])):e.createCommentVNode("",!0),d.value?(e.openBlock(),e.createElementBlock("div",g$,[...g[5]||(g[5]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("circle",{cx:"12",cy:"12",r:"10"}),e.createElementVNode("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),e.createElementVNode("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})],-1)])])):e.createCommentVNode("",!0)]),e.createElementVNode("div",b$,[e.createElementVNode("span",{class:"media-item__name",title:f.value},e.toDisplayString(f.value),9,y$),m.value?(e.openBlock(),e.createElementBlock("span",w$,e.toDisplayString(m.value),1)):e.createCommentVNode("",!0),c.value?(e.openBlock(),e.createElementBlock("span",k$,e.toDisplayString(c.value),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",_$,[s.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-item__action media-item__action--cancel",disabled:_.disabled,"aria-label":"Cancel upload",onClick:T},[...g[6]||(g[6]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.createElementVNode("line",{x1:"6",y1:"6",x2:"18",y2:"18"})],-1)])],8,E$)):e.createCommentVNode("",!0),d.value?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button",class:"media-item__action media-item__action--retry",disabled:_.disabled,"aria-label":"Retry upload",onClick:x},[...g[7]||(g[7]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("polyline",{points:"23 4 23 10 17 10"}),e.createElementVNode("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})],-1)])],8,x$)):e.createCommentVNode("",!0),_.showEdit&&_.item.media&&!s.value?(e.openBlock(),e.createElementBlock("button",{key:2,type:"button",class:"media-item__action media-item__action--edit",disabled:_.disabled,"aria-label":"Edit",onClick:w},[...g[8]||(g[8]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),e.createElementVNode("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})],-1)])],8,S$)):e.createCommentVNode("",!0),_.showRemove?(e.openBlock(),e.createElementBlock("button",{key:3,type:"button",class:"media-item__action media-item__action--remove",disabled:_.disabled,"aria-label":"Remove",onClick:v},[...g[9]||(g[9]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("polyline",{points:"3 6 5 6 21 6"}),e.createElementVNode("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})],-1)])],8,C$)):e.createCommentVNode("",!0)])],42,d$))}}),Id=Be(V$,[["__scopeId","data-v-ff81c9ec"]]),N$=["aria-label"],T$=["draggable","data-index","onDragstart","onDragover","onDragend","onDrop"],I$={key:0,class:"media-collection__footer"},B$={class:"media-collection__count"},M$={key:0},F$={key:0,class:"media-collection__uploading"},$$=["name","value"],D$=["name","value"],R$=["name","value"],A$=["name","value"],L$={key:3,class:"media-collection__errors",role:"alert","aria-live":"polite"},P$=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:f,isLoading:m,isUploading:p,isAtMaxItems:h,errors:v,dragState:w,getDragProps:x,adapter:T,formValues:_,acceptString:g,count:E,remainingSlots:S}=vs(i);e.provide("mediaAdapter",T),e.provide("mediaCollection",{items:r,addFiles:l,removeItem:d,reorderItems:c}),e.watch(()=>t.modelValue,I=>{I!==r.value&&s(I)},{deep:!0});const N=e.computed(()=>t.showUploadZone&&!t.disabled&&!t.readonly&&!h.value),V=e.computed(()=>({"media-collection":!0,"media-collection--disabled":t.disabled,"media-collection--readonly":t.readonly,"media-collection--loading":m.value,"media-collection--has-items":r.value.length>0,"media-collection--dragging":w.value.isDragging}));function A(I){l(I)}function j(I){d(I)}function C(I){f(I.clientId)}function $(I){u(I.clientId)}function y(I){}function R(I,P,Z){if(!t.sortable||t.disabled)return;const K=x(P,Z);K.onDragstart&&K.onDragstart(I)}function L(I,P){if(!t.sortable||t.disabled)return;I.preventDefault();const Z=r.value[P],K=x(Z,P);K.onDragover&&K.onDragover(I)}function U(I,P){const Z=x(I,P);Z.onDragend&&Z.onDragend()}function z(I,P){I.preventDefault();const Z=r.value[P],K=x(Z,P);K.onDrop&&K.onDrop(I)}return(I,P)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(V.value)},[e.renderSlot(I.$slots,"dropzone",{addFiles:e.unref(l)},()=>[N.value?(e.openBlock(),e.createBlock(Td,{key:0,accept:e.unref(g),multiple:I.maxItems!==1,disabled:I.disabled,"max-file-size":I.maxFileSize,"max-items":e.unref(S),onFiles:A},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(E)} 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:()=>j(Z)},()=>[e.createElementVNode("div",{class:e.normalizeClass(["media-collection__item-wrapper",{"media-collection__item-wrapper--drag-over":e.unref(w).dropIndex===K}]),draggable:I.sortable&&!I.disabled,"data-index":K,onDragstart:ve=>R(ve,Z,K),onDragover:ve=>L(ve,K),onDragend:ve=>U(Z,K),onDrop:ve=>z(ve,K)},[e.createVNode(Id,{item:Z,adapter:e.unref(T),disabled:I.disabled,sortable:I.sortable,"show-remove":!I.readonly,"show-edit":!1,index:K,onRemove:j,onRetry:C,onCancel:$,onEdit:y},null,8,["item","adapter","disabled","sortable","show-remove","index"])],42,T$)],!0)),128))],8,N$)):N.value?e.createCommentVNode("",!0):e.renderSlot(I.$slots,"empty",{key:1},()=>[P[0]||(P[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(E),isUploading:e.unref(p)},()=>[e.unref(r).length>0?(e.openBlock(),e.createElementBlock("div",I$,[e.createElementVNode("span",B$,[e.createTextVNode(e.toDisplayString(e.unref(E))+" "+e.toDisplayString(e.unref(E)===1?"file":"files")+" ",1),I.maxItems?(e.openBlock(),e.createElementBlock("span",M$," / "+e.toDisplayString(I.maxItems)+" max",1)):e.createCommentVNode("",!0)]),e.unref(p)?(e.openBlock(),e.createElementBlock("span",F$," 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(_),(Z,K)=>(e.openBlock(),e.createElementBlock("input",{key:`${I.name}-${Z.uuid}`,type:"hidden",name:`${I.name}[${K}][uuid]`,value:Z.uuid},null,8,$$))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(_),(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,D$))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(_),(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,R$))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(_),(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,A$)):e.createCommentVNode("",!0)],64))),128))],64)):e.createCommentVNode("",!0),e.unref(v).length>0?(e.openBlock(),e.createElementBlock("div",L$,[(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))}}),U$=Be(P$,[["__scopeId","data-v-10a5bfff"]]);function Bd(o={}){const{initialItem:a,onChange:t,onReplace:n,onUpload:i,onUploadComplete:r,onUploadError:s,onRemove:l,onError:d,onReadyToSubmitChange:c,...u}=o,m={...u,initialItems:a?[a]:[],maxItems:1,sortable:!1,onChange:N=>{t==null||t(N[0]||null)},onUpload:i,onUploadComplete:r,onUploadError:s,onRemove:l,onError:d,onReadyToSubmitChange:c},p=vs(m),h=e.computed(()=>p.items.value[0]||null),v=e.computed(()=>h.value!==null),w=e.computed(()=>p.formValues.value[0]||null);function x(N){N===null?p.clearAll():p.setItems([N])}async function T(N){const V=h.value;V&&p.removeItem(V),await p.addFiles([N])}function _(){h.value&&p.removeItem(h.value)}async function g(N){const V=h.value;V&&p.removeItem(V),await p.addFiles([N]);const A=p.items.value[0];A&&(n==null||n(V,A))}function E(){var N;(N=h.value)!=null&&N.upload&&p.cancelUpload(h.value.clientId)}async function S(){var N,V;((V=(N=h.value)==null?void 0:N.upload)==null?void 0:V.status)==="error"&&await p.retryUpload(h.value.clientId)}return{item:h,setItem:x,addFile:T,removeItem:_,replaceItem:g,cancelUpload:E,retryUpload:S,save:p.save,load:p.load,isLoading:p.isLoading,isUploading:p.isUploading,isReadyToSubmit:p.isReadyToSubmit,hasItem:v,errors:p.errors,adapter:p.adapter,formValue:w,acceptString:p.acceptString}}const O$=["accept","disabled"],z$={class:"media-attachment__preview"},j$=["name","value"],W$=["name","value"],H$=["name","value"],Z$=["name","value"],X$={key:4,class:"media-attachment__errors",role:"alert","aria-live":"polite"},G$=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:C=>{n("update:modelValue",C),n("change",C)},onUpload:C=>{n("upload",C)},onUploadComplete:C=>{n("upload-complete",C)},onUploadError:C=>{n("upload-error",C)},onRemove:C=>{n("remove",C)},onReplace:(C,$)=>{n("replace",$)},onError:C=>{n("validation-error",C)},onReadyToSubmitChange:C=>{n("is-ready-to-submit-change",C)}},{item:s,setItem:l,addFile:d,removeItem:c,replaceItem:u,cancelUpload:f,retryUpload:m,isLoading:p,hasItem:h,errors:v,adapter:w,formValue:x,acceptString:T}=Bd(r);e.provide("mediaAdapter",w),e.watch(()=>t.modelValue,C=>{C!==s.value&&l(C)},{deep:!0});const _=e.computed(()=>t.showUploadZone&&!t.disabled&&!t.readonly&&!h.value),g=e.computed(()=>({"media-attachment":!0,"media-attachment--disabled":t.disabled,"media-attachment--readonly":t.readonly,"media-attachment--loading":p.value,"media-attachment--has-item":h.value}));function E(C){C.length>0&&d(C[0])}function S(){var C;(C=i.value)==null||C.click()}function N(C){const $=C.target,y=$.files;y&&y.length>0&&u(y[0]),$.value=""}function V(C){c()}function A(C){m()}function j(C){f()}return(C,$)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(g.value)},[e.createElementVNode("input",{ref_key:"fileInputRef",ref:i,type:"file",accept:e.unref(T),disabled:C.disabled,class:"media-attachment__hidden-input",onChange:N},null,40,O$),_.value?e.renderSlot(C.$slots,"dropzone",{key:0,addFile:e.unref(d)},()=>[e.createVNode(Td,{accept:e.unref(T),multiple:!1,disabled:C.disabled,"max-file-size":C.maxFileSize,onFiles:E},null,8,["accept","disabled","max-file-size"])],!0):e.unref(h)&&e.unref(s)?e.renderSlot(C.$slots,"preview",{key:1,item:e.unref(s),remove:e.unref(c),replace:S},()=>[e.createElementVNode("div",z$,[e.createVNode(Id,{item:e.unref(s),adapter:e.unref(w),disabled:C.disabled,sortable:!1,"show-remove":!C.readonly,"show-edit":!1,onRemove:V,onRetry:A,onCancel:j},null,8,["item","adapter","disabled","show-remove"]),C.showReplaceButton&&!C.readonly&&!C.disabled&&e.unref(s).media?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-attachment__replace-button",onClick:S},[...$[0]||($[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(C.$slots,"empty",{key:2},()=>[$[1]||($[1]=e.createElementVNode("div",{class:"media-attachment__empty"},[e.createElementVNode("p",null,"No file selected")],-1))],!0),C.generateFormFields&&e.unref(x)?(e.openBlock(),e.createElementBlock(e.Fragment,{key:3},[e.createElementVNode("input",{type:"hidden",name:`${C.name}[uuid]`,value:e.unref(x).uuid},null,8,j$),e.createElementVNode("input",{type:"hidden",name:`${C.name}[name]`,value:e.unref(x).name},null,8,W$),e.createElementVNode("input",{type:"hidden",name:`${C.name}[order]`,value:e.unref(x).order},null,8,H$),e.unref(x).custom_properties?(e.openBlock(),e.createElementBlock("input",{key:0,type:"hidden",name:`${C.name}[custom_properties]`,value:JSON.stringify(e.unref(x).custom_properties)},null,8,Z$)):e.createCommentVNode("",!0)],64)):e.createCommentVNode("",!0),e.unref(v).length>0?(e.openBlock(),e.createElementBlock("div",X$,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(v),y=>(e.openBlock(),e.createElementBlock("p",{key:y.code||y.message,class:"media-attachment__error"},e.toDisplayString(y.message),1))),128))])):e.createCommentVNode("",!0)],2))}}),J$=Be(G$,[["__scopeId","data-v-26911174"]]),uf={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"}},K$=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:C=>{i("update:modelValue",C),i("change",C)},onUpload:C=>{i("upload",C)},onUploadComplete:C=>{i("upload-complete",C)},onUploadError:C=>{i("upload-error",C)},onRemove:C=>{i("remove",C)},onReorder:C=>{i("reorder",C)},onError:C=>{i("validation-error",C)},onReadyToSubmitChange:C=>{i("is-ready-to-submit-change",C)}},{items:s,setItems:l,addFiles:d,removeItem:c,reorderItems:u,updateItem:f,cancelUpload:m,retryUpload:p,isLoading:h,isUploading:v,isReadyToSubmit:w,isAtMaxItems:x,errors:T,dragState:_,getDragProps:g,adapter:E,formValues:S,acceptString:N}=vs(r);e.provide("mediaAdapter",E),e.provide("mediaCollection",{items:s,addFiles:d,removeItem:c,reorderItems:u}),e.watch(()=>n.modelValue,C=>{C!==s.value&&l(C)},{deep:!0});const V=e.computed(()=>({...uf,...n.labels})),A=e.computed(()=>({accept:N.value,multiple:n.maxItems!==1,disabled:n.disabled||n.readonly||x.value})),j=e.computed(()=>({items:s.value,isLoading:h.value,isUploading:v.value,isReadyToSubmit:w.value,isAtMaxItems:x.value,errors:T.value,addFiles:d,removeItem:c,reorderItems:u,clearAll:()=>{s.value.forEach(C=>c(C))},cancelUpload:m,retryUpload:p,labels:V.value,dropzoneProps:A.value}));return a({items:s,addFiles:d,removeItem:c,reorderItems:u,updateItem:f,cancelUpload:m,retryUpload:p,isLoading:h,isUploading:v,isReadyToSubmit:w,isAtMaxItems:x,errors:T,dragState:_,getDragProps:g,adapter:E,formValues:S,acceptString:N}),(C,$)=>e.renderSlot(C.$slots,"default",e.normalizeProps(e.guardReactiveProps(j.value)))}}),q$=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:V=>{i("update:modelValue",V),i("change",V)},onUpload:V=>{i("upload",V)},onUploadComplete:V=>{i("upload-complete",V)},onUploadError:V=>{i("upload-error",V)},onRemove:V=>{i("remove",V)},onReplace:(V,A)=>{i("replace",A)},onError:V=>{i("validation-error",V)},onReadyToSubmitChange:V=>{i("is-ready-to-submit-change",V)}},{item:s,setItem:l,addFile:d,removeItem:c,replaceItem:u,cancelUpload:f,retryUpload:m,isLoading:p,isUploading:h,isReadyToSubmit:v,hasItem:w,errors:x,adapter:T,formValue:_,acceptString:g}=Bd(r);e.provide("mediaAdapter",T),e.watch(()=>n.modelValue,V=>{V!==s.value&&l(V)},{deep:!0});const E=e.computed(()=>({...uf,...n.labels})),S=e.computed(()=>({accept:g.value,multiple:!1,disabled:n.disabled||n.readonly||w.value})),N=e.computed(()=>({item:s.value,hasItem:w.value,isLoading:p.value,isUploading:h.value,isReadyToSubmit:v.value,errors:x.value,addFile:d,removeItem:c,replaceItem:u,cancelUpload:f,retryUpload:m,labels:E.value,dropzoneProps:S.value}));return a({item:s,setItem:l,addFile:d,removeItem:c,replaceItem:u,cancelUpload:f,retryUpload:m,isLoading:p,isUploading:h,isReadyToSubmit:v,hasItem:w,errors:x,adapter:T,formValue:_,acceptString:g}),(V,A)=>e.renderSlot(V.$slots,"default",e.normalizeProps(e.guardReactiveProps(N.value)))}}),Y$=["name","value"],Q$=["name","value"],eD=["name","value"],tD=["name","value"],aD=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(()=>Cd(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,Y$),e.createElementVNode("input",{type:"hidden",name:s(u,"name"),value:c.name},null,8,Q$),e.createElementVNode("input",{type:"hidden",name:s(u,"order"),value:c.order},null,8,eD),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,tD)):e.createCommentVNode("",!0)],64))),128))}}),nD=["data-testid"],oD=["data-testid"],iD=["id"],rD=["value","maxlength","disabled","aria-labelledby","placeholder","data-testid","onInput"],sD=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,iD),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,rD)],8,oD))),128))],8,nD)):e.createCommentVNode("",!0)}}),lD=Be(sD,[["__scopeId","data-v-a153768a"]]),dD="/v1/media/deletion/check",cD="/v1/media/deletion/delete",dr=100;function _u(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 mf(o){const a=o.checkEndpoint??dD,t=o.deleteEndpoint??cD,n=e.ref(!1),i=e.ref(!1),r=e.ref(null),s=e.ref(null),l=e.ref(null);async function d(f){l.value=null;const m=_u(f);if(m.length===0)return r.value=[],[];if(m.length>dr){const p=new Error(`Cannot check more than ${dr} media items at once.`);throw l.value=p,p}n.value=!0;try{const p=await o.httpClient.post(a,{uuids:m}),h=((p==null?void 0:p.data)??[]).map(v=>{var w,x,T,_;return{uuid:v.uuid,canDelete:((w=v.report)==null?void 0:w.canDelete)??!1,blocks:Array.isArray((x=v.report)==null?void 0:x.blocks)?v.report.blocks:[],cascade:Array.isArray((T=v.report)==null?void 0:T.cascade)?v.report.cascade:[],variantCount:typeof((_=v.report)==null?void 0:_.variantCount)=="number"?v.report.variantCount:0}});return r.value=h,h}catch(p){throw l.value=p instanceof Error?p:new Error(String(p)),l.value}finally{n.value=!1}}async function c(f,m={}){l.value=null;const p=_u(f);if(p.length===0){const h={results:[],summary:{}};return s.value=h,h}if(p.length>dr){const h=new Error(`Cannot delete more than ${dr} media items at once.`);throw l.value=h,h}i.value=!0;try{const h=await o.httpClient.post(t,{uuids:p,force:m.force===!0}),v={results:Array.isArray(h==null?void 0:h.results)?h.results:[],summary:(h==null?void 0:h.summary)??{}};return s.value=v,v}catch(h){throw l.value=h instanceof Error?h:new Error(String(h)),l.value}finally{i.value=!1}}function u(){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:u}}const uD="/v1/user/media/trash";function mD(o){return`/v1/user/media/${encodeURIComponent(o)}/restore`}function pf(o){const a=o.listEndpoint??uD,t=o.buildRestoreEndpoint??mD,n=o.perPage??50,i=e.ref([]),r=e.ref(0),s=e.ref(1),l=e.ref(!1),d=e.ref(!1),c=e.ref(null);async function u(p=1){var h,v;c.value=null,l.value=!0;try{const w=await o.httpClient.get(a,{params:{page:p,per_page:n}});i.value=Array.isArray(w==null?void 0:w.data)?w.data:[],r.value=typeof((h=w==null?void 0:w.meta)==null?void 0:h.total)=="number"?w.meta.total:0,s.value=typeof((v=w==null?void 0:w.meta)==null?void 0:v.current_page)=="number"?w.meta.current_page:p}catch(w){throw c.value=w instanceof Error?w:new Error(String(w)),c.value}finally{l.value=!1}}async function f(p){c.value=null,d.value=!0;try{const h=await o.httpClient.post(t(p)),v={status:(h==null?void 0:h.status)??"failed",data:(h==null?void 0:h.data)??null,duplicate_uuid:(h==null?void 0:h.duplicate_uuid)??null};return typeof(h==null?void 0:h.message)=="string"&&(v.message=h.message),v.status==="restored"&&(i.value=i.value.filter(w=>w.uuid!==p),r.value=Math.max(0,r.value-1)),v}catch(h){const v=pD(h);if(v&&typeof v.status=="string"){const w={status:v.status,duplicate_uuid:typeof v.duplicate_uuid=="string"?v.duplicate_uuid:null};return typeof v.message=="string"&&(w.message=v.message),w}throw c.value=h instanceof Error?h:new Error(String(h)),c.value}finally{d.value=!1}}function m(){i.value=[],r.value=0,s.value=1,c.value=null}return{items:i,total:r,currentPage:s,isLoading:l,isRestoring:d,error:c,fetch:u,restore:f,reset:m}}function pD(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 fD={class:"media-management-view","data-testid":"media-management-view"},hD={class:"media-management-view__header"},vD={class:"media-management-view__title"},gD={class:"media-management-view__actions"},bD={key:0,class:"media-management-view__badge"},yD={key:0,class:"media-management-view__panel","data-testid":"panel-library"},wD={key:0,class:"media-management-view__status","data-testid":"library-loading"},kD={key:1,class:"media-management-view__status media-management-view__status--error","data-testid":"library-error"},_D={key:2,class:"media-management-view__empty","data-testid":"library-empty"},ED={class:"media-management-view__empty-state"},xD={class:"media-management-view__empty-title","data-testid":"library-empty-title"},SD={class:"media-management-view__empty-description","data-testid":"library-empty-description"},CD={key:3,class:"media-management-view__grid","data-testid":"library-grid"},VD=["data-testid"],ND=["data-testid","aria-pressed","onClick"],TD=["src","alt"],ID={key:1,class:"media-management-view__item-placeholder"},BD={class:"media-management-view__item-meta"},MD={class:"media-management-view__item-name"},FD=["data-testid"],$D={key:1,class:"media-management-view__item-badge","data-testid":"badge-orphaned"},DD={class:"media-management-view__bulk-bar","data-testid":"bulk-bar"},RD={"data-testid":"bulk-count"},AD=["disabled"],LD={key:1,class:"media-management-view__panel","data-testid":"panel-trash"},PD={key:0,class:"media-management-view__status","data-testid":"trash-loading"},UD={key:1,class:"media-management-view__empty","data-testid":"trash-empty"},OD={class:"media-management-view__empty-state"},zD={class:"media-management-view__empty-title","data-testid":"trash-empty-title"},jD={class:"media-management-view__empty-description","data-testid":"trash-empty-description"},WD={key:2,class:"media-management-view__grid","data-testid":"trash-grid"},HD=["data-testid"],ZD={class:"media-management-view__item-thumb"},XD=["src","alt"],GD={class:"media-management-view__item-meta"},JD={class:"media-management-view__item-name"},KD={key:0,class:"media-management-view__item-meta-line"},qD=["data-testid","disabled","onClick"],YD=["data-testid"],QD=e.defineComponent({__name:"MediaManagementView",props:{httpClient:{},capabilities:{default:()=>({})},labels:{default:()=>({})},confirmBulkDelete:{},onRestoreCollision:{}},emits:["deleted","restored","restore-conflict","error"],setup(o,{expose:a,emit:t}){const n=o,i=t,r=e.computed(()=>({showTrash:!0,allowBulkDelete:!0,showOwner:!1,...n.capabilities})),s=e.computed(()=>{var ne,ae,F,B,O,X,oe,ce,je,he,ge,pe,we,ye,Ne,De,Qe;return{title:((ne=n.labels)==null?void 0:ne.title)??"My Media",libraryTab:((ae=n.labels)==null?void 0:ae.libraryTab)??"Library",trashTab:((F=n.labels)==null?void 0:F.trashTab)??"Trash",loading:((B=n.labels)==null?void 0:B.loading)??"Loading…",emptyLibrary:((O=n.labels)==null?void 0:O.emptyLibrary)??"No media yet — upload your first creation.",emptyLibraryTitle:((X=n.labels)==null?void 0:X.emptyLibraryTitle)??"Your media library is ready",emptyLibraryDescription:((oe=n.labels)==null?void 0:oe.emptyLibraryDescription)??"Images and videos you upload for creations are saved here so you can reuse them later.",emptyTrash:((ce=n.labels)==null?void 0:ce.emptyTrash)??"Trash is empty.",emptyTrashTitle:((je=n.labels)==null?void 0:je.emptyTrashTitle)??"No media in trash",emptyTrashDescription:((he=n.labels)==null?void 0:he.emptyTrashDescription)??"Deleted files appear here for 30 days before permanent removal.",orphanedBadge:((ge=n.labels)==null?void 0:ge.orphanedBadge)??"Not in use",selectedCount:((pe=n.labels)==null?void 0:pe.selectedCount)??(et=>`${et} selected`),deleteButton:((we=n.labels)==null?void 0:we.deleteButton)??"Delete",restoreButton:((ye=n.labels)==null?void 0:ye.restoreButton)??"Restore",restoreUnavailable:((Ne=n.labels)==null?void 0:Ne.restoreUnavailable)??"Restore unavailable",purgeAfter:((De=n.labels)==null?void 0:De.purgeAfter)??(et=>`Purges ${et}`),ownerLabel:((Qe=n.labels)==null?void 0:Qe.ownerLabel)??(et=>`User ${et.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),f=e.computed(()=>s.value.emptyLibraryTitle),m=e.computed(()=>s.value.emptyLibraryDescription),p=e.computed(()=>s.value.emptyTrashTitle),h=e.computed(()=>s.value.emptyTrashDescription),v=e.computed(()=>s.value.orphanedBadge),w=e.computed(()=>s.value.deleteButton),x=e.computed(()=>s.value.restoreButton),T=e.computed(()=>s.value.restoreUnavailable);function _(ne){const ae=r.value.canRestore;return ae?ae(ne):!0}const g=e.ref("library"),E=e.ref({scope:"library"}),S=e.ref({}),N=xd({httpClient:n.httpClient,view:E,filters:S,perPage:50}),V=e.computed(()=>N.items.value),A=e.computed(()=>N.loading.value),j=e.computed(()=>{var ne;return((ne=N.error.value)==null?void 0:ne.message)??null}),C=ju(V),$=mf({httpClient:n.httpClient}),y=pf({httpClient:n.httpClient});function R(ne){return s.value.selectedCount(ne)}function L(ne){return s.value.purgeAfter(ne)}function U(ne){return s.value.ownerLabel(ne)}async function z(){const ne=C.selectedItems.value;if(ne.length===0)return;const ae=r.value.canDelete?ne.filter(F=>r.value.canDelete(F)):ne;if(ae.length!==0&&!(n.confirmBulkDelete&&!await n.confirmBulkDelete(ae)))try{const F=ae.map(X=>X.uuid),O=(await $.deleteMany(F)).results.filter(X=>X.status==="trashed"||X.status==="already_trashed").map(X=>X.uuid);if(O.length>0){for(const X of O)C.deselect(X);i("deleted",O),await N.refresh(),r.value.showTrash!==!1&&await y.fetch(y.currentPage.value).catch(()=>{})}}catch(F){i("error",F instanceof Error?F:new Error(String(F)))}}async function I(ne){var F;const ae=y.items.value.find(B=>B.uuid===ne);if(!(ae&&!_(ae)))try{const B=await y.restore(ne);if(B.status==="restored"){i("restored",ne),await N.refresh().catch(()=>{});return}if(B.status==="duplicate_conflict"){i("restore-conflict",{uuid:ne,duplicateUuid:B.duplicate_uuid??null}),(F=n.onRestoreCollision)==null||F.call(n,ne,B.duplicate_uuid??null);return}}catch(B){i("error",B instanceof Error?B:new Error(String(B)))}}async function P(){g.value="trash",y.items.value.length===0&&!y.isLoading.value&&await y.fetch().catch(ne=>{i("error",ne instanceof Error?ne:new Error(String(ne)))})}function Z(ne){if(ne==="trash"){P();return}g.value=ne}const K=e.computed(()=>({activeTab:g.value,setActiveTab:Z,trashCount:y.total.value,showTrash:r.value.showTrash!==!1,labels:{libraryTab:s.value.libraryTab,trashTab:s.value.trashTab}})),ve=e.computed(()=>({selectedCount:C.selectedCount.value,selectedItemIds:Array.from(C.selectedIds.value),selectedItems:C.selectedItems.value,isDeleting:$.isDeleting.value,onBulkDelete:z,clearSelection:C.clear,labels:{deleteButton:s.value.deleteButton,selectedCount:s.value.selectedCount}}));function Ve(ne){return{media:ne,canRestore:_(ne),isRestoring:y.isRestoring.value,onRestore:()=>I(ne.uuid),labels:{restoreButton:s.value.restoreButton,restoreUnavailable:s.value.restoreUnavailable}}}return e.watch(g,async ne=>{ne==="library"&&V.value.length===0&&!A.value&&await N.refresh().catch(()=>{})}),e.onMounted(async()=>{await N.refresh().catch(ne=>{i("error",ne instanceof Error?ne:new Error(String(ne)))}),r.value.showTrash!==!1&&y.fetch().catch(()=>{})}),a({refresh:()=>N.refresh(),refreshTrash:()=>y.fetch(),selection:C,deletion:$,trash:y}),(ne,ae)=>(e.openBlock(),e.createElementBlock("div",fD,[e.createElementVNode("header",hD,[e.createElementVNode("h2",vD,e.toDisplayString(l.value),1),e.createElementVNode("div",gD,[e.renderSlot(ne.$slots,"tabs",e.normalizeProps(e.guardReactiveProps(K.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":g.value==="library"}]),"data-testid":"tab-library",onClick:ae[0]||(ae[0]=F=>g.value="library")},e.toDisplayString(d.value),3),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["media-management-view__tab-button",{"is-active":g.value==="trash"}]),"data-testid":"tab-trash",onClick:P},[e.createTextVNode(e.toDisplayString(c.value)+" ",1),e.unref(y).total.value>0?(e.openBlock(),e.createElementBlock("span",bD,e.toDisplayString(e.unref(y).total.value),1)):e.createCommentVNode("",!0)],2)],64)):e.createCommentVNode("",!0)],!0)])]),g.value==="library"?(e.openBlock(),e.createElementBlock("section",yD,[A.value?(e.openBlock(),e.createElementBlock("div",wD,e.toDisplayString(u.value),1)):j.value?(e.openBlock(),e.createElementBlock("div",kD,e.toDisplayString(j.value),1)):V.value.length===0?(e.openBlock(),e.createElementBlock("div",_D,[e.renderSlot(ne.$slots,"empty-library",{},()=>[e.createElementVNode("div",ED,[e.createElementVNode("p",xD,e.toDisplayString(f.value),1),e.createElementVNode("p",SD,e.toDisplayString(m.value),1)])],!0)])):(e.openBlock(),e.createElementBlock("ul",CD,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(V.value,F=>(e.openBlock(),e.createElementBlock("li",{key:F.uuid,class:e.normalizeClass(["media-management-view__item",{"is-selected":e.unref(C).isSelected(F.uuid)}]),"data-testid":`media-item-${F.uuid}`},[e.createElementVNode("button",{type:"button",class:"media-management-view__item-thumb","data-testid":`btn-select-${F.uuid}`,"aria-pressed":e.unref(C).isSelected(F.uuid),onClick:B=>e.unref(C).toggle(F.uuid)},[F.thumbnail_url||F.original_url?(e.openBlock(),e.createElementBlock("img",{key:0,src:F.thumbnail_url||F.original_url,alt:F.alt_text||F.file_name,loading:"lazy"},null,8,TD)):(e.openBlock(),e.createElementBlock("span",ID,e.toDisplayString(F.file_name),1))],8,ND),e.createElementVNode("div",BD,[e.createElementVNode("span",MD,e.toDisplayString(F.file_name),1),r.value.showOwner&&F.user_id?(e.openBlock(),e.createElementBlock("span",{key:0,class:"media-management-view__item-owner","data-testid":`owner-${F.uuid}`},e.toDisplayString(U(F)),9,FD)):e.createCommentVNode("",!0),F.is_orphaned?(e.openBlock(),e.createElementBlock("span",$D,e.toDisplayString(v.value),1)):e.createCommentVNode("",!0)])],10,VD))),128))])),e.unref(C).selectedCount.value>0&&r.value.allowBulkDelete!==!1?e.renderSlot(ne.$slots,"bulk-actions",e.normalizeProps(e.mergeProps({key:4},ve.value)),()=>[e.createElementVNode("footer",DD,[e.createElementVNode("span",RD,e.toDisplayString(R(e.unref(C).selectedCount.value)),1),e.createElementVNode("button",{type:"button",class:"media-management-view__btn-delete","data-testid":"btn-bulk-delete",disabled:e.unref($).isDeleting.value,onClick:z},e.toDisplayString(w.value),9,AD)])],!0):e.createCommentVNode("",!0)])):g.value==="trash"?(e.openBlock(),e.createElementBlock("section",LD,[e.unref(y).isLoading.value?(e.openBlock(),e.createElementBlock("div",PD,e.toDisplayString(u.value),1)):e.unref(y).items.value.length===0?(e.openBlock(),e.createElementBlock("div",UD,[e.renderSlot(ne.$slots,"empty-trash",{},()=>[e.createElementVNode("div",OD,[e.createElementVNode("p",zD,e.toDisplayString(p.value),1),e.createElementVNode("p",jD,e.toDisplayString(h.value),1)])],!0)])):(e.openBlock(),e.createElementBlock("ul",WD,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(y).items.value,F=>(e.openBlock(),e.createElementBlock("li",{key:F.uuid,class:"media-management-view__item is-trashed","data-testid":`trash-item-${F.uuid}`},[e.createElementVNode("div",ZD,[F.thumbnail_url||F.original_url?(e.openBlock(),e.createElementBlock("img",{key:0,src:F.thumbnail_url||F.original_url,alt:F.alt_text||F.file_name,loading:"lazy"},null,8,XD)):e.createCommentVNode("",!0)]),e.createElementVNode("div",GD,[e.createElementVNode("span",JD,e.toDisplayString(F.file_name),1),F.purge_after?(e.openBlock(),e.createElementBlock("span",KD,e.toDisplayString(L(F.purge_after)),1)):e.createCommentVNode("",!0)]),e.renderSlot(ne.$slots,"trash-action",e.mergeProps({ref_for:!0},Ve(F)),()=>[_(F)?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-management-view__btn-restore","data-testid":`btn-restore-${F.uuid}`,disabled:e.unref(y).isRestoring.value,onClick:B=>I(F.uuid)},e.toDisplayString(x.value),9,qD)):(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__btn-restore is-unavailable","data-testid":`btn-restore-${F.uuid}-unavailable`,"aria-disabled":!0},e.toDisplayString(T.value),9,YD))],!0)],8,HD))),128))]))])):e.createCommentVNode("",!0)]))}}),eR=Be(QD,[["__scopeId","data-v-0118e1bd"]]);exports.AlbumBrowser=Pp;exports.AlbumManager=aF;exports.AlbumMediaGrid=fF;exports.AlbumTree=Lp;exports.ArrayBufferTarget=ql;exports.ExistingMediaSelector=jg;exports.ImageEditor=$u;exports.ImageEditorModal=Du;exports.LiveStreamManager=T5;exports.ManagedMediaGallery=wh;exports.MediaAlbumInlineCreate=Up;exports.MediaAlbumUnavailableState=Op;exports.MediaAttachment=J$;exports.MediaAttachmentMetadataFields=lD;exports.MediaCollection=U$;exports.MediaCollectionDropzone=Td;exports.MediaCollectionItem=Id;exports.MediaLibraryPicker=lf;exports.MediaLibraryPickerModal=R6;exports.MediaManagementView=eR;exports.MediaPreviewSheet=Gp;exports.MediaSelectionTray=X6;exports.MediaSourceSheet=Jp;exports.MediaThumbnailCell=qp;exports.MediaUploadSheet=Kp;exports.MediaWorkspace=vh;exports.ModelMediaManager=ug;exports.Muxer=im;exports.VideoEditor=Bp;exports.VideoEditorDialog=m3;exports.VideoEditorSimple=R3;exports.VideoExportPanel=hB;exports.VideoJobClient=ps;exports.VideoPlayer=Dp;exports.VideoTimeline=rI;exports.VideoToolsPanel=JI;exports.VideoUploader=aM;exports.VirtualMediaGrid=Yp;exports._sfc_main=K$;exports._sfc_main$1=q$;exports._sfc_main$2=aD;exports.applyTemporaryMediaStoreConfig=Cu;exports.configureMediaStore=wo;exports.createAdapter=df;exports.createEmptyEditorState=Of;exports.createImageEditor=J6;exports.createMediablesAdapter=Vd;exports.createSpatieAdapter=Nd;exports.deserializeEditorState=Uf;exports.formatFileSize=Or;exports.fromMediaArray=zl;exports.getFileExtension=Qp;exports.getImageDimensions=ef;exports.getMediablesAdapter=K6;exports.getSpatieAdapter=Q6;exports.isImageFile=kd;exports.normalizeEditorState=jl;exports.normalizeRecipeForServerRender=X4;exports.recipeHasServerRenderableEdits=Z4;exports.recipeHasUnsupportedServerEdits=$p;exports.resetMediablesAdapter=q6;exports.resetSpatieAdapter=e$;exports.restoreMediaStoreConfig=Su;exports.serializeEditorState=Eu;exports.snapshotMediaStoreConfig=xu;exports.toFormValues=Cd;exports.useAdminMediaStore=Vu;exports.useAlbumDragDrop=Ap;exports.useAlbumStore=hs;exports.useAlbums=Rp;exports.useGlobalImageEditor=G6;exports.useImageEditorModal=Sd;exports.useMediaAttachment=Bd;exports.useMediaCollection=vs;exports.useMediaDeletion=mf;exports.useMediaDragSort=cf;exports.useMediaLibraryPickerController=sf;exports.useMediaLibraryQuery=xd;exports.useMediaLibrarySession=nf;exports.useMediaLibraryStateMachine=of;exports.useMediaLibraryTelemetry=rf;exports.useMediaStore=va;exports.useMediaTrash=pf;exports.useMediaUploadQueue=Ed;exports.useMediaValidation=_d;exports.validateFile=tf;
|
|
357
|
-
//# sourceMappingURL=index-CljyFIEv.cjs.map
|