@codingfactory/mediables-vue 2.18.3 → 2.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/{PixiFrameExporter-YrJf3-l9.js → PixiFrameExporter-64httBgJ.js} +2 -2
  2. package/dist/{PixiFrameExporter-YrJf3-l9.js.map → PixiFrameExporter-64httBgJ.js.map} +1 -1
  3. package/dist/{PixiFrameExporter-DhAJGzIK.cjs → PixiFrameExporter-DkXTPJWn.cjs} +2 -2
  4. package/dist/{PixiFrameExporter-DhAJGzIK.cjs.map → PixiFrameExporter-DkXTPJWn.cjs.map} +1 -1
  5. package/dist/components/MediaAlbumPickerModal.vue.d.ts +6 -0
  6. package/dist/components/MediaFilterChips.vue.d.ts +10 -0
  7. package/dist/components/MediaInspectorPanel.vue.d.ts +13 -0
  8. package/dist/components/MediaLibraryShell.vue.d.ts +26 -0
  9. package/dist/components/MediaManagementView.vue.d.ts +1 -0
  10. package/dist/components/MediaTrashWorkspace.vue.d.ts +5 -0
  11. package/dist/composables/useMediaDeletion.d.ts +20 -0
  12. package/dist/composables/useMediaLibraryVisibility.d.ts +37 -0
  13. package/dist/composables/useMediaMetadata.d.ts +24 -0
  14. package/dist/editor-CiTXlIVO.js +4327 -0
  15. package/dist/editor-CiTXlIVO.js.map +1 -0
  16. package/dist/editor-P9MyuiTc.cjs +2 -0
  17. package/dist/editor-P9MyuiTc.cjs.map +1 -0
  18. package/dist/imageEditorState-BNQEZoCF.js +81 -0
  19. package/dist/imageEditorState-BNQEZoCF.js.map +1 -0
  20. package/dist/imageEditorState-PrcqbsfM.cjs +2 -0
  21. package/dist/imageEditorState-PrcqbsfM.cjs.map +1 -0
  22. package/dist/index-2jP5K__o.cjs +357 -0
  23. package/dist/index-2jP5K__o.cjs.map +1 -0
  24. package/dist/index-Dae8SHT7.js +6557 -0
  25. package/dist/index-Dae8SHT7.js.map +1 -0
  26. package/dist/{index-Dc-M8oj6.js → index-Dinl1Puu.js} +17147 -15638
  27. package/dist/index-Dinl1Puu.js.map +1 -0
  28. package/dist/index-QOKC8XA_.cjs +2 -0
  29. package/dist/index-QOKC8XA_.cjs.map +1 -0
  30. package/dist/index.d.ts +5 -1
  31. package/dist/mediables-primitives.cjs +2 -0
  32. package/dist/mediables-primitives.cjs.map +1 -0
  33. package/dist/mediables-primitives.mjs +21 -0
  34. package/dist/mediables-primitives.mjs.map +1 -0
  35. package/dist/mediables-vanilla.cjs +1 -1
  36. package/dist/mediables-vanilla.mjs +8 -7
  37. package/dist/mediables-vanilla.mjs.map +1 -1
  38. package/dist/mediables-vue.cjs +1 -1
  39. package/dist/mediables-vue.mjs +74 -70
  40. package/dist/mediables-vue.mjs.map +1 -1
  41. package/dist/primitives-exports.d.ts +37 -0
  42. package/dist/style.css +1 -1
  43. package/dist/types/media.d.ts +2 -0
  44. package/dist/types/mediaLibraryPicker.d.ts +5 -0
  45. package/dist/utils/focus.d.ts +4 -0
  46. package/dist/vanilla-editor/core/EventEmitter.d.ts +8 -8
  47. package/dist/vanilla-editor/core/State.d.ts +441 -95
  48. package/package.json +8 -2
  49. package/dist/editor-D85y_zTO.cjs +0 -2
  50. package/dist/editor-D85y_zTO.cjs.map +0 -1
  51. package/dist/editor-DAJxTvzM.js +0 -10873
  52. package/dist/editor-DAJxTvzM.js.map +0 -1
  53. package/dist/index-BFrh53TT.cjs +0 -357
  54. package/dist/index-BFrh53TT.cjs.map +0 -1
  55. package/dist/index-Dc-M8oj6.js.map +0 -1
@@ -1,357 +0,0 @@
1
- "use strict";var ch=Object.defineProperty;var uh=(o,a,t)=>a in o?ch(o,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[a]=t;var ae=(o,a,t)=>uh(o,typeof a!="symbol"?a+"":a,t);const Qr=require("pinia"),e=require("vue"),$t=require("pixi.js"),te=require("./editor-D85y_zTO.cjs"),H=require("@ionic/vue"),mh=require("pixi-filters");function ph(o){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(a,t,n.get?n:{enumerable:!0,get:()=>o[t]})}}return a.default=o,Object.freeze(a)}const Jt=ph($t),us=1,fh=new Set(["free","square","circle"]);function hh(o){if(typeof o!="number"||!Number.isFinite(o))return 0;const a=o%360;return a<0?a+360:a}function vh(o){const a=typeof o;return a==="string"||a==="number"||a==="boolean"}function gh(o){if(!o||typeof o!="object")return!1;const a=o;return typeof a.x=="number"&&typeof a.y=="number"&&typeof a.width=="number"&&typeof a.height=="number"}function Qs(o){if(!o||typeof o!="object")return null;const a=o;if(a.version!==us)return null;const t=a.crop,n=t&&gh(t.rect)?{...t.rect}:null,i=t&&typeof t.shape=="string"&&fh.has(t.shape)?t.shape:"free",r=t&&typeof t.aspectRatio=="string"?t.aspectRatio:"free",l=a.transform,s=hh(l==null?void 0:l.rotation),d=a.filters,c=[];if(Array.isArray(d))for(const u of d){if(!u||typeof u!="object")continue;const m=u;if(typeof m.id!="string")continue;const p={},f=m.values;if(f&&typeof f=="object"&&!Array.isArray(f))for(const[h,v]of Object.entries(f))vh(v)&&(p[h]=v);c.push({id:m.id,enabled:m.enabled!==!1,values:p})}return{version:us,crop:{rect:n,aspectRatio:r,shape:i},transform:{rotation:s},filters:c}}function Zu(o){const a=Qs(o);return a?JSON.stringify(a):null}function bh(o){try{const a=JSON.parse(o);return Qs(a)}catch{return null}}function yh(){return{version:us,crop:{rect:null,aspectRatio:"free",shape:"free"},transform:{rotation:0},filters:[]}}let ba={apiBaseUrl:"/api/v1",isAdmin:!1};function ic(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 $o(o){ba={...ba,...o}}function Gu(){return{...ba}}function Xu(o){ba={...o}}function Ku(o){const a=Gu();return $o(o),()=>{Xu(a)}}function wh(o){const a=o.trim().replace(/\/+$/,"");return a===""?"/api/v1":a.startsWith("/")?a:`/${a}`}function kh(o,a){const t=wh(a),n=(i,r="")=>{const l=`/api${t}`;return!t.startsWith("/api/")&&i.startsWith(`${l}/`)?`${i.slice(4)}${r}`:!t.startsWith("/api/")&&i===l?`${t}${r}`:`${i}${r}`};if(/^https?:\/\//i.test(o))try{const i=typeof window<"u"?window.location.origin:"http://localhost",r=new URL(o,i);if(r.origin===i)return n(r.pathname,`${r.search}${r.hash}`)}catch{return o}return n(o)}const _h=async(o,a={})=>{var s;const t=(s=document.querySelector('meta[name="csrf-token"]'))==null?void 0:s.getAttribute("content"),n={Accept:"application/json",...a.headers};t&&(n["X-CSRF-TOKEN"]=t),a.body instanceof FormData||(n["Content-Type"]="application/json");const r={method:a.method||"GET",headers:n,credentials:"include"};a.body instanceof FormData?r.body=a.body:a.body!==void 0&&(r.body=JSON.stringify(a.body));const l=await fetch(o,r);if(!l.ok){const d=await l.json().catch(()=>({message:"Request failed"}));throw new Error(d.message||`HTTP ${l.status}`)}if(l.status!==204)return await l.json()},xa=Qr.defineStore("media",()=>{const o=e.ref([]),a=e.ref([]),t=e.ref(!1),n=e.ref(null),i=e.ref(1),r=e.ref(1),l=e.ref(24),s=e.ref({type:null,uuid:null}),d=e.ref([]),c=e.ref(!1),u=e.ref(null),m=e.ref(new Map),p=e.ref(new Map),f=e.ref(new Set),h=e.ref(new Map),v=e.ref({}),k=5*60*1e3,y=e.computed(()=>{if(ba.apiScope)return ba.apiScope;if(ba.isAdmin)return"admin"}),w=e.computed(()=>y.value==="admin");function g(){return ba.httpClient||_h}function b(be){const Ee=ba.apiBaseUrl||"/api/v1",ye=y.value?`/${y.value}`:"";return`${Ee}${ye}${be}`}function R(be){return`${ba.apiBaseUrl||"/api/v1"}${be}`}function V(be,Ee){return`${y.value??"default"}-${be}-${JSON.stringify(Ee)}`}function I(be){return Date.now()-be<k}function x(){h.value.clear(),v.value={}}function T(be){if(!be||!be.data)return;const Ee={};be.data.forEach(ye=>{const xe=`${ye.file_name}-${ye.collection_name||"default"}`,Ce=Ee[xe];(!Ce||Object.keys(ye.generated_conversions||{}).length>Object.keys(Ce.generated_conversions||{}).length)&&(Ee[xe]=ye)}),o.value=Object.values(Ee),be.meta&&(i.value=be.meta.current_page,r.value=Math.ceil(be.meta.total/be.meta.per_page))}async function $(be=1,Ee={}){const ye=V(be,Ee),xe=h.value.get(ye);if(xe&&I(xe.timestamp)){const Ce=xe.data;return T(Ce),Ce}t.value=!0,n.value=null;try{const Ce=new URLSearchParams;Ce.append("page",be.toString()),Ce.append("per_page",l.value.toString()),w.value&&Ce.append("linked","1");for(const rt in Ee)if(Object.prototype.hasOwnProperty.call(Ee,rt)){const at=Ee[rt];at!=null&&at!==""&&Ce.append(rt,String(at))}const ze=await g()(b(`/media?${Ce}`));return h.value.set(ye,{data:ze,timestamp:Date.now()}),T(ze),ze}catch(Ce){throw n.value=Ce instanceof Error?Ce.message:"Failed to fetch media",o.value=[],new Error(n.value)}finally{t.value=!1}}async function S(be,Ee){t.value=!0,n.value=null;const ye=`${be.name}-${Date.now()}`,xe={file:be,progress:0,status:"uploading"};m.value.set(ye,xe);try{const Ce=new FormData;Ce.append("file",be),Ce.append("collection",Ee.collection),Ee.ownerUuid&&(Ce.append("owner_uuid",Ee.ownerUuid),Ce.append("owner_type",Ee.ownerType||"")),Ee.usageUuid&&(Ce.append("usage_uuid",Ee.usageUuid),Ce.append("usage_type",Ee.usageType||""),Ce.append("usage_purpose",Ee.usagePurpose||"")),Ee.customProperties&&Ce.append("custom_properties",JSON.stringify(Ee.customProperties));const ze=await g()(b("/media"),{method:"POST",body:Ce});return xe.status="completed",xe.progress=100,xe.media=ze==null?void 0:ze.data,i.value===1&&(ze!=null&&ze.data)&&(o.value=[ze.data,...o.value]),x(),(ze==null?void 0:ze.data)||null}catch(Ce){throw xe.status="error",xe.error=Ce instanceof Error?Ce.message:"Upload failed",n.value=xe.error,new Error(n.value)}finally{t.value=!1,setTimeout(()=>{m.value.delete(ye)},5e3)}}async function B(be){t.value=!0,n.value=null;const Ee=o.value.findIndex(xe=>xe.uuid===be);let ye;Ee!==-1&&(ye=o.value.splice(Ee,1)[0]);try{return await g()(b(`/media/${be}`),{method:"DELETE"}),f.value.delete(be),x(),!0}catch(xe){throw ye&&Ee!==-1&&o.value.splice(Ee,0,ye),n.value=xe instanceof Error?xe.message:"Failed to delete media",new Error(n.value)}finally{t.value=!1}}async function _(be,Ee){t.value=!0,n.value=null;try{const xe=await g()(b(`/media/${be}`),{method:"PATCH",body:Ee,data:Ee});if(xe!=null&&xe.data){const Ce=o.value.findIndex(Re=>Re.uuid===be);return Ce!==-1&&(o.value[Ce]={...o.value[Ce],...xe.data}),x(),xe.data}return null}catch(ye){throw n.value=ye instanceof Error?ye.message:"Failed to update media",new Error(n.value)}finally{t.value=!1}}async function A(){t.value=!0,n.value=null;try{const Ee=await g()(b("/media/collections"));return a.value=(Ee==null?void 0:Ee.data)||[],a.value}catch(be){throw n.value=be instanceof Error?be.message:"Failed to fetch collections",a.value=[],new Error(n.value)}finally{t.value=!1}}async function P(be,Ee,ye="images",xe){c.value=!0,u.value=null;try{const Ce=new URLSearchParams;Ce.append("collection",ye),xe&&Ce.append("search",xe);const ze=await g()(b(`/media/model/${be}/${Ee}?${Ce}`));return ze!=null&&ze.data?(d.value=ze.data,ze.data):[]}catch(Ce){throw u.value=Ce instanceof Error?Ce.message:"Failed to fetch model media",d.value=[],new Error(u.value)}finally{c.value=!1}}async function D(be,Ee,ye,xe="images"){c.value=!0,u.value=null;const Ce=[...d.value];try{const ze=await g()(b(`/media/model/${be}/${Ee}/attach`),{method:"POST",body:{media_uuids:ye,collection:xe}});return await P(be,Ee,xe),(ze==null?void 0:ze.data)||[]}catch(Re){throw d.value=Ce,u.value=Re instanceof Error?Re.message:"Failed to attach media",new Error(u.value)}finally{c.value=!1}}async function z(be,Ee,ye,xe="images"){c.value=!0,u.value=null;const Ce=[...d.value];d.value=d.value.filter(Re=>Re.uuid!==ye);try{return await g()(b(`/media/model/${be}/${Ee}/detach`),{method:"POST",body:{media_uuid:ye,collection:xe}}),!0}catch(Re){throw d.value=Ce,u.value=Re instanceof Error?Re.message:"Failed to detach media",new Error(u.value)}finally{c.value=!1}}async function M(be,Ee,ye,xe="images"){c.value=!0,u.value=null;const Ce=[...d.value],Re=new Map(d.value.map(ze=>[ze.uuid,ze]));d.value=ye.map(ze=>Re.get(ze)).filter(ze=>ze!==void 0);try{return await g()(b(`/media/model/${be}/${Ee}/reorder`),{method:"POST",body:{media_uuids:ye,collection:xe}}),!0}catch(ze){throw d.value=Ce,u.value=ze instanceof Error?ze.message:"Failed to reorder media",new Error(u.value)}finally{c.value=!1}}async function Z(be,Ee,ye={}){var lt,Ct;const xe=g(),Ce=ba.apiBaseUrl||"/api/v1";let Re=ic(Ee.documentId)?Ee.documentId:ic((lt=Ee.document)==null?void 0:lt.id)?Ee.document.id:null,ze=Ee.documentRevisionId??null,rt=typeof Ee.documentRevisionNumber=="number"?Ee.documentRevisionNumber:typeof((Ct=Ee.document)==null?void 0:Ct.revision)=="number"?Ee.document.revision:null;if(Ee.document){const Se=await xe(`${Ce}/media/${be}/editor-documents/materialize`,{method:"POST",body:{document_id:Re,base_document_revision:rt,document:Ee.document}});Re=Se.document_id,ze=Se.document_revision_id,rt=Se.document_revision_number}if(Ee.document&&Re&&ze&&typeof rt=="number"){const Se=new FormData,oe=(Ee.mimeType||Ee.blob.type||"image/png")==="image/jpeg"?"jpg":"png";Se.append("flattened_file",Ee.blob,`edited.${oe}`),Se.append("document_id",Re),Se.append("document_revision_id",ze),Se.append("expected_document_revision",String(rt)),Se.append("output_mode",ye.asVariant?"save-as-variant":"save-as-new");const De=await xe(`${Ce}/media/${be}/editor-documents/save`,{method:"POST",body:Se});if(De.media)return De.media;throw new Error("Unexpected response from layered editor save endpoint")}const at=new FormData,ht=(Ee.mimeType||Ee.blob.type||"image/png")==="image/jpeg"?"jpg":"png";at.append("image_file",Ee.blob,`edited.${ht}`);const St=Zu(Ee.state);St&&at.append("editor_state",St),at.append("save_as_new","true"),ye.asVariant&&at.append("as_variant","true"),ye.name!==void 0&&at.append("name",ye.name);const ut=await xe(`${Ce}/editor/${be}/save`,{method:"POST",body:at});if("media"in ut&&ut.media)return ut.media;if("status_url"in ut&&ut.status_url)return O(xe,kh(ut.status_url,Ce),ye.pollTimeout??6e4);throw new Error("Unexpected response from editor save endpoint")}async function O(be,Ee,ye){const xe=Date.now(),Ce=2e3;for(;Date.now()-xe<ye;){await new Promise(ze=>setTimeout(ze,Ce));const Re=await be(Ee);if(Re.status==="completed"&&Re.media)return Re.media;if(Re.status==="failed")throw new Error(Re.error??"Image processing failed")}throw new Error("Image processing timed out")}function K(be,Ee,ye){s.value=ye!==void 0?{type:be,uuid:Ee,collection:ye}:{type:be,uuid:Ee},v.value[`${be}-${Ee}`]={timestamp:Date.now()}}function de(){s.value={type:null,uuid:null},d.value=[],u.value=null}async function Ne(){if(!s.value.type||!s.value.uuid)return;const be=await P(s.value.type,s.value.uuid,s.value.collection||"images");d.value=be||[]}function ce(){o.value.forEach(be=>f.value.add(be.uuid))}function le(){f.value.clear()}function W(be){f.value.has(be)?f.value.delete(be):f.value.add(be)}function C(be){return f.value.has(be)}function U(){return Array.from(m.value.values()).some(be=>be.status==="uploading")}function j(be){return m.value.get(be)||p.value.get(be)}function re(){return[...Array.from(m.value.values()),...Array.from(p.value.values())]}async function ue(){const be=Array.from(f.value);let Ee=0;for(const ye of be)try{await B(ye),Ee++}catch{}return le(),Ee}function Xe(be,Ee){var ye;return Ee&&((ye=be.conversion_urls)!=null&&ye[Ee])?be.conversion_urls[Ee]||"":be.original_url||be.url||""}return{items:o,collections:a,loading:t,error:n,currentPage:i,totalPages:r,itemsPerPage:l,isAdmin:w,modelContext:s,modelMedia:d,isLoadingModelMedia:c,modelMediaError:u,selectedItems:f,uploadProgress:m,uploadQueue:p,cachedResponses:v,fetchMedia:$,uploadFile:S,deleteMedia:B,updateMedia:_,clearCache:x,fetchCollections:A,fetchModelMedia:P,attachMedia:D,detachMedia:z,reorderMedia:M,saveEditedImage:Z,setModelContext:K,clearModelContext:de,refreshModelMedia:Ne,selectAllItems:ce,clearSelection:le,toggleSelection:W,isSelected:C,deleteSelectedItems:ue,getHttpClient:g,getApiUrl:b,getEditorApiUrl:R,hasActiveUploads:U,getUploadProgress:j,getAllUploadProgress:re,getMediaUrl:Xe}}),Ju=()=>((ba.apiScope!=="admin"||ba.isAdmin!==!0)&&$o({...ba,apiScope:"admin",isAdmin:!0}),xa());class qu{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 Yu{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(l=>{var c;const s=((c=n==null?void 0:n.has)==null?void 0:c.call(n,l.id))??!1,d=i===l.id;this.element.appendChild(this._renderRow(l,s,d,r))})}_renderRow(a,t,n,i=null){const r=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)}}),l=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 p,f,h,v;u.stopPropagation();const m=!((f=(p=this.state.get("activeFilters"))==null?void 0:p.has)!=null&&f.call(p,a.id));(h=this._onToggle)==null||h.call(this,a.id,m,i),m&&((v=this._onSelect)==null||v.call(this,a.id,i))}});t&&(l.innerHTML=te.checkmark),r.appendChild(l);const s=te.el("div",{className:"filter-row-body"});s.appendChild(te.el("span",{className:"filter-row-name"},a.name));const d=this._buildSummary(a,t);d&&s.appendChild(te.el("span",{className:"filter-row-summary"},d)),r.appendChild(s);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 l=n[r.id];if(!(l===void 0||l===r.default)&&(i.push(this._formatControlValue(r,l)),i.length>=2))break}return i.length===0?"Active":i.join(" · ")}_formatControlValue(a,t){return a.type==="toggle"?a.label:typeof t=="number"?(a.max??1)<=1&&(a.min??0)>=0?`${a.label} ${Math.round(t*100)}%`:Number.isInteger(t)?`${a.label} ${t}`:`${a.label} ${t.toFixed(2)}`:typeof t=="string"?`${a.label}`:a.label}_refreshSummaries(){var i;const a=this.state.get("selectedCategory");if(!a||a==="crop")return;const t=this.filterManager.getFiltersByCategory(a),n=this.state.get("activeFilters");for(const r of t){const l=this.element.querySelector(`[data-filter="${r.id}"]`);if(!l)continue;const s=((i=n==null?void 0:n.has)==null?void 0:i.call(n,r.id))??!1,d=this._buildSummary(r,s),c=l.querySelector(".filter-row-summary");if(d&&c)c.textContent=d;else if(d&&!c){const u=l.querySelector(".filter-row-body");u==null||u.appendChild(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 Qu{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"}),l=this.state.getFilterValues(a);(n.controls||[]).forEach(d=>{if(d.hidden)return;const c=this._createControl(a,d,l[d.id]??d.default,t);c&&r.appendChild(c)});const s=this.filterManager.getInstance(a);if(s&&typeof s.getDynamicControls=="function"){let d=[];try{d=s.getDynamicControls()||[]}catch{}d.forEach(c=>{const u=c.property||c.id,m=l[u]??c.default,p=this._createControl(a,c,m,t);p&&r.appendChild(p)})}this.element.appendChild(r)}_createControl(a,t,n,i=null){if(t.hidden)return null;const r=t.label||t.id,l=this._normalizeControlType(t.type),s=t.property||t.id;switch(l){case"slider":return 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,s,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,s,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,s,d,i)}});case"select":{const d=(t.options||[]).map(c=>typeof c=="object"&&c.value!==void 0?{value:c.value,label:c.label||String(c.value)}:{value:c,label:String(c)});return 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,s,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,s,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 Eh{constructor(a,t){this.state=a,this.filterManager=t,this.element=null,this._unsubscribers=[],this._onRemove=null,this._onSelect=null,this._onClearAll=null}render({onRemove:a,onSelect:t,onClearAll:n}={}){return this._onRemove=a,this._onSelect=t,this._onClearAll=n,this.element=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 s;return(s=this._onClearAll)==null?void 0:s.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"}),l=this.state.get("selectedFilter");for(const s of a){const d=this.filterManager.getFilterDef(s);d&&r.appendChild(this._renderChip(d,s===l,n))}this.element.appendChild(r)}_renderChip(a,t,n=null){const i=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 l;return(l=this._onSelect)==null?void 0:l.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 l;return(l=this._onRemove)==null?void 0: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(".active-chip");t&&t.forEach(i=>{const r=i.getAttribute("data-filter");i.classList.toggle("selected",r===a)})}destroy(){var a;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(a=this.element)==null||a.remove(),this.element=null}}const So=["collapsed","half","full"];class Sh{constructor(a={}){this._onSnapChange=a.onSnapChange||null,this._ariaLabel=a.ariaLabel||"Filter controls drawer",this.element=null,this._handle=null,this._body=null,this._headerSlot=null,this._snap="half",this._dragging=!1,this._dragStartY=0,this._dragStartHeight=0,this._dragPointerId=null,this._containerHeight=0}build({header:a,body:t}={}){this.element=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={}){So.includes(a)&&this._applySnap(a,{animate:t.animate!==!1})}get snap(){return this._snap}setBodyContent(a){this._body&&(this._body.innerHTML="",a&&this._body.appendChild(a))}setHeaderContent(a){this._headerSlot&&(this._headerSlot.innerHTML="",a&&this._headerSlot.appendChild(a))}_onPointerDown(a){var t,n,i;if(!(a.button!==void 0&&a.button!==0)){this._dragging=!0,this._wasDragging=!1,this._dragPointerId=a.pointerId,this._dragStartY=a.clientY,this._dragStartHeight=((t=this.element)==null?void 0:t.offsetHeight)||0;try{(i=(n=this._handle)==null?void 0:n.setPointerCapture)==null||i.call(n,a.pointerId)}catch{}this.element&&(this.element.style.transition="none")}}_onPointerMove(a){if(!this._dragging||a.pointerId!==this._dragPointerId)return;const t=a.clientY-this._dragStartY,n=this._dragStartHeight-t;this._containerHeight||window.innerHeight;const i=this._heightForSnap("collapsed"),r=this._heightForSnap("full"),l=Math.max(i,Math.min(r,n));this.element&&(this.element.style.height=`${l}px`),Math.abs(t)>4&&(this._wasDragging=!0),a.preventDefault()}_onPointerEnd(a){var i,r,l;if(!this._dragging)return;this._dragging=!1;try{(r=(i=this._handle)==null?void 0:i.releasePointerCapture)==null||r.call(i,a.pointerId)}catch{}this._dragPointerId=null;const t=((l=this.element)==null?void 0:l.offsetHeight)||0,n=this._nearestSnap(t);this._applySnap(n,{animate:!0})}_cycleSnap(){const a=So.indexOf(this._snap),t=So[(a+1)%So.length];this._applySnap(t,{animate:!0})}_heightForSnap(a){const t=this._containerHeight||window.innerHeight||600;switch(a){case"collapsed":return 80;case"half":return Math.round(t*.45);case"full":return Math.round(t*.85);default:return Math.round(t*.45)}}_nearestSnap(a){let t=So[0],n=1/0;for(const i of So){const r=this._heightForSnap(i),l=Math.abs(r-a);l<n&&(n=l,t=i)}return t}_applySnap(a,{animate:t}){var r,l;if(!this.element)return;const n=this._snap;this._snap=a;const i=typeof window<"u"&&((r=window.matchMedia)==null?void 0:r.call(window,"(prefers-reduced-motion: reduce)").matches);t&&!i?this.element.style.transition="height 0.25s cubic-bezier(0.33, 1, 0.68, 1)":this.element.style.transition="none",this.element.style.height=`${this._heightForSnap(a)}px`,this.element.dataset.snap=a,this._handle&&this._handle.setAttribute("aria-expanded",a==="full"?"true":"false"),a!==n&&((l=this._onSnapChange)==null||l.call(this,a,n))}destroy(){var a;(a=this.element)==null||a.remove(),this.element=null,this._handle=null,this._body=null,this._headerSlot=null}}const Ch=[{id:"warm",label:"Warm",ariaLabel:"Apply warm gradient background",style:"linear-gradient(135deg, #101820 0%, #f2aa4c 100%)",fill:{gradientType:"linear",angle:135,stops:[{offset:0,color:"#101820"},{offset:1,color:"#f2aa4c"}]}},{id:"cool",label:"Cool",ariaLabel:"Apply cool gradient background",style:"linear-gradient(135deg, #0f766e 0%, #38bdf8 100%)",fill:{gradientType:"linear",angle:135,stops:[{offset:0,color:"#0f766e"},{offset:1,color:"#38bdf8"}]}},{id:"neutral",label:"Neutral",ariaLabel:"Apply neutral gradient background",style:"linear-gradient(135deg, #27272a 0%, #d4d4d8 100%)",fill:{gradientType:"linear",angle:135,stops:[{offset:0,color:"#27272a"},{offset:1,color:"#d4d4d8"}]}}];class em{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 f,h,v;if(!this.element)return;this.element.innerHTML="";const a=this._backgroundLayer(),t=a!=null&&a.fill&&typeof a.fill=="object"?a.fill:{kind:"transparent"},n=typeof t.fit=="string"?t.fit:"cover",i=this._backgroundBlur(a),r=(a==null?void 0:a.locked)===!0,l=t.kind==="color"&&typeof t.value=="string"?t.value:"#ffffff";this.element.appendChild(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 s=te.el("input",{type:"color",className:"color-input",value:l,disabled:r?"disabled":void 0,"aria-label":"Background color","data-testid":"v2-background-color",onInput:k=>{this._runAction(this.editor.setBackgroundColor(k.target.value))}});this.element.appendChild(this._field("Color",s));const d=te.el("div",{className:"background-gradient-grid"});for(const k of Ch){const y=te.el("button",{type:"button",className:"background-gradient-swatch",style:{background:k.style},"aria-label":k.ariaLabel,disabled:r?"disabled":void 0,"data-testid":`v2-background-gradient-${k.id}`,onClick:()=>{this._runAction(this.editor.setBackgroundGradient(k.fill))}},te.el("span",{className:"background-gradient-label"},k.label));d.appendChild(y)}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:k=>{var w;const y=(w=k.target.files)==null?void 0:w[0];y&&this._runAction(this.editor.setBackgroundImageFromFile(y,{fit:n})),k.target.value=""}});this.element.appendChild(this._field("Upload",c));const u=(v=(h=(f=this.editor)==null?void 0:f._options)==null?void 0:h.backgroundReplacement)==null?void 0:v.mediaChoices;if(Array.isArray(u)&&u.length>0){const k=te.el("div",{className:"background-media-grid"});for(const y of u)y!=null&&y.source&&k.appendChild(te.el("button",{type:"button",className:"background-media-choice","aria-label":`Use ${y.label||"media"} as background`,disabled:r?"disabled":void 0,"data-testid":`v2-background-media-${y.id||y.source.mediaUuid||"choice"}`,onClick:()=>{this._runAction(this.editor.setBackgroundMediaSource(y.source,{fit:y.fit||n}))}},y.label||"Media"));this.element.appendChild(this._field("Media",k))}const m=te.el("select",{className:"select-input",disabled:r?"disabled":void 0,"aria-label":"Background image fit","data-testid":"v2-background-fit",onChange:k=>{this._runAction(this.editor.setBackgroundFit(k.target.value))}},this._option("cover","Cover",n),this._option("contain","Contain",n),this._option("stretch","Stretch",n),this._option("tile","Tile",n));this.element.appendChild(this._field("Fit",m));const p=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:k=>{this._runAction(this.editor.setBackgroundBlur(Number(k.target.value)))}});this.element.appendChild(this._field("Blur",p)),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(l=>(l==null?void 0:l.id)==="background-blur"),i=Number((r=n==null?void 0:n.params)==null?void 0:r.amount);return Number.isFinite(i)?i:0}destroy(){var a;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(a=this.element)==null||a.remove(),this.element=null}}class tm{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),l=(a==null?void 0:a.visible)!==!1,s=(a==null?void 0:a.locked)===!0,d=this.state.get("activeLayerId")===i,c=[d?"active":null,l?"visible":"hidden",s?"locked":"unlocked"].filter(Boolean).join(", "),u=te.el("div",{className:`layer-row${d?" active":""}${l?"":" hidden"}${s?" locked":""}`,role:"option","aria-selected":d?"true":"false","aria-label":`${r}, ${this._layerTypeLabel(a)}, ${c}`,"data-layer-id":i,"data-testid":`v2-layer-row-${i}`});u.appendChild(this._button({testId:`v2-layer-select-${i}`,label:`Select ${r}`,className:"layer-row-select",onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).selectLayer)==null?void 0:f.call(p,i)})},this._thumbnail(a))),u.appendChild(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 m=te.el("div",{className:"layer-row-actions"});return m.appendChild(this._iconButton({testId:`v2-layer-${l?"hide":"show"}-${i}`,label:`${l?"Hide":"Show"} ${r}`,icon:l?te.eye:te.eyeOff,disabled:s,onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).setLayerVisibility)==null?void 0:f.call(p,i,!l)})})),m.appendChild(this._iconButton({testId:`v2-layer-${s?"unlock":"lock"}-${i}`,label:`${s?"Unlock":"Lock"} ${r}`,icon:s?te.lockClosed:te.lockOpen,onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).setLayerLocked)==null?void 0:f.call(p,i,!s)})})),m.appendChild(this._iconButton({testId:`v2-layer-move-up-${i}`,label:`Move ${r} up`,icon:te.chevronRight,disabled:s,onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).moveLayer)==null?void 0:f.call(p,i,"up")})})),m.appendChild(this._iconButton({testId:`v2-layer-move-down-${i}`,label:`Move ${r} down`,icon:te.chevronLeft,disabled:s,onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).moveLayer)==null?void 0:f.call(p,i,"down")})})),m.appendChild(this._iconButton({testId:`v2-layer-bring-front-${i}`,label:`Bring ${r} to front`,icon:te.chevronRight,disabled:s,onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).moveLayer)==null?void 0:f.call(p,i,"front")})})),m.appendChild(this._iconButton({testId:`v2-layer-send-back-${i}`,label:`Send ${r} to back`,icon:te.chevronLeft,disabled:s,onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).moveLayer)==null?void 0:f.call(p,i,"back")})})),m.appendChild(this._iconButton({testId:`v2-layer-rename-${i}`,label:`Rename ${r}`,icon:te.pencil,disabled:s,onClick:()=>this._renameLayer(i,r)})),m.appendChild(this._iconButton({testId:`v2-layer-duplicate-${i}`,label:`Duplicate ${r}`,icon:te.duplicate,disabled:s,onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).duplicateLayer)==null?void 0:f.call(p,i)})})),m.appendChild(this._iconButton({testId:`v2-layer-delete-${i}`,label:`Delete ${r}`,icon:te.trash,disabled:s||n<=1,onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).deleteLayer)==null?void 0:f.call(p,i)})})),u.appendChild(m),u}_thumbnail(a){const t=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 l=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 l.innerHTML=n,l}_renameLayer(a,t){var i;const n=(i=window.prompt)==null?void 0:i.call(window,"Layer name",t);typeof n=="string"&&this._runAction(()=>{var r,l;return(l=(r=this.editor).renameLayer)==null?void 0:l.call(r,a,n)})}_runAction(a){var t,n;try{Promise.resolve(a()).catch(i=>{var r,l;return(l=(r=this.editor).emit)==null?void 0:l.call(r,"error",{error:i,context:"layer-stack"})})}catch(i){(n=(t=this.editor).emit)==null||n.call(t,"error",{error:i,context:"layer-stack"})}}_layerName(a){return(typeof(a==null?void 0:a.name)=="string"?a.name.trim():"")||"Layer"}_layerTypeLabel(a){return(a==null?void 0:a.type)==="background"||(a==null?void 0:a.role)==="background"?"Background":(a==null?void 0:a.role)==="subject"?"Subject":(a==null?void 0:a.type)==="text"?"Text":"Image"}destroy(){var a;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(a=this.element)==null||a.remove(),this.element=null,this._listEl=null}}const xh=[{value:"400",label:"Regular"},{value:"500",label:"Medium"},{value:"600",label:"Semibold"},{value:"700",label:"Bold"},{value:"800",label:"Heavy"}],Nh=[{value:"left",label:"Left"},{value:"center",label:"Center"},{value:"right",label:"Right"}],Vh=[{value:"normal",label:"Normal"},{value:"multiply",label:"Multiply"},{value:"screen",label:"Screen"},{value:"overlay",label:"Overlay"}],ir={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 am{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:{},l=a.transform&&typeof a.transform=="object"?a.transform:{},s=this._textEffects(n.effects);this.element.appendChild(this._contentControl(a.id,n.content??"",t)),this.element.appendChild(this._controlGrid([this._numberField({label:"Opacity",testId:"v2-text-opacity",value:a.opacity??1,min:0,max:1,step:.05,disabled:t,onInput:d=>{var c,u;return this._runAction((u=(c=this.editor).updateTextLayer)==null?void 0:u.call(c,a.id,{opacity:d}))}}),this._selectField({label:"Blend",testId:"v2-text-blend-mode",value:a.blendMode||"normal",options:Vh,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:xh,disabled:t,onChange:d=>this._updateStyle(a.id,{fontWeight:Number(d)})}),this._selectField({label:"Style",testId:"v2-text-font-style",value:i.fontStyle||"normal",options:[{value:"normal",label:"Normal"},{value:"italic",label:"Italic"}],disabled:t,onChange:d=>this._updateStyle(a.id,{fontStyle:d})}),this._selectField({label:"Align",testId:"v2-text-align",value:i.align||"center",options:Nh,disabled:t,onChange:d=>this._updateStyle(a.id,{align:d})})])),this.element.appendChild(this._controlGrid([this._colorField({label:"Fill",testId:"v2-text-fill",value:i.fill||"#ffffff",disabled:t,onInput:d=>this._updateStyle(a.id,{fill:d})}),this._numberField({label:"Line",testId:"v2-text-line-height",value:i.lineHeight??1.2,min:.8,max:3,step:.05,disabled:t,onInput:d=>this._updateStyle(a.id,{lineHeight:d})}),this._numberField({label:"Track",testId:"v2-text-letter-spacing",value:i.letterSpacing??0,min:-100,max:100,step:.5,disabled:t,onInput:d=>this._updateStyle(a.id,{letterSpacing:d})})])),this.element.appendChild(this._controlGrid([this._numberField({label:"X",testId:"v2-text-box-x",value:r.x??.2,min:0,max:1,step:.01,disabled:t,onInput:d=>this._updateBox(a.id,{x:d})}),this._numberField({label:"Y",testId:"v2-text-box-y",value:r.y??.2,min:0,max:1,step:.01,disabled:t,onInput:d=>this._updateBox(a.id,{y:d})}),this._numberField({label:"W",testId:"v2-text-box-width",value:r.width??.6,min:.05,max:1,step:.01,disabled:t,onInput:d=>this._updateBox(a.id,{width:d})}),this._numberField({label:"H",testId:"v2-text-box-height",value:r.height??.18,min:.05,max:1,step:.01,disabled:t,onInput:d=>this._updateBox(a.id,{height:d})}),this._numberField({label:"Rotate",testId:"v2-text-rotation",value:l.rotation??0,min:0,max:360,step:1,disabled:t,onInput:d=>{var c,u;return this._runAction((u=(c=this.editor).updateTextLayer)==null?void 0:u.call(c,a.id,{transform:{rotation:d}}))}})])),this.element.appendChild(this._effectSection("Stroke",[this._checkboxField({label:"Stroke",testId:"v2-text-stroke-enabled",checked:s.stroke.enabled,disabled:t,onChange:d=>this._updateEffects(a.id,{stroke:{enabled:d}})}),this._colorField({label:"Stroke Color",testId:"v2-text-stroke-color",value:s.stroke.color,disabled:t,onInput:d=>this._updateEffects(a.id,{stroke:{color:d}})}),this._numberField({label:"Stroke Width",testId:"v2-text-stroke-width",value:s.stroke.width,min:0,max:80,step:1,disabled:t,onInput:d=>this._updateEffects(a.id,{stroke:{width:d}})})])),this.element.appendChild(this._effectSection("Shadow",[this._checkboxField({label:"Shadow",testId:"v2-text-shadow-enabled",checked:s.shadow.enabled,disabled:t,onChange:d=>this._updateEffects(a.id,{shadow:{enabled:d}})}),this._colorField({label:"Shadow Color",testId:"v2-text-shadow-color",value:s.shadow.color,disabled:t,onInput:d=>this._updateEffects(a.id,{shadow:{color:d}})}),this._numberField({label:"Shadow Alpha",testId:"v2-text-shadow-alpha",value:s.shadow.alpha,min:0,max:1,step:.05,disabled:t,onInput:d=>this._updateEffects(a.id,{shadow:{alpha:d}})}),this._numberField({label:"Shadow Blur",testId:"v2-text-shadow-blur",value:s.shadow.blur,min:0,max:120,step:1,disabled:t,onInput:d=>this._updateEffects(a.id,{shadow:{blur:d}})}),this._numberField({label:"Shadow Distance",testId:"v2-text-shadow-distance",value:s.shadow.distance,min:0,max:200,step:1,disabled:t,onInput:d=>this._updateEffects(a.id,{shadow:{distance:d}})}),this._numberField({label:"Shadow Angle",testId:"v2-text-shadow-angle",value:s.shadow.angle,min:0,max:360,step:1,disabled:t,onInput:d=>this._updateEffects(a.id,{shadow:{angle:d}})})])),this.element.appendChild(this._effectSection("Glow",[this._checkboxField({label:"Glow",testId:"v2-text-glow-enabled",checked:s.glow.enabled,disabled:t,onChange:d=>this._updateEffects(a.id,{glow:{enabled:d}})}),this._colorField({label:"Glow Color",testId:"v2-text-glow-color",value:s.glow.color,disabled:t,onInput:d=>this._updateEffects(a.id,{glow:{color:d}})}),this._numberField({label:"Glow Alpha",testId:"v2-text-glow-alpha",value:s.glow.alpha,min:0,max:1,step:.05,disabled:t,onInput:d=>this._updateEffects(a.id,{glow:{alpha:d}})}),this._numberField({label:"Glow Blur",testId:"v2-text-glow-blur",value:s.glow.blur,min:0,max:120,step:1,disabled:t,onInput:d=>this._updateEffects(a.id,{glow:{blur:d}})})])),this.element.appendChild(this._effectSection("Backdrop",[this._checkboxField({label:"Backdrop",testId:"v2-text-backdrop-enabled",checked:s.backdrop.enabled,disabled:t,onChange:d=>this._updateEffects(a.id,{backdrop:{enabled:d}})}),this._colorField({label:"Backdrop Color",testId:"v2-text-backdrop-color",value:s.backdrop.color,disabled:t,onInput:d=>this._updateEffects(a.id,{backdrop:{color:d}})}),this._numberField({label:"Backdrop Opacity",testId:"v2-text-backdrop-opacity",value:s.backdrop.opacity,min:0,max:1,step:.05,disabled:t,onInput:d=>this._updateEffects(a.id,{backdrop:{opacity:d}})}),this._numberField({label:"Backdrop Padding",testId:"v2-text-backdrop-padding",value:s.backdrop.padding,min:0,max:200,step:1,disabled:t,onInput:d=>this._updateEffects(a.id,{backdrop:{padding:d}})}),this._numberField({label:"Backdrop Radius",testId:"v2-text-backdrop-radius",value:s.backdrop.radius,min:0,max:200,step:1,disabled:t,onInput:d=>this._updateEffects(a.id,{backdrop:{radius:d}})}),this._numberField({label:"Backdrop Blur",testId:"v2-text-backdrop-blur",value:s.backdrop.blur,min:0,max:80,step:1,disabled:t,onInput:d=>this._updateEffects(a.id,{backdrop:{blur:d}})})]))}_contentControl(a,t,n){const i=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 l=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),l.value=r,l.blur();return}d.key==="Enter"&&(d.metaKey||d.ctrlKey)&&(d.preventDefault(),this._runAction((u=(c=this.editor).updateTextLayer)==null?void 0:u.call(c,a,{content:r})),l.blur())}});l.value=r,i.appendChild(l);const s=te.el("div",{className:"text-content-actions"});return s.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),l.value=r}},"Cancel")),s.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(s),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:l}){const s=te.el("select",{className:"select-input",disabled:r?"disabled":void 0,"data-testid":t,onChange:d=>l(d.target.value)});for(const d of i)s.appendChild(te.el("option",{value:d.value,selected:String(n)===String(d.value)?"selected":void 0},d.label));return this._field(a,s)}_numberField({label:a,testId:t,value:n,min:i,max:r,step:l,disabled:s,onInput:d}){const c=te.el("input",{type:"number",className:"text-number-input",min:String(i),max:String(r),step:String(l),value:String(n),disabled:s?"disabled":void 0,"data-testid":t,onInput:u=>d(Number(u.target.value))});return this._field(a,c)}_colorField({label:a,testId:t,value:n,disabled:i,onInput:r}){const l=te.el("input",{type:"color",className:"color-input",value:n,disabled:i?"disabled":void 0,"data-testid":t,onInput:s=>r(s.target.value)});return this._field(a,l)}_checkboxField({label:a,testId:t,checked:n,disabled:i,onChange:r}){const l=te.el("input",{type:"checkbox",className:"text-checkbox-input",checked:n?"checked":void 0,disabled:i?"disabled":void 0,"data-testid":t,onChange:s=>r(s.target.checked===!0)});return te.el("label",{className:"text-field text-checkbox-field"},te.el("span",{className:"text-field-label"},a),l)}_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:{...ir.stroke,...t.stroke&&typeof t.stroke=="object"?t.stroke:{}},shadow:{...ir.shadow,...t.shadow&&typeof t.shadow=="object"?t.shadow:{}},glow:{...ir.glow,...t.glow&&typeof t.glow=="object"?t.glow:{}},backdrop:{...ir.backdrop,...t.backdrop&&typeof t.backdrop=="object"?t.backdrop:{}}}}_runAction(a){this._errorMessage=null,Promise.resolve(a).catch(t=>{var i,r;const n=t instanceof Error?t:new Error(String(t));this._errorMessage=n.message||"Text update failed",(r=(i=this.editor)==null?void 0:i.emit)==null||r.call(i,"error",n),this._render()})}_activeTextLayer(){const a=this.state.get("activeLayerId"),t=this.state.get("layers");return!a||!Array.isArray(t)?null:t.find(n=>(n==null?void 0:n.id)===a&&(n.type==="text"||n.role==="text"))??null}destroy(){var a;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(a=this.element)==null||a.remove(),this.element=null}}class Th{constructor(a,t,n){this.state=a,this.filterManager=t,this.editor=n,this.element=null,this._headerEl=null,this._bodyEl=null,this._view="categories",this._onNavigate=null,this._callbacks=null,this._unsubscribers=[],this._categoryTabs=null,this._filterListView=null,this._filterControlsView=null,this._backgroundPanel=null,this._layerStackPanel=null,this._textPanel=null}build(a){return this._callbacks=a,this._onNavigate=a.onViewChange||null,this.element=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 qu(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 Yu(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 Qu(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 em(this.state,this.editor),this._backgroundPanelEl=this._backgroundPanel.render(),this._layerStackPanel=new tm(this.state,this.editor),this._layerStackPanelEl=this._layerStackPanel.render(),this._textPanel=new am(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,l,s;this._unsubscribers.forEach(d=>d()),this._unsubscribers=[],(a=this._categoryTabs)==null||a.destroy(),(t=this._filterListView)==null||t.destroy(),(n=this._filterControlsView)==null||n.destroy(),(i=this._backgroundPanel)==null||i.destroy(),(r=this._layerStackPanel)==null||r.destroy(),(l=this._textPanel)==null||l.destroy(),(s=this.element)==null||s.remove(),this.element=null}}class Bh{constructor(a,t){this.state=a,this.filterManager=t,this.element=null,this._onSelect=null,this._onRemove=null,this._unsubscribers=[]}render({onSelect:a,onRemove:t}={}){return this._onSelect=a,this._onRemove=t,this.element=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 l of a){const s=this.filterManager.getFilterDef(l);s&&n.appendChild(this._renderChip(s,l===i,r))}this.element.appendChild(n)}_renderChip(a,t,n=null){const i=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 l;return(l=this._onSelect)==null?void 0:l.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:l=>{var s;l.stopPropagation(),(s=this._onRemove)==null||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(".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 rc="(max-width: 900px)";let Ih=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._zoomOverlay=this._buildCanvasZoomOverlay(),this.canvasSection.appendChild(this._zoomOverlay),this.root.appendChild(this.canvasSection),this._isMobile=typeof window<"u"&&((t=window.matchMedia)==null?void 0:t.call(window,rc).matches)===!0,this._isMobile?this._buildMobileShell():this._buildDesktopShell(),typeof window<"u"&&window.matchMedia&&(this._mql=window.matchMedia(rc),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 qu(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 Yu(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 Qu(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 Eh(this.state,this.filterManager),a.appendChild(this._activeStack.render({onRemove:(t,n)=>this._callbacks.onFilterToggle(t,!1,n),onSelect:(t,n)=>this._callbacks.onFilterSelect(t,n),onClearAll:t=>{var n,i;return(i=(n=this._callbacks).onClearAll)==null?void 0:i.call(n,t)}})),this._desktopBackgroundSection=te.el("div",{className:"panel-section",style:{display:"none"}}),this._backgroundPanel=new em(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 tm(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 am(this.state,this.editor),this._desktopTextSection.appendChild(this._textPanel.render()),a.appendChild(this._desktopTextSection),this._panel.appendChild(a),this.root.appendChild(this._panel),this._mountCropControlsInActiveShell(),this._applyMode(this.state.get("mode"))}_buildMobileShell(){this._mobileChips=new Bh(this.state,this.filterManager);const a=this._mobileChips.render({onSelect:(r,l)=>{var s,d;this._callbacks.onFilterSelect(r,l),(s=this._mobileDrawer)==null||s.snapTo("full"),(d=this._mobileNav)==null||d.navigateTo("controls")},onRemove:(r,l)=>this._callbacks.onFilterToggle(r,!1,l)});this.root.appendChild(a),this._mobileDrawer=new Sh({onSnapChange:r=>{this.canvasContainer&&window.dispatchEvent(new Event("resize"))}}),this._mobileNav=new Th(this.state,this.filterManager,this.editor);const t=this._mobileNav.build({onFilterToggle:this._callbacks.onFilterToggle,onFilterSelect:this._callbacks.onFilterSelect,onFilterChange:this._callbacks.onFilterChange,onFilterReset:this._callbacks.onFilterReset,onFilterAction:this._callbacks.onFilterAction,onViewChange:r=>{var l;r==="controls"&&((l=this._mobileDrawer)==null?void 0:l.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,l,s,d,c,u;(a=this._categoryTabs)==null||a.destroy(),this._categoryTabs=null,(t=this._filterListView)==null||t.destroy(),this._filterListView=null,(n=this._filterControlsView)==null||n.destroy(),this._filterControlsView=null,(i=this._activeStack)==null||i.destroy(),this._activeStack=null,(r=this._backgroundPanel)==null||r.destroy(),this._backgroundPanel=null,(l=this._layerStackPanel)==null||l.destroy(),this._layerStackPanel=null,(s=this._textPanel)==null||s.destroy(),this._textPanel=null,this._desktopBackgroundSection=null,this._desktopLayerSection=null,this._desktopTextSection=null,this._desktopFilterListSection=null,(d=this._desktopCropWrapper)!=null&&d.parentElement&&((c=this._cropControlsEl)==null?void 0:c.parentElement)===this._desktopCropWrapper&&this._desktopCropWrapper.removeChild(this._cropControlsEl),this._desktopCropWrapper=null,(u=this._panel)==null||u.remove(),this._panel=null}_destroyMobileShell(){var a,t,n,i,r;(a=this._resizeObserver)==null||a.disconnect(),this._resizeObserver=null,(t=this._mobileNav)==null||t.destroy(),this._mobileNav=null,(n=this._mobileChips)==null||n.destroy(),this._mobileChips=null,this._mobileCropWrapper&&((i=this._cropControlsEl)==null?void 0:i.parentElement)===this._mobileCropWrapper&&this._mobileCropWrapper.removeChild(this._cropControlsEl),this._mobileCropWrapper=null,(r=this._mobileDrawer)==null||r.destroy(),this._mobileDrawer=null}_handleBreakpointChange(a){a!==this._isMobile&&(this._isMobile=a,a?(this._destroyDesktopShell(),this._buildMobileShell()):(this._destroyMobileShell(),this._buildDesktopShell()))}_mountCropControlsInActiveShell(){if(!this._cropControlsEl)return;this._cropControlsEl.remove();const a=this._isMobile?this._mobileCropWrapper:this._desktopCropWrapper;a==null||a.appendChild(this._cropControlsEl)}_handleDesktopCategoryChange(){if(this.state.get("mode")==="crop"||["background","layers","text"].includes(this.state.get("selectedCategory")))return;const t=this.state.get("selectedFilter");if(!t)return;this.filterManager.getFiltersByCategory(this.state.get("selectedCategory")).some(i=>i.id===t)||this.state.set("selectedFilter",null)}_applyMode(a){var s,d,c;const t=a==="crop",n=!t&&this.state.get("selectedCategory")==="background",i=!t&&this.state.get("selectedCategory")==="layers",r=!t&&this.state.get("selectedCategory")==="text",l=n||i||r;this._desktopFilterListSection&&(this._desktopFilterListSection.style.display=t||l?"none":""),(s=this._filterControlsView)!=null&&s.element&&(this._filterControlsView.element.style.display=t||l?"none":""),(d=this._activeStack)!=null&&d.element&&(this._activeStack.element.style.display=t||l?"none":""),this._desktopBackgroundSection&&(this._desktopBackgroundSection.style.display=n?"":"none"),this._desktopLayerSection&&(this._desktopLayerSection.style.display=i?"":"none"),this._desktopTextSection&&(this._desktopTextSection.style.display=r?"":"none"),this._desktopCropWrapper&&(this._desktopCropWrapper.style.display=t?"":"none"),(c=this._mobileNav)!=null&&c.element&&(this._mobileNav.element.style.display=t?"none":""),this._mobileCropWrapper&&(this._mobileCropWrapper.style.display=t?"":"none"),t&&this._mobileDrawer&&this._mobileDrawer.snapTo("half")}_buildCanvasZoomOverlay(){const a=te.el("div",{className:"canvas-zoom-overlay",role:"group","aria-label":"Zoom controls"}),t=te.createIconButton({icon:te.zoomOut,title:"Zoom Out",className:"canvas-zoom-btn",testId:"btn-zoom-out",ariaLabel:"Zoom out",onClick:()=>{const l=this.state.get("zoom");this.editor.setZoom(l-.25)}}),n=te.el("span",{className:"canvas-zoom-label","aria-live":"polite","aria-atomic":"true",role:"status"},`${Math.round((this.state.get("zoom")??1)*100)}%`),i=te.createIconButton({icon:te.zoomIn,title:"Zoom In",className:"canvas-zoom-btn",testId:"btn-zoom-in",ariaLabel:"Zoom in",onClick:()=>{const l=this.state.get("zoom");this.editor.setZoom(l+.25)}}),r=te.createIconButton({icon:te.expand,title:"Fit to Screen",className:"canvas-zoom-btn",testId:"btn-fit-screen",ariaLabel:"Fit to screen",onClick:()=>this.editor.fitToScreen()});return a.appendChild(t),a.appendChild(n),a.appendChild(i),a.appendChild(r),this._unsubscribers.push(this.state.on("change:zoom",({value:l})=>{n.textContent=`${Math.round(l*100)}%`})),a}destroy(){var a;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],this._mql&&this._mqlHandler&&(this._mql.removeEventListener?this._mql.removeEventListener("change",this._mqlHandler):this._mql.removeListener&&this._mql.removeListener(this._mqlHandler),this._mql=null,this._mqlHandler=null),this._destroyDesktopShell(),this._destroyMobileShell(),(a=this.root)==null||a.remove(),this.root=null,this.canvasSection=null,this.canvasContainer=null,this.cropOverlay=null}};function No(o){if(!Number.isFinite(Number(o)))return 0;const a=Number(o)%360;return a<0?a+360:a}function Mh(o,a){const t=No(o);return(No(a)-t+540)%360-180}function $h(){return new Date().toISOString()}function rr(o){return typeof o=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(o)}class Fh extends te.EventEmitter{constructor(a,t={}){var r,l,s,d,c;if(super(),!a)throw new Error("VanillaImageEditorV2: container element is required");this._container=a,this._destroyed=!1,this._loadVersion=0,this._objectUrls=new Set,this._activeObjectUrl=null;const n=t.preset?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:(l=this._options.backgroundRemoval)==null?void 0:l.endpoint,optionsEndpoint:(s=this._options.backgroundRemoval)==null?void 0:s.optionsEndpoint,savedEndpoint:(d=this._options.backgroundRemoval)==null?void 0:d.savedEndpoint,fallbackEndpoint:(c=this._options.backgroundRemoval)==null?void 0:c.fallbackEndpoint})),this._loadingOverlay=null,this._toolbar=null,this._layout=null,this._cropControls=null,this._editorEl=null,this._toolbarContainer=null,this._canvasContainer=null,this._cropOverlay=null,this._fileInput=null,this._mobileSaveBar=null,this._mobileSaveBtn=null,this._mobileSaveUnsub=null,this._resizeObserver=null,this._initPromise=Promise.resolve(this._init()).catch(u=>{this._destroyed||this.emit("error",u instanceof Error?u:new Error(String(u)))})}async _init(){this._state.detectTheme(),this._buildDOM(),!(!await this._renderer.mount(this._canvasContainer,0,{backgroundAlpha:0})||this._destroyed)&&(this._cropManager.setOverlayCanvas(this._cropOverlay),this._initUI(),this._setupResizeObserver(),this._setupWindowResize(),this._subscribeToState(),this._refreshBackgroundRemovalAvailability(),this._options.initialImage&&await this.loadImage(this._options.initialImage),this.emit("ready"))}_buildDOM(){this._container.innerHTML="",this._editorEl=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 Ih(this._state,this._filterManager,this);const{root:a,canvasContainer:t,cropOverlay:n}=this._layout.build({onFilterToggle:(i,r,l)=>this._handleFilterToggle(i,r,l),onFilterSelect:(i,r)=>this._handleFilterSelect(i,r),onFilterChange:(i,r,l,s)=>this._handleFilterChange(i,r,l,s),onFilterReset:(i,r)=>this._handleFilterReset(i,r),onFilterAction:(i,r,l)=>this._handleFilterAction(i,r,l),onClearAll:i=>this.resetAll(i)});this._canvasContainer=t,this._cropOverlay=n,this._editorEl.appendChild(a),this._buildMobileSaveBar(),this._mobileSaveBar&&this._editorEl.appendChild(this._mobileSaveBar),this._fileInput=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 l=te.REGISTRY_TO_UI[i.category]||i.category;this._state.get("selectedCategory")!==l&&this._state.set("selectedCategory",l)}}_handleFilterChange(a,t,n,i=void 0){this._filterManager.updateValue(a,t,n,i)||this._filterManager.applyFilters(),this._renderer.render()}_handleFilterReset(a,t=void 0){var n,i;this._filterManager.resetValues(a,t),(i=(n=this._filterManager)==null?void 0:n.applyFilters)==null||i.call(n)}_handleFilterAction(a,t,n=void 0){this._filterManager.performFilterAction(a,t,n)}_revokeObjectUrl(a){!a||!this._objectUrls.has(a)||(URL.revokeObjectURL(a),this._objectUrls.delete(a),this._activeObjectUrl===a&&(this._activeObjectUrl=null))}_replaceActiveObjectUrl(a){const t=this._activeObjectUrl;this._activeObjectUrl=a,this._objectUrls.add(a),t&&t!==a&&this._revokeObjectUrl(t)}_clearActiveObjectUrl(){this._activeObjectUrl&&this._revokeObjectUrl(this._activeObjectUrl)}async _renderCurrentDocument(){var a,t;return(t=(a=this._renderer).renderLayerDocument)==null?void 0:t.call(a,this._state.getSerializableDocument(),{fallbackImageUrl:this._state.get("imageUrl")??null})}async setBackgroundFill(a){var n;const t=this._state.setBackgroundFill(a);return await this._renderCurrentDocument(),this.emit("background-changed",{layerId:t,fill:((n=this._state.getLayer(t))==null?void 0:n.fill)??null}),t}async setBackgroundColor(a){return this.setBackgroundFill({kind:"color",value:typeof a=="string"&&a.trim()!==""?a:"#ffffff"})}async setBackgroundGradient(a={}){return this.setBackgroundFill({kind:"gradient",gradientType:a.gradientType||"linear",angle:Number.isFinite(Number(a.angle))?Number(a.angle):135,stops:Array.isArray(a.stops)?a.stops:[{offset:0,color:"#111827"},{offset:1,color:"#f59e0b"}],fit:a.fit||"cover"})}async setBackgroundMediaSource(a,t={}){if(!a||typeof a!="object")throw new Error("Background source is required");return this.setBackgroundFill({kind:"media",source:a,fit:t.fit||"cover"})}async setBackgroundImageFromFile(a,t={}){var i,r;if(!(a instanceof Blob))throw new Error("Background image file is required");const n=URL.createObjectURL(a);this._objectUrls.add(n);try{if(((r=(i=this._state).isBackgroundLayerLocked)==null?void 0:r.call(i))===!0)throw new Error("Background layer is locked");const l=this._captureEditorDocumentContext(),s=await this._probeImageDimensions(n);if(!this._isCurrentEditorDocumentContext(l))return URL.revokeObjectURL(n),this._objectUrls.delete(n),null;const d=this._state.ensureBackgroundLayer();if(!d)throw new Error("Background layer is locked");let c=null,u=this._captureEditorDocumentContext(d);if(this._canUploadBackgroundAsset()){if(!await this._materializeBackgroundLayerForUpload(d))return URL.revokeObjectURL(n),this._objectUrls.delete(n),null;if(u=this._captureEditorDocumentContext(d),c=await this._uploadBackgroundAsset(a,d,n),!this._isCurrentEditorDocumentContext(u))return URL.revokeObjectURL(n),this._objectUrls.delete(n),null}return c||(c={kind:"runtime",runtimeRef:`background-${Date.now()}`,originalWidth:s.width,originalHeight:s.height,sourceHash:null,previewUrl:n}),this._isCurrentEditorDocumentContext(u)?this.setBackgroundMediaSource(c,{fit:t.fit||"cover"}):(URL.revokeObjectURL(n),this._objectUrls.delete(n),null)}catch(l){throw URL.revokeObjectURL(n),this._objectUrls.delete(n),l}}async setBackgroundFit(a){if(!this._state.setBackgroundFit(a))return!1;const n=this._backgroundLayerId();await this._renderCurrentDocument();const i=n?this._state.getLayer(n):null;return i&&this.emit("background-changed",{layerId:n,fill:i.fill??null}),!0}async setBackgroundBlur(a){if(!this._state.setBackgroundBlur(a))return!1;const n=this._backgroundLayerId();await this._renderCurrentDocument();const i=n?this._state.getLayer(n):null;return i&&this.emit("background-changed",{layerId:n,effects:i.effects??[]}),!0}_backgroundLayerId(){const a=this._state.getSerializableDocument(),t=Array.isArray(a==null?void 0:a.layers)?a.layers.find(n=>(n==null?void 0:n.type)==="background"||(n==null?void 0:n.role)==="background"):null;return typeof(t==null?void 0:t.id)=="string"?t.id:null}async removeBackgroundLayer(){return this._state.removeBackgroundLayer()?(await this._renderCurrentDocument(),this.emit("background-changed",{layerId:null,fill:null}),!0):!1}async selectLayer(a){var n,i;return this._state.setActiveLayer(a)?((i=(n=this._filterManager)==null?void 0:n.applyFilters)==null||i.call(n),this.emit("layer-changed",{action:"select",layerId:a}),!0):!1}async renameLayer(a,t){var i;return this._state.renameLayer(a,t)?(this.emit("layer-changed",{action:"rename",layerId:a,name:((i=this._state.getLayer(a))==null?void 0:i.name)??null}),!0):!1}async duplicateLayer(a){const t=this._state.duplicateLayer(a);return t?(await this._renderCurrentDocument(),this.emit("layer-changed",{action:"duplicate",layerId:a,duplicateLayerId:t}),t):null}async deleteLayer(a){return this._state.deleteLayer(a)?(await this._renderCurrentDocument(),this.emit("layer-changed",{action:"delete",layerId:a,activeLayerId:this._state.get("activeLayerId")}),!0):!1}async moveLayer(a,t){return this._state.moveLayer(a,t)?(await this._renderCurrentDocument(),this.emit("layer-changed",{action:"move",layerId:a,direction:t}),!0):!1}async setLayerVisibility(a,t){return this._state.setLayerVisibility(a,t)?(await this._renderCurrentDocument(),this.emit("layer-changed",{action:"visibility",layerId:a,visible:!!t}),!0):!1}async setLayerLocked(a,t){return this._state.setLayerLocked(a,t)?(this.emit("layer-changed",{action:"lock",layerId:a,locked:!!t}),!0):!1}async addTextLayer(a={}){const t=this._state.addTextLayer(a);return t?(this._state.set("selectedCategory","text"),await this._renderCurrentDocument(),this.emit("layer-changed",{action:"text-add",layerId:t}),t):null}async updateTextLayer(a,t={}){return this._state.updateTextLayer(a,t)?(await this._renderCurrentDocument(),this.emit("layer-changed",{action:"text-update",layerId:a,patch:t}),!0):!1}_canUploadBackgroundAsset(){var r,l;const a=(l=(r=this._options)==null?void 0:r.backgroundReplacement)==null?void 0:l.assetEndpoint,t=this._state.getEditorDocumentBinding(),n=this._state.getSerializableDocument(),i=this._backgroundTargetMediaUuid(n);return typeof a=="string"&&a.trim()!==""&&!!(t!=null&&t.documentId)&&!!n&&typeof i=="string"&&i.trim()!==""}async _materializeBackgroundLayerForUpload(a){return this._materializeCurrentDocument("Background layer materialization failed",a)}_documentMaterializationSignature(a){try{return JSON.stringify(a??null)}catch{return null}}_captureDocumentMaterializationContext(a,t,n=null){return{loadVersion:this._loadVersion,documentId:(t==null?void 0:t.documentId)??null,documentRevisionId:(t==null?void 0:t.documentRevisionId)??null,documentRevisionNumber:(t==null?void 0:t.documentRevisionNumber)??null,documentSignature:this._documentMaterializationSignature(a),requiredLayerId:n}}_captureEditorDocumentContext(a=null){return{loadVersion:this._loadVersion,documentSignature:this._documentMaterializationSignature(this._state.getSerializableDocument()),requiredLayerId:a}}_isCurrentEditorDocumentContext(a){return!(!a||this._destroyed||this._loadVersion!==a.loadVersion||this._documentMaterializationSignature(this._state.getSerializableDocument())!==a.documentSignature||a.requiredLayerId&&!this._state.getLayer(a.requiredLayerId))}_isCurrentDocumentMaterializationContext(a){if(!a||this._destroyed||this._loadVersion!==a.loadVersion)return!1;const t=this._state.getEditorDocumentBinding();if(!t||(t.documentId??null)!==a.documentId||(t.documentRevisionId??null)!==a.documentRevisionId||(t.documentRevisionNumber??null)!==a.documentRevisionNumber)return!1;const n=this._state.getSerializableDocument();return!(this._documentMaterializationSignature(n)!==a.documentSignature||a.requiredLayerId&&!this._state.getLayer(a.requiredLayerId))}async _materializeCurrentDocument(a="Editor document materialization failed",t=null){const n=this._backgroundMaterializeEndpoint(),i=this._state.getEditorDocumentBinding(),r=this._state.getSerializableDocument();if(!n||!(i!=null&&i.documentId)||!r||t!==null&&!t)return!1;const l=this._resolveBackgroundEndpoint(n,r);if(!l)return!1;const s=this._captureDocumentMaterializationContext(r,i,t),d=rr(i.documentId)?i.documentId:null,c=await fetch(l,{method:"POST",credentials:"include",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({document_id:d,base_document_revision:d===null?null:i.documentRevisionNumber,document:r})});let u=null;try{u=await c.json()}catch{u=null}if(!c.ok){const m=(u==null?void 0:u.message)||a;throw new Error(m)}return this._isCurrentDocumentMaterializationContext(s)?(u!=null&&u.document&&this._state.setEditorDocument(u.document,{documentId:u.document_id??i.documentId,documentRevisionId:u.document_revision_id??i.documentRevisionId,documentRevisionNumber:typeof u.document_revision_number=="number"?u.document_revision_number:i.documentRevisionNumber}),!0):!1}async _uploadBackgroundAsset(a,t,n){var f,h,v;const i=(h=(f=this._options)==null?void 0:f.backgroundReplacement)==null?void 0:h.assetEndpoint,r=this._state.getEditorDocumentBinding(),l=this._state.getSerializableDocument();if(!i||!(r!=null&&r.documentId)||!l)return null;const s=this._resolveBackgroundEndpoint(i,l);if(!s)return null;const d=await this._sha256File(a),c=new FormData;c.append("asset_file",a,a instanceof File&&a.name?a.name:"background.png"),c.append("asset_kind","background-upload"),c.append("document_id",r.documentId),c.append("layer_id",t),c.append("client_hash",d);const u=await fetch(s,{method:"POST",credentials:"include",headers:{Accept:"application/json"},body:c});if(!u.ok)throw new Error("Background upload failed");const m=await u.json(),p=(v=m==null?void 0:m.asset)==null?void 0:v.source;if(!p||typeof p!="object")throw new Error("Background upload did not return a usable layer source");return{...p,previewUrl:n}}_backgroundMaterializeEndpoint(){var i,r,l,s,d,c;const a=(r=(i=this._options)==null?void 0:i.backgroundReplacement)==null?void 0:r.materializeEndpoint;if(typeof a=="string"&&a.trim()!=="")return a;const t=(s=(l=this._options)==null?void 0:l.backgroundReplacement)==null?void 0:s.assetEndpoint;if(typeof t=="string"&&t.trim()!=="")return t.replace(/\/editor-assets\/?$/,"/editor-documents/materialize");const n=(c=(d=this._options)==null?void 0:d.backgroundRemoval)==null?void 0:c.savedEndpoint;return typeof n=="string"&&n.trim()!==""?n.replace(/\/background-removal\/?$/,"/editor-documents/materialize"):null}_resolveBackgroundEndpoint(a,t){if(typeof a!="string"||a.trim()==="")return null;const n=this._backgroundTargetMediaUuid(t);return a.includes("{media}")?typeof n!="string"||n.trim()===""?null:a.replace("{media}",encodeURIComponent(n)):a}_backgroundTargetMediaUuid(a){var n,i;const t=(i=(n=this._options)==null?void 0:n.backgroundReplacement)==null?void 0:i.targetMediaUuid;return typeof t=="string"&&t.trim()!==""?t:typeof(a==null?void 0:a.sourceMediaUuid)=="string"&&a.sourceMediaUuid.trim()!==""?a.sourceMediaUuid:null}async _sha256File(a){var i,r,l;const t=await a.arrayBuffer(),n=await((l=(r=(i=globalThis.crypto)==null?void 0:i.subtle)==null?void 0:r.digest)==null?void 0:l.call(r,"SHA-256",t));if(!n)throw new Error("Background upload hashing is unavailable");return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}_probeImageDimensions(a){return new Promise(t=>{const n=new Image;n.onload=()=>t({width:Math.max(1,Math.round(n.naturalWidth||n.width||1)),height:Math.max(1,Math.round(n.naturalHeight||n.height||1))}),n.onerror=()=>t({width:1,height:1}),n.src=a})}setFilterRegistry(a){this._filterManager.setRegistry(a)}async loadImage(a,t={}){var s,d,c,u;if(this._destroyed)return;(d=(s=this._removeBgManager)==null?void 0:s.cancelActiveRequests)==null||d.call(s,"image-load");const n=++this._loadVersion;let i=a,r=null;this._resetEditorState(),this._state.set("hasImage",!1),this._state.set("imageUrl",null),a instanceof Blob&&(i=URL.createObjectURL(a),r=i,this._objectUrls.add(i));const l=await this._renderer.loadTexture(i,{isCurrent:()=>!this._destroyed&&this._loadVersion===n});if(this._destroyed||this._loadVersion!==n){this._revokeObjectUrl(r);return}if(!l){this._revokeObjectUrl(r),this.emit("error",new Error("Failed to load image"));return}r?this._replaceActiveObjectUrl(r):this._clearActiveObjectUrl(),this._state.set("hasImage",!0),this._state.set("imageUrl",i),t.document?await this._hydrateDocument(t.document,{documentId:t.documentId??(rr((c=t.document)==null?void 0:c.id)?t.document.id:null),documentRevisionId:t.documentRevisionId??null,documentRevisionNumber:t.documentRevisionNumber??((u=t.document)==null?void 0:u.revision)??null,fallbackImageUrl:i}):this._initializeDefaultDocument(i),t.state&&this._hydrateState(t.state),this._options.initialMode==="crop"&&this.setMode("crop"),this.emit("imageLoaded",{url:i})}_resetEditorState(){this._filterManager.resetAll(),this._state.set("crop.rect",null),this._state.set("crop.appliedRect",null),this._state.set("crop.appliedShape",null),this._state.set("crop.appliedAspect",null),this._state.set("crop.dirty",!1),this._state.set("crop.shape",this._options.cropShape||"free"),this._state.set("crop.aspect",this._options.initialAspectRatio||"free"),this._state.set("transform.rotation",0),this._state.clearEditorDocument(),this._state.get("mode")==="crop"&&(this._cropManager.disable(),this._state.set("mode","filters"))}_initializeDefaultDocument(a){var c,u,m,p;const t=this._renderer.originalTexture,n=Math.max(1,Math.round((t==null?void 0:t.width)||1)),i=Math.max(1,Math.round((t==null?void 0:t.height)||1)),r=$h(),l=typeof((u=(c=this._options)==null?void 0:c.backgroundReplacement)==null?void 0:u.targetMediaUuid)=="string"&&this._options.backgroundReplacement.targetMediaUuid.trim()!==""?this._options.backgroundReplacement.targetMediaUuid.trim():null,s=l?{kind:"media",mediaUuid:l,originalWidth:n,originalHeight:i,sourceHash:null}:{kind:"runtime",runtimeRef:"source-image",originalWidth:n,originalHeight:i,sourceHash:null,previewUrl:typeof a=="string"?a:null},d={version:2,id:`client-doc-${Date.now()}`,sourceMediaUuid:l,canvas:{width:n,height:i,backgroundPreviewColor:null},revision:0,layers:[{id:"subject-layer",type:"image",role:"subject",name:"Subject",visible:!0,locked:!1,opacity:1,blendMode:"normal",transform:{x:0,y:0,scaleX:1,scaleY:1,rotation:0},effects:[],metadata:{},source:s,crop:null,filters:[]}],activeLayerId:"subject-layer",export:{mimeType:"image/png",quality:null,preserveTransparency:!0,matteColor:null,trimTransparentBounds:!1},createdAt:r,updatedAt:r};this._state.setEditorDocument(d,{documentId:null,documentRevisionId:null,documentRevisionNumber:0}),(p=(m=this._renderer).renderLayerDocument)==null||p.call(m,d,{fallbackImageUrl:typeof a=="string"?a:null})}async _hydrateDocument(a,t={}){var n,i;!a||a.version!==2||(this._state.setEditorDocument(a,{documentId:t.documentId??(rr(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=No(((n=a.transform)==null?void 0:n.rotation)??0);if(t!==0&&this._renderer.rotateBy(t)&&this._state.set("transform.rotation",t),a.crop){const i=a.crop.shape||"free",r=a.crop.aspectRatio||"free";a.crop.rect&&(this._cropManager.applyFromPixelRect(a.crop.rect,i),this._state.set("crop.appliedRect",{...a.crop.rect}),this._state.set("crop.appliedShape",i),this._state.set("crop.appliedAspect",r)),this._state.set("crop.shape",i),this._state.set("crop.aspect",r)}if(Array.isArray(a.filters)){let i=null;for(const r of a.filters)if(r.enabled&&(i===null&&(i=r.id),this._state.toggleFilter(r.id,!0),this._filterManager.initializeValues(r.id),r.values))for(const[l,s]of Object.entries(r.values))this._state.setFilterValue(r.id,l,s);if(i!==null){this._state.set("selectedFilter",i);const r=this._filterManager.getFilterDef(i);if(typeof(r==null?void 0:r.category)=="string"){const l=te.REGISTRY_TO_UI[r.category]??r.category;this._state.set("selectedCategory",l)}}this._filterManager.applyFilters()}}openFilePicker(){var a;(a=this._fileInput)==null||a.click()}exportImage(a="png",t=.92,n={}){return!this._state.get("hasImage")||!this._applyPendingCropBeforeExport("VanillaImageEditorV2.exportImage")?null:this._renderer.exportImage(a,t,n.maxEdge??0,n.dontUpscale!==!1,n.maxPixels??0)}async exportBlob(a="png",t=.92,n={}){return!this._state.get("hasImage")||!this._applyPendingCropBeforeExport("VanillaImageEditorV2.exportBlob")?null:this._renderer.exportBlob(a,t,n)}_applyPendingCropBeforeExport(a){return!(this._state.get("crop.rect")&&!this._cropManager.apply())}async save(){if(!this._state.get("hasImage"))return;this._state.set("isSaving",!0);let a=null;try{const t=await this.exportBlob("png",.92);if(!t)throw new Error("Failed to export image");const n=i.createElement("a");a=URL.createObjectURL(t.blob),n.href=a,n.download=`edited-image-${Date.now()}.png`,i.body.appendChild(n),n.click(),i.body.removeChild(n);const i=this.getSerializableDocument(),r=this.getEditorDocumentBinding();this.emit("save",{blob:t.blob,mimeType:t.blob.type||"image/png",dimensions:{width:t.width,height:t.height},state:this.getSerializableState(),document:i,documentId:(r==null?void 0:r.documentId)??(rr(i==null?void 0:i.id)?i.id:null),documentRevisionId:(r==null?void 0:r.documentRevisionId)??null,documentRevisionNumber:(r==null?void 0:r.documentRevisionNumber)??(i==null?void 0:i.revision)??null})}catch(t){this.emit("error",{error:t})}finally{a&&URL.revokeObjectURL(a),this._state.set("isSaving",!1)}}getSerializableState(){const a=this._state.get("activeFilters"),t=[];if(a)for(const l of a){const s=this._state.getFilterValues(l);t.push({id:l,enabled:!0,values:{...s}})}const n=this._state.get("crop.appliedRect"),i=this._state.get("crop.rect"),r=n||i;return{version:1,crop:{rect:r?{...r}:null,aspectRatio:this._state.get("crop.appliedAspect")||this._state.get("crop.aspect")||"free",shape:this._state.get("crop.appliedShape")||this._state.get("crop.shape")||"free"},transform:{rotation:No(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=No(this._state.get("transform.rotation")??0),n=No(a),i=Mh(t,n),r=this._state.get("mode")==="crop";if(Math.abs(i)>.001){if(r&&this._cropManager.disable(),!this._renderer.rotateBy(i))return r&&this._cropManager.enable(),!1;this._filterManager.applyFilters(),this._state.set("crop.rect",null),this._state.set("crop.dirty",!1),r&&this._cropManager.enable()}return this._state.set("transform.rotation",n),this.emit("transformChanged",{rotation:n}),!0}resetRotation(){return this.setRotationAngle(0)}toggleTheme(){const a=this._state.get("isDarkMode");this._state.set("isDarkMode",!a)}setTheme(a){this._state.set("theme",a),this._state.detectTheme()}setMode(a){a==="crop"?this._cropManager.enable():this._cropManager.disable(),this._state.set("mode",a)}getState(){return this._state.getAll()}async removeBackground(a={}){var t,n,i,r,l,s,d,c,u,m;if(!this._removeBgManager)throw new Error("Background removal is not enabled");if(!this._state.get("hasImage"))throw new Error("No image loaded");if(!this.canRemoveBackground())throw new Error("Background removal is not available for the current editor state");this._state.set("isProcessing",!0),this._showLoadingOverlay("Removing background...");try{const p=this._activeBackgroundRemovalLayer();if(this._hasSavedEditorDocumentBinding()&&p!==null&&this._backgroundMaterializeEndpoint()&&!await this._materializeCurrentDocument("Background removal materialization failed"))return this.emit("background-removal-stale",{operationId:a.operationId??null,targetLayerId:p.id}),{stale:!0};const f=this._buildSavedBackgroundRemovalContext(a);if(f){const b=await this._removeBgManager.removeSavedMediaBackground(f.request);if(!this._isCurrentBackgroundRemovalContext(f,b))return this.emit("background-removal-stale",{operationId:f.request.operationId,targetLayerId:f.request.targetLayerId}),{stale:!0};const R=(t=b==null?void 0:b.result)==null?void 0:t.source;if(!R||R.kind!=="edit-asset")throw new Error("Background removal did not return a persisted layer source");const V=(n=b==null?void 0:b.result)==null?void 0:n.previewDataUrl;return typeof V=="string"&&V.startsWith("data:image/")&&(!await this._renderer.loadTexture(V,{isCurrent:()=>!this._destroyed&&this._isCurrentBackgroundRemovalContext(f,b)})||!this._isCurrentBackgroundRemovalContext(f,b))?(this.emit("background-removal-stale",{operationId:f.request.operationId,targetLayerId:f.request.targetLayerId}),{stale:!0}):this._isCurrentBackgroundRemovalContext(f,b)?(this._state.replaceLayerSource(f.request.targetLayerId,R),await((r=(i=this._renderer).renderLayerDocument)==null?void 0:r.call(i,this._state.getSerializableDocument(),{fallbackImageUrl:this._state.get("imageUrl")??null})),this.emit("background-removed",{model:(l=b==null?void 0:b.result)==null?void 0:l.model,processMs:(s=b==null?void 0:b.result)==null?void 0:s.process_ms,source:R,operationId:f.request.operationId,targetLayerId:f.request.targetLayerId}),{model:(d=b==null?void 0:b.result)==null?void 0:d.model,processMs:(c=b==null?void 0:b.result)==null?void 0:c.process_ms,source:R}):(this.emit("background-removal-stale",{operationId:f.request.operationId,targetLayerId:f.request.targetLayerId}),{stale:!0})}const h=this._buildPreviewBackgroundRemovalInput(a);if(!h)throw new Error("Failed to export image for background removal");const v=this._buildPreviewBackgroundRemovalContext(h.options),k=await this._removeBgManager.preparePreviewRequest(h.imageData,h.options),y=this._resolvePreviewBackgroundRemovalContext(v,k);if(!await this._isCurrentPreviewBackgroundRemovalContext(y))return this.emit("background-removal-stale",{operationId:y.operationId,sourceHash:y.sourceHash,targetLayerId:y.activeLayerId??null}),{stale:!0};const w=await this._removeBgManager.removeBackground(k.blob,k);if(!await this._isCurrentPreviewBackgroundRemovalContext(y,w))return this.emit("background-removal-stale",{operationId:y.operationId,sourceHash:y.sourceHash}),{stale:!0};const g=await this._applyPreviewBackgroundRemovalResult(y,w);return g?(this.emit("background-removed",{model:w.model,processMs:w.processMs,operationId:y.operationId,targetLayerId:y.activeLayerId??null,source:g.source}),{model:w.model,processMs:w.processMs,...g.source?{source:g.source}:{}}):(this.emit("background-removal-stale",{operationId:y.operationId,sourceHash:y.sourceHash,targetLayerId:y.activeLayerId??null}),{stale:!0})}catch(p){throw this.emit("error",{error:p,context:"background-removal"}),p}finally{(m=(u=this._state)==null?void 0:u.set)==null||m.call(u,"isProcessing",!1),this._hideLoadingOverlay()}}async isBackgroundRemovalAvailable(){return this._removeBgManager?this._refreshBackgroundRemovalAvailability():!1}canRemoveBackground(){if(!this._removeBgManager||this._state.get("hasImage")!==!0||this._backgroundRemovalAvailable!==!0)return!1;const a=this._state.getSerializableDocument();return(a==null?void 0:a.version)===2&&Array.isArray(a.layers)?this._activeBackgroundRemovalLayer({requireSourceHash:this._hasSavedEditorDocumentBinding()})!==null:!0}async _refreshBackgroundRemovalAvailability(){if(!this._removeBgManager)return this._backgroundRemovalAvailable=!1,this._state.set("backgroundRemovalAvailable",!1),!1;const a=await this._removeBgManager.isAvailable();return this._destroyed?!1:(this._backgroundRemovalAvailable=a,this._state.set("backgroundRemovalAvailable",a),a)}_hasSavedEditorDocumentBinding(){const a=this._state.getEditorDocumentBinding();return!!(a!=null&&a.documentId)&&!!(a!=null&&a.documentRevisionId)}_activeBackgroundRemovalLayer(a={}){var l;const t=a.requireSourceHash!==!1,n=this._state.get("activeLayerId");if(!n)return null;const i=this._state.getLayer(n);if(!i||i.type!=="image"||i.locked===!0||i.visible===!1)return null;const r=(l=i==null?void 0:i.source)==null?void 0:l.sourceHash;return t&&(typeof r!="string"||!/^[a-f0-9]{64}$/i.test(r))?null:i}_buildSavedBackgroundRemovalContext(a={}){var u,m,p,f,h;const t=this._state.getSerializableDocument(),n=this._state.getEditorDocumentBinding();if(!t||!(n!=null&&n.documentId)||!(n!=null&&n.documentRevisionId))return null;const i=typeof t.sourceMediaUuid=="string"&&t.sourceMediaUuid!==""?t.sourceMediaUuid:null;if(!i)return null;const r=this._activeBackgroundRemovalLayer({requireSourceHash:!0}),l=r==null?void 0:r.id,s=(u=r==null?void 0:r.source)==null?void 0:u.sourceHash;if(!l||typeof s!="string"||!/^[a-f0-9]{64}$/i.test(s))return null;const d=a.operationId||((p=(m=globalThis.crypto)==null?void 0:m.randomUUID)==null?void 0:p.call(m))||`op-${Date.now()}-${Math.random().toString(16).slice(2)}`,c={loadVersion:this._loadVersion,activeLayerId:l,documentRevisionId:n.documentRevisionId,documentSignature:this._documentMaterializationSignature(t),sourceHash:s,request:{targetMediaUuid:i,operationId:d,documentId:n.documentId,documentRevisionId:n.documentRevisionId,targetLayerId:l,expectedSourceHash:s,tier:a.tier||((h=(f=this._options)==null?void 0:f.backgroundRemoval)==null?void 0:h.defaultTier)||"balanced"}};return a.model&&(c.request.model=a.model),a.alpha_matting!==void 0&&(c.request.alpha_matting=a.alpha_matting),a.max_megapixels!==void 0&&(c.request.max_megapixels=a.max_megapixels),c}_buildPreviewBackgroundRemovalContext(a){const t=this._state.getSerializableDocument(),n=(t==null?void 0:t.version)===2&&Array.isArray(t.layers),i=n?this._activeBackgroundRemovalLayer({requireSourceHash:!1}):null;return{loadVersion:this._loadVersion,activeLayerId:n?(i==null?void 0:i.id)??null:null,documentSignature:n?this._documentMaterializationSignature(t):null,imageUrl:this._state.get("imageUrl")??null,operationId:a.operationId,sessionKey:a.sessionKey,sourceHash:a.sourceHash,targetRef:a.targetRef??null}}_resolvePreviewBackgroundRemovalContext(a,t){return{...a,operationId:t.operationId,sessionKey:t.sessionKey,sourceHash:t.sourceHash,targetRef:t.targetRef??a.targetRef??null}}_buildPreviewBackgroundRemovalInput(a={}){const t=this._state.getSerializableDocument();if((t==null?void 0:t.version)===2&&Array.isArray(t.layers)){const i=this._activeBackgroundRemovalLayer({requireSourceHash:!1}),r=this._sourceUrlForLayerSource(i==null?void 0:i.source);return!i||!r?null:{imageData:r,options:{...a,targetRef:i.id}}}const n=this.exportImage("png");return n?{imageData:n,options:a}:null}_sourceUrlForLayerSource(a){if(!a||typeof a!="object")return null;for(const t of["previewUrl","sourceUrl","url"]){const n=a[t];if(typeof n=="string"&&n.trim()!=="")return n}return null}async _applyPreviewBackgroundRemovalResult(a,t){var r,l;if(a.documentSignature===null||!a.activeLayerId)return await this.loadImage(t.dataUrl),{source:null};const n=await this._probeImageDimensions(t.dataUrl);if(!await this._isCurrentPreviewBackgroundRemovalContext(a,t))return null;const i={kind:"runtime",runtimeRef:`background-removal-${a.operationId||Date.now()}`,originalWidth:n.width,originalHeight:n.height,sourceHash:null,previewUrl:t.dataUrl};return this._state.replaceLayerSource(a.activeLayerId,i)?(await((l=(r=this._renderer).renderLayerDocument)==null?void 0:l.call(r,this._state.getSerializableDocument(),{fallbackImageUrl:this._state.get("imageUrl")??null})),{source:i}):null}async _isCurrentPreviewBackgroundRemovalContext(a,t=null){if(this._destroyed||this._loadVersion!==a.loadVersion||this._state.get("hasImage")!==!0||(this._state.get("imageUrl")??null)!==a.imageUrl)return!1;if(t){if(t.operationId&&t.operationId!==a.operationId||t.sessionKey&&t.sessionKey!==a.sessionKey||t.sourceHash&&t.sourceHash!==a.sourceHash)return!1;if(a.documentSignature!==null){if(!a.targetRef||a.targetRef!==a.activeLayerId||t.targetRef!==a.targetRef)return!1}else if(t.targetRef&&a.targetRef&&t.targetRef!==a.targetRef)return!1}if(a.documentSignature!==null){const i=this._state.getSerializableDocument();if(this._documentMaterializationSignature(i)!==a.documentSignature)return!1;const r=this._activeBackgroundRemovalLayer({requireSourceHash:!1});return!(!r||r.id!==a.activeLayerId)}const n=this.exportImage("png");return n?await this._removeBgManager.computeImageDataHash(n)===a.sourceHash:!1}_isCurrentBackgroundRemovalContext(a,t=null){var l;if(this._destroyed||this._loadVersion!==a.loadVersion)return!1;const n=this._state.getEditorDocumentBinding();if(!n||n.documentRevisionId!==a.documentRevisionId)return!1;const i=this._state.getSerializableDocument();if(this._documentMaterializationSignature(i)!==a.documentSignature||this._state.get("activeLayerId")!==a.activeLayerId)return!1;const r=this._state.getLayer(a.request.targetLayerId);return!(!r||((l=r==null?void 0:r.source)==null?void 0:l.sourceHash)!==a.sourceHash||r.locked===!0||r.visible===!1||t&&(t.operation_id&&t.operation_id!==a.request.operationId||t.target_layer_id&&t.target_layer_id!==a.request.targetLayerId||t.document_revision_id&&t.document_revision_id!==a.request.documentRevisionId||t.source_hash&&t.source_hash!==a.request.expectedSourceHash))}_showLoadingOverlay(a){var n;if(!this._loadingOverlay)this._loadingOverlay=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()}_buildMobileSaveBar(){var l,s;this._mobileSaveBar=te.el("div",{className:"editor-v2-mobile-save-bar",role:"region","aria-label":"Save bar"}),this._mobileSaveBtn=te.el("button",{type:"button",className:"mobile-save-btn",title:"Save Image","aria-label":"Save image",dataset:{testid:"btn-save-edit-mobile"},onClick:()=>this.save()});const a=te.el("span",{className:"mobile-save-icon"});a.innerHTML=te.save;const t=a.querySelector("svg");t&&t.setAttribute("aria-hidden","true"),this._mobileSaveBtn.appendChild(a),this._mobileSaveBtn.appendChild(te.el("span",{className:"mobile-save-label"},"Save")),this._mobileSaveBar.appendChild(this._mobileSaveBtn);const n=()=>{var m,p;if(!this._mobileSaveBtn)return;const d=((m=this._state)==null?void 0:m.get("hasImage"))===!0,c=((p=this._state)==null?void 0:p.get("isProcessing"))===!0,u=!d||c;this._mobileSaveBtn.disabled=u,this._mobileSaveBtn.setAttribute("aria-disabled",u?"true":"false")};n();const i=(l=this._state)==null?void 0:l.on("change:hasImage",n),r=(s=this._state)==null?void 0:s.on("change:isProcessing",n);this._mobileSaveUnsub=()=>{try{i==null||i()}catch{}try{r==null||r()}catch{}}}destroy(){var a,t,n,i,r,l,s,d;this._destroyed=!0,(t=(a=this._removeBgManager)==null?void 0:a.cancelActiveRequests)==null||t.call(a,"editor-destroy");for(const c of this._objectUrls)try{URL.revokeObjectURL(c)}catch{}this._objectUrls.clear(),this._activeObjectUrl=null,(n=this._resizeObserver)==null||n.disconnect(),this._renderer.destroy(),this._cropManager.disable(),this._handleWindowResize&&window.removeEventListener("resize",this._handleWindowResize),(i=this._toolbar)==null||i.destroy(),(r=this._cropControls)==null||r.destroy(),(l=this._layout)==null||l.destroy(),(s=this._mobileSaveUnsub)==null||s.call(this),this._mobileSaveUnsub=null,this._mobileSaveBtn=null,this._mobileSaveBar=null,(d=this._editorEl)==null||d.remove(),this._container=null,this._state=null,this.emit("destroyed"),this.removeAllListeners()}}function Dh(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 Ah=78e5,Rh=e.defineComponent({__name:"ImageEditor",props:{initialImage:{},initialState:{default:null},initialDocument:{default:null},initialDocumentId:{default:null},initialDocumentRevisionId:{default:null},initialDocumentRevisionNumber:{default:null},sessionKey:{default:0},theme:{default:"auto"},cropShape:{default:"square"},preset:{},editorVersion:{default:"v2"},backgroundRemoval:{default:null},backgroundReplacement:{default:null},primaryColor:{default:"#3880ff"},secondaryColor:{default:"#5260ff"},saveButtonColor:{default:"#3880ff"},downloadButtonColor:{default:"#2dd36f"}},emits:["save","cancel","error"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(null);let r=null,l=null;function s(v){return typeof v=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v)}function d(){const v={state:t.initialState??null,sessionKey:t.sessionKey};return t.initialDocument&&(v.document=t.initialDocument,v.documentId=t.initialDocumentId,v.documentRevisionId=t.initialDocumentRevisionId,v.documentRevisionNumber=t.initialDocumentRevisionNumber),v}async function c(){var v,k,y;try{if(!r){n("error",new Error("Editor not initialized"));return}const w=await((v=r.exportBlob)==null?void 0:v.call(r,"png",.92,{maxPixels:Ah}));if(!w){n("error",new Error("Failed to export image — the image could not be processed"));return}const g=r.getSerializableState(),b={blob:w.blob,mimeType:w.blob.type||"image/png",dimensions:{width:w.width,height:w.height},state:g},R=((k=r.getSerializableDocument)==null?void 0:k.call(r))??null;if(R){const V=((y=r.getEditorDocumentBinding)==null?void 0:y.call(r))??null;b.document=R,b.documentId=(V==null?void 0:V.documentId)??(s(R.id)?R.id:null),b.documentRevisionId=(V==null?void 0:V.documentRevisionId)??null,b.documentRevisionNumber=(V==null?void 0:V.documentRevisionNumber)??R.revision??null}n("save",b)}catch(w){n("error",w instanceof Error?w:new Error("Failed to export image"))}}function u(){n("cancel")}function m(v){if(v instanceof Error)return v;if(v!==null&&typeof v=="object"&&"error"in v){const k=v.error;if(k instanceof Error)return k;if(typeof k=="string"&&k.trim()!=="")return new Error(k)}return typeof v=="string"&&v.trim()!==""?new Error(v):new Error("Failed to load image")}function p(v){n("error",m(v))}function f(){if(!i.value||r)return;window.PIXI=Jt,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 k=t.editorVersion==="v2"?Fh:te.VanillaImageEditor,y=new k(i.value,v);r=y,y.setFilterRegistry({getAllFilters:te.getAllFilters,getFilter:te.getFilter,getFiltersByCategory:te.getFiltersByCategory}),y.save=function(){c()},y.on("cancel",u),y.on("error",p),t.initialImage&&y.loadImage(t.initialImage,d())}e.onMounted(()=>{i.value&&(i.value.clientWidth>0?f():(l=new ResizeObserver(v=>{const k=v[0];k&&k.contentRect.width>0&&!r&&(f(),l==null||l.disconnect(),l=null)}),l.observe(i.value)))});const h=()=>{!r||!t.initialImage||r.loadImage(t.initialImage,d())};return e.watch(()=>t.initialImage,(v,k)=>{!r||!v||v===k||h()}),e.watch(()=>t.sessionKey,(v,k)=>{v!==k&&h()}),e.watch(()=>t.initialState,(v,k)=>{v!==k&&h()}),e.watch(()=>[t.initialDocument,t.initialDocumentId,t.initialDocumentRevisionId,t.initialDocumentRevisionNumber],(v,k)=>{v!==k&&h()}),e.onUnmounted(()=>{l==null||l.disconnect(),l=null,r&&(r.destroy(),r=null)}),(v,k)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"containerRef",ref:i,class:"vanilla-editor-wrapper","data-testid":"vanilla-image-editor"},null,512))}}),$e=(o,a)=>{const t=o.__vccOpts||o;for(const[n,i]of a)t[n]=i;return t},nm=$e(Rh,[["__scopeId","data-v-8ab74f83"]]),Lh={class:"editor-modal-panel"},Ph={class:"editor-fill"},Uh=e.defineComponent({__name:"ImageEditorModal",props:{modelValue:{type:Boolean,default:!1},initialImage:{},initialState:{default:null},initialDocument:{default:null},initialDocumentId:{default:null},initialDocumentRevisionId:{default:null},initialDocumentRevisionNumber:{default:null},sessionKey:{default:0},acceptedFormats:{default:"image/jpeg,image/png,image/webp,image/gif"},maxFileSize:{default:10},theme:{default:"auto"},cropShape:{default:"square"},preset:{},editorVersion:{default:"v2"},backgroundRemoval:{default:null},backgroundReplacement:{default:null},primaryColor:{default:"#3880ff"},secondaryColor:{default:"#5260ff"},saveButtonColor:{default:"#3880ff"},downloadButtonColor:{default:"#2dd36f"},saveHandler:{}},emits:["update:modelValue","save","cancel","error"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(null),r=e.ref(t.modelValue),l=e.ref(!1),s=e.ref(null),d=v=>{n("error",v)},c=()=>{e.nextTick(()=>{if(i.value){const v=i.value.querySelector("button:not([disabled]), [href], input:not([disabled])");v&&v.focus()}})};e.watch(()=>t.modelValue,v=>{r.value=v,v&&(s.value=document.activeElement,c())},{immediate:!0});const u=async v=>{try{if(l.value=!0,t.saveHandler){await t.saveHandler(v);return}n("save",v)}catch(k){d(k instanceof Error?k:new Error("Failed to save image"))}finally{l.value=!1}},m=()=>{n("cancel"),f()},p=()=>{l.value||f()},f=()=>{r.value=!1,n("update:modelValue",!1),s.value&&s.value instanceof HTMLElement&&(s.value.focus(),s.value=null)},h=v=>{if(v.key==="Escape"&&r.value&&!l.value){f();return}if(v.key==="Tab"&&r.value&&i.value){const k=i.value.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])');if(k.length===0)return;const y=k[0],w=k[k.length-1];v.shiftKey&&document.activeElement===y?(v.preventDefault(),w.focus()):!v.shiftKey&&document.activeElement===w&&(v.preventDefault(),y.focus())}};return e.onMounted(()=>{document.addEventListener("keydown",h)}),e.onBeforeUnmount(()=>{document.removeEventListener("keydown",h)}),(v,k)=>(e.openBlock(),e.createBlock(e.Teleport,{to:"body"},[r.value?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"overlayRef",ref:i,role:"dialog","aria-modal":"true","aria-label":"Image editor",class:"editor-modal-overlay","data-testid":"image-editor-modal",onKeydown:e.withKeys(p,["escape"])},[e.createElementVNode("div",{class:"editor-modal-backdrop",onClick:p}),e.createElementVNode("div",Lh,[e.createElementVNode("div",Ph,[e.createVNode(nm,{"initial-image":v.initialImage,"initial-state":v.initialState,"initial-document":v.initialDocument,"initial-document-id":v.initialDocumentId,"initial-document-revision-id":v.initialDocumentRevisionId,"initial-document-revision-number":v.initialDocumentRevisionNumber,"session-key":v.sessionKey,theme:v.theme,"crop-shape":v.cropShape,preset:v.preset,"editor-version":v.editorVersion,"background-removal":v.backgroundRemoval,"background-replacement":v.backgroundReplacement,"primary-color":v.primaryColor,"secondary-color":v.secondaryColor,"save-button-color":v.saveButtonColor,"download-button-color":v.downloadButtonColor,onSave:u,onCancel:m,onError:d},null,8,["initial-image","initial-state","initial-document","initial-document-id","initial-document-revision-id","initial-document-revision-number","session-key","theme","crop-shape","preset","editor-version","background-removal","background-replacement","primary-color","secondary-color","save-button-color","download-button-color"])])])],544)):e.createCommentVNode("",!0)]))}}),om=$e(Uh,[["__scopeId","data-v-bd4e671f"]]),Oh={class:"media-workspace"},zh={class:"media-workspace-toolbar"},jh={class:"media-workspace-label"},Wh=["value"],Hh={class:"media-workspace-grid"},Zh=["onClick"],Gh=e.defineComponent({__name:"MediaWorkspace",props:{apiScope:{},subScopes:{},initialScopeId:{}},emits:["scope-change","update:media","upload","preview"],setup(o,{emit:a}){var m;const t=o,n=a,i=xa(),r=e.ref(t.initialScopeId??((m=t.subScopes[0])==null?void 0:m.id)??""),l=e.computed(()=>t.subScopes),s=e.computed(()=>l.value.find(p=>p.id===r.value));let d=null;function c(){d&&(d(),d=null),t.apiScope&&(d=Ku({apiScope:t.apiScope,isAdmin:t.apiScope==="admin"}))}async function u(){var f;const p={};(f=s.value)!=null&&f.collection&&(p.collection=s.value.collection),await i.fetchMedia(1,p),n("update:media",[...i.items])}return e.watch(()=>t.initialScopeId,p=>{p&&p!==r.value&&(r.value=p)}),e.watch(()=>t.subScopes,p=>{if(p.length===0){r.value="";return}p.some(f=>f.id===r.value)||(r.value=p[0].id)},{deep:!0}),e.watch(()=>t.apiScope,()=>{c(),u()}),e.watch(r,p=>{p&&(n("scope-change",p),u())}),e.onMounted(()=>{c(),u()}),e.onUnmounted(()=>{d&&(d(),d=null)}),(p,f)=>(e.openBlock(),e.createElementBlock("div",Oh,[e.createElementVNode("div",zh,[e.createElementVNode("label",jh,[f[2]||(f[2]=e.createElementVNode("span",{class:"media-workspace-label-text"},"Scope",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":f[0]||(f[0]=h=>r.value=h),"data-testid":"scope-select",class:"media-workspace-select"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(l.value,h=>(e.openBlock(),e.createElementBlock("option",{key:h.id,value:h.id},e.toDisplayString(h.label),9,Wh))),128))],512),[[e.vModelSelect,r.value]])]),e.createElementVNode("button",{type:"button",class:"media-workspace-upload","data-testid":"upload-button",onClick:f[1]||(f[1]=h=>n("upload"))}," Upload ")]),e.createElementVNode("div",Hh,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(i).items,h=>(e.openBlock(),e.createElementBlock("button",{key:h.uuid,type:"button",class:"media-workspace-item","data-testid":"media-item",onClick:v=>n("preview",h)},e.toDisplayString(h.file_name),9,Zh))),128))])]))}}),Xh=$e(Gh,[["__scopeId","data-v-895f26fe"]]),Kh={class:"managed-media-gallery"},Jh={class:"gallery-grid"},qh=e.defineComponent({__name:"ManagedMediaGallery",props:{media:{},selectable:{type:Boolean},multiple:{type:Boolean}},emits:["select","remove"],setup(o){return(a,t)=>(e.openBlock(),e.createElementBlock("div",Kh,[e.createElementVNode("div",Jh,[e.renderSlot(a.$slots,"default",{},void 0,!0)])]))}}),Yh=$e(qh,[["__scopeId","data-v-10a9b8c5"]]),kr="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>",ed="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M256 112v288M400 256H112' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Qh="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M256 48C141.31 48 48 141.31 48 256s93.31 208 208 208 208-93.31 208-208S370.69 48 256 48zm0 319.91a20 20 0 1120-20 20 20 0 01-20 20zm21.72-201.15l-5.74 122a16 16 0 01-32 0l-5.74-121.94v-.05a21.74 21.74 0 1143.44 0z'/></svg>",td="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M448 256c0-106-86-192-192-192S64 150 64 256s86 192 192 192 192-86 192-192z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path d='M250.26 166.05L256 288l5.73-121.95a5.74 5.74 0 00-5.79-6h0a5.74 5.74 0 00-5.68 6z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path d='M256 367.91a20 20 0 1120-20 20 20 0 01-20 20z'/></svg>",ev="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='48' d='M244 400L100 256l144-144M120 256h292' class='ionicon-fill-none'/></svg>",tv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='48' d='M268 112l144 144-144 144M392 256H100' class='ionicon-fill-none'/></svg>",lc="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M448 256L272 88v96C103.57 184 64 304.77 64 424c48.61-62.24 91.6-96 208-96v96z' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",sc="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M240 424v-96c116.4 0 159.39 33.76 208 96 0-119.23-39.57-240-208-240V88L64 256z' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",ui="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M452.37 59.63h0a40.49 40.49 0 00-57.26 0L184 294.74c23.08 4.7 46.12 27.29 49.26 49.26l219.11-227.11a40.49 40.49 0 000-57.26zM138 336c-29.88 0-54 24.5-54 54.86 0 23.95-20.88 36.57-36 36.57C64.56 449.74 92.82 464 120 464c39.78 0 72-32.73 72-73.14 0-30.36-24.12-54.86-54-54.86z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",av="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M350.54 148.68l-26.62-42.06C318.31 100.08 310.62 96 302 96h-92c-8.62 0-16.31 4.08-21.92 10.62l-26.62 42.06C155.85 155.23 148.62 160 140 160H80a32 32 0 00-32 32v192a32 32 0 0032 32h352a32 32 0 0032-32V192a32 32 0 00-32-32h-59c-8.65 0-16.85-4.77-22.46-11.32z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='256' cy='272' r='80' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-linejoin='round' d='M124 158v-22h-24v22' class='ionicon-fill-none ionicon-stroke-width'/></svg>",im="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>",rm="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>",dc="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='48' d='M328 112L184 256l144 144' class='ionicon-fill-none'/></svg>",nv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='48' d='M112 184l144 144 144-144' class='ionicon-fill-none'/></svg>",ov="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='48' d='M184 112l144 144-144 144' class='ionicon-fill-none'/></svg>",cc="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='48' d='M184 112l144 144-144 144' class='ionicon-fill-none'/></svg>",Yn="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M368 368L144 144M368 144L144 368' class='ionicon-fill-none ionicon-stroke-width'/></svg>",uc="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M320 367.79h76c55 0 100-29.21 100-83.6s-53-81.47-96-83.6c-8.89-85.06-71-136.8-144-136.8-69 0-113.44 45.79-128 91.2-60 5.7-112 43.88-112 106.4s54 106.4 120 106.4h56' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-linejoin='round' d='M320 255.79l-64-64-64 64M256 448.21V207.79' class='ionicon-fill-none ionicon-stroke-width'/></svg>",iv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><circle cx='256' cy='184' r='120' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='344' cy='328' r='120' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='168' cy='328' r='120' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Cn="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M430.11 347.9c-6.6-6.1-16.3-7.6-24.6-9-11.5-1.9-15.9-4-22.6-10-14.3-12.7-14.3-31.1 0-43.8l30.3-26.9c46.4-41 46.4-108.2 0-149.2-34.2-30.1-80.1-45-127.8-45-55.7 0-113.9 20.3-158.8 60.1-83.5 73.8-83.5 194.7 0 268.5 41.5 36.7 97.5 55 152.9 55.4h1.7c55.4 0 110-17.9 148.8-52.4 14.4-12.7 11.99-36.6.1-47.7z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='144' cy='208' r='32'/><circle cx='152' cy='311' r='32'/><circle cx='224' cy='144' r='32'/><circle cx='256' cy='367' r='48'/><circle cx='328' cy='144' r='32'/></svg>",rv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M304 416V304h112M314.2 314.23L432 432M208 96v112H96M197.8 197.77L80 80M416 208H304V96M314.23 197.8L432 80M96 304h112v112M197.77 314.2L80 432' class='ionicon-fill-none ionicon-stroke-width'/></svg>",ai="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>",ms="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>",lv="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>",mc="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>",Fr="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>",Fo="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>",sv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><circle cx='256' cy='256' r='32' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='416' cy='256' r='32' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='96' cy='256' r='32' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/></svg>",dv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M432 320v112H320M421.8 421.77L304 304M80 192V80h112M90.2 90.23L208 208M320 80h112v112M421.77 90.2L304 208M192 432H80V320M90.23 421.8L208 304' class='ionicon-fill-none ionicon-stroke-width'/></svg>",cv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M432 320v112H320M421.8 421.77L304 304M80 192V80h112M90.2 90.23L208 208M320 80h112v112M421.77 90.2L304 208M192 432H80V320M90.23 421.8L208 304' class='ionicon-fill-none ionicon-stroke-width'/></svg>",uv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M432 448a15.92 15.92 0 01-11.31-4.69l-352-352a16 16 0 0122.62-22.62l352 352A16 16 0 01432 448zM255.66 384c-41.49 0-81.5-12.28-118.92-36.5-34.07-22-64.74-53.51-88.7-91v-.08c19.94-28.57 41.78-52.73 65.24-72.21a2 2 0 00.14-2.94L93.5 161.38a2 2 0 00-2.71-.12c-24.92 21-48.05 46.76-69.08 76.92a31.92 31.92 0 00-.64 35.54c26.41 41.33 60.4 76.14 98.28 100.65C162 402 207.9 416 255.66 416a239.13 239.13 0 0075.8-12.58 2 2 0 00.77-3.31l-21.58-21.58a4 4 0 00-3.83-1 204.8 204.8 0 01-51.16 6.47zM490.84 238.6c-26.46-40.92-60.79-75.68-99.27-100.53C349 110.55 302 96 255.66 96a227.34 227.34 0 00-74.89 12.83 2 2 0 00-.75 3.31l21.55 21.55a4 4 0 003.88 1 192.82 192.82 0 0150.21-6.69c40.69 0 80.58 12.43 118.55 37 34.71 22.4 65.74 53.88 89.76 91a.13.13 0 010 .16 310.72 310.72 0 01-64.12 72.73 2 2 0 00-.15 2.95l19.9 19.89a2 2 0 002.7.13 343.49 343.49 0 0068.64-78.48 32.2 32.2 0 00-.1-34.78z'/><path d='M256 160a95.88 95.88 0 00-21.37 2.4 2 2 0 00-1 3.38l112.59 112.56a2 2 0 003.38-1A96 96 0 00256 160zM165.78 233.66a2 2 0 00-3.38 1 96 96 0 00115 115 2 2 0 001-3.38z'/></svg>",mi="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M255.66 112c-77.94 0-157.89 45.11-220.83 135.33a16 16 0 00-.27 17.77C82.92 340.8 161.8 400 255.66 400c92.84 0 173.34-59.38 221.79-135.25a16.14 16.14 0 000-17.47C428.89 172.28 347.8 112 255.66 112z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='256' cy='256' r='80' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/></svg>",pc="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>",zl="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M315.27 33L96 304h128l-31.51 173.23a2.36 2.36 0 002.33 2.77h0a2.36 2.36 0 001.89-.95L416 208H288l31.66-173.25a2.45 2.45 0 00-2.44-2.75h0a2.42 2.42 0 00-1.95 1z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",mv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M496 152a56 56 0 00-56-56H220.11a23.89 23.89 0 01-13.31-4L179 73.41A55.77 55.77 0 00147.89 64H72a56 56 0 00-56 56v48a8 8 0 008 8h464a8 8 0 008-8zM16 392a56 56 0 0056 56h368a56 56 0 0056-56V216a8 8 0 00-8-8H24a8 8 0 00-8 8z'/></svg>",pv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><circle cx='129' cy='96' r='48' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='129' cy='416' r='48' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-linejoin='round' d='M129 144v224' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='385' cy='288' r='48' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path d='M129 144c0 96 112 144 208 144' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",jl="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M432 112V96a48.14 48.14 0 00-48-48H64a48.14 48.14 0 00-48 48v256a48.14 48.14 0 0048 48h16' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><rect x='96' y='128' width='400' height='336' rx='45.99' ry='45.99' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><ellipse cx='372.92' cy='219.64' rx='30.77' ry='30.55' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path d='M342.15 372.17L255 285.78a30.93 30.93 0 00-42.18-1.21L96 387.64M265.23 464l118.59-117.73a31 31 0 0141.46-1.87L496 402.91' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",fv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M248 64C146.39 64 64 146.39 64 248s82.39 184 184 184 184-82.39 184-184S349.61 64 248 64z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-linejoin='round' d='M220 220h32v116' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-miterlimit='10' d='M208 340h88' class='ionicon-fill-none ionicon-stroke-width'/><path d='M248 130a26 26 0 1026 26 26 26 0 00-26-26z'/></svg>",hv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M368 128h80M64 128h240M368 384h80M64 384h240M208 256h240M64 256h80' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='336' cy='128' r='32' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='176' cy='256' r='32' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='336' cy='384' r='32' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",vv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M208 432h-48a16 16 0 01-16-16V96a16 16 0 0116-16h48a16 16 0 0116 16v320a16 16 0 01-16 16zM352 432h-48a16 16 0 01-16-16V96a16 16 0 0116-16h48a16 16 0 0116 16v320a16 16 0 01-16 16z'/></svg>",gv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M256 48C141.31 48 48 141.31 48 256s93.31 208 208 208 208-93.31 208-208S370.69 48 256 48zm-32 272a16 16 0 01-32 0V192a16 16 0 0132 0zm96 0a16 16 0 01-32 0V192a16 16 0 0132 0z'/></svg>",lm="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>",ad="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M176 96h16v320h-16zM320 96h16v320h-16z' class='ionicon-fill-none ionicon-stroke-width'/></svg>",bv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M133 440a35.37 35.37 0 01-17.5-4.67c-12-6.8-19.46-20-19.46-34.33V111c0-14.37 7.46-27.53 19.46-34.33a35.13 35.13 0 0135.77.45l247.85 148.36a36 36 0 010 61l-247.89 148.4A35.5 35.5 0 01133 440z'/></svg>",yv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M30.71 229.47l188.87-113a30.54 30.54 0 0131.09-.39 33.74 33.74 0 0116.76 29.47v79.05l180.72-108.16a30.54 30.54 0 0131.09-.39A33.74 33.74 0 01496 145.52v221A33.73 33.73 0 01479.24 396a30.54 30.54 0 01-31.09-.39L267.43 287.4v79.08A33.73 33.73 0 01250.67 396a30.54 30.54 0 01-31.09-.39l-188.87-113a31.27 31.27 0 010-53z'/></svg>",wv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M480 145.52v221c0 13.28-13 21.72-23.63 15.35L267.5 268.8c-9.24-5.53-9.24-20.07 0-25.6l188.87-113C467 123.8 480 132.24 480 145.52zM251.43 145.52v221c0 13.28-13 21.72-23.63 15.35L38.93 268.8c-9.24-5.53-9.24-20.07 0-25.6l188.87-113c10.64-6.4 23.63 2.04 23.63 15.32z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/></svg>",kv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M256 48C141.31 48 48 141.31 48 256s93.31 208 208 208 208-93.31 208-208S370.69 48 256 48zm74.77 217.3l-114.45 69.14a10.78 10.78 0 01-16.32-9.31V186.87a10.78 10.78 0 0116.32-9.31l114.45 69.14a10.89 10.89 0 010 18.6z'/></svg>",sm="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M448 256c0-106-86-192-192-192S64 150 64 256s86 192 192 192 192-86 192-192z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path d='M216.32 334.44l114.45-69.14a10.89 10.89 0 000-18.6l-114.45-69.14a10.78 10.78 0 00-16.32 9.31v138.26a10.78 10.78 0 0016.32 9.31z'/></svg>",_v="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M481.29 229.47l-188.87-113a30.54 30.54 0 00-31.09-.39 33.74 33.74 0 00-16.76 29.47v79.05L63.85 116.44a30.54 30.54 0 00-31.09-.39A33.74 33.74 0 0016 145.52v221A33.74 33.74 0 0032.76 396a30.54 30.54 0 0031.09-.39L244.57 287.4v79.08A33.74 33.74 0 00261.33 396a30.54 30.54 0 0031.09-.39l188.87-113a31.27 31.27 0 000-53z'/></svg>",Ev="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M32 145.52v221c0 13.28 13 21.72 23.63 15.35l188.87-113c9.24-5.53 9.24-20.07 0-25.6l-188.87-113C45 123.8 32 132.24 32 145.52zM260.57 145.52v221c0 13.28 13 21.72 23.63 15.35l188.87-113c9.24-5.53 9.24-20.07 0-25.6l-188.87-113c-10.64-6.47-23.63 1.97-23.63 15.25z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/></svg>",nd="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M112 111v290c0 17.44 17 28.52 31 20.16l247.9-148.37c12.12-7.25 12.12-26.33 0-33.58L143 90.84c-14-8.36-31 2.72-31 20.16z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Sv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M400 111v290c0 17.44-17 28.52-31 20.16L121.09 272.79c-12.12-7.25-12.12-26.33 0-33.58L369 90.84c14-8.36 31 2.72 31 20.16z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-miterlimit='10' d='M112 80v352' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Cv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M112 111v290c0 17.44 17 28.52 31 20.16l247.9-148.37c12.12-7.25 12.12-26.33 0-33.58L143 90.84c-14-8.36-31 2.72-31 20.16z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-miterlimit='10' d='M400 80v352' class='ionicon-fill-none ionicon-stroke-width'/></svg>",io="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M320 146s24.36-12-64-12a160 160 0 10160 160' stroke-linecap='round' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-linejoin='round' d='M256 58l80 80-80 80' class='ionicon-fill-none ionicon-stroke-width'/></svg>",xv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M448 256c0-106-86-192-192-192S64 150 64 256s86 192 192 192 192-86 192-192z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-linejoin='round' d='M336 256H176' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Nv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M400 256H112' class='ionicon-fill-none ionicon-stroke-width'/></svg>",fc="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M304 96h112v112M405.77 106.2L111.98 400.02M208 416H96V304' class='ionicon-fill-none ionicon-stroke-width'/></svg>",el="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>",Vv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><circle cx='256' cy='256' r='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>",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='M400 304l48 48-48 48M400 112l48 48-48 48M64 352h85.19a80 80 0 0066.56-35.62L256 256' class='ionicon-fill-none ionicon-stroke-width'/><path d='M64 160h85.19a80 80 0 0166.56 35.62l80.5 120.76A80 80 0 00362.81 352H416M416 160h-53.19a80 80 0 00-66.56 35.62L288 208' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Sn="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512' class='ionicon'><path d='M259.92 262.91L216.4 149.77a9 9 0 00-16.8 0l-43.52 113.14a9 9 0 01-5.17 5.17L37.77 311.6a9 9 0 000 16.8l113.14 43.52a9 9 0 015.17 5.17l43.52 113.14a9 9 0 0016.8 0l43.52-113.14a9 9 0 015.17-5.17l113.14-43.52a9 9 0 000-16.8l-113.14-43.52a9 9 0 01-5.17-5.17zM108 68L88 16 68 68 16 88l52 20 20 52 20-52 52-20-52-20zM426.67 117.33L400 48l-26.67 69.33L304 144l69.33 26.67L400 240l26.67-69.33L496 144l-69.33-26.67z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",ni="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>",hc="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M304 48l112 112-112 112M398.87 160H96M208 464L96 352l112-112M114 352h302' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Tv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M512 128v256a64.07 64.07 0 01-64 64H64a64.07 64.07 0 01-64-64V128a64.07 64.07 0 0164-64h384a64.07 64.07 0 0164 64zM32 384a32 32 0 0032 32h384a32 32 0 0032-32V128a32 32 0 00-32-32H64a32 32 0 00-32 32z'/><path d='M0 128a64.07 64.07 0 0164-64h384a64.07 64.07 0 0164 64v256a64.07 64.07 0 01-64 64H64a64.07 64.07 0 01-64-64V128m480 256V128a32 32 0 00-32-32H64a32 32 0 00-32 32v256a32 32 0 0032 32h384a32 32 0 0032-32m-16 0a16 16 0 01-16 16H64a16 16 0 01-16-16V128a16 16 0 0116-16h384a16 16 0 0116 16v256z'/></svg>",dm="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>",Dr="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>",cm="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M374.79 308.78L457.5 367a16 16 0 0022.5-14.62V159.62A16 16 0 00457.5 145l-82.71 58.22A16 16 0 00368 216.3v79.4a16 16 0 006.79 13.08z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path d='M268 384H84a52.15 52.15 0 01-52-52V180a52.15 52.15 0 0152-52h184.48A51.68 51.68 0 01320 179.52V332a52.15 52.15 0 01-52 52z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Bv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M232 416a23.88 23.88 0 01-14.2-4.68 8.27 8.27 0 01-.66-.51L125.76 336H56a24 24 0 01-24-24V200a24 24 0 0124-24h69.75l91.37-74.81a8.27 8.27 0 01.66-.51A24 24 0 01256 120v272a24 24 0 01-24 24zm-106.18-80zm-.27-159.86zM320 336a16 16 0 01-14.29-23.19c9.49-18.87 14.3-38 14.3-56.81 0-19.38-4.66-37.94-14.25-56.73a16 16 0 0128.5-14.54C346.19 208.12 352 231.44 352 256c0 23.86-6 47.81-17.7 71.19A16 16 0 01320 336z'/><path d='M368 384a16 16 0 01-13.86-24C373.05 327.09 384 299.51 384 256c0-44.17-10.93-71.56-29.82-103.94a16 16 0 0127.64-16.12C402.92 172.11 416 204.81 416 256c0 50.43-13.06 83.29-34.13 120a16 16 0 01-13.87 8z'/><path d='M416 432a16 16 0 01-13.39-24.74C429.85 365.47 448 323.76 448 256c0-66.5-18.18-108.62-45.49-151.39a16 16 0 1127-17.22C459.81 134.89 480 181.74 480 256c0 64.75-14.66 113.63-50.6 168.74A16 16 0 01416 432z'/></svg>",Iv="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>",Mv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M264 416.19a23.92 23.92 0 01-14.21-4.69l-.66-.51-91.46-75H88a24 24 0 01-24-24V200a24 24 0 0124-24h69.65l91.46-75 .66-.51A24 24 0 01288 119.83v272.34a24 24 0 01-24 24zM352 336a16 16 0 01-14.29-23.18c9.49-18.9 14.3-38 14.3-56.82 0-19.36-4.66-37.92-14.25-56.73a16 16 0 0128.5-14.54C378.2 208.16 384 231.47 384 256c0 23.83-6 47.78-17.7 71.18A16 16 0 01352 336z'/><path d='M400 384a16 16 0 01-13.87-24C405 327.05 416 299.45 416 256c0-44.12-10.94-71.52-29.83-103.95A16 16 0 01413.83 136C434.92 172.16 448 204.88 448 256c0 50.36-13.06 83.24-34.12 120a16 16 0 01-13.88 8z'/></svg>",$v="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M157.65 192H88a8 8 0 00-8 8v112a8 8 0 008 8h69.65a16 16 0 0110.14 3.63l91.47 75a8 8 0 0012.74-6.46V119.83a8 8 0 00-12.74-6.44l-91.47 75a16 16 0 01-10.14 3.61zM352 320c9.74-19.41 16-40.81 16-64 0-23.51-6-44.4-16-64M400 368c19.48-34 32-64 32-112s-12-77.7-32-112' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Fv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-miterlimit='10' d='M416 432L64 80' class='ionicon-fill-none ionicon-stroke-width'/><path d='M243.33 98.86a23.89 23.89 0 00-25.55 1.82l-.66.51-28.52 23.35a8 8 0 00-.59 11.85l54.33 54.33a8 8 0 0013.66-5.66v-64.49a24.51 24.51 0 00-12.67-21.71zM251.33 335.29L96.69 180.69A16 16 0 0085.38 176H56a24 24 0 00-24 24v112a24 24 0 0024 24h69.76l92 75.31a23.9 23.9 0 0025.87 1.69A24.51 24.51 0 00256 391.45v-44.86a16 16 0 00-4.67-11.3zM352 256c0-24.56-5.81-47.87-17.75-71.27a16 16 0 10-28.5 14.55C315.34 218.06 320 236.62 320 256q0 4-.31 8.13a8 8 0 002.32 6.25l14.36 14.36a8 8 0 0013.55-4.31A146 146 0 00352 256zM416 256c0-51.18-13.08-83.89-34.18-120.06a16 16 0 00-27.64 16.12C373.07 184.44 384 211.83 384 256c0 23.83-3.29 42.88-9.37 60.65a8 8 0 001.9 8.26L389 337.4a8 8 0 0013.13-2.79C411 311.76 416 287.26 416 256z'/><path d='M480 256c0-74.25-20.19-121.11-50.51-168.61a16 16 0 10-27 17.22C429.82 147.38 448 189.5 448 256c0 46.19-8.43 80.27-22.43 110.53a8 8 0 001.59 9l11.92 11.92a8 8 0 0012.92-2.16C471.6 344.9 480 305 480 256z'/></svg>",Dv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-miterlimit='10' d='M416 432L64 80' class='ionicon-fill-none ionicon-stroke-width'/><path d='M224 136.92v33.8a4 4 0 001.17 2.82l24 24a4 4 0 006.83-2.82v-74.15a24.53 24.53 0 00-12.67-21.72 23.91 23.91 0 00-25.55 1.83 8.27 8.27 0 00-.66.51l-31.94 26.15a4 4 0 00-.29 5.92l17.05 17.06a4 4 0 005.37.26zM224 375.08l-78.07-63.92a32 32 0 00-20.28-7.16H64v-96h50.72a4 4 0 002.82-6.83l-24-24a4 4 0 00-2.82-1.17H56a24 24 0 00-24 24v112a24 24 0 0024 24h69.76l91.36 74.8a8.27 8.27 0 00.66.51 23.93 23.93 0 0025.85 1.69A24.49 24.49 0 00256 391.45v-50.17a4 4 0 00-1.17-2.82l-24-24a4 4 0 00-6.83 2.82zM125.82 336zM352 256c0-24.56-5.81-47.88-17.75-71.27a16 16 0 00-28.5 14.54C315.34 218.06 320 236.62 320 256q0 4-.31 8.13a8 8 0 002.32 6.25l19.66 19.67a4 4 0 006.75-2A146.89 146.89 0 00352 256zM416 256c0-51.19-13.08-83.89-34.18-120.06a16 16 0 00-27.64 16.12C373.07 184.44 384 211.83 384 256c0 23.83-3.29 42.88-9.37 60.65a8 8 0 001.9 8.26l16.77 16.76a4 4 0 006.52-1.27C410.09 315.88 416 289.91 416 256z'/><path d='M480 256c0-74.26-20.19-121.11-50.51-168.61a16 16 0 10-27 17.22C429.82 147.38 448 189.5 448 256c0 47.45-8.9 82.12-23.59 113a4 4 0 00.77 4.55L443 391.39a4 4 0 006.4-1C470.88 348.22 480 307 480 256z'/></svg>",Av="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>",lr="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 vc=()=>{};function Rv(o,a){function t(...n){return new Promise((i,r)=>{Promise.resolve(o(()=>a.apply(this,n),{fn:a,thisArg:this,args:n})).then(i).catch(r)})}return t}function Lv(o,a={}){let t,n,i=vc;const r=d=>{clearTimeout(d),i(),i=vc};let l;return d=>{const c=e.toValue(o),u=e.toValue(a.maxWait);return t&&r(t),c<=0||u!==void 0&&u<=0?(n&&(r(n),n=null),Promise.resolve(d())):new Promise((m,p)=>{i=a.rejectOnCancel?p:m,l=d,u&&!n&&(n=setTimeout(()=>{t&&r(t),n=null,m(l())},u)),t=setTimeout(()=>{n&&r(n),n=null,m(d())},c)})}}function Pv(o,a=200,t={}){return Rv(Lv(a,t),o)}const oi=new Map;function Uv(o){const a=e.getCurrentScope();function t(s){var d;const c=oi.get(o)||new Set;c.add(s),oi.set(o,c);const u=()=>i(s);return(d=a==null?void 0:a.cleanups)==null||d.push(u),u}function n(s){function d(...c){i(d),s(...c)}return t(d)}function i(s){const d=oi.get(o);d&&(d.delete(s),d.size||r())}function r(){oi.delete(o)}function l(s,d){var c;(c=oi.get(o))==null||c.forEach(u=>u(s,d))}return{on:t,once:n,off:i,emit:l,reset:r}}function um(){var r,l;const o=typeof window<"u"&&"Capacitor"in window&&((l=(r=window.Capacitor)==null?void 0:r.isNativePlatform)==null?void 0:l.call(r));return{selection:()=>{var s,d;if(o)try{const c=(d=(s=window.Capacitor)==null?void 0:s.Plugins)==null?void 0:d.Haptics;c&&c.impact({style:"LIGHT"})}catch{}else"vibrate"in navigator&&navigator.vibrate(10)},success:()=>{var s,d;if(o)try{const c=(d=(s=window.Capacitor)==null?void 0:s.Plugins)==null?void 0:d.Haptics;c&&c.impact({style:"MEDIUM"})}catch{}else"vibrate"in navigator&&navigator.vibrate(30)},error:()=>{var s,d;if(o)try{const c=(d=(s=window.Capacitor)==null?void 0:s.Plugins)==null?void 0:d.Haptics;c&&c.impact({style:"HEAVY"})}catch{}else"vibrate"in navigator&&navigator.vibrate([50,50,50])},notification:()=>{var s,d;if(o)try{const c=(d=(s=window.Capacitor)==null?void 0:s.Plugins)==null?void 0:d.Haptics;c&&c.notification({type:"SUCCESS"})}catch{}else"vibrate"in navigator&&navigator.vibrate([20,100,20])}}}function tl(o,a={}){const t=e.ref(new Set),n=e.ref(new Map),i=e.ref(null),r=e.ref(-1),l=e.ref(a.scopeKey!==void 0?e.toValue(a.scopeKey):"default"),s=e.ref(!1),d=e.ref(null),c=Uv("media-selection"),u=um(),m=()=>{if(a.currentPage===void 0)return null;const O=e.toValue(a.currentPage);return typeof O=="number"&&Number.isFinite(O)?O:null};function p(O){t.value=O,n.value=new Map(Array.from(n.value.entries()).filter(([K])=>O.has(K)))}function f(O){if(n.value.has(O))return;const K=new Map(n.value);K.set(O,{uuid:O,selectedAt:Date.now(),page:m()}),n.value=K}const h=e.computed(()=>o.value.filter(O=>t.value.has(O.uuid))),v=e.computed(()=>t.value.size),k=e.computed(()=>Array.from(n.value.values()).sort((O,K)=>O.selectedAt-K.selectedAt).map(O=>O.uuid)),y=e.computed(()=>Math.max(0,v.value-h.value.length)),w=e.computed(()=>{const O=new Map;for(const K of n.value.values())K.page!==null&&O.set(K.page,(O.get(K.page)??0)+1);return O});e.watch(t,O=>{c.emit({type:"selection:changed",count:O.size,selectedIds:Array.from(O)})}),a.scopeKey!==void 0&&e.watch(()=>e.toValue(a.scopeKey),(O,K)=>{O!==void 0&&O!==K&&z(O)});const g=e.computed(()=>o.value.length>0&&o.value.every(O=>t.value.has(O.uuid))),b=e.computed(()=>o.value.some(O=>t.value.has(O.uuid)));function R(O){return t.value.has(O)}function V(O){const K=new Set(t.value),de=K.size===0;K.add(O),f(O),t.value=K,i.value=O,r.value=o.value.findIndex(Ne=>Ne.uuid===O),de&&u.selection()}function I(O){const K=new Set(t.value);K.delete(O);const de=new Map(n.value);de.delete(O),n.value=de,t.value=K,i.value===O&&(i.value=null,r.value=-1)}function x(O){if(t.value.has(O)){I(O);return}V(O)}function T(){const O=new Set(t.value);for(const K of o.value)O.add(K.uuid),f(K.uuid);t.value=O}function $(){t.value=new Set,n.value=new Map,i.value=null,r.value=-1,s.value=!1,d.value=null}function S(){if(g.value){$();return}T()}function B(O,K){const de=o.value.findIndex(Ne=>Ne.uuid===O);if(de!==-1){if(K!=null&&K.shiftKey&&r.value!==-1){const Ne=Math.min(r.value,de),ce=Math.max(r.value,de),le=new Set(t.value);for(let W=Ne;W<=ce;W++){const C=o.value[W];C!==void 0&&(le.add(C.uuid),f(C.uuid))}t.value=le;return}x(O)}}function _(){if(o.value.length===0)return;let O=r.value+1;O>=o.value.length&&(O=0),$();const K=o.value[O];K!==void 0&&V(K.uuid)}function A(){if(o.value.length===0)return;let O=r.value-1;O<0&&(O=o.value.length-1),$();const K=o.value[O];K!==void 0&&V(K.uuid)}function P(O){switch(O.key){case"ArrowDown":O.preventDefault(),_();break;case"ArrowUp":O.preventDefault(),A();break;case"a":(O.ctrlKey||O.metaKey)&&(O.preventDefault(),T());break;case"Escape":O.preventDefault(),$();break;case" ":i.value&&(O.preventDefault(),x(i.value));break}}async function D(O){var de;if(v.value===0||l.value===O)return!0;const K=(de=a.confirmScopeChange)==null?void 0:de.call(a,{from:l.value,to:O,selectedCount:v.value});return K===void 0?!0:await K}async function z(O){return l.value===O?!0:await D(O)?(l.value=O,$(),!0):!1}async function M(){if(!a.fetchMatchingUuids){const K={uuids:o.value.map(de=>de.uuid),overCap:!1,totalMatching:o.value.length};return Z(K),K}const O=await a.fetchMatchingUuids();return Z(O),O}function Z(O){const K=new Set(O.uuids),de=new Map,Ne=Date.now();O.uuids.forEach((ce,le)=>{de.set(ce,{uuid:ce,selectedAt:Ne+le,page:m()})}),p(K),n.value=de,s.value=O.overCap,d.value=O.totalMatching}return{selectedIds:e.computed(()=>t.value),selectedRecords:e.computed(()=>n.value),selectedItems:h,selectedCount:v,orderedIds:k,crossPageCount:y,selectedPages:w,overCap:e.computed(()=>s.value),totalMatching:e.computed(()=>d.value),activeScopeKey:e.computed(()=>l.value),isAllSelected:g,isSomeSelected:b,lastSelectedId:e.computed(()=>i.value),isSelected:R,toggle:x,select:V,deselect:I,selectAll:T,clear:$,toggleAll:S,rangeSelect:B,selectAcrossAllPages:M,setScopeKey:z,canChangeScope:D,selectNext:_,selectPrevious:A,handleKeydown:P,selectionBus:c}}const Ov={class:"flex items-center justify-between w-full px-4"},zv={class:"p-4"},jv={key:0,class:"mb-4 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg"},Wv={class:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"},Hv=["value"],Zv={class:"flex gap-2 mt-4"},Gv={class:"flex justify-end mb-4"},Xv={key:1,class:"flex justify-center items-center h-64"},Kv={key:2,class:"flex flex-col items-center justify-center h-64 text-center"},Jv={class:"text-sm text-theme-secondary"},qv={key:0},Yv={class:"mb-4"},Qv={class:"mb-4"},eg={class:"flex gap-2"},tg={class:"flex items-center justify-between px-4 py-2"},ag={class:"text-sm text-theme-secondary"},ng={key:0},og={key:0},ig={key:1},rg={class:"flex gap-2"},lg=e.defineComponent({__name:"AdminMediaBrowser",props:{isOpen:{type:Boolean},selectionMode:{default:"single"},selectedItems:{default:()=>[]},modelType:{},modelId:{},collection:{default:"images"},maxSelection:{}},emits:["close","confirm"],setup(o,{emit:a}){const t=o,n=a,i=e.ref("recent"),r=e.ref("grid"),l=e.ref(""),s=e.ref(!1),d=e.ref([]),{selectedItems:c}=e.toRefs(t),u=e.ref(new Set(c.value)),m=e.ref(!1),p=e.ref({}),f=e.ref(["images","documents","videos"]),h=e.ref(1),v=e.ref(!0),k=e.ref(!1),y=Ju(),w=tl(d);function g(W){var be;const C=W.conversion_urls||{},U=W.proxy_url||W.original_url||W.url||"",j=C.thumb||C.preview||W.preview_url||W.thumbnail_url||U,re=W.custom_properties||{},ue=re.width,Xe=re.height;return{...W,uuid:W.uuid,name:W.name||W.file_name,file_name:W.file_name,filename:W.file_name,mime_type:W.mime_type,size:W.size,collection_name:W.collection_name||"images",disk:W.disk,original_url:U,url:U,thumbnail_url:j,conversions:W.conversions||{},conversion_urls:C,generated_conversions:W.generated_conversions||{},custom_properties:re,caption:W.caption||null,alt_text:W.alt_text||null,created_at:W.created_at,updated_at:W.updated_at,is_image:((be=W.mime_type)==null?void 0:be.startsWith("image/"))||!1,...typeof ue=="number"?{width:ue}:{},...typeof Xe=="number"?{height:Xe}:{},...W.formatted_size!==void 0?{formatted_size:W.formatted_size}:{}}}e.watch(()=>t.selectedItems,W=>{u.value=new Set(W),w.clear(),W.forEach(C=>w.select(C))});const b=e.computed(()=>{var C;let W=d.value;return(C=p.value.types)!=null&&C.length&&(W=W.filter(U=>{var re,ue;const j=(re=U.mime_type)==null?void 0:re.split("/")[0];return(ue=p.value.types)==null?void 0:ue.includes(j)})),(p.value.sizeMin!==void 0||p.value.sizeMax!==void 0)&&(W=W.filter(U=>{const j=U.size/1048576;return!(p.value.sizeMin!==void 0&&j<p.value.sizeMin||p.value.sizeMax!==void 0&&j>p.value.sizeMax)})),W}),R=e.computed(()=>{var C;let W=0;return p.value.search&&W++,p.value.collection&&W++,(p.value.dateFrom||p.value.dateTo)&&W++,(C=p.value.types)!=null&&C.length&&(W+=p.value.types.length),(p.value.sizeMin!==void 0||p.value.sizeMax!==void 0)&&W++,W}),V=e.computed(()=>{const W=w.selectedCount.value;return W===0?"Select Media":`Select ${t.selectionMode==="multiple"?`${W} ${W===1?"Item":"Items"}`:"Item"}`}),I=e.computed(()=>{const W=w.selectedCount.value;return!!(W===0||t.selectionMode==="single"&&W>1||t.maxSelection&&W>t.maxSelection)}),x=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 T(W=!0){W?(s.value=!0,d.value=[],h.value=1,v.value=!0):k.value=!0;try{const C={collection:p.value.collection||t.collection,per_page:24};switch((l.value||p.value.search)&&(C.search=l.value||p.value.search||""),p.value.dateFrom&&(C.from_date=p.value.dateFrom),p.value.dateTo&&(C.to_date=p.value.dateTo),i.value){case"recent":await y.fetchMedia(h.value,C),W?d.value=y.items.map(U=>g(U)):d.value=[...d.value,...y.items.map(U=>g(U))],v.value=y.currentPage<y.totalPages;break;case"model":if(t.modelType&&t.modelId){const U=await y.fetchModelMedia(t.modelType,t.modelId,C.collection,C.search);d.value=U?U.map(j=>g(j)):[],v.value=!1}break;case"library":await y.fetchMedia(h.value,C),W?d.value=y.items.map(U=>g(U)):d.value=[...d.value,...y.items.map(U=>g(U))],v.value=y.currentPage<y.totalPages;break}}catch{}finally{s.value=!1,k.value=!1}}async function $(W){if(!v.value||k.value){W!=null&&W.target&&W.target.complete();return}h.value++,await T(!1),W!=null&&W.target&&(W.target.complete(),v.value||(W.target.disabled=!0))}function S(W){return W==="recent"||W==="model"||W==="library"}function B(W){i.value=W,T()}function _(W){typeof W=="string"&&S(W)&&B(W)}async function A(W){t.selectionMode==="single"?(w.clear(),w.select(W.uuid)):(w.toggle(W.uuid),t.maxSelection&&w.selectedCount.value>t.maxSelection&&(w.deselect(W.uuid),await(await H.toastController.create({message:`Maximum ${t.maxSelection} items can be selected`,duration:2e3,color:"warning"})).present()))}function P(){n("confirm",w.selectedItems.value)}function D(){n("close")}function z(W){}const M=e.ref(null),Z=e.ref(!1);function O(W){M.value=W,Z.value=!0}function K(W){const C=d.value.findIndex(j=>j.uuid===W.uuid);C!==-1&&(d.value[C]=W);const U={};W.alt_text!==void 0&&(U.alt_text=W.alt_text),W.caption!==void 0&&(U.caption=W.caption),W.custom_properties!==void 0&&(U.custom_properties=W.custom_properties),y.updateMedia(W.uuid,U)}function de(){T()}function Ne(){p.value={},l.value="",T()}const ce=Pv(()=>{T(!0)},300);e.watch(l,()=>{t.isOpen&&ce()});async function le(W){try{await(await H.alertController.create({header:"Delete Media",message:"Are you sure you want to delete this media item?",buttons:[{text:"Cancel",role:"cancel"},{text:"Delete",role:"destructive",handler:async()=>{await y.deleteMedia(W),await T()}}]})).present()}catch{}}return e.watch(()=>t.isOpen,W=>{W&&T()}),e.onMounted(()=>{t.selectedItems.length>0&&t.selectedItems.forEach(W=>w.select(W))}),(W,C)=>{const U=e.resolveComponent("AdminMediaGrid"),j=e.resolveComponent("AdminMediaListItem");return e.openBlock(),e.createBlock(e.unref(H.IonModal),{"is-open":W.isOpen,onDidDismiss:D,"backdrop-dismiss":!1,class:"media-browser-modal"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonHeader),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonToolbar),null,{end:e.withCtx(()=>[e.createVNode(e.unref(H.IonButtons),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButton),{onClick:D},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{name:"close-outline"})]),_:1})]),_:1})]),default:e.withCtx(()=>[e.createVNode(e.unref(H.IonTitle),null,{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(x.value),1)]),_:1})]),_:1}),e.createVNode(e.unref(H.IonToolbar),null,{default:e.withCtx(()=>[e.createElementVNode("div",Ov,[e.createVNode(e.unref(H.IonSegment),{value:i.value,onIonChange:C[0]||(C[0]=re=>_(re.detail.value)),class:"max-w-xs"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonSegmentButton),{value:"recent"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...C[15]||(C[15]=[e.createTextVNode("Recent",-1)])]),_:1})]),_:1}),t.modelType&&t.modelId?(e.openBlock(),e.createBlock(e.unref(H.IonSegmentButton),{key:0,value:"model"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...C[16]||(C[16]=[e.createTextVNode("Model",-1)])]),_:1})]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(H.IonSegmentButton),{value:"library"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...C[17]||(C[17]=[e.createTextVNode("Library",-1)])]),_:1})]),_:1})]),_:1},8,["value"]),e.createVNode(e.unref(H.IonButton),{fill:"clear",size:"small",onClick:C[1]||(C[1]=re=>m.value=!m.value),class:"relative"},{"icon-only":e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{name:"filter-outline"})]),default:e.withCtx(()=>[R.value>0?(e.openBlock(),e.createBlock(e.unref(H.IonBadge),{key:0,color:"primary",class:"absolute -top-1 -right-1 min-w-[20px] h-5 rounded-full flex items-center justify-center text-xs"},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(R.value),1)]),_:1})):e.createCommentVNode("",!0)]),_:1})])]),_:1})]),_:1}),e.createVNode(e.unref(H.IonContent),null,{default:e.withCtx(()=>[e.createElementVNode("div",zv,[m.value?(e.openBlock(),e.createElementBlock("div",jv,[e.createElementVNode("div",Wv,[e.createElementVNode("div",null,[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...C[18]||(C[18]=[e.createTextVNode("Collection",-1)])]),_:1}),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":C[2]||(C[2]=re=>p.value.collection=re),class:"w-full p-2 border rounded"},[C[19]||(C[19]=e.createElementVNode("option",{value:""},"All Collections",-1)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(f.value,re=>(e.openBlock(),e.createElementBlock("option",{key:re,value:re},e.toDisplayString(re),9,Hv))),128))],512),[[e.vModelSelect,p.value.collection]])]),e.createElementVNode("div",null,[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...C[20]||(C[20]=[e.createTextVNode("From Date",-1)])]),_:1}),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":C[3]||(C[3]=re=>p.value.dateFrom=re),type:"date",class:"w-full p-2 border rounded"},null,512),[[e.vModelText,p.value.dateFrom]])]),e.createElementVNode("div",null,[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...C[21]||(C[21]=[e.createTextVNode("To Date",-1)])]),_:1}),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":C[4]||(C[4]=re=>p.value.dateTo=re),type:"date",class:"w-full p-2 border rounded"},null,512),[[e.vModelText,p.value.dateTo]])])]),e.createElementVNode("div",Zv,[e.createVNode(e.unref(H.IonButton),{size:"small",onClick:de},{default:e.withCtx(()=>[...C[22]||(C[22]=[e.createTextVNode("Apply",-1)])]),_:1}),e.createVNode(e.unref(H.IonButton),{size:"small",fill:"clear",onClick:Ne},{default:e.withCtx(()=>[...C[23]||(C[23]=[e.createTextVNode("Clear",-1)])]),_:1})])])):e.createCommentVNode("",!0),e.createVNode(e.unref(H.IonSearchbar),{modelValue:l.value,"onUpdate:modelValue":C[5]||(C[5]=re=>l.value=re),placeholder:"Search media...",debounce:300,class:"mb-4"},null,8,["modelValue"]),e.createElementVNode("div",Gv,[e.createVNode(e.unref(H.IonButtons),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButton),{fill:r.value==="grid"?"solid":"clear",size:"small",onClick:C[6]||(C[6]=re=>r.value="grid")},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{name:"grid-outline"})]),_:1},8,["fill"]),e.createVNode(e.unref(H.IonButton),{fill:r.value==="list"?"solid":"clear",size:"small",onClick:C[7]||(C[7]=re=>r.value="list")},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{name:"list-outline"})]),_:1},8,["fill"])]),_:1})]),s.value?(e.openBlock(),e.createElementBlock("div",Xv,[e.createVNode(e.unref(H.IonSpinner),{name:"crescent"})])):b.value.length===0?(e.openBlock(),e.createElementBlock("div",Kv,[e.createVNode(e.unref(H.IonIcon),{name:"images-outline",class:"text-6xl text-theme-secondary mb-4"}),C[24]||(C[24]=e.createElementVNode("h3",{class:"text-lg font-medium text-theme mb-2"}," No Media Found ",-1)),e.createElementVNode("p",Jv,e.toDisplayString(l.value?"Try adjusting your search":"No media items available"),1)])):r.value==="grid"?(e.openBlock(),e.createBlock(U,{key:3,"media-items":b.value,"selected-items":e.unref(w).selectedItems.value,"is-loading":!1,"selection-mode":!0,columns:{mobile:2,sm:3,md:4,lg:5,xl:6},onToggleSelect:A,onPreview:z,onEdit:O,onDelete:le},null,8,["media-items","selected-items"])):(e.openBlock(),e.createBlock(e.unref(H.IonList),{key:4,lines:"none",class:"rounded-lg overflow-hidden"},{default:e.withCtx(()=>[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(b.value,(re,ue)=>(e.openBlock(),e.createBlock(j,{key:re.uuid,media:re,selected:e.unref(w).isSelected(re.uuid),"selection-mode":!0,index:ue,onToggleSelect:A,onPreview:z,onEdit:O,onDelete:le},null,8,["media","selected","index"]))),128))]),_:1})),!s.value&&b.value.length>0&&i.value!=="model"?(e.openBlock(),e.createBlock(e.unref(H.IonInfiniteScroll),{key:5,threshold:"100px",onIonInfinite:C[8]||(C[8]=re=>$(re))},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonInfiniteScrollContent),{"loading-spinner":"crescent","loading-text":"Loading more media..."})]),_:1})):e.createCommentVNode("",!0)])]),_:1}),e.createVNode(e.unref(H.IonModal),{"is-open":Z.value,onDidDismiss:C[14]||(C[14]=re=>Z.value=!1)},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonHeader),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonToolbar),null,{end:e.withCtx(()=>[e.createVNode(e.unref(H.IonButtons),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButton),{onClick:C[9]||(C[9]=re=>Z.value=!1)},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{name:"close-outline"})]),_:1})]),_:1})]),default:e.withCtx(()=>[e.createVNode(e.unref(H.IonTitle),null,{default:e.withCtx(()=>[...C[25]||(C[25]=[e.createTextVNode("Edit Media Info",-1)])]),_:1})]),_:1})]),_:1}),e.createVNode(e.unref(H.IonContent),{class:"p-4"},{default:e.withCtx(()=>[M.value?(e.openBlock(),e.createElementBlock("div",qv,[e.createElementVNode("div",Yv,[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...C[26]||(C[26]=[e.createTextVNode("Caption",-1)])]),_:1}),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":C[10]||(C[10]=re=>M.value.caption=re),type:"text",class:"w-full p-2 border rounded mt-1",placeholder:"Enter caption..."},null,512),[[e.vModelText,M.value.caption]])]),e.createElementVNode("div",Qv,[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...C[27]||(C[27]=[e.createTextVNode("Alt Text",-1)])]),_:1}),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":C[11]||(C[11]=re=>M.value.alt_text=re),type:"text",class:"w-full p-2 border rounded mt-1",placeholder:"Enter alt text..."},null,512),[[e.vModelText,M.value.alt_text]])]),e.createElementVNode("div",eg,[e.createVNode(e.unref(H.IonButton),{onClick:C[12]||(C[12]=re=>K(M.value))},{default:e.withCtx(()=>[...C[28]||(C[28]=[e.createTextVNode("Save",-1)])]),_:1}),e.createVNode(e.unref(H.IonButton),{fill:"clear",onClick:C[13]||(C[13]=re=>Z.value=!1)},{default:e.withCtx(()=>[...C[29]||(C[29]=[e.createTextVNode("Cancel",-1)])]),_:1})])])):e.createCommentVNode("",!0)]),_:1})]),_:1},8,["is-open"]),e.createVNode(e.unref(H.IonFooter),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonToolbar),null,{default:e.withCtx(()=>[e.createElementVNode("div",tg,[e.createElementVNode("div",ag,[e.unref(w).selectedCount.value>0?(e.openBlock(),e.createElementBlock("span",ng,[e.createTextVNode(e.toDisplayString(e.unref(w).selectedCount.value)+" selected ",1),t.maxSelection?(e.openBlock(),e.createElementBlock("span",og," / "+e.toDisplayString(t.maxSelection)+" max ",1)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("span",ig," Select "+e.toDisplayString(t.selectionMode==="multiple"?"items":"an item"),1))]),e.createElementVNode("div",rg,[e.createVNode(e.unref(H.IonButton),{fill:"clear",onClick:D},{default:e.withCtx(()=>[...C[30]||(C[30]=[e.createTextVNode(" Cancel ",-1)])]),_:1}),e.createVNode(e.unref(H.IonButton),{disabled:I.value,onClick:P},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(V.value),1)]),_:1},8,["disabled"])])])]),_:1})]),_:1})]),_:1},8,["is-open"])}}}),sg=$e(lg,[["__scopeId","data-v-9a8c0954"]]),dg={key:1,class:"flex flex-col items-center justify-center py-16"},cg=["draggable","onDragstart","onDragover","onDrop"],ug={key:0,class:"absolute top-2 left-2 z-20"},mg=["checked","onChange"],pg={key:2,class:"absolute top-2 right-2 z-20 opacity-0 group-hover:opacity-100 transition-opacity cursor-move"},fg=["data-media-id"],hg={key:0,class:"w-full h-full flex items-center justify-center"},vg=["src","alt","onError","onLoad"],gg={key:2,class:"w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-700"},bg={class:"text-center"},yg={class:"text-4xl text-gray-400 mb-2"},wg={class:"text-sm font-medium text-gray-500"},kg={class:"absolute inset-0 bg-black/70 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2"},_g=["onClick"],Eg=["onClick"],Sg=["onClick"],Cg={class:"p-3"},xg={class:"text-sm font-medium truncate mb-1"},Ng={class:"text-xs text-gray-600 dark:text-gray-400"},Vg={key:0},Tg={key:0,class:"text-xs text-gray-500 dark:text-gray-500 mt-1 truncate"},Bg=e.defineComponent({__name:"MediaGrid",props:{mediaItems:{default:()=>[]},selectedItems:{default:()=>[]},isLoading:{type:Boolean,default:!1},selectionMode:{type:Boolean,default:!1},reorderable:{type:Boolean,default:!1},showEditButton:{type:Boolean,default:!1},columns:{default:()=>({mobile:2,sm:3,md:4,lg:5,xl:6})}},emits:["toggleSelect","preview","edit","delete","reorder","upload"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(null),r=e.ref(null),l=e.ref(new Set),s=e.ref(null),d=I=>t.selectedItems.some(x=>x.uuid===I.uuid),c=e.computed(()=>{const I=t.columns,x=["grid","gap-4"];switch(I.mobile){case 1:x.push("grid-cols-1");break;case 2:x.push("grid-cols-2");break;case 3:x.push("grid-cols-3");break;case 4:x.push("grid-cols-4");break;default:x.push("grid-cols-2");break}switch(I.sm){case 1:x.push("sm:grid-cols-1");break;case 2:x.push("sm:grid-cols-2");break;case 3:x.push("sm:grid-cols-3");break;case 4:x.push("sm:grid-cols-4");break;case 5:x.push("sm:grid-cols-5");break;default:x.push("sm:grid-cols-3");break}switch(I.md){case 2:x.push("md:grid-cols-2");break;case 3:x.push("md:grid-cols-3");break;case 4:x.push("md:grid-cols-4");break;case 5:x.push("md:grid-cols-5");break;case 6:x.push("md:grid-cols-6");break;default:x.push("md:grid-cols-4");break}switch(I.lg){case 3:x.push("lg:grid-cols-3");break;case 4:x.push("lg:grid-cols-4");break;case 5:x.push("lg:grid-cols-5");break;case 6:x.push("lg:grid-cols-6");break;case 7:x.push("lg:grid-cols-7");break;default:x.push("lg:grid-cols-5");break}switch(I.xl){case 4:x.push("xl:grid-cols-4");break;case 5:x.push("xl:grid-cols-5");break;case 6:x.push("xl:grid-cols-6");break;case 7:x.push("xl:grid-cols-7");break;case 8:x.push("xl:grid-cols-8");break;default:x.push("xl:grid-cols-6");break}return x.join(" ")});function u(I,x,T){t.reorderable&&(i.value=x,I.dataTransfer&&(I.dataTransfer.effectAllowed="move",I.dataTransfer.setData("text/html","")))}function m(I,x){t.reorderable&&(I.preventDefault(),r.value=x)}function p(){r.value=null}function f(I,x){if(!t.reorderable||!i.value)return;I.preventDefault();const T=[...t.mediaItems],$=T.findIndex(S=>{var B;return S.uuid===((B=i.value)==null?void 0:B.uuid)});if($!==-1&&$!==x&&i.value){const[S]=T.splice($,1);T.splice(x,0,S),n("reorder",T)}i.value=null,r.value=null}function h(I){return I<1024?I+" B":I<1024*1024?(I/1024).toFixed(1)+" KB":(I/(1024*1024)).toFixed(1)+" MB"}function v(I){var T;return I.thumbnail_url||((T=I.conversion_urls)==null?void 0:T.thumb)||I.original_url||I.url||""}function k(I){var $,S,B;const x=(($=I.mime_type)==null?void 0:$.startsWith("image/"))||!1,T=!!(I.thumbnail_url||(S=I.conversion_urls)!=null&&S.thumb||(B=I.conversion_urls)!=null&&B.preview||I.original_url||I.url);return x&&T}function y(I){var x;return((x=I.split(".").pop())==null?void 0:x.toUpperCase())||""}function w(I){var T;const x=((T=I.mime_type)==null?void 0:T.toLowerCase())||"";return x.startsWith("image/")?"image":x.startsWith("video/")?"videocam":x.startsWith("audio/")?"musical-notes":x.includes("pdf")?"document-text":x.includes("zip")||x.includes("rar")?"archive":x.includes("sheet")||x.includes("excel")?"grid":x.includes("document")||x.includes("word")?"document-text":"document"}e.onMounted(()=>{typeof window<"u"&&"IntersectionObserver"in window&&(s.value=new IntersectionObserver(I=>{I.forEach(x=>{var T;if(x.isIntersecting){const $=x.target.getAttribute("data-media-id");$&&(l.value.add($),(T=s.value)==null||T.unobserve(x.target))}})},{rootMargin:"50px"}))}),e.onUnmounted(()=>{s.value&&s.value.disconnect()});function g(I){return!0}function b(){s.value&&e.nextTick(()=>{document.querySelectorAll("[data-media-id]").forEach(x=>{var $;const T=x.getAttribute("data-media-id");T&&!l.value.has(T)&&(($=s.value)==null||$.observe(x))})})}e.watch(()=>t.mediaItems,()=>{l.value.clear(),b()},{immediate:!0,deep:!0});function R(I,x){const T=I.target;delete T.dataset.fallbackIndex}function V(I,x){const T=I.target,$=T.closest("[data-media-id]"),S=[x.original_url,x.url,x.thumbnail_url,"preview_url"in x?x.preview_url:void 0].filter(B=>B&&B.trim()!==""&&B!==T.src);if(S.length>0&&T.dataset.fallbackIndex){const B=parseInt(T.dataset.fallbackIndex);if(B<S.length){T.dataset.fallbackIndex=(B+1).toString(),T.src=S[B]||"";return}}else if(S.length>0){T.dataset.fallbackIndex="1",T.src=S[0]||"";return}if(T.style.display="none",$&&!$.querySelector(".media-fallback-icon")){const _=document.createElement("div");_.className="media-fallback-icon w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-800",_.innerHTML=`
2
- <div class="text-center">
3
- <div class="text-4xl text-gray-400 mb-2">${w(x)}</div>
4
- <p class="text-sm font-medium text-gray-500">${y(x.file_name)}</p>
5
- </div>
6
- `,$.appendChild(_)}}return(I,x)=>I.isLoading?(e.openBlock(),e.createElementBlock("div",{key:0,class:e.normalizeClass(c.value)},[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(12,T=>e.createElementVNode("div",{key:`skeleton-${T}`,class:"relative"},[...x[1]||(x[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)):!I.mediaItems||!I.mediaItems.length?(e.openBlock(),e.createElementBlock("div",dg,[x[2]||(x[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)),x[3]||(x[3]=e.createElementVNode("h3",{class:"text-lg font-medium mb-2"}," No Media Items ",-1)),x[4]||(x[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:x[0]||(x[0]=T=>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(I.mediaItems,(T,$)=>(e.openBlock(),e.createElementBlock("div",{key:T.uuid,class:e.normalizeClass(["relative group",{"ring-2 ring-blue-500 ring-offset-2":r.value===$}]),draggable:I.reorderable,onDragstart:S=>u(S,T),onDragover:S=>m(S,$),onDragleave:p,onDrop:S=>f(S,$)},[I.selectionMode?(e.openBlock(),e.createElementBlock("div",ug,[e.createElementVNode("input",{type:"checkbox",checked:d(T),onChange:S=>n("toggleSelect",T),class:"w-5 h-5 bg-white dark:bg-gray-800 rounded cursor-pointer"},null,40,mg)])):e.createCommentVNode("",!0),I.$slots.badge?(e.openBlock(),e.createElementBlock("div",{key:1,class:e.normalizeClass(["absolute top-2 z-20",I.selectionMode?"left-10":"left-2"])},[e.renderSlot(I.$slots,"badge",{media:T,index:$},void 0,!0)],2)):e.createCommentVNode("",!0),I.reorderable?(e.openBlock(),e.createElementBlock("div",pg,[...x[5]||(x[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(T)}])},[e.createElementVNode("div",{class:"relative aspect-square bg-gray-100 dark:bg-gray-700 overflow-hidden","data-media-id":T.uuid},[k(T)&&!g(T.uuid)?(e.openBlock(),e.createElementBlock("div",hg,[...x[6]||(x[6]=[e.createElementVNode("div",{class:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"},null,-1)])])):e.createCommentVNode("",!0),k(T)&&g(T.uuid)?(e.openBlock(),e.createElementBlock("img",{key:1,src:v(T),alt:T.alt_text||T.file_name,class:"w-full h-full object-cover",loading:"lazy",onError:S=>V(S,T),onLoad:S=>R(S)},null,40,vg)):(e.openBlock(),e.createElementBlock("div",gg,[e.createElementVNode("div",bg,[e.createElementVNode("div",yg,e.toDisplayString(w(T)),1),e.createElementVNode("p",wg,e.toDisplayString(y(T.file_name)),1)])])),e.createElementVNode("div",kg,[e.createElementVNode("button",{onClick:S=>n("preview",T),class:"p-2 bg-white/20 text-white rounded hover:bg-white/30",title:"Preview"},[...x[7]||(x[7]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24","stroke-width":"1.5",stroke:"currentColor",class:"w-5 h-5"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round",d:"M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"}),e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})],-1)])],8,_g),I.showEditButton&&k(T)?(e.openBlock(),e.createElementBlock("button",{key:0,onClick:S=>n("edit",T),class:"p-2 bg-white/20 text-white rounded hover:bg-white/30",title:"Edit"},[...x[8]||(x[8]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24","stroke-width":"1.5",stroke:"currentColor",class:"w-5 h-5"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round",d:"M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10"})],-1)])],8,Eg)):e.createCommentVNode("",!0),e.createElementVNode("button",{onClick:S=>n("delete",T.uuid),class:"p-2 bg-red-500/20 text-red-300 rounded hover:bg-red-500/30",title:"Delete"},[...x[9]||(x[9]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24","stroke-width":"1.5",stroke:"currentColor",class:"w-5 h-5"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round",d:"M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0"})],-1)])],8,Sg)])],8,fg),e.createElementVNode("div",Cg,[e.createElementVNode("h4",xg,e.toDisplayString(T.file_name),1),e.createElementVNode("p",Ng,[e.createTextVNode(e.toDisplayString(h(T.size))+" ",1),T.width&&T.height?(e.openBlock(),e.createElementBlock("span",Vg," • "+e.toDisplayString(T.width)+"x"+e.toDisplayString(T.height),1)):e.createCommentVNode("",!0)]),T.caption?(e.openBlock(),e.createElementBlock("p",Tg,e.toDisplayString(T.caption),1)):e.createCommentVNode("",!0)])],2)],42,cg))),128))],2))}}),Ig=$e(Bg,[["__scopeId","data-v-f0c343b7"]]),Mg={class:"model-media-manager"},$g=["accept","multiple"],Fg={class:"flex items-center justify-between mb-4"},Dg={key:0,class:"text-lg font-medium"},Ag={class:"flex gap-2"},Rg={key:0,class:"flex items-center justify-center py-8"},Lg={key:1,class:"flex flex-col items-center justify-center py-12 text-center border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg"},Pg={class:"text-gray-600 dark:text-gray-400"},Ug={class:"flex gap-2 mt-4"},Og={key:0,class:"px-2 py-1 bg-blue-500 text-white text-xs font-medium rounded"},zg=e.defineComponent({__name:"ModelMediaManager",props:{mediableType:{},mediableId:{},collection:{},mode:{default:"user"},initialMedia:{},maxFiles:{},acceptedMimeTypes:{},maxFileSize:{},allowReorder:{type:Boolean,default:!0},allowUpload:{type:Boolean,default:!0},allowBrowse:{type:Boolean,default:!0},allowDetach:{type:Boolean,default:!0},allowEdit:{type:Boolean,default:!1},editMode:{default:"replace"},showPrimaryBadge:{type:Boolean,default:!0},emptyText:{default:"No media attached"},title:{default:"Media"}},emits:["loading","update:media","error","attach","detach","reorder","upload-progress","edit-complete"],setup(o,{emit:a}){const t=o,n=a,i=xa(),r=e.ref(!1),l=e.ref(!1),s=e.ref(!1),d=e.ref(!1),c=e.ref(null),u=e.ref(0),m=e.ref(null),p=e.ref(null),f=e.ref(null),h=e.ref(null),v=e.ref(null),k=e.ref(void 0),y=e.ref(null),w=e.ref(null),g=e.computed(()=>{if(t.maxFiles!==void 0)return Math.max(0,t.maxFiles-i.modelMedia.length)}),b=e.computed(()=>i.modelMedia.map(ce=>ce.uuid)),R=e.computed(()=>{if(!(!t.acceptedMimeTypes||t.acceptedMimeTypes.length===0))return t.acceptedMimeTypes.join(",")});function V(){$o({isAdmin:t.mode==="admin"})}async function I(ce){await(await H.toastController.create({message:ce,duration:3e3,color:"danger",position:"bottom"})).present()}async function x(){if(!l.value)if(l.value=!0,V(),i.setModelContext(t.mediableType,t.mediableId,t.collection),t.initialMedia&&t.initialMedia.length>0)i.modelMedia=[...t.initialMedia],n("update:media",i.modelMedia);else{r.value=!0,n("loading",!0);try{await i.fetchModelMedia(t.mediableType,t.mediableId,t.collection),n("update:media",i.modelMedia)}catch(ce){const le=ce instanceof Error?ce.message:"Failed to fetch media";n("error",{operation:"fetch",message:le,details:ce})}finally{r.value=!1,n("loading",!1)}}}e.watch(()=>i.modelMedia,ce=>{l.value&&n("update:media",ce)},{deep:!0}),e.watch(()=>[t.mediableType,t.mediableId,t.collection],()=>{l.value=!1,x()}),e.watch(()=>t.mode,()=>{V()}),e.onMounted(()=>{x()}),e.onUnmounted(()=>{i.clearModelContext()});function T(){return i.modelMedia.length>0}function $(){return t.maxFiles===void 0?!1:i.modelMedia.length>=t.maxFiles}function S(ce){var W,C,U;if(!((W=ce.mime_type)!=null&&W.startsWith("image/")))return null;const le=ce.original_url||ce.url||((C=ce.conversion_urls)==null?void 0:C.preview)||((U=ce.conversion_urls)==null?void 0:U.thumb)||ce.thumbnail_url;return le&&le.trim()!==""?le:null}function B(){c.value=null,k.value=void 0,m.value=null,p.value=null,f.value=null,h.value=null,v.value=null}function _(){s.value=!0}function A(){var ce;(ce=w.value)==null||ce.click()}function P(){s.value=!1}async function D(ce){if(t.allowEdit&&S(ce)){B(),c.value=ce,u.value++;try{const le=i.getHttpClient(),W=i.getEditorApiUrl(""),C=await le(`${W.replace(/\/$/,"")}/editor/${ce.uuid}/edit`);if(!C.editable_source_url)throw new Error("Editor source URL missing from edit context");k.value=C.editable_source_url,m.value=C.editor_state??null,p.value=C.editor_document??null,f.value=C.editor_document_id??null,h.value=C.editor_document_revision_id??null,v.value=C.editor_document_revision_number??null}catch(le){B();const W=le instanceof Error?`Unable to load image editor: ${le.message}`:"Unable to load image editor";await I(W);return}d.value=!0}}function z(){d.value=!1,B()}async function M(ce){if(!c.value)throw new Error("No media selected for editing");const le=c.value,W=t.editMode==="variant";try{y.value=null;const C=await i.saveEditedImage(le.uuid,ce,{asVariant:W});W||await i.detachMedia(t.mediableType,t.mediableId,le.uuid,t.collection),await i.attachMedia(t.mediableType,t.mediableId,[C.uuid],t.collection),n("edit-complete",{originalMedia:le,editedMedia:C,mode:t.editMode}),d.value=!1,B()}catch(C){const U=C instanceof Error?C.message:"Failed to save edited image";throw y.value=U,await I(U),C}}function Z(ce){if(y.value===ce.message){y.value=null;return}I(ce.message)}async function O(ce){const le=ce.target,W=le.files;if(!(!W||W.length===0)){for(let C=0;C<W.length;C++){const U=W[C];if(g.value!==void 0&&g.value<=0)break;if(t.acceptedMimeTypes&&t.acceptedMimeTypes.length>0&&!t.acceptedMimeTypes.includes(U.type)){n("error",{operation:"upload",message:`File type ${U.type} is not accepted`,details:{file:U.name}});continue}if(t.maxFileSize!==void 0&&U.size>t.maxFileSize){n("error",{operation:"upload",message:`File size exceeds limit of ${t.maxFileSize} bytes`,details:{file:U.name,size:U.size}});continue}n("upload-progress",{status:"uploading",progress:0,file:U});try{const j=await i.uploadFile(U,{collection:t.collection});j!=null&&j.uuid&&(await i.attachMedia(t.mediableType,t.mediableId,[j.uuid],t.collection),n("upload-progress",{status:"complete",progress:100,file:U}),n("attach",[j]))}catch(j){const re=j instanceof Error?j.message:"Upload failed";n("error",{operation:"upload",message:re,details:j}),n("upload-progress",{status:"error",progress:0,file:U,error:re})}}le.value=""}}async function K(ce){const le=ce.map(W=>W.uuid);try{await i.reorderMedia(t.mediableType,t.mediableId,le,t.collection),n("reorder",i.modelMedia)}catch(W){const C=W instanceof Error?W.message:"Failed to reorder media";n("error",{operation:"reorder",message:C,details:W}),await I(C)}}async function de(ce){const le=i.modelMedia.find(W=>W.uuid===ce);try{await i.detachMedia(t.mediableType,t.mediableId,ce,t.collection),le&&n("detach",le)}catch(W){const C=W instanceof Error?W.message:"Failed to detach media";n("error",{operation:"detach",message:C,details:W}),await I(C)}}async function Ne(ce){s.value=!1;const le=ce.map(U=>U.uuid),W=new Set(b.value);let C=Array.from(new Set(le)).filter(U=>!W.has(U));if(g.value!==void 0&&C.length>g.value&&(C=C.slice(0,g.value)),C.length!==0)try{await i.attachMedia(t.mediableType,t.mediableId,C,t.collection);const U=i.modelMedia.filter(j=>C.includes(j.uuid));n("attach",U)}catch(U){const j=U instanceof Error?U.message:"Failed to attach media";n("error",{operation:"attach",message:j,details:U})}}return(ce,le)=>(e.openBlock(),e.createElementBlock("div",Mg,[e.createElementVNode("input",{ref_key:"fileInputRef",ref:w,type:"file",accept:R.value,multiple:g.value===void 0||g.value>1,class:"hidden","data-testid":"upload-input",onChange:O},null,40,$g),e.createElementVNode("div",Fg,[ce.title?(e.openBlock(),e.createElementBlock("h3",Dg,e.toDisplayString(ce.title),1)):e.createCommentVNode("",!0),e.createElementVNode("div",Ag,[ce.allowBrowse?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:0,fill:"outline",size:"small",disabled:$(),"data-testid":"browse-button",onClick:_},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{slot:"start",icon:e.unref(jl)},null,8,["icon"]),le[1]||(le[1]=e.createTextVNode(" Browse ",-1))]),_:1},8,["disabled"])):e.createCommentVNode("",!0),ce.allowUpload?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:1,fill:"solid",size:"small",disabled:$(),"data-testid":"upload-button",onClick:A},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{slot:"start",icon:e.unref(uc)},null,8,["icon"]),le[2]||(le[2]=e.createTextVNode(" Upload ",-1))]),_:1},8,["disabled"])):e.createCommentVNode("",!0)])]),r.value||e.unref(i).isLoadingModelMedia?(e.openBlock(),e.createElementBlock("div",Rg,[e.createVNode(e.unref(H.IonSpinner),{"data-testid":"spinner"})])):T()?(e.openBlock(),e.createBlock(Ig,{key:2,"media-items":e.unref(i).modelMedia,reorderable:!!ce.allowReorder,"is-loading":r.value||e.unref(i).isLoadingModelMedia,"show-edit-button":!!ce.allowEdit,"selection-mode":!1,onReorder:K,onDelete:de,onEdit:D},e.createSlots({_:2},[ce.showPrimaryBadge?{name:"badge",fn:e.withCtx(({index:W})=>[W===0?(e.openBlock(),e.createElementBlock("div",Og," Primary ")):e.createCommentVNode("",!0)]),key:"0"}:void 0]),1032,["media-items","reorderable","is-loading","show-edit-button"])):(e.openBlock(),e.createElementBlock("div",Lg,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(jl),class:"w-12 h-12 text-gray-400 mb-4"},null,8,["icon"]),e.createElementVNode("p",Pg,e.toDisplayString(ce.emptyText),1),e.createElementVNode("div",Ug,[ce.allowBrowse?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:0,fill:"outline",size:"small","data-testid":"browse-button-empty",onClick:_},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{slot:"start",icon:e.unref(jl)},null,8,["icon"]),le[3]||(le[3]=e.createTextVNode(" Browse Library ",-1))]),_:1})):e.createCommentVNode("",!0),ce.allowUpload?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:1,fill:"solid",size:"small","data-testid":"upload-button-empty",onClick:A},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{slot:"start",icon:e.unref(uc)},null,8,["icon"]),le[4]||(le[4]=e.createTextVNode(" Upload Files ",-1))]),_:1})):e.createCommentVNode("",!0)])])),e.createVNode(sg,e.mergeProps({"is-open":s.value,"selected-items":b.value,collection:ce.collection},g.value!==null&&g.value!==void 0?{maxSelection:g.value}:{},{onConfirm:Ne,onClose:P}),null,16,["is-open","selected-items","collection"]),e.createVNode(om,{modelValue:d.value,"onUpdate:modelValue":le[0]||(le[0]=W=>d.value=W),"initial-image":k.value,"initial-state":m.value,"initial-document":p.value,"initial-document-id":f.value,"initial-document-revision-id":h.value,"initial-document-revision-number":v.value,"session-key":u.value,"save-handler":M,onCancel:z,onError:Z},null,8,["modelValue","initial-image","initial-state","initial-document","initial-document-id","initial-document-revision-id","initial-document-revision-number","session-key"])]))}}),jg=$e(zg,[["__scopeId","data-v-c58d85c8"]]),Wg={class:"existing-media-selector","data-testid":"existing-media-selector"},Hg={key:0,class:"existing-media-selector__status","data-testid":"existing-media-loading"},Zg=["data-testid"],Gg={class:"existing-media-selector__section-header"},Xg={class:"existing-media-selector__section-title"},Kg=["data-testid","aria-label","onClick"],Jg={class:"existing-media-selector__grid"},qg=["data-testid","aria-label","aria-pressed","onClick"],Yg=["src","alt"],Qg={key:0,class:"existing-media-selector__selected-badge"},eb={key:1,class:"existing-media-selector__caption"},tb={key:0,class:"existing-media-selector__section existing-media-selector__section--albums","data-testid":"existing-media-albums"},ab={class:"existing-media-selector__section-header"},nb={class:"existing-media-selector__section-title"},ob={class:"existing-media-selector__albums"},ib=["data-testid","aria-label","aria-pressed","onClick"],rb={class:"existing-media-selector__album-name"},lb={key:0,class:"existing-media-selector__album-count"},sb={class:"existing-media-selector__album-panel","data-testid":"existing-media-active-album"},db={class:"existing-media-selector__section-header"},cb={class:"existing-media-selector__section-subtitle"},ub={key:0,class:"existing-media-selector__section-description"},mb={key:0,class:"existing-media-selector__status","data-testid":"existing-media-active-album-loading"},pb={key:1,class:"existing-media-selector__grid"},fb=["data-testid","aria-label","aria-pressed","onClick"],hb=["src","alt"],vb={key:0,class:"existing-media-selector__selected-badge"},gb={key:1,class:"existing-media-selector__caption"},bb={key:2,class:"existing-media-selector__empty","data-testid":"existing-media-active-album-empty"},yb={key:1,class:"existing-media-selector__empty","data-testid":"existing-media-empty"},wb=e.defineComponent({__name:"ExistingMediaSelector",props:{sections:{default:()=>[]},albums:{default:()=>[]},selectedId:{default:null},activeAlbumId:{default:null},activeAlbumItems:{default:()=>[]},activeAlbumTitle:{},activeAlbumDescription:{},isLoading:{type:Boolean,default:!1},isAlbumLoading:{type:Boolean,default:!1},emptyMessage:{default:"No media available yet."},albumBrowseTitle:{default:"Browse Your Albums"},albumSectionTitle:{default:"Selected Album"},activeAlbumEmptyMessage:{default:"No media available in this album yet."}},emits:["select","update:activeAlbumId"],setup(o,{emit:a}){const t=o,n=a,i=e.reactive({}),r=e.computed(()=>t.sections.filter(b=>b.items.length>0)),l=e.computed(()=>t.albums.length>0),s=e.computed(()=>r.value.length>0||l.value),d=e.computed(()=>{if(typeof t.activeAlbumTitle=="string"&&t.activeAlbumTitle.trim().length>0)return t.activeAlbumTitle.trim();const b=t.albums.find(R=>R.id===t.activeAlbumId);return b!=null&&b.name.trim().length?b.name.trim():t.albumSectionTitle}),c=e.computed(()=>{if(typeof t.activeAlbumDescription=="string"&&t.activeAlbumDescription.trim().length>0)return t.activeAlbumDescription.trim();const b=t.albums.find(R=>R.id===t.activeAlbumId);return typeof(b==null?void 0:b.description)=="string"&&b.description.trim().length>0?b.description.trim():""});function u(b){const R=b.initialVisibleCount??6;return R>0?R:6}function m(b){return i[b]===!0}function p(b){i[b]=!m(b)}function f(b){return m(b.id)?b.items:b.items.slice(0,u(b))}function h(b){return b.items.length>u(b)}function v(b){n("select",b)}function k(b){n("update:activeAlbumId",b)}function y(b){var V;const R=(V=b.description)==null?void 0:V.trim();return R&&R.length>0?`Select ${R}`:"Select existing media"}function w(b,R){var I;const V=(I=R.description)==null?void 0:I.trim();return typeof R.alt=="string"&&R.alt.trim().length>0?R.alt.trim():V&&V.length>0?V:b.title}function g(b){const R=typeof b.mediaCount=="number"?` with ${b.mediaCount} item${b.mediaCount===1?"":"s"}`:"";return`Browse album ${b.name}${R}`}return(b,R)=>(e.openBlock(),e.createElementBlock("div",Wg,[b.isLoading?(e.openBlock(),e.createElementBlock("div",Hg," Loading your media... ")):(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.value,V=>(e.openBlock(),e.createElementBlock("section",{key:V.id,class:"existing-media-selector__section","data-testid":`existing-media-section-${V.id}`},[e.createElementVNode("div",Gg,[e.createElementVNode("h3",Xg,e.toDisplayString(V.title),1),h(V)?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"existing-media-selector__toggle","data-testid":`existing-media-toggle-${V.id}`,"aria-label":m(V.id)?`Show fewer items from ${V.title}`:`Show more items from ${V.title}`,onClick:I=>p(V.id)},e.toDisplayString(m(V.id)?"See less":"See more"),9,Kg)):e.createCommentVNode("",!0)]),e.createElementVNode("div",Jg,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(f(V),I=>(e.openBlock(),e.createElementBlock("button",{key:I.id,type:"button",class:e.normalizeClass(["existing-media-selector__item",{"is-selected":b.selectedId===I.id}]),"data-testid":`existing-media-item-${V.id}-${I.id}`,"aria-label":y(I),"aria-pressed":b.selectedId===I.id?"true":"false",onClick:x=>v(I)},[e.createElementVNode("img",{class:"existing-media-selector__image",src:I.previewUrl,alt:w(V,I)},null,8,Yg),b.selectedId===I.id?(e.openBlock(),e.createElementBlock("div",Qg," Selected ")):e.createCommentVNode("",!0),I.description?(e.openBlock(),e.createElementBlock("div",eb,e.toDisplayString(I.description),1)):e.createCommentVNode("",!0)],10,qg))),128))])],8,Zg))),128)),l.value?(e.openBlock(),e.createElementBlock("section",tb,[e.createElementVNode("div",ab,[e.createElementVNode("h3",nb,e.toDisplayString(b.albumBrowseTitle),1)]),e.createElementVNode("div",ob,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(b.albums,V=>(e.openBlock(),e.createElementBlock("button",{key:V.id,type:"button",class:e.normalizeClass(["existing-media-selector__album",{"is-active":b.activeAlbumId===V.id}]),"data-testid":`existing-media-album-${V.id}`,"aria-label":g(V),"aria-pressed":b.activeAlbumId===V.id?"true":"false",onClick:I=>k(V.id)},[e.createElementVNode("span",rb,e.toDisplayString(V.name),1),typeof V.mediaCount=="number"?(e.openBlock(),e.createElementBlock("span",lb,e.toDisplayString(V.mediaCount),1)):e.createCommentVNode("",!0)],10,ib))),128))]),e.createElementVNode("div",sb,[e.createElementVNode("div",db,[e.createElementVNode("div",null,[e.createElementVNode("h4",cb,e.toDisplayString(d.value),1),c.value?(e.openBlock(),e.createElementBlock("p",ub,e.toDisplayString(c.value),1)):e.createCommentVNode("",!0)])]),b.isAlbumLoading?(e.openBlock(),e.createElementBlock("div",mb," Loading album... ")):b.activeAlbumItems.length>0?(e.openBlock(),e.createElementBlock("div",pb,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(b.activeAlbumItems,V=>(e.openBlock(),e.createElementBlock("button",{key:V.id,type:"button",class:e.normalizeClass(["existing-media-selector__item",{"is-selected":b.selectedId===V.id}]),"data-testid":`existing-media-item-album-${V.id}`,"aria-label":y(V),"aria-pressed":b.selectedId===V.id?"true":"false",onClick:I=>v(V)},[e.createElementVNode("img",{class:"existing-media-selector__image",src:V.previewUrl,alt:V.alt||V.description||d.value},null,8,hb),b.selectedId===V.id?(e.openBlock(),e.createElementBlock("div",vb," Selected ")):e.createCommentVNode("",!0),V.description?(e.openBlock(),e.createElementBlock("div",gb,e.toDisplayString(V.description),1)):e.createCommentVNode("",!0)],10,fb))),128))])):(e.openBlock(),e.createElementBlock("div",bb,[e.renderSlot(b.$slots,"active-album-empty",{},()=>[e.createTextVNode(e.toDisplayString(b.activeAlbumEmptyMessage),1)],!0)]))])])):e.createCommentVNode("",!0),s.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",yb,[e.renderSlot(b.$slots,"empty",{},()=>[e.createTextVNode(e.toDisplayString(b.emptyMessage),1)],!0)]))],64))]))}}),kb=$e(wb,[["__scopeId","data-v-904abb6b"]]);function sr(o,a,t,n){if(t<=0||n<=0)return!1;try{return a.drawImage(o,0,0,t,n),!0}catch(i){return i instanceof DOMException&&i.name==="InvalidStateError",!1}}function _b(o,a){return o?{display:"block",position:"absolute",inset:"0",width:"100%",height:"100%",objectFit:a,opacity:"0",pointerEvents:"none"}:{display:"block",position:"relative",inset:"auto",width:"100%",height:"100%",objectFit:a,opacity:"1",pointerEvents:"auto"}}const Eb=["src","crossorigin"],Sb={class:"preview-controls"},Cb=["aria-label"],xb={class:"time-display"},Nb={class:"current-time"},Vb={class:"total-time"},Tb={key:0,class:"fps-display"},Bb={key:0,class:"loading-overlay"},Ib={key:1,class:"error-overlay"},Mb=.1,$b=e.defineComponent({__name:"VideoPreview",props:{source:{},filters:{},playhead:{},fallbackDuration:{default:0},isPlaying:{type:Boolean,default:!1},showFps:{type:Boolean,default:!1},targetFps:{default:30},fitMode:{default:"contain"},active:{type:Boolean,default:!0}},emits:["frame-update","play-pause","duration-change","error"],setup(o,{expose:a,emit:t}){const{ColorMatrixFilter:n,BlurFilter:i}=Jt,r=o,l=t,s=e.ref(),d=e.ref(),c=e.ref(),u=e.ref(!0),m=e.ref(),p=e.ref(0),f=e.ref(0),h=e.ref(!1);let v,k,y=null,w=null,g=null,b=[],R="",V=null,I=0,x=0,T=0,$=0,S=!1,B=0,_=0,A,P=null,D=!1,z=!1,M=0;const Z=e.computed(()=>r.source&&typeof r.source=="string"?r.source:""),O=e.computed(()=>{const Se=Z.value;if(!(!Se||Se.startsWith("blob:")))return"anonymous"}),K=e.computed(()=>_b(h.value,r.fitMode));function de(Se){return typeof Se=="number"&&Number.isFinite(Se)&&Se>=0?Se:Number.isFinite(r.fallbackDuration)&&r.fallbackDuration>0?r.fallbackDuration:0}function Ne(Se){const J=de(Se.duration);return J<=0?!1:Se.currentTime>=Math.max(0,J-Mb)}async function ce(){var Se,J;if(!z&&d.value&&!v&&!(!c.value||c.value.readyState<3)){z=!0;try{m.value=void 0;let oe=((Se=s.value)==null?void 0:Se.clientWidth)||800,De=((J=s.value)==null?void 0:J.clientHeight)||450;if((oe<=0||De<=0)&&(oe=c.value.videoWidth||800,De=c.value.videoHeight||450),v=new Jt.Application,await v.init({width:oe,height:De,background:0,resolution:window.devicePixelRatio||1,autoDensity:!0,antialias:!0,powerPreference:"high-performance",preserveDrawingBuffer:!0}),d.value.appendChild(v.canvas),c.value){if(c.value.videoWidth===0||c.value.videoHeight===0){setTimeout(()=>{c.value&&c.value.videoWidth>0&&!v&&ce()},100),v&&(v.destroy(!0),v=null);return}if(I=c.value.videoWidth,x=c.value.videoHeight,w=document.createElement("canvas"),w.width=I,w.height=x,g=w.getContext("2d"),!g)throw new Error("Unable to create 2D canvas context for video preview");const fe=sr(c.value,g,I,x),Ae=Jt.Texture.from(w);y=Ae.source,k=new Jt.Sprite(Ae),k.visible=!0,k.alpha=1,St(),v.stage.addChild(k),v.renderer&&!v.renderer.destroyed&&v.render()}U(),r.targetFps<60?le():v.ticker.add(W),h.value=!0,"ResizeObserver"in window&&(V=new ResizeObserver(fe=>{S||(S=!0,requestAnimationFrame(()=>{S=!1;const Ae=fe[fe.length-1],{width:Ye,height:st}=Ae.contentRect;if(Ye<=0||st<=0)return;const Bt=Math.round(Ye),Vt=Math.round(st);Bt===T&&Vt===$||(T=Bt,$=Vt,St())}))}),V.observe(s.value)),r.filters&&r.filters.length>0&&U(),r.showFps&&ze(),M=0}catch{if(Dt(),!D&&!!c.value&&c.value.readyState>=2&&c.value.videoWidth>0&&c.value.videoHeight>0&&M<2){M+=1,window.setTimeout(()=>{D||ce()},M*150);return}m.value="Failed to initialize video preview",l("error",m.value)}finally{z=!1}}}function le(){const Se=1e3/r.targetFps;let J=performance.now();function oe(){if(D||!v)return;const De=performance.now(),fe=De-J;fe>=Se&&(W(),J=De-fe%Se),P=requestAnimationFrame(oe)}P=requestAnimationFrame(oe)}function W(){if(!(!v||!k||D)&&r.active)try{g&&w&&y&&c.value&&(c.value.readyState>=2&&sr(c.value,g,w.width,w.height)&&y.update(),c.value.paused||l("frame-update",ue())),r.showFps&&_++,v.renderer&&!v.renderer.destroyed&&v.render()}catch{D=!0}}function C(){for(const Se of b)try{Se.destroy()}catch{}b=[]}function U(){if(k){if(!r.filters||r.filters.length===0){k.filters=null,C();return}C(),r.filters.forEach(Se=>{const J=j(Se);J&&b.push(J)}),k.filters=b.length>0?b:null,R=JSON.stringify(r.filters),v&&v.render()}}function j(Se){const J=Se.filterId,oe=Se.params||{},De=te.getFilter(J);if(De&&!te.isFilterCompatibleWithMedia(J,"video"))return null;if(De&&De.createFilter)try{return De.createFilter(oe)}catch{}const fe=(Ae,Ye,st)=>Math.min(st,Math.max(Ye,Ae));switch(J){case"brightness":{const Ae=new n,Ye=fe(typeof oe.brightness=="number"?oe.brightness:typeof oe.value=="number"?oe.value:1,0,5);return Ae.brightness(Ye,!0),Ae}case"contrast":{const Ae=new n,Ye=fe(typeof oe.contrast=="number"?oe.contrast:typeof oe.value=="number"?oe.value:1,0,5);return Ae.contrast(Ye,!0),Ae}case"saturation":{const Ae=new n,Ye=fe(typeof oe.saturation=="number"?oe.saturation:typeof oe.value=="number"?oe.value:1,0,5);return Ae.saturate(Ye,!0),Ae}case"hue":{const Ae=new n,Ye=fe(typeof oe.value=="number"?oe.value:0,-180,180);return Ae.hue(Ye,!0),Ae}case"gaussian-blur":case"blur":{const Ae=fe(typeof oe.blur=="number"?oe.blur:typeof oe.value=="number"?oe.value:2,0,10);return new i(Ae)}case"grayscale":{const Ae=new n;return Ae.desaturate(),Ae}case"sepia":case"color-matrix":{const Ae=new n;return Ae.sepia(!0),Ae}case"vignette":{const Ae=typeof oe.value=="number"?oe.value:.3;return re(fe(Ae,0,1))}default:return null}}function re(Se){const J=`
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 Jt.Filter(void 0,J,{strength:Se})}function ue(){var J;return!v||!k?null:{dataUrl:v.canvas.toDataURL("image/jpeg",.8),timestamp:((J=c.value)==null?void 0:J.currentTime)||0,width:I||0,height:x||0}}function Xe(){var Se;p.value=de((Se=c.value)==null?void 0:Se.duration),l("duration-change",p.value)}function be(){u.value=!1,m.value=void 0}function Ee(){u.value&&(u.value=!1),!h.value&&r.active?ce():h.value}function ye(){var J,oe,De;const Se=((J=c.value)==null?void 0:J.currentTime)||0;l("frame-update",{dataUrl:null,timestamp:Se,width:((oe=c.value)==null?void 0:oe.videoWidth)||0,height:((De=c.value)==null?void 0:De.videoHeight)||0})}function xe(){c.value&&(c.value.currentTime=0),l("play-pause")}function Ce(Se){var oe;const J=Se.target;if(J!=null&&J.error)switch(J.error.code){case J.error.MEDIA_ERR_ABORTED:m.value="Video playback aborted";break;case J.error.MEDIA_ERR_NETWORK:m.value="Network error loading video";break;case J.error.MEDIA_ERR_DECODE:m.value="Video format not supported";break;case J.error.MEDIA_ERR_SRC_NOT_SUPPORTED:m.value=`Video source not supported: ${(oe=J.src)==null?void 0:oe.substring(0,100)}`;break;default:m.value="Failed to load video"}else m.value="Failed to load video";l("error",m.value),u.value=!1}function Re(Se){c.value&&(c.value.currentTime=Math.max(0,Math.min(Se,p.value)))}function ze(){A=window.setInterval(()=>{const Se=performance.now(),J=Se-B;f.value=Math.round(_*1e3/J),_=0,B=Se},1e3)}function rt(Se){if(!Number.isFinite(Se)||Se<0)return"00:00";const J=Math.floor(Se/60),oe=Math.floor(Se%60);return`${J.toString().padStart(2,"0")}:${oe.toString().padStart(2,"0")}`}function at(){m.value=void 0,u.value=!0,M=0,Dt(),c.value&&c.value.load()}function Dt(){if(V&&(V.disconnect(),V=null),P&&(cancelAnimationFrame(P),P=null),v!=null&&v.ticker&&(v.ticker.stop(),v.ticker.remove(W)),v)try{v.destroy(!0,{children:!0,texture:!0})}catch{}d.value&&(d.value.innerHTML=""),C(),v=null,k=null,y=null,w=null,g=null,h.value=!1,S=!1,R=""}function ht(){v&&(S||(S=!0,requestAnimationFrame(()=>{S=!1,St()})))}function St(){if(!v||!k||!I||!x||!s.value)return;const Se=Math.round(s.value.clientWidth),J=Math.round(s.value.clientHeight);if(Se<=0||J<=0)return;v.renderer.resize(Se,J);const oe=v.screen.width/I,De=v.screen.height/x;let fe=1;switch(r.fitMode){case"cover":fe=Math.max(oe,De);break;case"none":fe=1;break;case"contain":default:fe=Math.min(oe,De);break}k.scale.set(fe),k.anchor.set(.5),k.position.set(v.screen.width/2,v.screen.height/2),k.visible=!0,k.alpha=1,v.renderer&&!v.renderer.destroyed&&v.render()}e.watch(()=>r.filters,()=>{h.value&&U()},{deep:!0}),e.watch(()=>r.active,async Se=>{if(Se&&!v&&c.value&&c.value.readyState>=2){await ce();return}v&&(Se&&(await e.nextTick(),s.value&&s.value.getBoundingClientRect(),k&&g&&w&&y&&(c.value&&c.value.readyState>=2&&sr(c.value,g,w.width,w.height)&&y.update(),St(),v.renderer&&!v.renderer.destroyed&&v.render())),r.targetFps>=60&&v.ticker&&(Se?v.ticker.start():v.ticker.stop()))}),e.watch(Z,Se=>{Se?(u.value=!0,m.value=void 0,e.nextTick(()=>{c.value&&c.value.load()})):(u.value=!1,m.value="No video source provided")},{immediate:!0});async function ut(){if(c.value){m.value=void 0,Ne(c.value)&&(c.value.currentTime=0);try{await c.value.play();return}catch{if(!c.value.muted){c.value.muted=!0;try{await c.value.play();return}catch{}}}m.value="Unable to start preview playback",l("error",m.value)}}e.watch(()=>r.isPlaying,Se=>{c.value&&(Se?ut():c.value.pause())}),e.watch(()=>r.playhead,Se=>{c.value&&Math.abs(c.value.currentTime-Se)>.5&&Re(Se)}),e.watch(()=>r.fitMode,()=>{St()}),e.onMounted(()=>{D=!1,e.nextTick(()=>{s.value&&s.value.getBoundingClientRect(),c.value}),window.addEventListener("resize",ht),B=performance.now(),e.nextTick(()=>{c.value&&c.value.readyState>=2&&!h.value?ce():c.value&&c.value.src&&c.value.readyState===0&&c.value.load()})}),e.onUnmounted(()=>{if(D=!0,P&&(cancelAnimationFrame(P),P=null),window.removeEventListener("resize",ht),V&&(V.disconnect(),V=null),A&&clearInterval(A),v&&v.ticker&&(v.ticker.stop(),v.ticker.remove(W)),v){try{v.destroy(!0,{children:!0,texture:!0})}catch{}v=null}b.forEach(Se=>{try{Se.destroy()}catch{}}),b=[],k=null,y=null,w=null,g=null,c.value&&(c.value.pause(),c.value.removeAttribute("src"),c.value.load())});async function lt(Se){if(!await Ct()||!c.value||!g||!w||!y)return null;const oe=c.value,De=Number.isFinite(p.value)&&p.value>0?p.value:Number.isFinite(oe.duration)&&oe.duration>0?oe.duration:0,fe=Math.max(0,Math.min(Se,De));return await new Promise(Ye=>{let st=!1,Bt=0;const Vt=()=>{st||(st=!0,oe.removeEventListener("seeked",Lt),window.clearTimeout(Bt),Ye())},Lt=()=>{Vt()},Pt=Number.isFinite(oe.currentTime)?oe.currentTime:0;if(Math.abs(Pt-fe)<.016){requestAnimationFrame(()=>Vt());return}oe.addEventListener("seeked",Lt),Bt=window.setTimeout(()=>Vt(),700),oe.currentTime=fe}),sr(oe,g,w.width,w.height)?(y.update(),v.render(),v.canvas):null}async function Ct(){if(!c.value)return!1;if(!v){if(!(c.value.readyState>=2))return!1;await ce()}if(!v||!k||!g||!w||!y)return!1;if(r.filters&&r.filters.length>0){const Se=k.filters,J=Array.isArray(Se)?Se.length:0,De=JSON.stringify(r.filters)!==R;(J===0||J!==r.filters.length||De)&&U()}return await e.nextTick(),await new Promise(Se=>{requestAnimationFrame(()=>Se())}),!0}return a({captureFrameAt:lt,ensureReadyForCapture:Ct,duration:p,pixiCanvas:e.computed(()=>v?v.canvas:null),videoElement:e.computed(()=>c.value??null)}),(Se,J)=>(e.openBlock(),e.createElementBlock("div",{class:"video-preview",ref_key:"containerRef",ref:s},[e.createElementVNode("div",{class:"canvas-container",ref_key:"canvasContainerRef",ref:d},null,512),e.createElementVNode("video",{ref_key:"videoRef",ref:c,src:Z.value,onLoadedmetadata:Xe,onLoadeddata:be,onCanplay:Ee,onTimeupdate:ye,onEnded:xe,onError:Ce,style:e.normalizeStyle(K.value),crossorigin:O.value,preload:"auto",playsinline:"",controls:""},null,44,Eb),e.createElementVNode("div",Sb,[e.createElementVNode("button",{class:"play-button",onClick:J[0]||(J[0]=oe=>Se.$emit("play-pause")),"aria-label":Se.isPlaying?"Pause":"Play"},[e.createVNode(e.unref(H.IonIcon),{icon:Se.isPlaying?e.unref(lm):e.unref(sm)},null,8,["icon"])],8,Cb),e.createElementVNode("div",xb,[e.createElementVNode("span",Nb,e.toDisplayString(rt(Se.playhead)),1),J[1]||(J[1]=e.createElementVNode("span",{class:"separator"},"/",-1)),e.createElementVNode("span",Vb,e.toDisplayString(rt(p.value)),1)]),Se.showFps?(e.openBlock(),e.createElementBlock("div",Tb,e.toDisplayString(f.value)+" FPS ",1)):e.createCommentVNode("",!0)]),u.value?(e.openBlock(),e.createElementBlock("div",Bb,[e.createVNode(e.unref(H.IonSpinner),{name:"crescent"}),J[2]||(J[2]=e.createElementVNode("p",null,"Loading video...",-1))])):e.createCommentVNode("",!0),m.value?(e.openBlock(),e.createElementBlock("div",Ib,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(td)},null,8,["icon"]),e.createElementVNode("p",null,e.toDisplayString(m.value),1),e.createElementVNode("button",{onClick:at},"Retry")])):e.createCommentVNode("",!0)],512))}}),ps=$e($b,[["__scopeId","data-v-dd1744f4"]]);var od=(o,a,t)=>{if(!a.has(o))throw TypeError("Cannot "+t)},Y=(o,a,t)=>(od(o,a,"read from private field"),t?t.call(o):a.get(o)),nt=(o,a,t)=>{if(a.has(o))throw TypeError("Cannot add the same private member more than once");a instanceof WeakSet?a.add(o):a.set(o,t)},na=(o,a,t,n)=>(od(o,a,"write to private field"),a.set(o,t),t),Fb=(o,a,t,n)=>({set _(i){na(o,a,i)},get _(){return Y(o,a,n)}}),ct=(o,a,t)=>(od(o,a,"access private method"),t),vt=new Uint8Array(8),an=new DataView(vt.buffer),ta=o=>[(o%256+256)%256],kt=o=>(an.setUint16(0,o,!1),[vt[0],vt[1]]),Db=o=>(an.setInt16(0,o,!1),[vt[0],vt[1]]),mm=o=>(an.setUint32(0,o,!1),[vt[1],vt[2],vt[3]]),We=o=>(an.setUint32(0,o,!1),[vt[0],vt[1],vt[2],vt[3]]),Ab=o=>(an.setInt32(0,o,!1),[vt[0],vt[1],vt[2],vt[3]]),Qn=o=>(an.setUint32(0,Math.floor(o/2**32),!1),an.setUint32(4,o,!1),[vt[0],vt[1],vt[2],vt[3],vt[4],vt[5],vt[6],vt[7]]),id=o=>(an.setInt16(0,2**8*o,!1),[vt[0],vt[1]]),Qa=o=>(an.setInt32(0,2**16*o,!1),[vt[0],vt[1],vt[2],vt[3]]),Hl=o=>(an.setInt32(0,2**30*o,!1),[vt[0],vt[1],vt[2],vt[3]]),Ia=(o,a=!1)=>{let t=Array(o.length).fill(null).map((n,i)=>o.charCodeAt(i));return a&&t.push(0),t},Ar=o=>o&&o[o.length-1],rd=o=>{let a;for(let t of o)(!a||t.presentationTimestamp>a.presentationTimestamp)&&(a=t);return a},tn=(o,a,t=!0)=>{let n=o*a;return t?Math.round(n):n},pm=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]},fm=pm(0),hm=o=>[Qa(o[0]),Qa(o[1]),Hl(o[2]),Qa(o[3]),Qa(o[4]),Hl(o[5]),Qa(o[6]),Qa(o[7]),Hl(o[8])],gi=o=>!o||typeof o!="object"?o:Array.isArray(o)?o.map(gi):Object.fromEntries(Object.entries(o).map(([a,t])=>[a,gi(t)])),Do=o=>o>=0&&o<2**32,Yt=(o,a,t)=>({type:o,contents:a&&new Uint8Array(a.flat(10)),children:t}),Rt=(o,a,t,n,i)=>Yt(o,[ta(a),mm(t),n??[]],i),Rb=o=>{let a=512;return o.fragmented?Yt("ftyp",[Ia("iso5"),We(a),Ia("iso5"),Ia("iso6"),Ia("mp41")]):Yt("ftyp",[Ia("isom"),We(a),Ia("isom"),o.holdsAvc?Ia("avc1"):[],Ia("mp41")])},fs=o=>({type:"mdat",largeSize:o}),Lb=o=>({type:"free",size:o}),_r=(o,a,t=!1)=>Yt("moov",null,[Pb(a,o),...o.map(n=>Ub(n,a)),t?g0(o):null]),Pb=(o,a)=>{let t=tn(Math.max(0,...a.filter(l=>l.samples.length>0).map(l=>{const s=rd(l.samples);return s.presentationTimestamp+s.duration})),gs),n=Math.max(...a.map(l=>l.id))+1,i=!Do(o)||!Do(t),r=i?Qn:We;return Rt("mvhd",+i,0,[r(o),r(o),We(gs),r(t),Qa(1),id(1),Array(10).fill(0),hm(fm),Array(24).fill(0),We(n)])},Ub=(o,a)=>Yt("trak",null,[Ob(o,a),zb(o,a)]),Ob=(o,a)=>{let t=rd(o.samples),n=tn(t?t.presentationTimestamp+t.duration:0,gs),i=!Do(a)||!Do(n),r=i?Qn:We,l;return o.info.type==="video"?l=typeof o.info.rotation=="number"?pm(o.info.rotation):o.info.rotation:l=fm,Rt("tkhd",+i,3,[r(a),r(a),We(o.id),We(0),r(n),Array(8).fill(0),kt(0),kt(0),id(o.info.type==="audio"?1:0),kt(0),hm(l),Qa(o.info.type==="video"?o.info.width:0),Qa(o.info.type==="video"?o.info.height:0)])},zb=(o,a)=>Yt("mdia",null,[jb(o,a),Wb(o.info.type==="video"?"vide":"soun"),Hb(o)]),jb=(o,a)=>{let t=rd(o.samples),n=tn(t?t.presentationTimestamp+t.duration:0,o.timescale),i=!Do(a)||!Do(n),r=i?Qn:We;return Rt("mdhd",+i,0,[r(a),r(a),We(o.timescale),r(n),kt(21956),kt(0)])},Wb=o=>Rt("hdlr",0,0,[Ia("mhlr"),Ia(o),We(0),We(0),We(0),Ia("mp4-muxer-hdlr",!0)]),Hb=o=>Yt("minf",null,[o.info.type==="video"?Zb():Gb(),Xb(),qb(o)]),Zb=()=>Rt("vmhd",0,1,[kt(0),kt(0),kt(0),kt(0)]),Gb=()=>Rt("smhd",0,0,[kt(0),kt(0)]),Xb=()=>Yt("dinf",null,[Kb()]),Kb=()=>Rt("dref",0,0,[We(1)],[Jb()]),Jb=()=>Rt("url ",0,1),qb=o=>{const a=o.compositionTimeOffsetTable.length>1||o.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return Yt("stbl",null,[Yb(o),u0(o),m0(o),p0(o),f0(o),h0(o),a?v0(o):null])},Yb=o=>Rt("stsd",0,0,[We(1)],[o.info.type==="video"?Qb(N0[o.info.codec],o):s0(T0[o.info.codec],o)]),Qb=(o,a)=>Yt(o,[Array(6).fill(0),kt(1),kt(0),kt(0),Array(12).fill(0),kt(a.info.width),kt(a.info.height),We(4718592),We(4718592),We(0),kt(1),Array(32).fill(0),kt(24),Db(65535)],[V0[a.info.codec](a),a.info.decoderConfig.colorSpace?n0(a):null]),e0={bt709:1,bt470bg:5,smpte170m:6},t0={bt709:1,smpte170m:6,"iec61966-2-1":13},a0={rgb:0,bt709:1,bt470bg:5,smpte170m:6},n0=o=>Yt("colr",[Ia("nclx"),kt(e0[o.info.decoderConfig.colorSpace.primaries]),kt(t0[o.info.decoderConfig.colorSpace.transfer]),kt(a0[o.info.decoderConfig.colorSpace.matrix]),ta((o.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),o0=o=>o.info.decoderConfig&&Yt("avcC",[...new Uint8Array(o.info.decoderConfig.description)]),i0=o=>o.info.decoderConfig&&Yt("hvcC",[...new Uint8Array(o.info.decoderConfig.description)]),r0=o=>{if(!o.info.decoderConfig)return null;let a=o.info.decoderConfig;if(!a.colorSpace)throw new Error("'colorSpace' is required in the decoder config for VP9.");let t=a.codec.split("."),n=Number(t[1]),i=Number(t[2]),s=(Number(t[3])<<4)+(0<<1)+Number(a.colorSpace.fullRange);return Rt("vpcC",1,0,[ta(n),ta(i),ta(s),ta(2),ta(2),ta(2),kt(0)])},l0=()=>{let t=(1<<7)+1;return Yt("av1C",[t,0,0,0])},s0=(o,a)=>Yt(o,[Array(6).fill(0),kt(1),kt(0),kt(0),We(0),kt(a.info.numberOfChannels),kt(16),kt(0),kt(0),Qa(a.info.sampleRate)],[B0[a.info.codec](a)]),d0=o=>{let a=new Uint8Array(o.info.decoderConfig.description);return Rt("esds",0,0,[We(58753152),ta(32+a.byteLength),kt(1),ta(0),We(75530368),ta(18+a.byteLength),ta(64),ta(21),mm(0),We(130071),We(130071),We(92307584),ta(a.byteLength),...a,We(109084800),ta(1),ta(2)])},c0=o=>{var i;let a=3840,t=0;const n=(i=o.info.decoderConfig)==null?void 0:i.description;if(n){if(n.byteLength<18)throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.");const r=ArrayBuffer.isView(n)?new DataView(n.buffer,n.byteOffset,n.byteLength):new DataView(n);a=r.getUint16(10,!0),t=r.getInt16(14,!0)}return Yt("dOps",[ta(0),ta(o.info.numberOfChannels),kt(a),We(o.info.sampleRate),id(t),ta(0)])},u0=o=>Rt("stts",0,0,[We(o.timeToSampleTable.length),o.timeToSampleTable.map(a=>[We(a.sampleCount),We(a.sampleDelta)])]),m0=o=>{if(o.samples.every(t=>t.type==="key"))return null;let a=[...o.samples.entries()].filter(([,t])=>t.type==="key");return Rt("stss",0,0,[We(a.length),a.map(([t])=>We(t+1))])},p0=o=>Rt("stsc",0,0,[We(o.compactlyCodedChunkTable.length),o.compactlyCodedChunkTable.map(a=>[We(a.firstChunk),We(a.samplesPerChunk),We(1)])]),f0=o=>Rt("stsz",0,0,[We(0),We(o.samples.length),o.samples.map(a=>We(a.size))]),h0=o=>o.finalizedChunks.length>0&&Ar(o.finalizedChunks).offset>=2**32?Rt("co64",0,0,[We(o.finalizedChunks.length),o.finalizedChunks.map(a=>Qn(a.offset))]):Rt("stco",0,0,[We(o.finalizedChunks.length),o.finalizedChunks.map(a=>We(a.offset))]),v0=o=>Rt("ctts",0,0,[We(o.compositionTimeOffsetTable.length),o.compositionTimeOffsetTable.map(a=>[We(a.sampleCount),We(a.sampleCompositionTimeOffset)])]),g0=o=>Yt("mvex",null,o.map(b0)),b0=o=>Rt("trex",0,0,[We(o.id),We(1),We(0),We(0),We(0)]),gc=(o,a)=>Yt("moof",null,[y0(o),...a.map(w0)]),y0=o=>Rt("mfhd",0,0,[We(o)]),vm=o=>{let a=0,t=0,n=0,i=0,r=o.type==="delta";return t|=+r,r?a|=1:a|=2,a<<24|t<<16|n<<8|i},w0=o=>Yt("traf",null,[k0(o),_0(o),E0(o)]),k0=o=>{let a=0;a|=8,a|=16,a|=32,a|=131072;let t=o.currentChunk.samples[1]??o.currentChunk.samples[0],n={duration:t.timescaleUnitsToNextSample,size:t.size,flags:vm(t)};return Rt("tfhd",0,a,[We(o.id),We(n.duration),We(n.size),We(n.flags)])},_0=o=>Rt("tfdt",1,0,[Qn(tn(o.currentChunk.startTimestamp,o.timescale))]),E0=o=>{let a=o.currentChunk.samples.map(v=>v.timescaleUnitsToNextSample),t=o.currentChunk.samples.map(v=>v.size),n=o.currentChunk.samples.map(vm),i=o.currentChunk.samples.map(v=>tn(v.presentationTimestamp-v.decodeTimestamp,o.timescale)),r=new Set(a),l=new Set(t),s=new Set(n),d=new Set(i),c=s.size===2&&n[0]!==n[1],u=r.size>1,m=l.size>1,p=!c&&s.size>1,f=d.size>1||[...d].some(v=>v!==0),h=0;return h|=1,h|=4*+c,h|=256*+u,h|=512*+m,h|=1024*+p,h|=2048*+f,Rt("trun",1,h,[We(o.currentChunk.samples.length),We(o.currentChunk.offset-o.currentChunk.moofOffset||0),c?We(n[0]):[],o.currentChunk.samples.map((v,k)=>[u?We(a[k]):[],m?We(t[k]):[],p?We(n[k]):[],f?Ab(i[k]):[]])])},S0=o=>Yt("mfra",null,[...o.map(C0),x0()]),C0=(o,a)=>Rt("tfra",1,0,[We(o.id),We(63),We(o.finalizedChunks.length),o.finalizedChunks.map(n=>[Qn(tn(n.startTimestamp,o.timescale)),Qn(n.moofOffset),We(a+1),We(1),We(1)])]),x0=()=>Rt("mfro",0,0,[We(0)]),N0={avc:"avc1",hevc:"hvc1",vp9:"vp09",av1:"av01"},V0={avc:o0,hevc:i0,vp9:r0,av1:l0},T0={aac:"mp4a",opus:"Opus"},B0={aac:d0,opus:c0},al=class{},ld=class extends al{constructor(){super(...arguments),this.buffer=null}},gm=class extends al{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.")}},I0=class extends al{constructor(o,a){if(super(),this.stream=o,this.options=a,!(o instanceof FileSystemWritableFileStream))throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");if(a!==void 0&&typeof a!="object")throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");if(a&&a.chunkSize!==void 0&&(!Number.isInteger(a.chunkSize)||a.chunkSize<=0))throw new TypeError("options.chunkSize, when provided, must be a positive integer")}},On,xo,bm=class{constructor(){this.pos=0,nt(this,On,new Uint8Array(8)),nt(this,xo,new DataView(Y(this,On).buffer)),this.offsets=new WeakMap}seek(o){this.pos=o}writeU32(o){Y(this,xo).setUint32(0,o,!1),this.write(Y(this,On).subarray(0,4))}writeU64(o){Y(this,xo).setUint32(0,Math.floor(o/2**32),!1),Y(this,xo).setUint32(4,o,!1),this.write(Y(this,On).subarray(0,8))}writeAscii(o){for(let a=0;a<o.length;a++)Y(this,xo).setUint8(a%8,o.charCodeAt(a)),a%8===7&&this.write(Y(this,On));o.length%8!==0&&this.write(Y(this,On).subarray(0,o.length%8))}writeBox(o){if(this.offsets.set(o,this.pos),o.contents&&!o.children)this.writeBoxHeader(o,o.size??o.contents.byteLength+8),this.write(o.contents);else{let a=this.pos;if(this.writeBoxHeader(o,0),o.contents&&this.write(o.contents),o.children)for(let i of o.children)i&&this.writeBox(i);let t=this.pos,n=o.size??t-a;this.seek(a),this.writeBoxHeader(o,n),this.seek(t)}}writeBoxHeader(o,a){this.writeU32(o.largeSize?1:a),this.writeAscii(o.type),o.largeSize&&this.writeU64(a)}measureBoxHeader(o){return 8+(o.largeSize?8:0)}patchBox(o){let a=this.pos;this.seek(this.offsets.get(o)),this.writeBox(o),this.seek(a)}measureBox(o){if(o.contents&&!o.children)return this.measureBoxHeader(o)+o.contents.byteLength;{let a=this.measureBoxHeader(o);if(o.contents&&(a+=o.contents.byteLength),o.children)for(let t of o.children)t&&(a+=this.measureBox(t));return a}}};On=new WeakMap;xo=new WeakMap;var Er,Jn,Ti,pi,Sr,hs,M0=class extends bm{constructor(o){super(),nt(this,Sr),nt(this,Er,void 0),nt(this,Jn,new ArrayBuffer(2**16)),nt(this,Ti,new Uint8Array(Y(this,Jn))),nt(this,pi,0),na(this,Er,o)}write(o){ct(this,Sr,hs).call(this,this.pos+o.byteLength),Y(this,Ti).set(o,this.pos),this.pos+=o.byteLength,na(this,pi,Math.max(Y(this,pi),this.pos))}finalize(){ct(this,Sr,hs).call(this,this.pos),Y(this,Er).buffer=Y(this,Jn).slice(0,Math.max(Y(this,pi),this.pos))}};Er=new WeakMap;Jn=new WeakMap;Ti=new WeakMap;pi=new WeakMap;Sr=new WeakSet;hs=function(o){let a=Y(this,Jn).byteLength;for(;a<o;)a*=2;if(a===Y(this,Jn).byteLength)return;let t=new ArrayBuffer(a),n=new Uint8Array(t);n.set(Y(this,Ti),0),na(this,Jn,t),na(this,Ti,n)};var $0=2**24,F0=2,bi,zn,fi,un,Va,Rr,vs,sd,ym,dd,wm,yi,Lr,cd=class extends bm{constructor(o){var a,t;super(),nt(this,Rr),nt(this,sd),nt(this,dd),nt(this,yi),nt(this,bi,void 0),nt(this,zn,[]),nt(this,fi,void 0),nt(this,un,void 0),nt(this,Va,[]),na(this,bi,o),na(this,fi,((a=o.options)==null?void 0:a.chunked)??!1),na(this,un,((t=o.options)==null?void 0:t.chunkSize)??$0)}write(o){Y(this,zn).push({data:o.slice(),start:this.pos}),this.pos+=o.byteLength}flush(){var t,n;if(Y(this,zn).length===0)return;let o=[],a=[...Y(this,zn)].sort((i,r)=>i.start-r.start);o.push({start:a[0].start,size:a[0].data.byteLength});for(let i=1;i<a.length;i++){let r=o[o.length-1],l=a[i];l.start<=r.start+r.size?r.size=Math.max(r.size,l.start+l.data.byteLength-r.start):o.push({start:l.start,size:l.data.byteLength})}for(let i of o){i.data=new Uint8Array(i.size);for(let r of Y(this,zn))i.start<=r.start&&r.start<i.start+i.size&&i.data.set(r.data,r.start-i.start);Y(this,fi)?(ct(this,Rr,vs).call(this,i.data,i.start),ct(this,yi,Lr).call(this)):(n=(t=Y(this,bi).options).onData)==null||n.call(t,i.data,i.start)}Y(this,zn).length=0}finalize(){Y(this,fi)&&ct(this,yi,Lr).call(this,!0)}};bi=new WeakMap;zn=new WeakMap;fi=new WeakMap;un=new WeakMap;Va=new WeakMap;Rr=new WeakSet;vs=function(o,a){let t=Y(this,Va).findIndex(s=>s.start<=a&&a<s.start+Y(this,un));t===-1&&(t=ct(this,dd,wm).call(this,a));let n=Y(this,Va)[t],i=a-n.start,r=o.subarray(0,Math.min(Y(this,un)-i,o.byteLength));n.data.set(r,i);let l={start:i,end:i+r.byteLength};if(ct(this,sd,ym).call(this,n,l),n.written[0].start===0&&n.written[0].end===Y(this,un)&&(n.shouldFlush=!0),Y(this,Va).length>F0){for(let s=0;s<Y(this,Va).length-1;s++)Y(this,Va)[s].shouldFlush=!0;ct(this,yi,Lr).call(this)}r.byteLength<o.byteLength&&ct(this,Rr,vs).call(this,o.subarray(r.byteLength),a+r.byteLength)};sd=new WeakSet;ym=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)};dd=new WeakSet;wm=function(o){let t={start:Math.floor(o/Y(this,un))*Y(this,un),data:new Uint8Array(Y(this,un)),written:[],shouldFlush:!1};return Y(this,Va).push(t),Y(this,Va).sort((n,i)=>n.start-i.start),Y(this,Va).indexOf(t)};yi=new WeakSet;Lr=function(o=!1){var a,t;for(let n=0;n<Y(this,Va).length;n++){let i=Y(this,Va)[n];if(!(!i.shouldFlush&&!o)){for(let r of i.written)(t=(a=Y(this,bi).options).onData)==null||t.call(a,i.data.subarray(r.start,r.end),i.start+r.start);Y(this,Va).splice(n--,1)}}};var D0=class extends cd{constructor(o){var a;super(new gm({onData:(t,n)=>o.stream.write({type:"write",data:t,position:n}),chunked:!0,chunkSize:(a=o.options)==null?void 0:a.chunkSize}))}},gs=1e3,A0=["avc","hevc","vp9","av1"],R0=["aac","opus"],L0=2082844800,P0=["strict","offset","cross-track-offset"],Ke,qe,Pr,Na,ra,aa,Vo,To,ud,jn,Wn,wi,bs,km,ys,_m,md,Em,ws,Sm,pd,Cm,Cr,ks,Ya,cn,fd,xm,ki,Ur,Or,hd,Ao,Ai,xr,_s,Nm=class{constructor(o){if(nt(this,bs),nt(this,ys),nt(this,md),nt(this,ws),nt(this,pd),nt(this,Cr),nt(this,Ya),nt(this,fd),nt(this,ki),nt(this,Or),nt(this,Ao),nt(this,xr),nt(this,Ke,void 0),nt(this,qe,void 0),nt(this,Pr,void 0),nt(this,Na,void 0),nt(this,ra,null),nt(this,aa,null),nt(this,Vo,Math.floor(Date.now()/1e3)+L0),nt(this,To,[]),nt(this,ud,1),nt(this,jn,[]),nt(this,Wn,[]),nt(this,wi,!1),ct(this,bs,km).call(this,o),o.video=gi(o.video),o.audio=gi(o.audio),o.fastStart=gi(o.fastStart),this.target=o.target,na(this,Ke,{firstTimestampBehavior:"strict",...o}),o.target instanceof ld)na(this,qe,new M0(o.target));else if(o.target instanceof gm)na(this,qe,new cd(o.target));else if(o.target instanceof I0)na(this,qe,new D0(o.target));else throw new Error(`Invalid target: ${o.target}`);ct(this,ws,Sm).call(this),ct(this,ys,_m).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(ct(this,xr,_s).call(this),!Y(this,Ke).video)throw new Error("No video track declared.");if(typeof Y(this,Ke).fastStart=="object"&&Y(this,ra).samples.length===Y(this,Ke).fastStart.expectedVideoChunks)throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${Y(this,Ke).fastStart.expectedVideoChunks}).`);let l=ct(this,Cr,ks).call(this,Y(this,ra),o,a,t,n,i,r);if(Y(this,Ke).fastStart==="fragmented"&&Y(this,aa)){for(;Y(this,Wn).length>0&&Y(this,Wn)[0].decodeTimestamp<=l.decodeTimestamp;){let s=Y(this,Wn).shift();ct(this,Ya,cn).call(this,Y(this,aa),s)}l.decodeTimestamp<=Y(this,aa).lastDecodeTimestamp?ct(this,Ya,cn).call(this,Y(this,ra),l):Y(this,jn).push(l)}else ct(this,Ya,cn).call(this,Y(this,ra),l)}addAudioChunk(o,a,t){if(!(o instanceof EncodedAudioChunk))throw new TypeError("addAudioChunk's first argument (sample) must be of type EncodedAudioChunk.");if(a&&typeof a!="object")throw new TypeError("addAudioChunk's second argument (meta), when provided, must be an object.");if(t!==void 0&&(!Number.isFinite(t)||t<0))throw new TypeError("addAudioChunk's third argument (timestamp), when provided, must be a non-negative real number.");let n=new Uint8Array(o.byteLength);o.copyTo(n),this.addAudioChunkRaw(n,o.type,t??o.timestamp,o.duration,a)}addAudioChunkRaw(o,a,t,n,i){if(!(o instanceof Uint8Array))throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");if(a!=="key"&&a!=="delta")throw new TypeError("addAudioChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(t)||t<0)throw new TypeError("addAudioChunkRaw's third argument (timestamp) must be a non-negative real number.");if(!Number.isFinite(n)||n<0)throw new TypeError("addAudioChunkRaw's fourth argument (duration) must be a non-negative real number.");if(i&&typeof i!="object")throw new TypeError("addAudioChunkRaw's fifth argument (meta), when provided, must be an object.");if(ct(this,xr,_s).call(this),!Y(this,Ke).audio)throw new Error("No audio track declared.");if(typeof Y(this,Ke).fastStart=="object"&&Y(this,aa).samples.length===Y(this,Ke).fastStart.expectedAudioChunks)throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${Y(this,Ke).fastStart.expectedAudioChunks}).`);let r=ct(this,Cr,ks).call(this,Y(this,aa),o,a,t,n,i);if(Y(this,Ke).fastStart==="fragmented"&&Y(this,ra)){for(;Y(this,jn).length>0&&Y(this,jn)[0].decodeTimestamp<=r.decodeTimestamp;){let l=Y(this,jn).shift();ct(this,Ya,cn).call(this,Y(this,ra),l)}r.decodeTimestamp<=Y(this,ra).lastDecodeTimestamp?ct(this,Ya,cn).call(this,Y(this,aa),r):Y(this,Wn).push(r)}else ct(this,Ya,cn).call(this,Y(this,aa),r)}finalize(){if(Y(this,wi))throw new Error("Cannot finalize a muxer more than once.");if(Y(this,Ke).fastStart==="fragmented"){for(let a of Y(this,jn))ct(this,Ya,cn).call(this,Y(this,ra),a);for(let a of Y(this,Wn))ct(this,Ya,cn).call(this,Y(this,aa),a);ct(this,Or,hd).call(this,!1)}else Y(this,ra)&&ct(this,ki,Ur).call(this,Y(this,ra)),Y(this,aa)&&ct(this,ki,Ur).call(this,Y(this,aa));let o=[Y(this,ra),Y(this,aa)].filter(Boolean);if(Y(this,Ke).fastStart==="in-memory"){let a;for(let n=0;n<2;n++){let i=_r(o,Y(this,Vo)),r=Y(this,qe).measureBox(i);a=Y(this,qe).measureBox(Y(this,Na));let l=Y(this,qe).pos+r+a;for(let s of Y(this,To)){s.offset=l;for(let{data:d}of s.samples)l+=d.byteLength,a+=d.byteLength}if(l<2**32)break;a>=2**32&&(Y(this,Na).largeSize=!0)}let t=_r(o,Y(this,Vo));Y(this,qe).writeBox(t),Y(this,Na).size=a,Y(this,qe).writeBox(Y(this,Na));for(let n of Y(this,To))for(let i of n.samples)Y(this,qe).write(i.data),i.data=null}else if(Y(this,Ke).fastStart==="fragmented"){let a=Y(this,qe).pos,t=S0(o);Y(this,qe).writeBox(t);let n=Y(this,qe).pos-a;Y(this,qe).seek(Y(this,qe).pos-4),Y(this,qe).writeU32(n)}else{let a=Y(this,qe).offsets.get(Y(this,Na)),t=Y(this,qe).pos-a;Y(this,Na).size=t,Y(this,Na).largeSize=t>=2**32,Y(this,qe).patchBox(Y(this,Na));let n=_r(o,Y(this,Vo));if(typeof Y(this,Ke).fastStart=="object"){Y(this,qe).seek(Y(this,Pr)),Y(this,qe).writeBox(n);let i=a-Y(this,qe).pos;Y(this,qe).writeBox(Lb(i))}else Y(this,qe).writeBox(n)}ct(this,Ao,Ai).call(this),Y(this,qe).finalize(),na(this,wi,!0)}};Ke=new WeakMap;qe=new WeakMap;Pr=new WeakMap;Na=new WeakMap;ra=new WeakMap;aa=new WeakMap;Vo=new WeakMap;To=new WeakMap;ud=new WeakMap;jn=new WeakMap;Wn=new WeakMap;wi=new WeakMap;bs=new WeakSet;km=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 al))throw new TypeError("The target must be provided and an instance of Target.");if(o.video){if(!A0.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(!R0.includes(o.audio.codec))throw new TypeError(`Unsupported audio codec: ${o.audio.codec}`);if(!Number.isInteger(o.audio.numberOfChannels)||o.audio.numberOfChannels<=0)throw new TypeError(`Invalid number of audio channels: ${o.audio.numberOfChannels}. Must be a positive integer.`);if(!Number.isInteger(o.audio.sampleRate)||o.audio.sampleRate<=0)throw new TypeError(`Invalid audio sample rate: ${o.audio.sampleRate}. Must be a positive integer.`)}if(o.firstTimestampBehavior&&!P0.includes(o.firstTimestampBehavior))throw new TypeError(`Invalid first timestamp behavior: ${o.firstTimestampBehavior}`);if(typeof o.fastStart=="object"){if(o.video){if(o.fastStart.expectedVideoChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedVideoChunks'.");if(!Number.isInteger(o.fastStart.expectedVideoChunks)||o.fastStart.expectedVideoChunks<0)throw new TypeError("'expectedVideoChunks' must be a non-negative integer.")}if(o.audio){if(o.fastStart.expectedAudioChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedAudioChunks'.");if(!Number.isInteger(o.fastStart.expectedAudioChunks)||o.fastStart.expectedAudioChunks<0)throw new TypeError("'expectedAudioChunks' must be a non-negative integer.")}}else if(![!1,"in-memory","fragmented"].includes(o.fastStart))throw new TypeError("'fastStart' option must be false, 'in-memory', 'fragmented' or an object.");if(o.minFragmentDuration!==void 0&&(!Number.isFinite(o.minFragmentDuration)||o.minFragmentDuration<0))throw new TypeError("'minFragmentDuration' must be a non-negative number.")};ys=new WeakSet;_m=function(){var o;if(Y(this,qe).writeBox(Rb({holdsAvc:((o=Y(this,Ke).video)==null?void 0:o.codec)==="avc",fragmented:Y(this,Ke).fastStart==="fragmented"})),na(this,Pr,Y(this,qe).pos),Y(this,Ke).fastStart==="in-memory")na(this,Na,fs(!1));else if(Y(this,Ke).fastStart!=="fragmented"){if(typeof Y(this,Ke).fastStart=="object"){let a=ct(this,md,Em).call(this);Y(this,qe).seek(Y(this,qe).pos+a)}na(this,Na,fs(!0)),Y(this,qe).writeBox(Y(this,Na))}ct(this,Ao,Ai).call(this)};md=new WeakSet;Em=function(){if(typeof Y(this,Ke).fastStart!="object")return;let o=0,a=[Y(this,Ke).fastStart.expectedVideoChunks,Y(this,Ke).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};ws=new WeakSet;Sm=function(){if(Y(this,Ke).video&&na(this,ra,{id:1,info:{type:"video",codec:Y(this,Ke).video.codec,width:Y(this,Ke).video.width,height:Y(this,Ke).video.height,rotation:Y(this,Ke).video.rotation??0,decoderConfig:null},timescale:Y(this,Ke).video.frameRate??57600,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),Y(this,Ke).audio&&(na(this,aa,{id:Y(this,Ke).video?2:1,info:{type:"audio",codec:Y(this,Ke).audio.codec,numberOfChannels:Y(this,Ke).audio.numberOfChannels,sampleRate:Y(this,Ke).audio.sampleRate,decoderConfig:null},timescale:Y(this,Ke).audio.sampleRate,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),Y(this,Ke).audio.codec==="aac")){let o=ct(this,pd,Cm).call(this,2,Y(this,Ke).audio.sampleRate,Y(this,Ke).audio.numberOfChannels);Y(this,aa).info.decoderConfig={codec:Y(this,Ke).audio.codec,description:o,numberOfChannels:Y(this,Ke).audio.numberOfChannels,sampleRate:Y(this,Ke).audio.sampleRate}}};pd=new WeakSet;Cm=function(o,a,t){let i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350].indexOf(a),r=t,l="";l+=o.toString(2).padStart(5,"0"),l+=i.toString(2).padStart(4,"0"),i===15&&(l+=a.toString(2).padStart(24,"0")),l+=r.toString(2).padStart(4,"0");let s=Math.ceil(l.length/8)*8;l=l.padEnd(s,"0");let d=new Uint8Array(l.length/8);for(let c=0;c<l.length;c+=8)d[c/8]=parseInt(l.slice(c,c+8),2);return d};Cr=new WeakSet;ks=function(o,a,t,n,i,r,l){let s=n/1e6,d=(n-(l??0))/1e6,c=i/1e6,u=ct(this,fd,xm).call(this,s,d,o);return s=u.presentationTimestamp,d=u.decodeTimestamp,r!=null&&r.decoderConfig&&(o.info.decoderConfig===null?o.info.decoderConfig=r.decoderConfig:Object.assign(o.info.decoderConfig,r.decoderConfig)),{presentationTimestamp:s,decodeTimestamp:d,duration:c,data:a,size:a.byteLength,type:t,timescaleUnitsToNextSample:tn(c,o.timescale)}};Ya=new WeakSet;cn=function(o,a){Y(this,Ke).fastStart!=="fragmented"&&o.samples.push(a);const t=tn(a.presentationTimestamp-a.decodeTimestamp,o.timescale);if(o.lastTimescaleUnits!==null){let i=tn(a.decodeTimestamp,o.timescale,!1),r=Math.round(i-o.lastTimescaleUnits);if(o.lastTimescaleUnits+=r,o.lastSample.timescaleUnitsToNextSample=r,Y(this,Ke).fastStart!=="fragmented"){let l=Ar(o.timeToSampleTable);l.sampleCount===1?(l.sampleDelta=r,l.sampleCount++):l.sampleDelta===r?l.sampleCount++:(l.sampleCount--,o.timeToSampleTable.push({sampleCount:2,sampleDelta:r}));const s=Ar(o.compositionTimeOffsetTable);s.sampleCompositionTimeOffset===t?s.sampleCount++:o.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:t})}}else o.lastTimescaleUnits=0,Y(this,Ke).fastStart!=="fragmented"&&(o.timeToSampleTable.push({sampleCount:1,sampleDelta:tn(a.duration,o.timescale)}),o.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:t}));o.lastSample=a;let n=!1;if(!o.currentChunk)n=!0;else{let i=a.presentationTimestamp-o.currentChunk.startTimestamp;if(Y(this,Ke).fastStart==="fragmented"){let r=Y(this,ra)??Y(this,aa);const l=Y(this,Ke).minFragmentDuration??1;o===r&&a.type==="key"&&i>=l&&(n=!0,ct(this,Or,hd).call(this))}else n=i>=.5}n&&(o.currentChunk&&ct(this,ki,Ur).call(this,o),o.currentChunk={startTimestamp:a.presentationTimestamp,samples:[]}),o.currentChunk.samples.push(a)};fd=new WeakSet;xm=function(o,a,t){var l,s;const n=Y(this,Ke).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(Y(this,Ke).firstTimestampBehavior==="offset"||Y(this,Ke).firstTimestampBehavior==="cross-track-offset"){t.firstDecodeTimestamp===void 0&&(t.firstDecodeTimestamp=a);let d;Y(this,Ke).firstTimestampBehavior==="offset"?d=t.firstDecodeTimestamp:d=Math.min(((l=Y(this,ra))==null?void 0:l.firstDecodeTimestamp)??1/0,((s=Y(this,aa))==null?void 0:s.firstDecodeTimestamp)??1/0),a-=d,o-=d}if(a<t.lastDecodeTimestamp)throw new Error(`Timestamps must be monotonically increasing (DTS went from ${t.lastDecodeTimestamp*1e6} to ${a*1e6}).`);return t.lastDecodeTimestamp=a,{presentationTimestamp:o,decodeTimestamp:a}};ki=new WeakSet;Ur=function(o){if(Y(this,Ke).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),Y(this,To).push(o.currentChunk),(o.compactlyCodedChunkTable.length===0||Ar(o.compactlyCodedChunkTable).samplesPerChunk!==o.currentChunk.samples.length)&&o.compactlyCodedChunkTable.push({firstChunk:o.finalizedChunks.length,samplesPerChunk:o.currentChunk.samples.length}),Y(this,Ke).fastStart==="in-memory"){o.currentChunk.offset=0;return}o.currentChunk.offset=Y(this,qe).pos;for(let a of o.currentChunk.samples)Y(this,qe).write(a.data),a.data=null;ct(this,Ao,Ai).call(this)}};Or=new WeakSet;hd=function(o=!0){if(Y(this,Ke).fastStart!=="fragmented")throw new Error("Can't finalize a fragment unless 'fastStart' is set to 'fragmented'.");let a=[Y(this,ra),Y(this,aa)].filter(s=>s&&s.currentChunk);if(a.length===0)return;let t=Fb(this,ud)._++;if(t===1){let s=_r(a,Y(this,Vo),!0);Y(this,qe).writeBox(s)}let n=Y(this,qe).pos,i=gc(t,a);Y(this,qe).writeBox(i);{let s=fs(!1),d=0;for(let u of a)for(let m of u.currentChunk.samples)d+=m.size;let c=Y(this,qe).measureBox(s)+d;c>=2**32&&(s.largeSize=!0,c=Y(this,qe).measureBox(s)+d),s.size=c,Y(this,qe).writeBox(s)}for(let s of a){s.currentChunk.offset=Y(this,qe).pos,s.currentChunk.moofOffset=n;for(let d of s.currentChunk.samples)Y(this,qe).write(d.data),d.data=null}let r=Y(this,qe).pos;Y(this,qe).seek(Y(this,qe).offsets.get(i));let l=gc(t,a);Y(this,qe).writeBox(l),Y(this,qe).seek(r);for(let s of a)s.finalizedChunks.push(s.currentChunk),Y(this,To).push(s.currentChunk),s.currentChunk=null;o&&ct(this,Ao,Ai).call(this)};Ao=new WeakSet;Ai=function(){Y(this,qe)instanceof cd&&Y(this,qe).flush()};xr=new WeakSet;_s=function(){if(Y(this,wi))throw new Error("Cannot add new video or audio chunks after the file has been finalized.")};const Bi=30;class Ro extends Error{constructor({message:t="",code:n=""},...i){super(t,...i);ae(this,"message");ae(this,"code");this.code=n,this.message=t}}class mn extends Ro{}class qt extends Ro{}class zr extends Ro{}class bc extends Ro{}function U0(o,a=Bi){if(a<1)throw new qt({code:"invalidArgument",message:"FPS must be greater or equal to 1"});return Math.round(o*a)}function Bo(o,a=Bi){if(a<1)throw new qt({code:"invalidArgument",message:"FPS must be greater or equal to 1"});return Math.round(o/a*1e3)}class je{constructor(a=0){ae(this,"time");this.time=Math.round(a)}get millis(){return this.time}set millis(a){this.time=Math.round(a)}get frames(){return U0(this.millis/1e3)}set frames(a){this.millis=Bo(a)}get seconds(){return this.millis/1e3}set seconds(a){this.millis=a*1e3}addMillis(a){return this.millis=this.millis+a,this}addFrames(a){const t=Bo(a);return this.millis=this.millis+t,this}add(a){return new je(a.millis+this.millis)}subtract(a){return new je(this.millis-a.millis)}static fromSeconds(a){const t=new je;return t.millis=a*1e3,t}static fromFrames(a,t){const n=new je;return n.millis=Bo(a,t),n}copy(){return new je(this.millis)}toJSON(){return this.millis}static fromJSON(a){return new je(a)}}function yc(o,a){return[o.slice(0,a),o.slice(a)].filter(t=>t.length>0)}function Nr(o,a){return a?Math.floor(Math.random()*(a-o+1)+o):o}function O0(o,a,t){t<0&&(t=0);const n=o[a];o.splice(a,1),o.splice(t,0,n)}function wc(o){return typeof o!="function"?!1:/^class\s/.test(Function.prototype.toString.call(o))}function z0(o){const a=o.numberOfChannels,t=o.length,n=new Int16Array(t*a);for(let i=0;i<t;i++)for(let r=0;r<a;r++){let l=o.getChannelData(r)[i]*32767;l>32767&&(l=32767),l<-32767&&(l=-32767),n[i*a+r]=l}return n}function j0(o,a=44100,t=2){if(o.sampleRate==a&&o.numberOfChannels==t)return o;const n=Math.floor(o.duration*a),i=new OfflineAudioContext(t,1,a).createBuffer(t,n,a);for(let r=0;r<o.numberOfChannels;r++){const l=o.getChannelData(r),s=i.getChannelData(r),d=o.sampleRate/a;for(let c=0;c<s.length;c++){const u=c*d,m=Math.floor(u),p=Math.ceil(u);if(p>=l.length)s[c]=l[m];else{const f=u-m;s[c]=l[m]*(1-f)+l[p]*f}}}return i}async function W0(o){const{fps:a,height:t,width:n,bitrate:i}=o,r=["avc1.640034","avc1.4d0034","avc1.640028","avc1.640C32","avc1.64001f","avc1.42001E"],l=["prefer-hardware","prefer-software"],s=[];for(const c of r)for(const u of l)s.push({codec:c,hardwareAcceleration:u,width:n,height:t,bitrate:i,framerate:a});const d=[];if(!("VideoEncoder"in window))return d;for(const c of s){const u=await VideoEncoder.isConfigSupported(c);u.supported&&d.push(u.config??c)}return d.sort(H0)}function H0(o,a){const t=o.hardwareAcceleration??"",n=a.hardwareAcceleration??"";return t<n?-1:t>n?1:0}async function Z0(o,a="untitled"){const t=document.createElement("a");if(document.head.appendChild(t),t.download=a,typeof o=="string"&&o.startsWith("data:image/svg+xml;base64,")){const n=o.split(",")[1],i=atob(n),r=new Array(i.length);for(let d=0;d<i.length;d++)r[d]=i.charCodeAt(d);const l=new Uint8Array(r),s=new Blob([l],{type:"image/svg+xml"});t.href=URL.createObjectURL(s),t.download=a.split(".")[0]+".svg"}else typeof o=="string"?t.href=o:t.href=URL.createObjectURL(o);t.click(),t.remove()}function kc(o){return`${o.hours.toString().padStart(2,"0")}:${o.minutes.toString().padStart(2,"0")}:${o.seconds.toString().padStart(2,"0")},`+o.milliseconds.toString().padStart(3,"0")}function _c(o){const a=new Date(1970,0,1);return a.setSeconds(o),a.setMilliseconds(Math.round(o%1*1e3)),{hours:a.getHours(),minutes:a.getMinutes(),seconds:a.getSeconds(),milliseconds:a.getMilliseconds()}}class dr{constructor(a){ae(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 je}get stop(){var a;return((a=this.words.at(-1))==null?void 0:a.stop)??new je}}var Es=(o=>(o.en="en",o.de="de",o))(Es||{});class Ec{constructor(a,t,n,i){ae(this,"id",crypto.randomUUID());ae(this,"text");ae(this,"start");ae(this,"stop");ae(this,"confidence");this.text=a,this.start=new je(t),this.stop=new je(n),this.confidence=i}get duration(){return this.stop.subtract(this.start)}}class Zn{constructor(a=[],t=Es.en){ae(this,"id",crypto.randomUUID());ae(this,"language",Es.en);ae(this,"groups",[]);this.groups=a,this.language=t}get text(){return this.groups.map(({text:a})=>a).join(" ")}get words(){return this.groups.flatMap(({words:a})=>a)}*iter({count:a,duration:t,length:n}){for(const i of this.groups){let r;for(const[l,s]of i.words.entries())r&&(a&&r.words.length>=Nr(...a)?(yield r,r=void 0):t&&(r==null?void 0:r.duration.seconds)>=Nr(...t)?(yield r,r=void 0):n&&r.text.length>=Nr(...n)&&(yield r,r=void 0)),r?r.words.push(s):r=new dr([s]),l==i.words.length-1&&(yield r)}}optimize(){const a=this.groups.flatMap(t=>t.words);for(let t=0;t<a.length-1;t++){const n=a[t],i=a[t+1];i.start.millis-n.stop.millis<0?i.start.millis=n.stop.millis+1:n.stop.millis=i.start.millis-1}return this}toSRT(a={}){let t=1,n="";for(const i of this.iter(a)){const r=_c(i.start.seconds),l=_c(i.stop.seconds);n+=`${t}
22
- `+kc(r)+" --> "+kc(l)+`
23
- ${i.text}
24
-
25
- `,t+=1}return{text:n,blob:new Blob([n],{type:"text/plain;charset=utf8"})}}toJSON(){return this.groups.map(a=>a.words.map(t=>({token:t.text,start:t.start.millis,stop:t.stop.millis})))}slice(a,t=!0){let n=0;const i=[];for(const r of this.groups)for(const l of r.words)if(i.length==0&&t&&(n=l.start.millis),i.push(new Ec(l.text,l.start.millis-n,l.stop.millis-n)),i.length==a)return new Zn([new dr(i)]);return new Zn([new dr(i)])}copy(){return Zn.fromJSON(this.toJSON())}static fromJSON(a){const t=new Zn;for(const n of a){const i=new dr;for(const r of n)i.words.push(new Ec(r.token,r.start,r.stop));t.groups.push(i)}return t}static async from(a,t){const n=await fetch(a,t);if(!n.ok)throw new mn({code:"unexpectedIOError",message:"An unexpected error occurred while fetching the file"});return Zn.fromJSON(await n.json())}}function Vr(o,a,t){return o+(a-o)*t}function G0(o,a,t){const n=Number.parseInt(o.slice(1),16),i=Number.parseInt(a.slice(1),16),r=n>>16&255,l=n>>8&255,s=n&255,d=i>>16&255,c=i>>8&255,u=i&255,m=Math.round(Vr(r,d,t)),p=Math.round(Vr(l,c,t)),f=Math.round(Vr(s,u,t));return`#${((1<<24)+(m<<16)+(p<<8)+f).toString(16).slice(1)}`}const X0={linear:o=>o,easeIn:o=>o*o,easeOut:o=>o*(2-o),easeInOut:o=>o<.5?2*o*o:-1+(4-2*o)*o};class Ge{constructor(a,t,n={}){ae(this,"input");ae(this,"output");ae(this,"options");if(a.length!==t.length)throw new qt({code:"invalidKeyframes",message:"inputRange and outputRange must have the same length"});this.input=a.map(i=>Bo(i)),this.output=t,this.options={extrapolate:"clamp",easing:"linear",type:"number",...JSON.parse(JSON.stringify(n))}}normalize(a){const{input:t}=this;if(a<t[0])return this.options.extrapolate==="clamp"?{t:0,segment:0}:{t:(a-t[0])/(t[1]-t[0]),segment:0};if(a>t[t.length-1])return this.options.extrapolate==="clamp"?{t:1,segment:t.length-2}:{t:(a-t[t.length-2])/(t[t.length-1]-t[t.length-2]),segment:t.length-2};for(let n=0;n<t.length-1;n++){const i=t[n],r=t[n+1];if(a>=i&&a<=r)return{t:(a-i)/(r-i),segment:n}}return{t:0,segment:0}}interpolate(a,t){const n=this.output[t],i=this.output[t+1],r=X0[this.options.easing](a);if(typeof n=="number"&&typeof i=="number")return Vr(n,i,r);if(typeof n=="string"&&typeof i=="string")return G0(n,i,r);if(this.output.length==1)return this.output[0];throw new qt({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 Ge([],[]);return Object.assign(t,a),t}}class $a{constructor(){ae(this,"id",crypto.randomUUID())}toJSON(){const a={};return(this.constructor.__serializableProperties||[]).forEach(({propertyKey:t,serializer:n})=>{const i=this[t];n&&i instanceof n?a[t]=i.toJSON():a[t]=i}),a}static fromJSON(a){const t=new this;return(this.__serializableProperties||[]).forEach(({propertyKey:n,serializer:i})=>{if(a.hasOwnProperty(n))if(i){const r=i.fromJSON(a[n]);t[n]=r}else t[n]=a[n]}),t}}function Le(o){return function(a,t){a.constructor.__serializableProperties||(a.constructor.__serializableProperties=[]),a.constructor.__serializableProperties.push({propertyKey:t,serializer:o})}}function Ri(o){return class extends o{constructor(){super(...arguments);ae(this,"_handlers",{})}on(t,n){if(typeof n!="function")throw new Error("The callback of an event listener needs to be a function.");const i=crypto.randomUUID();return this._handlers[t]?this._handlers[t][i]=n:this._handlers[t]={[i]:n},i}off(t,...n){if(t){if(t==="*"){this._handlers={};return}for(const i of Object.values(this._handlers))t in i&&delete i[t];for(const i of n)this.off(i)}}trigger(t,n){var r,l;const i=new CustomEvent(t,{detail:n});Object.defineProperty(i,"currentTarget",{writable:!1,value:this});for(const s in this._handlers[t]??{})(r=this._handlers[t])==null||r[s](i);for(const s in this._handlers["*"]??{})(l=this._handlers["*"])==null||l[s](i)}bubble(t){return this.on("*",n=>{t.trigger(n.type,n.detail)})}resolve(t){return(n,i)=>{this.on("error",i),this.on(t,n)}}}}function vd(o,a,t=0){if(!(o instanceof $t.Container||o instanceof $t.Filter||t==3))for(const n in o){const i=o[n];n&&(i instanceof Ge&&(o[n]=i.value(a)),i!=null&&typeof i=="object"&&Object.keys(i).length&&vd(i,a,t+1))}}var K0=Object.defineProperty,nl=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&K0(a,t,i),i};const Li=class Vm extends Ri($a){constructor(t={}){super();ae(this,"_name");ae(this,"_start",new je);ae(this,"_stop",je.fromSeconds(16));ae(this,"type","base");ae(this,"source");ae(this,"view",new $t.Container);ae(this,"createdAt",new Date);ae(this,"disabled",!1);ae(this,"state","IDLE");ae(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",je.fromFrames(t))):(this.start.addMillis(t.millis),this.stop.addMillis(t.millis),this.trigger("offsetBy",t)),this.trigger("frame",void 0),this}async init(){}enter(){}update(t){}exit(){}detach(){var t;return(t=this.track)==null||t.remove(this),this}async split(t){var r,l;if(t||(t=(l=(r=this.track)==null?void 0:r.composition)==null?void 0:l.frame),typeof t=="number"&&(t=je.fromFrames(t)),!t||t.millis<=this.start.millis||t.millis>=this.stop.millis)throw new qt({code:"splitOutOfRange",message:"Cannot split clip at the specified time"});if(!this.track)throw new qt({code:"trackNotAttached",message:"Track must be attached to a track"});const n=this.copy();this.stop=t.copy(),n.start=t.copy().addMillis(1),vd(n,n.start.subtract(this.start));const i=this.track.clips.findIndex(s=>s.id==this.id);return await this.track.add(n,i+1),n}copy(){return Vm.fromJSON(JSON.parse(JSON.stringify(this)))}set(t){return t&&Object.assign(this,t),this.trigger("update",void 0),this}};nl([Le()],Li.prototype,"_name");nl([Le(je)],Li.prototype,"_start");nl([Le(je)],Li.prototype,"_stop");nl([Le()],Li.prototype,"disabled");let Pi=Li;var J0=Object.defineProperty,ro=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&J0(a,t,i),i};class nn extends Ri($a){constructor(){super(...arguments);ae(this,"state","IDLE");ae(this,"metadata");ae(this,"objectURL");ae(this,"duration",je.fromSeconds(16));ae(this,"added",!1);ae(this,"type","base");ae(this,"name","");ae(this,"mimeType");ae(this,"externalURL");ae(this,"external",!1);ae(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 qt({code:"fileNotAccessible",message:"The desired file cannot be accessed"});return this.file}async loadFile(t){this.name=t.name,this.mimeType=Ns(t.type),this.external=!1,this.file=t}async loadUrl(t,n){const i=await fetch(t,n);if(!(i!=null&&i.ok))throw new mn({code:"unexpectedIOError",message:"An unexpected error occurred while fetching the file"});const r=await i.blob();this.name=t.toString().split("/").at(-1)??"",this.external=!0,this.file=new File([r],this.name,{type:r.type}),this.externalURL=t,this.mimeType=Ns(r.type)}async from(t,n){try{this.state="LOADING",t instanceof File?await this.loadFile(t):await this.loadUrl(t,n),this.state="READY",this.trigger("load",void 0)}catch(i){throw this.state=="ERROR",this.trigger("error",new Error(String(i))),i}return this}async arrayBuffer(){return await(await this.getFile()).arrayBuffer()}async remove(){this.state="IDLE",this.objectURL&&(URL.revokeObjectURL(this.objectURL),this.objectURL=void 0),delete this.file}async download(){const t=await this.getFile();Z0(t,this.name)}async thumbnail(){return document.createElement("div")}static async from(t,n,i=new this){return i.from(t,n)}}ro([Le()],nn.prototype,"objectURL");ro([Le()],nn.prototype,"duration");ro([Le()],nn.prototype,"type");ro([Le()],nn.prototype,"name");ro([Le()],nn.prototype,"mimeType");ro([Le()],nn.prototype,"externalURL");ro([Le()],nn.prototype,"external");const Sc="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3C/svg%3E";function q0(o){const a=new TextEncoder().encode(o);let t="";const n=a.byteLength;for(let i=0;i<n;i++)t+=String.fromCharCode(a[i]);return btoa(t)}function Cc(o){if(!o||!o.body)return Sc;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 Sc;const l=new XMLSerializer,s=i?l.serializeToString(i):"",d=l.serializeToString(r),c=`
26
- <svg xmlns="http://www.w3.org/2000/svg" width="${a}" height="${t}">
27
- body { padding: 0; }
28
- ${s}
29
- <foreignObject width="100%" height="100%">
30
- ${d}
31
- </foreignObject>
32
- </svg>`;return"data:image/svg+xml;base64,"+q0(c)}class xc extends nn{constructor(){super();ae(this,"type","html");ae(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=l=>r(l)})}async loadFile(t){await super.loadFile(t),this.iframe.setAttribute("src",URL.createObjectURL(this.file)),await new Promise((n,i)=>{this.iframe.onload=()=>n(),this.iframe.onerror=r=>i(r)})}update(){this.objectURL&&(this.objectURL=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 Y0(o,a={}){const{threshold:t=.02,hopSize:n=1024,minDuration:i=500}=a,r=[],l=o.getChannelData(0),s=o.sampleRate,d=Math.floor(i/1e3*s);let c=null,u=0;for(let m=0;m<l.length;m+=n){let p=0;const f=Math.min(m+n,l.length);for(let h=m;h<f;h++)p+=l[h]*l[h];p=Math.sqrt(p/(f-m)),p<t?(u+=n,c===null&&(c=m)):(c!==null&&u>=d&&r.push({start:je.fromSeconds(c/s),stop:je.fromSeconds(m/s)}),c=null,u=0)}return c!==null&&u>=d&&r.push({start:je.fromSeconds(c/s),stop:je.fromSeconds(l.length/s)}),r}const Zl=3e3;class xn extends nn{constructor(){super(...arguments);ae(this,"type","audio");ae(this,"decoding",!1);ae(this,"_silences");ae(this,"transcript");ae(this,"audioBuffer")}async decode(t=2,n=48e3,i=!1){if(this.decoding&&i&&(await new Promise(this.resolve("update")),this.audioBuffer))return this.audioBuffer;this.decoding=!0;const r=await this.arrayBuffer(),l=await new OfflineAudioContext(t,1,n).decodeAudioData(r);return this.duration.seconds=l.duration,i&&(this.audioBuffer=l),this.decoding=!1,this.trigger("update",void 0),l}async samples(t=60,n=50,i=0){const r=this.audioBuffer??await this.decode(1,3e3,!0),l=Math.round(r.sampleRate/n),s=r.sampleRate*r.duration-l,d=Math.ceil(s/t),c=r.getChannelData(0),u=[];for(let m=0;m<s;m+=d){let p=0;for(let f=m;f<m+l;f++)p+=Math.abs(c[m]);u.push(Math.log1p(p/l*100))}return u.map(m=>Math.round(m/Math.max(...u)*(100-i))+i)}async fastsampler({length:t=60,start:n=0,stop:i,logarithmic:r=!1}={}){typeof n=="object"&&(n=n.millis),typeof i=="object"&&(i=i.millis);const l=this.audioBuffer??await this.decode(1,Zl,!0),s=l.getChannelData(0),d=Math.floor(Math.max(n*Zl/1e3,0)),c=i?Math.floor(Math.min(i*Zl/1e3,l.length)):l.length,u=Math.floor((c-d)/t),m=new Float32Array(t);for(let p=0;p<t;p++){const f=d+p*u,h=f+u;let v=-1/0;for(let k=f;k<h;k++){const y=s[k];y>v&&(v=y)}m[p]=r?Math.log2(1+v):v}return m}async thumbnail(...t){const n=await this.samples(...t),i=document.createElement("div");i.className="flex flex-row absolute space-between inset-0 audio-samples";for(const r of n){const l=document.createElement("div");l.className="audio-sample-item",l.style.height=`${r}%`,i.appendChild(l)}return i}async silences(t={}){if(this._silences)return this._silences;const n=await this.arrayBuffer(),i=new AudioContext,r=await i.decodeAudioData(n);return this._silences=Y0(r,t),i.close(),this._silences}}class Ss extends nn{constructor(){super(...arguments);ae(this,"type","image")}async thumbnail(){const t=new Image;return t.src=await this.createObjectURL(),t.className="object-cover w-full aspect-video h-auto",t}}class Xn extends xn{constructor(){super(...arguments);ae(this,"type","video");ae(this,"downloadInProgress",!0)}async loadUrl(t,n){const i=await fetch(t,n);if(!(i!=null&&i.ok))throw new mn({code:"unexpectedIOError",message:"An unexpected error occurred while fetching the file"});this.name=t.toString().split("/").at(-1)??"",this.external=!0,this.externalURL=t,this.objectURL=String(t),this.mimeType=Ns(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 qt({code:"fileNotAccessible",message:"The desired file cannot be accessed"});return this.file}async thumbnail(){const t=document.createElement("video");return t.className="object-cover w-full aspect-video h-auto",t.controls=!1,t.addEventListener("loadedmetadata",()=>{this.duration.seconds=t.duration,this.trigger("update",void 0)}),t.addEventListener("mousemove",n=>{const i=n.currentTarget,r=i==null?void 0:i.getBoundingClientRect(),l=n.clientX-((r==null?void 0:r.left)??0),s=i==null?void 0:i.duration;s&&r&&r.width>0&&(i.currentTime=Math.round(s*(l/r.width)))}),t.src=await this.createObjectURL(),t}async getBlob(t){try{this.downloadInProgress=!0;const n=await t.blob();this.file=new File([n],this.name,{type:n.type}),this.trigger("load",void 0)}catch(n){this.state=="ERROR",this.trigger("error",new Error(String(n)))}finally{this.downloadInProgress=!1}}}class Q0{static fromJSON(a){return[new je(a[0]),new je(a[1])]}}var ey=Object.defineProperty,ty=Object.getOwnPropertyDescriptor,Po=(o,a,t,n)=>{for(var i=n>1?void 0:n?ty(a,t):a,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=(n?l(a,t,i):l(i))||i);return n&&i&&ey(a,t,i),i};const lo=class Tm extends Pi{constructor(t={}){super();ae(this,"source",new xn);ae(this,"_offset",new je);ae(this,"playing",!1);ae(this,"duration",new je);ae(this,"range",[new je,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=je.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=je.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",je.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 bc({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=je.fromFrames(t)),typeof n=="number"&&(n=je.fromFrames(n)),t.millis>=n.millis)throw new qt({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=Tm.fromJSON(JSON.parse(JSON.stringify(this)));return t.source=this.source,t}async split(t){var r,l;if(t||(t=(l=(r=this.track)==null?void 0:r.composition)==null?void 0:l.frame),typeof t=="number"&&(t=je.fromFrames(t)),!t||t.millis<=this.start.millis||t.millis>=this.stop.millis)throw new qt({code:"invalidKeyframe",message:"Cannot split clip at the specified time"});if(!this.track)throw new bc({code:"trackNotDefined",message:"Clip must be attached to a track"});t=t.subtract(this.offset);const n=this.copy();this.range[1]=t.copy(),n.range[0]=t.copy().addMillis(1),vd(n,n.start.subtract(this.start));const i=this.track.clips.findIndex(s=>s.id==this.id);return await this.track.add(n,i+1),n}async addCaptions(t){var n;if(!((n=this.track)!=null&&n.composition))throw new qt({code:"compositionNotDefined",message:"Captions can only be generated after the clip has been added to the composition"});return await this.track.composition.createTrack("caption").from(this).generate(t)}set(t){return super.set(t)}async generateCaptions(t){return this.addCaptions(t)}async removeSilences(t={}){["READY","ATTACHED"].includes(this.state)||await this.init();const n=(await this.source.silences(t)).filter(l=>Nc(l,this.range)).sort((l,s)=>l.start.millis-s.start.millis);if(n.length==0)return[this];const i=t.padding??500,r=[this];for(const l of n){const s=r.at(-1);if(!s)break;if(!Nc(l,s.range))continue;const d=new je(Math.min(l.start.millis+i,l.stop.millis));if(l.start.millis>s.range[0].millis&&l.stop.millis<s.range[1].millis){const c=s.copy();s.range[1]=d,c.range[0]=l.stop,r.push(c)}else l.start.millis<=s.range[0].millis?s.range[0]=l.stop:l.stop.millis>=s.range[1].millis&&(s.range[1]=d)}return r}};Po([Le(je)],lo.prototype,"_offset",2);Po([Le(je)],lo.prototype,"duration",2);Po([Le(Q0)],lo.prototype,"range",2);Po([Le(Zn)],lo.prototype,"transcript",1);Po([Le()],lo.prototype,"muted",1);Po([Le()],lo.prototype,"volume",1);let ol=lo;function Nc(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 cr{static fromJSON(a){return typeof a=="object"?Ge.fromJSON(a):a}}class Gl{static fromJSON(a){return typeof a.x=="object"&&(a.x=Ge.fromJSON(a.x)),typeof a.y=="object"&&(a.y=Ge.fromJSON(a.y)),a}}let ay=class{constructor(o){ae(this,"target");ae(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 Ge(i,r,{easing:n})}};function ny(o){const a=new Proxy(o,{get(t,n){return n=="to"?(i,r)=>{if(!t.animation)throw new qt({code:"undefinedKeyframe",message:"Cannot use 'to() before selecting a property"});const l=new je(t.animation.input.at(-1)).frames+r;return t.animation.push(l,i),a}:(i,r,l)=>(t.init(n,i,r,l),a)}});return a}class oy extends ay{}var iy=Object.defineProperty,ry=Object.getOwnPropertyDescriptor,En=(o,a,t,n)=>{for(var i=n>1?void 0:n?ry(a,t):a,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=(n?l(a,t,i):l(i))||i);return n&&i&&iy(a,t,i),i};function il(o){class a extends o{constructor(){super(...arguments);ae(this,"filters");ae(this,"_height");ae(this,"_width");ae(this,"_position",{x:this.view.position.x,y:this.view.position.y});ae(this,"_scale");ae(this,"rotation",this.view.angle);ae(this,"alpha",1);ae(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 Ge||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 $t.Sprite?{x:this.view.children[0].anchor.x,y:this.view.children[0].anchor.y}:{x:0,y:0}}set anchor(i){const r=typeof i=="number"?{x:i,y:i}:i;for(const l of this.view.children)l instanceof $t.Sprite&&l.anchor.set(r.x,r.y)}enter(){this.filters&&!this.view.filters&&(this.view.filters=this.filters)}exit(){this.filters&&this.view.filters&&(this.view.filters=null)}animate(){return ny(new oy(this))}}return En([Le(cr)],a.prototype,"_height",2),En([Le(cr)],a.prototype,"_width",2),En([Le(Gl)],a.prototype,"_position",2),En([Le(Gl)],a.prototype,"_scale",2),En([Le(cr)],a.prototype,"rotation",2),En([Le(cr)],a.prototype,"alpha",2),En([Le(Gl)],a.prototype,"translate",2),En([Le()],a.prototype,"anchor",1),a}function rl(o,a,t){const n=t.value;return t.value=function(...i){var m,p,f,h;const r=i[0].subtract(this.start),l={width:((p=(m=this.track)==null?void 0:m.composition)==null?void 0:p.width)??1920,height:((h=(f=this.track)==null?void 0:f.composition)==null?void 0:h.height)??1080};let s;typeof this.translate.x=="number"?s=this.translate.x:typeof this.translate.x=="function"?s=this.translate.x.bind(this)(r):s=this.translate.x.value(r);let d;typeof this.translate.y=="number"?d=this.translate.y:typeof this.translate.y=="function"?d=this.translate.y.bind(this)(r):d=this.translate.y.value(r);let c;typeof this._position.x=="number"?c=this._position.x:typeof this._position.x=="string"?c=Number.parseFloat(this._position.x)*l.width/100:typeof this._position.x=="function"?c=this._position.x.bind(this)(r):c=this._position.x.value(r);let u;if(typeof this._position.y=="number"?u=this._position.y:typeof this._position.y=="string"?u=Number.parseFloat(this._position.y)*l.height/100:typeof this._position.y=="function"?u=this._position.y.bind(this)(r):u=this._position.y.value(r),this.view.position.set(c+s,u+d),typeof this._height=="string"?this.view.height=Math.round(Number.parseFloat(this._height)*l.height/100):typeof this._height=="object"?this.view.height=this._height.value(r):typeof this._height=="function"?this.view.height=this._height.bind(this)(r):this._height&&(this.view.height=this._height),this._height&&!this._width&&this.view.scale.set(this.view.scale.y),typeof this._width=="string"?this.view.width=Math.round(Number.parseFloat(this._width)*l.width/100):typeof this._width=="object"?this.view.width=this._width.value(r):typeof this._width=="function"?this.view.width=this._width.bind(this)(r):this._width&&(this.view.width=this._width),this._width&&!this._height&&this.view.scale.set(this.view.scale.x),this._scale){let v;typeof this._scale.x=="number"?v=this._scale.x:typeof this._scale.x=="function"?v=this._scale.x.bind(this)(r):v=this._scale.x.value(r);let k;typeof this._scale.y=="number"?k=this._scale.y:typeof this._scale.y=="function"?k=this._scale.y.bind(this)(r):k=this._scale.y.value(r),(this._width||this._height)&&(v*=this.view.scale._x,k*=this.view.scale._y),this.view.scale.set(v,k)}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 ly=Object.defineProperty,sy=Object.getOwnPropertyDescriptor,dy=(o,a,t,n)=>{for(var i=sy(a,t),r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&ly(a,t,i),i};const Bm=class Im extends il(Pi){constructor(t,n={}){super();ae(this,"type","image");ae(this,"element",new Image);ae(this,"source",new Ss);ae(this,"sprite",new $t.Sprite);this.view.addChild(this.sprite),t instanceof Ss&&(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=$t.Texture.from(this.element),this.state="READY",t()},this.element.onerror=i=>{this.state="ERROR",n(new mn({code:"sourceNotProcessable",message:"An error occurred while processing the input medium."}))}})}update(t){}copy(){const t=Im.fromJSON(JSON.parse(JSON.stringify(this)));return t.filters=this.filters,t.source=this.source,t}};dy([rl],Bm.prototype,"update");let cy=Bm;const ur={"The Bold Font":{weights:["500"],url:"https://diffusion-studio-public.s3.eu-central-1.amazonaws.com/fonts/the-bold-font.ttf"},"Komika Axis":{weights:["400"],url:"https://diffusion-studio-public.s3.eu-central-1.amazonaws.com/fonts/komika-axis.ttf"},Geologica:{weights:["100","200","300","400","500","600","700","800","900"],url:"https://fonts.gstatic.com/s/geologica/v1/oY1l8evIr7j9P3TN9YwNAdyjzUyDKkKdAGOJh1UlCDUIhAIdhCZOn1fLsig7jfvCCPHZckUWE1lELWNN-w.woff2"},Figtree:{weights:["300","400","500","600","700","800","900"],url:"https://fonts.gstatic.com/s/figtree/v5/_Xms-HUzqDCFdgfMm4S9DaRvzig.woff2"},Urbanist:{weights:["100","200","300","400","500","600","700","800","900"],url:"https://fonts.gstatic.com/s/urbanist/v15/L0x-DF02iFML4hGCyMqlbS1miXK2.woff2"},Montserrat:{weights:["100","200","300","400","500","600","700","800","900"],url:"https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459WlhyyTh89Y.woff2"},Bangers:{weights:["400"],url:"https://fonts.gstatic.com/s/bangers/v20/FeVQS0BTqb0h60ACH55Q2J5hm24.woff2"},Chewy:{weights:["400"],url:"https://fonts.gstatic.com/s/chewy/v18/uK_94ruUb-k-wn52KjI9OPec.woff2"},"Source Code Pro":{weights:["200","300","400","500","600","700","800","900"],url:"https://fonts.gstatic.com/s/sourcecodepro/v22/HI_SiYsKILxRpg3hIP6sJ7fM7PqlPevWnsUnxg.woff2"}};var uy=Object.defineProperty,ll=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&uy(a,t,i),i};const Ui=class Cs extends Ri($a){constructor(t){super();ae(this,"loaded",!1);ae(this,"family");ae(this,"weight");ae(this,"source");ae(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=Cs.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(ur).map(t=>({family:t,variants:ur[t].weights.map(n=>({family:t,source:`url(${ur[t].url})`,weight:n}))}))}static fromFamily({family:t,weight:n}){return new Cs({family:t,source:`url(${ur[t].url})`,weight:n})}};ll([Le()],Ui.prototype,"family");ll([Le()],Ui.prototype,"weight");ll([Le()],Ui.prototype,"source");ll([Le()],Ui.prototype,"style");let ua=Ui;const en=4,Mm={center:.5,justify:.5,left:0,right:1},$m={alphabetic:0,top:0,middle:.5,hanging:1,bottom:1,ideographic:1};var my=Object.defineProperty,py=Object.getOwnPropertyDescriptor,ka=(o,a,t,n)=>{for(var i=py(a,t),r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&my(a,t,i),i};const fa=class Fm extends il(Pi){constructor(t){super();ae(this,"type","text");ae(this,"_text","");ae(this,"_textCase");ae(this,"_anchor",{x:0,y:0});ae(this,"_font",new ua);ae(this,"style",new $t.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 $t.Text({text:this.transformedText,style:this.style,resolution:en,scale:en});this.view.addChild(n)}this.view.children[0]instanceof $t.Text&&this.transformedText&&(this.view.children[0].text=this.transformedText)}get name(){return this._text}get font(){return this._font}set font(t){if(this._font=t,t.loaded){this.style.fontFamily=t.name;return}this._font.load().then(()=>{this.style.fontFamily=t.name,this.trigger("update",void 0)})}get maxWidth(){if(this.style.wordWrap)return this.style.wordWrapWidth*en}set maxWidth(t){t?(this.style.wordWrap=!0,this.style.wordWrapWidth=t/en):this.style.wordWrap=!1}get textAlign(){return this.style.align}set textAlign(t){this.style.align=t,this.anchor.x=Mm[t]}get padding(){return this.style.padding}set padding(t){this.style.padding=t}get textBaseline(){return this.style.textBaseline}set textBaseline(t){this.style.textBaseline=t,this.anchor.y=$m[t]}get fillStyle(){const{fill:t}=this.style;return new $t.Color(t.toString()).toHex().toUpperCase()}set fillStyle(t){this.style.fill=t}get anchor(){return this._anchor}set anchor(t){typeof t=="number"?this._anchor={x:t,y:t}:this._anchor=t}get stroke(){if(!this.style.stroke)return;let{color:t="#000000",alpha:n=1,width:i=3,join:r="round",miterLimit:l}=this.style.stroke;return t=new $t.Color(t).toHex().toUpperCase(),{color:t,alpha:n,width:i,join:r,miterLimit:l}}set stroke(t){if(!t){this.style.stroke=void 0;return}const{color:n="#000000",alpha:i=1,width:r=3,join:l="round",miterLimit:s}=t;this.style.stroke={color:n,alpha:i,width:r,join:l,miterLimit:s}}get textCase(){return this._textCase}set textCase(t){this._textCase=t,this.view.children[0]instanceof $t.Text&&this.transformedText&&(this.view.children[0].text=this.transformedText)}get shadow(){if(!this.style.dropShadow)return;const{alpha:t,angle:n,blur:i,color:r,distance:l}=this.style.dropShadow,s=new $t.Color(r).toHex().toUpperCase();return{alpha:t,angle:n,blur:i,color:s,distance:l}}set shadow(t){t?this.style.dropShadow=t:this.style.dropShadow=!1}get fontFamily(){return Array.isArray(this.style.fontFamily)?this.style.fontFamily[0]:this.style.fontFamily}get fontSize(){return this.style.fontSize}set fontSize(t){this.style.fontSize=t}get leading(){return this.style.leading}set leading(t){this.style.leading=t}update(t){}copy(){const t=Fm.fromJSON(JSON.parse(JSON.stringify(this)));return t.filters=this.filters,t.font=this.font,t}get transformedText(){return this.textCase=="lower"?this._text.toLocaleLowerCase():this.textCase=="upper"?this._text.toUpperCase():this._text}reflectUpdate(){var r,l,s;const t=((r=this.view.children[0])==null?void 0:r.width)??0,n=((l=this.view.children[0])==null?void 0:l.height)??0,i=(((s=this.style.dropShadow)==null?void 0:s.distance)??0)*en;this.view.pivot={x:(t-i)*this._anchor.x,y:(n-i)*this._anchor.y}}set(t){return super.set(t)}};ka([Le()],fa.prototype,"text");ka([Le(ua)],fa.prototype,"font");ka([Le()],fa.prototype,"maxWidth");ka([Le()],fa.prototype,"textAlign");ka([Le()],fa.prototype,"padding");ka([Le()],fa.prototype,"textBaseline");ka([Le()],fa.prototype,"fillStyle");ka([Le()],fa.prototype,"anchor");ka([Le()],fa.prototype,"stroke");ka([Le()],fa.prototype,"textCase");ka([Le()],fa.prototype,"shadow");ka([Le()],fa.prototype,"fontSize");ka([Le()],fa.prototype,"leading");ka([rl],fa.prototype,"update");let Uo=fa;function Xl(o){const a=o.split(" ").map(t=>`${t} `);return a[a.length-1]=a[a.length-1].replace(/ $/,""),a}const fy={get(o,a){const t=o[a];return typeof t=="number"?t*en:Array.isArray(t)&&typeof t[0]=="number"?t.map(n=>n*en):t}};function hy(o){return new Proxy(o,fy)}class vy{constructor(){ae(this,"tokens",[])}get width(){return this.tokens.reduce((a,t)=>a+t.metrics.lineWidths[0],0)}get height(){return Math.max(...this.tokens.map(a=>a.metrics.lineHeight))}}class Vc{constructor(){ae(this,"lines",[])}get width(){return Math.max(...this.lines.map(a=>a.width))}get height(){return this.lines.reduce((a,t)=>a+t.height,0)}}class gy{static fromJSON(a){return a.map(t=>(t.font&&(t.font=ua.fromJSON(t.font)),t))}}var by=Object.defineProperty,yy=Object.getOwnPropertyDescriptor,Oo=(o,a,t,n)=>{for(var i=n>1?void 0:n?yy(a,t):a,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=(n?l(a,t,i):l(i))||i);return n&&i&&by(a,t,i),i};const so=class Dm extends Uo{constructor(t){super();ae(this,"type","complex_text");ae(this,"_maxWidth");ae(this,"_textAlign","left");ae(this,"_textBaseline","top");ae(this,"model",new $t.Container);ae(this,"segments",[]);ae(this,"metrics",new Vc);ae(this,"background");ae(this,"styles");this.view.addChild(this.model),typeof t=="string"?(this.text=t,this.reflectUpdate()):t&&(Object.assign(this,t),this.reflectUpdate())}get text(){return this._text}set text(t){this._text=t}get maxWidth(){return this._maxWidth}set maxWidth(t){this._maxWidth=t}get textAlign(){return this._textAlign}set textAlign(t){this._textAlign=t,this._anchor.x=Mm[t];const n=this.metrics.width;for(const i of this.metrics.lines){let r=0;(t=="center"||t=="justify")&&(r=(n-i.width)/2),t=="right"&&(r=n-i.width);for(const l of i.tokens)this.model.children[l.index].x=r,r+=l.metrics.lineWidths[0]}}get textBaseline(){return this._textBaseline}set textBaseline(t){this._textBaseline=t,this._anchor.y=$m[t];let n=0;for(const i of this.metrics.lines){const r=i.height;for(const l of i.tokens){let s=0;t=="middle"&&(s=(r-l.metrics.lineHeight)/2),t=="bottom"&&(s=r-l.metrics.lineHeight),this.model.children[l.index].y=n+s}n+=r}}copy(){const t=Dm.fromJSON(JSON.parse(JSON.stringify(this)));return t.filters=this.filters,t.font=this.font,t}createRenderSplits(t=[]){var r,l;const n=this.transformedText??"",i=[{index:void 0,tokens:Xl(n.substring(0,(r=t==null?void 0:t.at(0))==null?void 0:r.start))}];for(let s=0;s<t.length;s++)i.push({index:t[s].index,tokens:Xl(n.substring(t[s].start,t[s].stop))}),!((t[s].stop??n.length)>=n.length)&&i.push({index:void 0,tokens:Xl(n.substring(t[s].stop,(l=t.at(s+1))==null?void 0:l.start))});return i.filter(s=>s.tokens.join("").trim().length)}createTextMetrics(t,n){var r,l,s;const i=new Vc;for(const d of t){const c=d.index!=null?n[d.index]:this.style;for(let u=0;u<d.tokens.length;u++){const m=hy($t.CanvasTextMetrics.measureText(d.tokens[u],c)),p=(((r=i.lines.at(-1))==null?void 0:r.width)??0)+m.lineWidths[0],f=this.maxWidth??Number.POSITIVE_INFINITY,h=(l=d.tokens.at(u-1))==null?void 0:l.match(/(\n|\\n).$/gim);(p>f||h||!i.lines.length)&&i.lines.push(new vy),this.model.addChild(new $t.Text({text:d.tokens[u],style:c,resolution:en,scale:en})),(s=i.lines.at(-1))==null||s.tokens.push({metrics:m,index:this.model.children.length-1})}}return i}createTextStyles(){var t;return((t=this.styles)==null?void 0:t.map(n=>{var r;const i=this.style.clone();return i.fill=n.fillStyle??this.style.fill,i.fontSize=n.fontSize??this.style.fontSize,i.stroke=n.stroke??this.style.stroke,i.fontFamily=((r=n.font)==null?void 0:r.name)??this.style.fontFamily,i}))??[]}drawBackground(){var s,d;if(this.view.children.length>1&&this.view.removeChildAt(0),!this.background)return;const t=this.model.width,n=this.model.height,i=((s=this.background.padding)==null?void 0:s.x)??40,r=((d=this.background.padding)==null?void 0:d.y)??10,l=new $t.Graphics;l.roundRect(0-i/2,2-r/2,t+i,n+r,this.background.borderRadius??20),l.fill(this.background.fill??"#000000"),l.alpha=this.background.alpha??1,this.view.addChildAt(l,0)}reflectUpdate(){var s;if(!this.transformedText)return;this.model.removeChildren();const t=this.createRenderSplits(this.segments),n=this.createTextStyles();this.metrics=this.createTextMetrics(t,n),this.textAlign=this.textAlign,this.textBaseline=this.textBaseline;const i=this.view.width,r=this.view.height,l=(((s=this.style.dropShadow)==null?void 0:s.distance)??0)*en;this.view.pivot={x:(i-l)*this._anchor.x,y:(r-l)*this._anchor.y},this.drawBackground()}};Oo([Le()],so.prototype,"background",2);Oo([Le(gy)],so.prototype,"styles",2);Oo([Le()],so.prototype,"text",1);Oo([Le()],so.prototype,"maxWidth",1);Oo([Le()],so.prototype,"textAlign",1);Oo([Le()],so.prototype,"textBaseline",1);let sl=so;const Am="KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO3ZhciBtPSh0PT4odFt0LkFWTUVESUFfVFlQRV9VTktOT1dOPS0xXT0iQVZNRURJQV9UWVBFX1VOS05PV04iLHRbdC5BVk1FRElBX1RZUEVfVklERU89MF09IkFWTUVESUFfVFlQRV9WSURFTyIsdFt0LkFWTUVESUFfVFlQRV9BVURJTz0xXT0iQVZNRURJQV9UWVBFX0FVRElPIix0W3QuQVZNRURJQV9UWVBFX0RBVEE9Ml09IkFWTUVESUFfVFlQRV9EQVRBIix0W3QuQVZNRURJQV9UWVBFX1NVQlRJVExFPTNdPSJBVk1FRElBX1RZUEVfU1VCVElUTEUiLHRbdC5BVk1FRElBX1RZUEVfQVRUQUNITUVOVD00XT0iQVZNRURJQV9UWVBFX0FUVEFDSE1FTlQiLHRbdC5BVk1FRElBX1RZUEVfTkI9NV09IkFWTUVESUFfVFlQRV9OQiIsdCkpKG18fHt9KSxvPSh0PT4odC5GRm1wZWdXb3JrZXJMb2FkZWQ9IkZGbXBlZ1dvcmtlckxvYWRlZCIsdC5XQVNNUnVudGltZUluaXRpYWxpemVkPSJXQVNNUnVudGltZUluaXRpYWxpemVkIix0LkxvYWRXQVNNPSJMb2FkV0FTTSIsdC5HZXRBVlBhY2tldD0iR2V0QVZQYWNrZXQiLHQuR2V0QVZQYWNrZXRzPSJHZXRBVlBhY2tldHMiLHQuR2V0QVZTdHJlYW09IkdldEFWU3RyZWFtIix0LkdldEFWU3RyZWFtcz0iR2V0QVZTdHJlYW1zIix0LlJlYWRBVlBhY2tldD0iUmVhZEFWUGFja2V0Iix0LkFWUGFja2V0U3RyZWFtPSJBVlBhY2tldFN0cmVhbSIsdC5SZWFkTmV4dEFWUGFja2V0PSJSZWFkTmV4dEFWUGFja2V0Iix0LlN0b3BSZWFkQVZQYWNrZXQ9IlN0b3BSZWFkQVZQYWNrZXQiLHQpKShvfHx7fSk7Y29uc3QgQT0iS0daMWJtTjBhVzl1S0NsN0luVnpaU0J6ZEhKcFkzUWlPMnhsZENCbU8zTmxiR1l1Y0c5emRFMWxjM05oWjJVb2UzUjVjR1U2SWtaR2JYQmxaMWR2Y210bGNreHZZV1JsWkNKOUtTeHpaV3htTG1Ga1pFVjJaVzUwVEdsemRHVnVaWElvSW0xbGMzTmhaMlVpTEdGemVXNWpJR1oxYm1OMGFXOXVLR3dwZTJOdmJuTjBlM1I1Y0dVNmRDeGtZWFJoT21NOWUzMHNiWE5uU1dRNmIzMDliQzVrWVhSaE8zUnllWHRwWmloMFBUMDlJa3h2WVdSWFFWTk5JaWw3WTI5dWMzUjdkMkZ6YlV4dllXUmxjbEJoZEdnNlpYMDlZM3g4ZTMwN1pqMWhkMkZwZENoaGQyRnBkQ0JwYlhCdmNuUW9aU2twTG1SbFptRjFiSFFvS1gxbGJITmxJR2xtS0hROVBUMGlSMlYwUVZaVGRISmxZVzBpS1h0amIyNXpkSHRtYVd4bE9tVXNjM1J5WldGdFZIbHdaVHB6TEhOMGNtVmhiVWx1WkdWNE9tRjlQV01zY2oxbUxtZGxkRUZXVTNSeVpXRnRLR1VzY3l4aEtUdHpaV3htTG5CdmMzUk5aWE56WVdkbEtIdDBlWEJsT25Rc2JYTm5TV1E2Ynl4eVpYTjFiSFE2Y24wc1czSXVZMjlrWldOd1lYSXVaWGgwY21Ga1lYUmhMbUoxWm1abGNsMHBmV1ZzYzJVZ2FXWW9kRDA5UFNKSFpYUkJWbE4wY21WaGJYTWlLWHRqYjI1emRIdG1hV3hsT21WOVBXTXNjejFtTG1kbGRFRldVM1J5WldGdGN5aGxLVHR6Wld4bUxuQnZjM1JOWlhOellXZGxLSHQwZVhCbE9uUXNiWE5uU1dRNmJ5eHlaWE4xYkhRNmMzMHNjeTV0WVhBb1lUMCtZUzVqYjJSbFkzQmhjaTVsZUhSeVlXUmhkR0V1WW5WbVptVnlLU2w5Wld4elpTQnBaaWgwUFQwOUlrZGxkRUZXVUdGamEyVjBJaWw3WTI5dWMzUjdabWxzWlRwbExIUnBiV1U2Y3l4emRISmxZVzFVZVhCbE9tRXNjM1J5WldGdFNXNWtaWGc2Y24wOVl5eHVQV1l1WjJWMFFWWlFZV05yWlhRb1pTeHpMR0VzY2lrN2MyVnNaaTV3YjNOMFRXVnpjMkZuWlNoN2RIbHdaVHAwTEcxelowbGtPbThzY21WemRXeDBPbTU5TEZ0dUxtUmhkR0V1WW5WbVptVnlYU2w5Wld4elpTQnBaaWgwUFQwOUlrZGxkRUZXVUdGamEyVjBjeUlwZTJOdmJuTjBlMlpwYkdVNlpTeDBhVzFsT25OOVBXTXNZVDFtTG1kbGRFRldVR0ZqYTJWMGN5aGxMSE1wTzNObGJHWXVjRzl6ZEUxbGMzTmhaMlVvZTNSNWNHVTZkQ3h0YzJkSlpEcHZMSEpsYzNWc2REcGhmU3hoTG0xaGNDaHlQVDV5TG1SaGRHRXVZblZtWm1WeUtTbDlaV3h6WlNCcFppaDBQVDA5SWxKbFlXUkJWbEJoWTJ0bGRDSXBlMk52Ym5OMGUyWnBiR1U2WlN4emRHRnlkRHB6TEdWdVpEcGhMSE4wY21WaGJWUjVjR1U2Y2l4emRISmxZVzFKYm1SbGVEcHVmVDFqTEdROVppNXlaV0ZrUVZaUVlXTnJaWFFvYnl4bExITXNZU3h5TEc0cE8zTmxiR1l1Y0c5emRFMWxjM05oWjJVb2UzUjVjR1U2ZEN4dGMyZEpaRHB2TEhKbGMzVnNkRHBrZlNsOWZXTmhkR05vS0dVcGUzTmxiR1l1Y0c5emRFMWxjM05oWjJVb2UzUjVjR1U2ZEN4dGMyZEpaRHB2TEdWeWNrMXpaenBsSUdsdWMzUmhibU5sYjJZZ1JYSnliM0kvWlM1dFpYTnpZV2RsT2lKVmJtdHViM2R1SUVWeWNtOXlJbjBwZlgwcGZTa29LVHNLIixnPXQ9PlVpbnQ4QXJyYXkuZnJvbShhdG9iKHQpLGU9PmUuY2hhckNvZGVBdCgwKSksVj10eXBlb2Ygc2VsZjwidSImJnNlbGYuQmxvYiYmbmV3IEJsb2IoW2coQSldLHt0eXBlOiJ0ZXh0L2phdmFzY3JpcHQ7Y2hhcnNldD11dGYtOCJ9KTtmdW5jdGlvbiBFKHQpe2xldCBlO3RyeXtpZihlPVYmJihzZWxmLlVSTHx8c2VsZi53ZWJraXRVUkwpLmNyZWF0ZU9iamVjdFVSTChWKSwhZSl0aHJvdyIiO2NvbnN0IHM9bmV3IFdvcmtlcihlLHtuYW1lOnQ/Lm5hbWV9KTtyZXR1cm4gcy5hZGRFdmVudExpc3RlbmVyKCJlcnJvciIsKCk9Pnsoc2VsZi5VUkx8fHNlbGYud2Via2l0VVJMKS5yZXZva2VPYmplY3RVUkwoZSl9KSxzfWNhdGNoe3JldHVybiBuZXcgV29ya2VyKCJkYXRhOnRleHQvamF2YXNjcmlwdDtiYXNlNjQsIitBLHtuYW1lOnQ/Lm5hbWV9KX1maW5hbGx5e2UmJihzZWxmLlVSTHx8c2VsZi53ZWJraXRVUkwpLnJldm9rZU9iamVjdFVSTChlKX19Y29uc3QgdT0xZTY7Y2xhc3MgcHtmZm1wZWdXb3JrZXI7ZmZtcGVnV29ya2VyTG9hZFN0YXR1czttc2dJZDtmaWxlO2NvbnN0cnVjdG9yKGUpe3RoaXMuZmZtcGVnV29ya2VyPW5ldyBFLHRoaXMuZmZtcGVnV29ya2VyTG9hZFN0YXR1cz1uZXcgUHJvbWlzZSgocyxhKT0+e3RoaXMuZmZtcGVnV29ya2VyLmFkZEV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGk9Pntjb25zdHt0eXBlOnIsZXJyTXNnOmR9PWkuZGF0YTtyPT09by5GRm1wZWdXb3JrZXJMb2FkZWQmJnRoaXMucG9zdChvLkxvYWRXQVNNLHt3YXNtTG9hZGVyUGF0aDplLndhc21Mb2FkZXJQYXRofSkscj09PW8uV0FTTVJ1bnRpbWVJbml0aWFsaXplZCYmcyghMCkscj09PW8uTG9hZFdBU00mJmQmJmEoZCl9KX0pLHRoaXMubXNnSWQ9MH1wb3N0KGUscyxhKXt0aGlzLmZmbXBlZ1dvcmtlci5wb3N0TWVzc2FnZSh7dHlwZTplLG1zZ0lkOmE/P3RoaXMubXNnSWQrKyxkYXRhOnN9KX1hc3luYyBsb2FkKGUpe2NvbnN0IHM9YXdhaXQgdGhpcy5mZm1wZWdXb3JrZXJMb2FkU3RhdHVzO3JldHVybiB0aGlzLmZpbGU9ZSxzfWRlc3Ryb3koKXt0aGlzLmZpbGU9dm9pZCAwLHRoaXMuZmZtcGVnV29ya2VyLnRlcm1pbmF0ZSgpfWdldEFWU3RyZWFtKGU9bS5BVk1FRElBX1RZUEVfVklERU8scz0tMSl7cmV0dXJuIG5ldyBQcm9taXNlKChhLGkpPT57aWYoIXRoaXMuZmlsZSl7aSgiZmlsZSBpcyBub3QgbG9hZGVkIik7cmV0dXJufWNvbnN0IHI9dGhpcy5tc2dJZCxkPSh7ZGF0YTpufSk9PntuLnR5cGU9PT1vLkdldEFWU3RyZWFtJiZuLm1zZ0lkPT09ciYmKG4uZXJyTXNnP2kobi5lcnJNc2cpOmEobi5yZXN1bHQpLHRoaXMuZmZtcGVnV29ya2VyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGQpKX07dGhpcy5mZm1wZWdXb3JrZXIuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsZCksdGhpcy5wb3N0KG8uR2V0QVZTdHJlYW0se2ZpbGU6dGhpcy5maWxlLHN0cmVhbVR5cGU6ZSxzdHJlYW1JbmRleDpzfSl9KX1nZXRBVlN0cmVhbXMoKXtyZXR1cm4gbmV3IFByb21pc2UoKGUscyk9PntpZighdGhpcy5maWxlKXtzKCJmaWxlIGlzIG5vdCBsb2FkZWQiKTtyZXR1cm59Y29uc3QgYT10aGlzLm1zZ0lkLGk9KHtkYXRhOnJ9KT0+e3IudHlwZT09PW8uR2V0QVZTdHJlYW1zJiZyLm1zZ0lkPT09YSYmKHIuZXJyTXNnP3Moci5lcnJNc2cpOmUoci5yZXN1bHQpLHRoaXMuZmZtcGVnV29ya2VyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGkpKX07dGhpcy5mZm1wZWdXb3JrZXIuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsaSksdGhpcy5wb3N0KG8uR2V0QVZTdHJlYW1zLHtmaWxlOnRoaXMuZmlsZX0pfSl9Z2V0QVZQYWNrZXQoZSxzPW0uQVZNRURJQV9UWVBFX1ZJREVPLGE9LTEpe3JldHVybiBuZXcgUHJvbWlzZSgoaSxyKT0+e2lmKCF0aGlzLmZpbGUpe3IoImZpbGUgaXMgbm90IGxvYWRlZCIpO3JldHVybn1jb25zdCBkPXRoaXMubXNnSWQsbj1oPT57Y29uc3QgbD1oLmRhdGE7bC50eXBlPT09by5HZXRBVlBhY2tldCYmbC5tc2dJZD09PWQmJihsLmVyck1zZz9yKGwuZXJyTXNnKTppKGwucmVzdWx0KSx0aGlzLmZmbXBlZ1dvcmtlci5yZW1vdmVFdmVudExpc3RlbmVyKCJtZXNzYWdlIixuKSl9O3RoaXMuZmZtcGVnV29ya2VyLmFkZEV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLG4pLHRoaXMucG9zdChvLkdldEFWUGFja2V0LHtmaWxlOnRoaXMuZmlsZSx0aW1lOmUsc3RyZWFtVHlwZTpzLHN0cmVhbUluZGV4OmF9KX0pfWdldEFWUGFja2V0cyhlKXtyZXR1cm4gbmV3IFByb21pc2UoKHMsYSk9PntpZighdGhpcy5maWxlKXthKCJmaWxlIGlzIG5vdCBsb2FkZWQiKTtyZXR1cm59Y29uc3QgaT10aGlzLm1zZ0lkLHI9ZD0+e2NvbnN0IG49ZC5kYXRhO24udHlwZT09PW8uR2V0QVZQYWNrZXRzJiZuLm1zZ0lkPT09aSYmKG4uZXJyTXNnP2Eobi5lcnJNc2cpOnMobi5yZXN1bHQpLHRoaXMuZmZtcGVnV29ya2VyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLHIpKX07dGhpcy5mZm1wZWdXb3JrZXIuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsciksdGhpcy5wb3N0KG8uR2V0QVZQYWNrZXRzLHtmaWxlOnRoaXMuZmlsZSx0aW1lOmV9KX0pfXJlYWRBVlBhY2tldChlPTAscz0wLGE9bS5BVk1FRElBX1RZUEVfVklERU8saT0tMSl7Y29uc3Qgcj1uZXcgQ291bnRRdWV1aW5nU3RyYXRlZ3koe2hpZ2hXYXRlck1hcms6MX0pLGQ9dGhpcy5tc2dJZDtsZXQgbj0wO3JldHVybiBuZXcgUmVhZGFibGVTdHJlYW0oe3N0YXJ0Omg9PntpZighdGhpcy5maWxlKXtoLmVycm9yKCJmaWxlIGlzIG5vdCBsb2FkZWQiKTtyZXR1cm59Y29uc3QgbD1mPT57Y29uc3QgYz1mLmRhdGE7Yy50eXBlPT09by5SZWFkQVZQYWNrZXQmJmMubXNnSWQ9PT1kJiZjLmVyck1zZyYmKGguZXJyb3IoYy5lcnJNc2cpLHRoaXMuZmZtcGVnV29ya2VyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGwpKSxjLnR5cGU9PT1vLkFWUGFja2V0U3RyZWFtJiZjLm1zZ0lkPT09ZCYmKGMucmVzdWx0P2guZW5xdWV1ZShjLnJlc3VsdCk6aC5jbG9zZSgpKX07dGhpcy5mZm1wZWdXb3JrZXIuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsbCksdGhpcy5wb3N0KG8uUmVhZEFWUGFja2V0LHtmaWxlOnRoaXMuZmlsZSxzdGFydDplLGVuZDpzLHN0cmVhbVR5cGU6YSxzdHJlYW1JbmRleDppfSl9LHB1bGw6KCk9PntuPjAmJnRoaXMucG9zdChvLlJlYWROZXh0QVZQYWNrZXQsdm9pZCAwLGQpLG4rK30sY2FuY2VsOigpPT57dGhpcy5wb3N0KG8uU3RvcFJlYWRBVlBhY2tldCx2b2lkIDAsZCl9fSxyKX1nZXRWaWRlb1N0cmVhbShlKXtyZXR1cm4gdGhpcy5nZXRBVlN0cmVhbShtLkFWTUVESUFfVFlQRV9WSURFTyxlKX1nZXRBdWRpb1N0cmVhbShlKXtyZXR1cm4gdGhpcy5nZXRBVlN0cmVhbShtLkFWTUVESUFfVFlQRV9BVURJTyxlKX1zZWVrVmlkZW9QYWNrZXQoZSl7cmV0dXJuIHRoaXMuZ2V0QVZQYWNrZXQoZSxtLkFWTUVESUFfVFlQRV9WSURFTyl9c2Vla0F1ZGlvUGFja2V0KGUpe3JldHVybiB0aGlzLmdldEFWUGFja2V0KGUsbS5BVk1FRElBX1RZUEVfQVVESU8pfXJlYWRWaWRlb1BhY2tldChlLHMpe3JldHVybiB0aGlzLnJlYWRBVlBhY2tldChlLHMsbS5BVk1FRElBX1RZUEVfVklERU8pfXJlYWRBdWRpb1BhY2tldChlLHMpe3JldHVybiB0aGlzLnJlYWRBVlBhY2tldChlLHMsbS5BVk1FRElBX1RZUEVfQVVESU8pfWdlblZpZGVvRGVjb2RlckNvbmZpZyhlKXtyZXR1cm57Y29kZWM6ZS5jb2RlY3Bhci5jb2RlY19zdHJpbmcsY29kZWRXaWR0aDplLmNvZGVjcGFyLndpZHRoLGNvZGVkSGVpZ2h0OmUuY29kZWNwYXIuaGVpZ2h0LGRlc2NyaXB0aW9uOmUuY29kZWNwYXIuZXh0cmFkYXRhPy5sZW5ndGg+MD9lLmNvZGVjcGFyLmV4dHJhZGF0YTp2b2lkIDB9fWdlbkVuY29kZWRWaWRlb0NodW5rKGUpe3JldHVybiBuZXcgRW5jb2RlZFZpZGVvQ2h1bmsoe3R5cGU6ZS5rZXlmcmFtZT09PTE/ImtleSI6ImRlbHRhIix0aW1lc3RhbXA6ZS50aW1lc3RhbXAqdSxkdXJhdGlvbjplLmR1cmF0aW9uKnUsZGF0YTplLmRhdGF9KX1nZW5BdWRpb0RlY29kZXJDb25maWcoZSl7cmV0dXJue2NvZGVjOmUuY29kZWNwYXIuY29kZWNfc3RyaW5nfHwiIixzYW1wbGVSYXRlOmUuY29kZWNwYXIuc2FtcGxlX3JhdGUsbnVtYmVyT2ZDaGFubmVsczplLmNvZGVjcGFyLmNoYW5uZWxzLGRlc2NyaXB0aW9uOmUuY29kZWNwYXIuZXh0cmFkYXRhPy5sZW5ndGg+MD9lLmNvZGVjcGFyLmV4dHJhZGF0YTp2b2lkIDB9fWdlbkVuY29kZWRBdWRpb0NodW5rKGUpe3JldHVybiBuZXcgRW5jb2RlZEF1ZGlvQ2h1bmsoe3R5cGU6ZS5rZXlmcmFtZT09PTE/ImtleSI6ImRlbHRhIix0aW1lc3RhbXA6ZS50aW1lc3RhbXAqdSxkdXJhdGlvbjplLmR1cmF0aW9uKnUsZGF0YTplLmRhdGF9KX1hc3luYyBnZXRWaWRlb0RlY29kZXJDb25maWcoKXtjb25zdCBlPWF3YWl0IHRoaXMuZ2V0VmlkZW9TdHJlYW0oKTtyZXR1cm4gdGhpcy5nZW5WaWRlb0RlY29kZXJDb25maWcoZSl9YXN5bmMgc2Vla0VuY29kZWRWaWRlb0NodW5rKGUpe2NvbnN0IHM9YXdhaXQgdGhpcy5zZWVrVmlkZW9QYWNrZXQoZSk7cmV0dXJuIHRoaXMuZ2VuRW5jb2RlZFZpZGVvQ2h1bmsocyl9YXN5bmMgZ2V0QXVkaW9EZWNvZGVyQ29uZmlnKCl7Y29uc3QgZT1hd2FpdCB0aGlzLmdldEF1ZGlvU3RyZWFtKCk7cmV0dXJuIHRoaXMuZ2VuQXVkaW9EZWNvZGVyQ29uZmlnKGUpfWFzeW5jIHNlZWtFbmNvZGVkQXVkaW9DaHVuayhlKXtjb25zdCBzPWF3YWl0IHRoaXMuc2Vla0F1ZGlvUGFja2V0KGUpO3JldHVybiB0aGlzLmdlbkVuY29kZWRBdWRpb0NodW5rKHMpfX1jbGFzcyBre3ZpZGVvO2N1cnJlbnRGcmFtZXM9MDt0b3RhbEZyYW1lcztjdXJyZW50VGltZTtmcHM7Zmlyc3RUaW1lc3RhbXA7Y29uc3RydWN0b3IoZSxzKXt0aGlzLmN1cnJlbnRUaW1lPWVbMF0qMWU2LHRoaXMuZmlyc3RUaW1lc3RhbXA9ZVswXSoxZTYsdGhpcy50b3RhbEZyYW1lcz0oZVsxXS1lWzBdKSpzKzEsdGhpcy5mcHM9cyx0aGlzLnZpZGVvPW5ldyBWaWRlb0RlY29kZXIoe291dHB1dDp0aGlzLmhhbmRsZUZyYW1lT3V0cHV0LmJpbmQodGhpcyksZXJyb3I6dGhpcy5oYW5kbGVFcnJvci5iaW5kKHRoaXMpfSl9cG9zdEZyYW1lKGUpe3NlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImZyYW1lIixmcmFtZTplfSksdGhpcy5jdXJyZW50VGltZSs9TWF0aC5mbG9vcigxL3RoaXMuZnBzKjFlNiksdGhpcy5jdXJyZW50RnJhbWVzKz0xfWhhbmRsZUZyYW1lT3V0cHV0KGUpe2NvbnN0IHM9ZS50aW1lc3RhbXAsYT1lLmR1cmF0aW9uPz8wLGk9cythO2lmKCF0aGlzLmlzRnJhbWVJblJhbmdlKHMpKXtlLmNsb3NlKCk7cmV0dXJufWZvcig7aT50aGlzLmN1cnJlbnRUaW1lJiZ0aGlzLmN1cnJlbnRGcmFtZXM8PXRoaXMudG90YWxGcmFtZXM7KXRoaXMucG9zdEZyYW1lKGUpO2UuY2xvc2UoKX1pc0ZyYW1lSW5SYW5nZShlKXtyZXR1cm4gZT49dGhpcy5maXJzdFRpbWVzdGFtcH1oYW5kbGVFcnJvcihlKXtjb25zb2xlLmVycm9yKCJlcnJvciBpbiB3b3JrZXIiLGUpLHNlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImVycm9yIixtZXNzYWdlOmUubWVzc2FnZT8/IkFuIHVua25vd24gd29ya2VyIGVycm9yIG9jY3VycmVkIn0pLHNlbGYuY2xvc2UoKX19ZnVuY3Rpb24gSSh0KXtyZXR1cm4gYXN5bmMgZT0+e3RyeXthd2FpdCB0KGUpfWNhdGNoKHMpe3NlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImVycm9yIixtZXNzYWdlOnM/Lm1lc3NhZ2U/PyJBbiB1bmtvd24gd29ya2VyIGVycm9yIG9jY3VyZWQifSl9fX1mdW5jdGlvbiBXKHQpe3JldHVybiB0LmNvZGVjPT0idnAwOSImJih0LmNvZGVjPSJ2cDA5LjAwLjEwLjA4IiksdH1jb25zdCBaPTMwO2FzeW5jIGZ1bmN0aW9uIFAodCl7aWYodC5kYXRhPy50eXBlIT0iaW5pdCIpcmV0dXJuO2NvbnN0e2ZpbGU6ZSxyYW5nZTpzLGZwczphfT10LmRhdGEsaT1uZXcgcCh7d2FzbUxvYWRlclBhdGg6Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9ucG0vQGRpZmZ1c2lvbnN0dWRpby9mZm1wZWctd2FzbUAxLjAuMC9kaXN0L2ZmbXBlZy5qcyJ9KTthd2FpdCBpLmxvYWQoZSk7Y29uc3Qgcj1hd2FpdCBpLmdldFZpZGVvRGVjb2RlckNvbmZpZygpO1cocik7Y29uc3QgZD1uZXcgayhzLGEpO2QudmlkZW8uY29uZmlndXJlKHIpO2NvbnN0IG49aS5yZWFkQVZQYWNrZXQoc1swXSxzWzFdKS5nZXRSZWFkZXIoKTtuLnJlYWQoKS50aGVuKGFzeW5jIGZ1bmN0aW9uIGgoe2RvbmU6bCx2YWx1ZTpmfSl7aWYobCl7YXdhaXQgZC52aWRlby5mbHVzaCgpLHNlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImRvbmUifSksc2VsZi5jbG9zZSgpO3JldHVybn1jb25zdCBjPWkuZ2VuRW5jb2RlZFZpZGVvQ2h1bmsoZik7cmV0dXJuIGQudmlkZW8uZGVjb2RlUXVldWVTaXplPlomJmF3YWl0IG5ldyBQcm9taXNlKEw9PntkLnZpZGVvLm9uZGVxdWV1ZT0oKT0+TCgpfSksYy50aW1lc3RhbXA8PXNbMV0qMWU2JiZkLnZpZGVvLmRlY29kZShjKSxuLnJlYWQoKS50aGVuKGgpfSl9c2VsZi5hZGRFdmVudExpc3RlbmVyKCJtZXNzYWdlIixJKFApKX0pKCk7Cg==",wy=o=>Uint8Array.from(atob(o),a=>a.charCodeAt(0)),Tc=typeof self<"u"&&self.Blob&&new Blob([wy(Am)],{type:"text/javascript;charset=utf-8"});function ky(o){let a;try{if(a=Tc&&(self.URL||self.webkitURL).createObjectURL(Tc),!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,"+Am,{name:o==null?void 0:o.name})}finally{a&&(self.URL||self.webkitURL).revokeObjectURL(a)}}class _y{constructor(){ae(this,"frames",[]);ae(this,"state","active");ae(this,"onenqueue");ae(this,"onclose")}enqueue(a){var t;this.frames.unshift(a),(t=this.onenqueue)==null||t.call(this)}async dequeue(){if(this.frames.length==0&&this.state=="active"&&await this.waitFor(2e4),!(this.frames.length==0&&this.state=="closed"))return this.frames.pop()}close(){var a;this.state="closed",(a=this.onclose)==null||a.call(this)}terminate(){for(const a of this.frames)a.close()}async waitFor(a){await new Promise((t,n)=>{const i=setTimeout(()=>{n(`Promise timed out after ${a} ms`)},a);this.onenqueue=()=>{clearTimeout(i),t()},this.onclose=()=>{clearTimeout(i),t()}})}}function Ey(o,a,t){const n=t.value;return t.value=function(...i){var r,l,s,d;return(l=(r=this.track)==null?void 0:r.composition)!=null&&l.rendering&&this.sprite.texture.source.uid!=this.textrues.canvas.source.uid&&(this.sprite.texture=this.textrues.canvas),!((d=(s=this.track)==null?void 0:s.composition)!=null&&d.rendering)&&this.sprite.texture.source.uid!=this.textrues.html5.source.uid&&(this.sprite.texture=this.textrues.html5),n.apply(this,i)},t}var Sy=Object.defineProperty,Cy=Object.getOwnPropertyDescriptor,xy=(o,a,t,n)=>{for(var i=Cy(a,t),r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&Sy(a,t,i),i};const Rm=class Lm extends il(ol){constructor(t,n={}){super();ae(this,"source",new Xn);ae(this,"type","video");ae(this,"worker");ae(this,"buffer");ae(this,"canvas",document.createElement("canvas"));ae(this,"context",this.canvas.getContext("2d"));ae(this,"element",document.createElement("video"));ae(this,"textrues",{html5:$t.Texture.from(this.element),canvas:$t.Texture.from(this.canvas)});ae(this,"sprite",new $t.Sprite);this.element.controls=!1,this.element.playsInline=!0,this.element.style.display="hidden",this.element.crossOrigin="anonymous",this.textrues.html5.source.autoPlay=!1,this.textrues.html5.source.loop=!1,this.sprite.texture=this.textrues.html5,this.view.addChild(this.sprite),t instanceof Xn&&(this.source=t),t instanceof File&&this.source.from(t),this.element.addEventListener("play",()=>{this.playing=!0}),this.element.addEventListener("pause",()=>{this.playing=!1}),Object.assign(this,n)}async init(){const t=await this.source.createObjectURL();this.element.setAttribute("src",t),await new Promise((n,i)=>{this.element.oncanplay=()=>{this.duration.seconds=this.element.duration,this.state="READY",n()},this.element.onerror=()=>{this.state="ERROR";const r=new mn({code:"sourceNotProcessable",message:"An error occurred while processing the input medium."});i(this.element.error??r)}})}async connect(t){var i;super.connect(t);const n=((i=t.composition)==null?void 0:i.frame)??0;await this.seek(je.fromFrames(n))}enter(){var t,n,i;super.enter(),(n=(t=this.track)==null?void 0:t.composition)!=null&&n.rendering&&((i=this.buffer)==null?void 0:i.state)!="active"&&this.decodeVideo()}update(t){var n,i,r,l,s,d;if((i=(n=this.track)==null?void 0:n.composition)!=null&&i.playing&&!this.playing)this.element.play();else if(!((l=(r=this.track)==null?void 0:r.composition)!=null&&l.playing)&&this.playing)this.element.pause();else if((d=(s=this.track)==null?void 0:s.composition)!=null&&d.rendering)return this.nextFrame()}exit(){this.playing&&this.element.pause(),this.filters&&this.view.filters&&(this.view.filters=null)}copy(){const t=Lm.fromJSON(JSON.parse(JSON.stringify(this)));return t.filters=this.filters,t.source=this.source,t}async decodeVideo(){var t,n;return this.buffer=new _y,this.worker=new ky,this.worker.addEventListener("message",i=>{var r,l;i.data.type=="frame"?(r=this.buffer)==null||r.enqueue(i.data.frame):i.data.type=="error"?this.cancelDecoding():i.data.type=="done"&&((l=this.buffer)==null||l.close())}),this.worker.postMessage({type:"init",file:await this.source.getFile(),range:this.demuxRange,fps:((n=(t=this.track)==null?void 0:t.composition)==null?void 0:n.fps)??Bi}),this.buffer}async nextFrame(){if(!this.buffer)return;const t=await this.buffer.dequeue();t&&(this.canvas.width=t.displayWidth,this.canvas.height=t.displayHeight,this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.context.drawImage(t,0,0),this.textrues.canvas.source.update(),t.close())}get demuxRange(){var r;const t=(r=this.track)==null?void 0:r.composition;let n;this.start.millis<0?n=Math.abs(this.offset.seconds):n=this.range[0].seconds;let i;return t&&this.stop.millis>t.duration.millis?i=t.duration.subtract(this.offset).seconds:i=this.range[1].seconds,[n,i]}cancelDecoding(){var t,n;(t=this.worker)==null||t.terminate(),this.worker=void 0,(n=this.buffer)==null||n.terminate(),this.buffer=void 0}};xy([rl,Ey],Rm.prototype,"update");let xs=Rm;class _i extends ol{constructor(t,n={}){super();ae(this,"type","audio");ae(this,"source",new xn);ae(this,"element",new Audio);t instanceof xn&&(this.source=t),t instanceof File&&this.source.from(t),this.element.addEventListener("play",()=>{this.playing=!0}),this.element.addEventListener("pause",()=>{this.playing=!1}),Object.assign(this,n)}async init(){const t=await this.source.createObjectURL();this.element.setAttribute("src",t),this.element.load(),await new Promise((n,i)=>{this.element.oncanplay=()=>{this.duration.seconds=this.element.duration,this.state="READY",n()},this.element.onerror=()=>{this.state="ERROR";const r=new mn({code:"sourceNotProcessable",message:"An error occurred while processing the input medium."});i(this.element.error??r)}})}update(){var t,n,i,r,l,s;if((n=(t=this.track)==null?void 0:t.composition)!=null&&n.rendering)return this.exit();(r=(i=this.track)==null?void 0:i.composition)!=null&&r.playing&&!this.playing?this.element.play():!((s=(l=this.track)==null?void 0:l.composition)!=null&&s.playing)&&this.playing&&this.element.pause()}exit(){this.playing&&this.element.pause()}copy(){const t=_i.fromJSON(JSON.parse(JSON.stringify(this)));return t.source=this.source,t}}const Ny={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 Ns(o){if(!Object.keys(Ny.MIXED).includes(o??""))throw new qt({message:`${o} is not an accepted mime type`,code:"invalid_mimetype"});return o}var Vy=Object.defineProperty,Ty=Object.getOwnPropertyDescriptor,By=(o,a,t,n)=>{for(var i=Ty(a,t),r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&Vy(a,t,i),i};const Iy=class Pm extends il(Pi){constructor(t,n={}){super();ae(this,"type","html");ae(this,"source",new xc);ae(this,"element",new Image);ae(this,"canvas",document.createElement("canvas"));ae(this,"context",this.canvas.getContext("2d"));ae(this,"sprite",new $t.Sprite);this.view.addChild(this.sprite),Object.assign(this,n),t instanceof xc&&(this.source=t),t instanceof File&&this.source.from(t),this.element.addEventListener("load",()=>{var l,s,d,c;const i=(s=(l=this.source.document)==null?void 0:l.body)==null?void 0:s.scrollWidth,r=(c=(d=this.source.document)==null?void 0:d.body)==null?void 0:c.scrollHeight;!i||!r||(this.canvas.width=i,this.canvas.height=r,this.context.imageSmoothingEnabled=!1,this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.context.drawImage(this.element,0,0),this.sprite.texture=$t.Texture.from(this.canvas,!0),this.trigger("load",void 0))}),this.element.addEventListener("error",i=>{this.state="ERROR",this.trigger("error",new mn({code:"sourceNotProcessable",message:"An error occurred while processing the input medium."})),this.track&&this.detach()}),this.on("update",async()=>{this.source.update(),this.element.setAttribute("src",await this.source.createObjectURL())})}async init(){this.element.setAttribute("src",await this.source.createObjectURL()),await new Promise((t,n)=>{this.element.onload=()=>{var l,s,d,c;const i=(s=(l=this.source.document)==null?void 0:l.body)==null?void 0:s.scrollWidth,r=(c=(d=this.source.document)==null?void 0:d.body)==null?void 0:c.scrollHeight;if(!i||!r)return n(new mn({code:"sourceNotProcessable",message:"Cannot display source with height or width at 0"}));this.state="READY",t()},this.element.onerror=i=>{n(new mn({code:"sourceNotProcessable",message:"An error occurred while processing the input medium."}))}})}update(t){}copy(){const t=Pm.fromJSON(JSON.parse(JSON.stringify(this)));return t.filters=this.filters,t.source=this.source,t}};By([rl],Iy.prototype,"update");const Um=["DEFAULT","STACK"];class Bc{constructor(){ae(this,"mode",Um[0]);ae(this,"pauseAlignmet",!1)}add(a,t){let n=!0;for(let i=0;i<t.clips.length&&(n=$c(a,t.clips[i]),!!n);i++)Mc(a,t.clips[i]);n&&(t.clips.push(a),t.clips.sort(Ic))}update(a,t){if(!this.pauseAlignmet){t.clips.sort(Ic);for(let n=0;n<t.clips.length;n++)if(a.id!=t.clips[n].id){if(!$c(a,t.clips[n]))break;Mc(a,t.clips[n])}}}offset(a,t){this.pauseAlignmet=!0;for(const n of t.clips)n.offsetBy(a);this.pauseAlignmet=!1}}class My{constructor(){ae(this,"mode",Um[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 je(i-a.start.millis+1)),n==null?t.clips.push(a):(t.clips.splice(n,0,a),t.clips.slice(n+1).forEach(l=>{l.offsetBy(a.stop.subtract(a.start))}))}update(a,t){let n=0;for(const i of t.clips){if(i.start.millis!=n){const r=n-i.start.millis;i.offsetBy(new je(r))}n=i.stop.millis+1}}offset(){}}function Ic(o,a){return o.start.millis-a.start.millis}function Mc(o,a){o.start.millis>=a.start.millis&&o.start.millis<=a.stop.millis&&(o.start=a.stop.copy().addMillis(1)),o.stop.millis>=a.start.millis&&o.stop.millis<=a.stop.millis&&(o.stop=a.start.copy().addMillis(-1))}function $c(o,a){var t,n,i,r,l;if(o.start.millis>=a.start.millis&&o.stop.millis<=a.stop.millis){const s=(n=(t=a.track)==null?void 0:t.composition)==null?void 0:n.tracks.find(d=>d.type==o.type&&!d.clips.some(c=>o.id!=c.id&&o.start.millis>=c.start.millis&&o.stop.millis<=c.stop.millis));return s?(s.add(o.detach()),!1):((l=(r=(i=a.track)==null?void 0:i.composition)==null?void 0:r.createTrack(o.type))==null||l.add(o.detach()),!1)}return!0}class zo extends Ri($a){constructor(){super(...arguments);ae(this,"_disabled",!1);ae(this,"view",new $t.Container);ae(this,"clips",[]);ae(this,"pointer",0);ae(this,"composition");ae(this,"type","base");ae(this,"strategy",new Bc)}get disabled(){return this._disabled}set disabled(t){var n;t&&this.clipRef&&Jl(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 My,this.strategy.update(new Pi,this)):this.strategy=new Bc,this.trigger("update",void 0),this}layer(t){var s,d;const n=((s=this.composition)==null?void 0:s.tracks)??[],i=n.findIndex(c=>c.id==this.id),r=n.length-1;if(i==-1)return this;let l=0;return t=="bottom"?l=r:t=="top"||t<0?l=0:t>r?l=r:l=t,O0(n,i,l),(d=this.composition)==null||d.stage.setChildIndex(this.view,r-l),this.trigger("update",void 0),this}seek(t){}offsetBy(t){return typeof t=="number"?this.strategy.offset(je.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(Jl(this.clipRef)&&(!Kl(n,this.clipRef)||(i=this.clipRef)!=null&&i.disabled)&&(this.clipRef&&this.view.removeChild(this.clipRef.view),(r=this.clipRef)==null||r.exit()),!!Kl(n,this))for(let l=0;l<this.clips.length;l++){const s=(this.pointer+l)%this.clips.length,d=this.clips[s],c=this.clips[s-1];if(Kl(n,d)&&!d.disabled)return this.pointer=s,Jl(d)||(d.enter(),this.view.addChild(d.view)),d.update(t);if(n<d.start.millis&&n>((c==null?void 0:c.stop.millis)??0)){this.pointer=s;return}}}async add(t,n){return this.composition&&!this.composition.renderer&&await new Promise(this.composition.resolve("init")),await t.init(),await t.connect(this),await this.strategy.add(t,this,n),t.on("frame",()=>{this.strategy.update(t,this)}),t.bubble(this),this.trigger("attach",void 0),t}remove(t){const n=this.clips.findIndex(i=>i.id==t.id);if(t.state=="ATTACHED"&&(t.state="READY"),t.view.parent&&this.view.removeChild(t.view),n!=null&&n>=0)return this.clips.splice(n,1),this.strategy.update(t,this),this.trigger("detach",void 0),t.off("*"),t}get stop(){var t;return((t=this.clips.at(-1))==null?void 0:t.stop)??new je}get start(){var t;return((t=this.clips.at(0))==null?void 0:t.start)??new je}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 Kl(o,a){return a?o>=a.start.millis&&o<=a.stop.millis:!1}function Jl(o){return o?!!o.view.parent:!1}class $y{static fromType(a){switch(a.type){case"video":return new Fy;case"audio":return new Ay;case"html":return new Ry;case"image":return new Dy;case"text":return new Fc;case"complex_text":return new Fc;case"caption":return new Py;default:return new zo}}}class Om extends zo{constructor(){super(...arguments);ae(this,"clips",[])}async seek(t){for(const n of this.clips)await n.seek(t)}async removeSilences(t={}){const n=[];for(const i of this.clips.map(r=>r.detach()))n.push(...await i.removeSilences(t));for(const i of n)await this.add(i)}}class Fy extends Om{constructor(){super(...arguments);ae(this,"type","video")}async seek(t){var n;(n=this.composition)!=null&&n.rendering?this.view.removeChildren():super.seek(t)}}class Dy extends zo{constructor(){super(...arguments);ae(this,"type","image")}}class Ay extends Om{constructor(){super(...arguments);ae(this,"type","audio")}}class Fc extends zo{constructor(){super(...arguments);ae(this,"type","text")}}class Ry extends zo{constructor(){super(...arguments);ae(this,"type","html")}}var Ly=Object.defineProperty,gd=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&Ly(a,t,i),i};class Oi extends $a{constructor(t={}){super();ae(this,"generatorOptions");ae(this,"type","CLASSIC");ae(this,"position");this.generatorOptions=t.generatorOptions??{duration:[.2]},this.position=t.position??{x:"50%",y:"50%"}}async applyTo(t){var r,l,s;if(!((r=t.clip)!=null&&r.transcript)||!((l=t.composition)!=null&&l.width))throw new qt({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((s=t.clip)==null?void 0:s.offset)??new je,i=await ua.fromFamily({family:"Figtree",weight:"700"}).load();for(const d of t.clip.transcript.iter(this.generatorOptions))await t.add(new Uo({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 Ge([0,8],[.96,1],{easing:"easeOut"}),alpha:new Ge([0,4],[0,1],{easing:"easeOut"})}))}}gd([Le()],Oi.prototype,"generatorOptions");gd([Le()],Oi.prototype,"type");gd([Le()],Oi.prototype,"position");class Py extends zo{constructor(){super(...arguments);ae(this,"clip");ae(this,"type","caption");ae(this,"preset",new Oi)}from(t){var n;return this.clip=t,(n=this.clip)==null||n.on("offsetBy",i=>this.offsetBy(i.detail)),this}async generate(t){let n=this.preset;return typeof t=="object"?n=t:t&&(n=new t),this.clips=[],this.trigger("update",void 0),this.preset=n,await n.applyTo(this),this.trigger("update",void 0),this}}var Uy=Object.defineProperty,dl=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&Uy(a,t,i),i};class zi extends $a{constructor(t={}){super();ae(this,"generatorOptions");ae(this,"type","SPOTLIGHT");ae(this,"color");ae(this,"position");this.generatorOptions=t.generatorOptions??{duration:[.2]},this.color=t.color??"#00FF4C",this.position=t.position??{x:"50%",y:"50%"}}async applyTo(t){var r,l,s;if(!((r=t.clip)!=null&&r.transcript)||!((l=t.composition)!=null&&l.width))throw new qt({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((s=t.clip)==null?void 0:s.offset)??new je,i=await ua.fromFamily({family:"The Bold Font",weight:"500"}).load();for(const d of t.clip.transcript.iter(this.generatorOptions))for(let c=0;c<d.words.length;c++){const u=d.words.map(m=>m.text);await t.add(new sl({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)}))}}}dl([Le()],zi.prototype,"generatorOptions");dl([Le()],zi.prototype,"type");dl([Le()],zi.prototype,"color");dl([Le()],zi.prototype,"position");var Oy=Object.defineProperty,bd=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&Oy(a,t,i),i};class cl extends $a{constructor(t={}){super();ae(this,"type","GUINEA");ae(this,"colors");ae(this,"position");this.colors=t.colors??["#1BD724","#FFEE0C","#FF2E17"],this.position=t.position??{x:"50%",y:"50%"}}async applyTo(t){var r,l,s,d,c,u,m;if(!((r=t.clip)!=null&&r.transcript)||!((l=t.composition)!=null&&l.width))throw new qt({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((s=t.clip)==null?void 0:s.offset)??new je,i=await ua.fromFamily({family:"The Bold Font",weight:"500"}).load();for(const p of t.clip.transcript.iter({length:[18]})){const{segments:f,words:h}=this.splitSequence(p);for(let v=0;v<p.words.length;v++){const k=(c=(d=h[v])==null?void 0:d.at(0))==null?void 0:c.start,y=(m=(u=h[v])==null?void 0:u.at(-1))==null?void 0:m.stop;!k||!y||await t.add(new sl({text:f.join(`
33
- `),textAlign:"center",textBaseline:"middle",fontSize:20,fillStyle:"#FFFFFF",shadow:{color:"#000000",blur:16,alpha:.8,angle:Math.PI/4,distance:1},stroke:{width:4,color:"#000000"},maxWidth:t.composition.width*.8,leading:1.3,font:i,textCase:"upper",position:this.position,stop:y.add(n),start:k.add(n),styles:[{fillStyle:this.colors[0],fontSize:23},{fillStyle:this.colors[1],fontSize:23},{fillStyle:this.colors[2],fontSize:23}],segments:[{index:Nr(0,2),start:f.slice(0,v).join(" ").length,stop:f.slice(0,v+1).join(" ").length+v*2}]}))}}}splitSequence(t){const n=t.text,i=Math.ceil(n.length/2);let r=n.length;for(let d=i,c=i;d>0&&c<t.text.length-1;d--,c++){if(n[d].match(/ /)){r=d;break}if(n[c].match(/ /)){r=c;break}}const l=[...yc(n,r).map(d=>d.trim())],s=yc(t.words,l[0].split(/ /).length);return{segments:l,words:s}}}bd([Le()],cl.prototype,"type");bd([Le()],cl.prototype,"colors");bd([Le()],cl.prototype,"position");var zy=Object.defineProperty,yd=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&zy(a,t,i),i};class ul extends $a{constructor(t={}){super();ae(this,"generatorOptions");ae(this,"type","CASCADE");ae(this,"position");this.generatorOptions=t.generatorOptions??{duration:[1.4]},this.position=t.position??{x:"12%",y:"44%"}}async applyTo(t){var r,l,s;if(!((r=t.clip)!=null&&r.transcript)||!((l=t.composition)!=null&&l.width))throw new qt({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((s=t.clip)==null?void 0:s.offset)??new je,i=await ua.fromFamily({family:"Geologica",weight:"400"}).load();for(const d of t.clip.transcript.iter(this.generatorOptions))for(let c=0;c<d.words.length;c++){const u=()=>d.words.length==1?d.text:d.words.map(m=>m.text).slice(0,c+1).join(" ");await t.add(new Uo({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)}))}}}yd([Le()],ul.prototype,"generatorOptions");yd([Le()],ul.prototype,"type");yd([Le()],ul.prototype,"position");var jy=Object.defineProperty,wd=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&jy(a,t,i),i};class ml extends $a{constructor(t={}){super();ae(this,"generatorOptions");ae(this,"type","SOLAR");ae(this,"position");this.generatorOptions=t.generatorOptions??{duration:[.2]},this.position=t.position??{x:"50%",y:"50%"}}async applyTo(t){var l,s,d;if(!((l=t.clip)!=null&&l.transcript)||!((s=t.composition)!=null&&s.width))throw new qt({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=await ua.fromFamily({family:"Urbanist",weight:"800"}).load(),i=((d=t.clip)==null?void 0:d.offset)??new je,r=new mh.GlowFilter({color:"#fffe41",alpha:.25,distance:90,quality:.05});for(const c of t.clip.transcript.iter(this.generatorOptions))await t.add(new Uo({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 Ge([0,8],[.96,1],{easing:"easeOut"}),alpha:new Ge([0,4],[0,1],{easing:"easeOut"}),filters:r}))}}wd([Le()],ml.prototype,"generatorOptions");wd([Le()],ml.prototype,"type");wd([Le()],ml.prototype,"position");var Wy=Object.defineProperty,pl=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&Wy(a,t,i),i};class ji extends $a{constructor(t={}){super();ae(this,"generatorOptions");ae(this,"type","WHISPER");ae(this,"color");ae(this,"position");this.generatorOptions=t.generatorOptions??{length:[20]},this.color=t.color??"#8c8c8c",this.position=t.position??{x:"50%",y:"50%"}}async applyTo(t){var r,l,s;if(!((r=t.clip)!=null&&r.transcript)||!((l=t.composition)!=null&&l.width))throw new qt({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((s=t.clip)==null?void 0:s.offset)??new je,i=await ua.fromFamily({family:"Montserrat",weight:"300"}).load();for(const d of t.clip.transcript.iter(this.generatorOptions))for(let c=0;c<d.words.length;c++){const u=d.words.map(m=>m.text);await t.add(new sl({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}))}}}pl([Le()],ji.prototype,"generatorOptions");pl([Le()],ji.prototype,"type");pl([Le()],ji.prototype,"color");pl([Le()],ji.prototype,"position");var Hy=Object.defineProperty,fl=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&Hy(a,t,i),i};class hl extends $a{constructor(t={}){super();ae(this,"type","VERDANT");ae(this,"generatorOptions");ae(this,"color");ae(this,"position");this.generatorOptions=t.generatorOptions??{duration:[1]},this.color=t.color??"#69E34C",this.position=t.position??{x:"50%",y:"50%"}}async applyTo(t){var r,l,s;if(!((r=t.clip)!=null&&r.transcript)||!((l=t.composition)!=null&&l.width))throw new qt({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((s=t.clip)==null?void 0:s.offset)??new je,i=await ua.fromFamily({family:"Montserrat",weight:"800"}).load();for(const d of t.clip.transcript.iter(this.generatorOptions))for(let c=0;c<d.words.length;c++){const u=d.words.map(m=>m.text);await t.add(new sl({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}]}))}}}fl([Le()],hl.prototype,"type");fl([Le()],hl.prototype,"generatorOptions");fl([Le()],hl.prototype,"color");fl([Le()],hl.prototype,"position");class Zy extends Ri($a){constructor({height:t=1080,width:n=1920,background:i="#000000",backend:r="webgpu"}={}){super();ae(this,"_duration",new je);ae(this,"renderer");ae(this,"stage",new $t.Container);ae(this,"settings");ae(this,"tracks",[]);ae(this,"frame",0);ae(this,"fixedDuration");ae(this,"state","IDLE");ae(this,"fps",Bi);ae(this,"canvas");ae(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)),$t.autoDetectRenderer({...this.settings,preference:r}).then(l=>{this.renderer=l,this.trigger("init",void 0)}).catch(l=>{this.trigger("error",new Ro({code:"backendDetectionError",message:`${l}`}))})}get playing(){return this.state=="PLAY"}get rendering(){return this.state=="RENDER"}get width(){return this.settings.width}get height(){return this.settings.height}get duration(){return this.fixedDuration?this.fixedDuration:this._duration}set duration(t){var n;t?t instanceof je?this.fixedDuration=t:this.fixedDuration=je.fromFrames(t):this.fixedDuration=void 0,this.trigger("frame",((n=this.fixedDuration)==null?void 0:n.frames)??0)}resize(t,n){var i;this.settings.width=t,this.settings.height=n,(i=this.renderer)==null||i.resize(t,n),this.canvas&&(this.canvas.height=n,this.canvas.width=t),this.trigger("resize",void 0),this.computeFrame()}attachPlayer(t){this.canvas||(this.canvas=document.createElement("canvas"),this.canvas.height=this.settings.height,this.canvas.width=this.settings.width,this.canvas.style.background="black",this.context=this.canvas.getContext("2d"),this.context.imageSmoothingEnabled=!1,this.computeFrame()),t.appendChild(this.canvas)}detachPlayer(t){this.canvas&&t.removeChild(this.canvas)}shiftTrack(t){const n=typeof t=="object"?t:new t;return n.connect(this),this.stage.addChild(n.view),this.tracks.unshift(n),n.bubble(this),this.trigger("update",void 0),n}createTrack(t){const n=$y.fromType({type:t});return this.shiftTrack(n),n}async add(t){return await this.createTrack(t.type).add(t),t}remove(t){for(const n of this.tracks)if(n.clips.find(i=>i.id==t.id))return n.remove(t)}removeTracks(t){const n=this.tracks.filter(i=>i instanceof t);return this.tracks=this.tracks.filter(i=>!(i instanceof t)),n.forEach(i=>this.removeTrack(i)),n}findTracks(t){return this.tracks.filter(n=>{let i;return wc(t)?i=n instanceof t:i=t(n),i})}findClips(t){const n=[];for(const i of this.tracks)for(const r of i.clips){let l;wc(t)?l=r instanceof t:l=t(r),l&&n.push(r)}return n}computeFrame(){var t,n;if(this.renderer){for(let i=0;i<this.tracks.length;i++)this.tracks[i].update(je.fromFrames(this.frame));this.renderer.render(this.stage),(t=this.context)==null||t.clearRect(0,0,this.settings.width,this.settings.height),(n=this.context)==null||n.drawImage(this.renderer.canvas,0,0),this.trigger("currentframe",this.frame),this.playing&&this.frame++}}screenshot(t="png",n=1){if(this.computeFrame(),!this.renderer)throw new Ro({code:"rendererNotDefined",message:"Please wait until the renderer is defined"});return this.renderer.canvas.toDataURL(`image/${t}`,n)}async seek(t){typeof t=="number"?this.frame=Math.round(t>0?t:0):this.frame=t.frames>0?t.frames:0,this.playing&&this.pause();for(const n of this.tracks)await n.seek(je.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(je.fromFrames(this.frame));this.ticker(),this.trigger("play",this.frame)}}async pause(){this.state="IDLE",this.computeFrame(),this.trigger("pause",this.frame)}async audio(t=2,n=48e3){var l;const i=this.duration.seconds*n,r=new OfflineAudioContext({sampleRate:n,length:i,numberOfChannels:t}).createBuffer(t,i,n);for(const s of this.findClips(ol)){if(s.disabled||s.muted||(l=s.track)!=null&&l.disabled)continue;const d=Math.round(s.offset.seconds*r.sampleRate),c=Math.round(s.range[0].seconds*r.sampleRate),u=Math.round(s.range[1].seconds*r.sampleRate);try{const m=await s.source.decode(t,n),p=m.numberOfChannels-1;for(let f=0;f<t;f++){const h=r.getChannelData(f),v=m.getChannelData(f>p?p:f);for(let k=0;k<h.length-1;k++)k<d+c||k>d+u||k-d<0||(h[k]+=(v[k-d]??0)*s.volume,h[k]>1&&(h[k]=1),h[k]<-1&&(h[k]=-1));r.getChannelData(f).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/Bi;let n=performance.now(),i=0;do{const r=await new Promise(requestAnimationFrame);r-n<t-i||(i=Math.min(t,i+r-n-t),n=r,this.computeFrame())}while(this.frame<=this.duration.frames&&this.playing);this.playing&&this.seek(0)}update(){this._duration.frames=Math.max(...this.tracks.filter(t=>!t.disabled).map(t=>{var n;return((n=t.stop)==null?void 0:n.frames)??0}),0),this.computeFrame()}}function Gy(o,a){const t=new Uint8Array(19);return t[0]=79,t[1]=112,t[2]=117,t[3]=115,t[4]=72,t[5]=101,t[6]=97,t[7]=100,t[8]=1,t[9]=a,t[10]=0,t[11]=0,t[12]=o&255,t[13]=o>>8&255,t[14]=o>>16&255,t[15]=o>>24&255,t[16]=0,t[17]=0,t[18]=0,t}const Vs=[8e3,12e3,16e3,24e3,48e3],Xy="https://cdn.jsdelivr.net/npm/@diffusionstudio/libopus-wasm@1.0.0/dist/opus.wasm",Ky="https://cdn.jsdelivr.net/npm/@diffusionstudio/libopus-wasm@1.0.0/dist/opus.js";class Jy{constructor(a){ae(this,"output");ae(this,"error");ae(this,"config");ae(this,"encoder");ae(this,"opus");ae(this,"meta");this.output=a.output,this.error=a.error}async configure(a){const t=await import(Ky),{numberOfChannels:n,sampleRate:i}=this.config=a;if(!Vs.includes(i))throw new zr({code:"sampleRateNotSupported",message:`Unsupported sample rate, supported: ${Vs.join()}`});this.opus=await t.default({locateFile(r,l){return r.endsWith(".wasm")?Xy:l+r}}),this.encoder=this.opus._opus_encoder_create(i,n,2048),this.meta={decoderConfig:{codec:"opus",description:Gy(i,n).buffer,numberOfChannels:n,sampleRate:i}}}encode({data:a,numberOfFrames:t,timestamp:n=0}){if(!this.encoder||!this.opus||!this.config||!this.meta)throw new zr({code:"unconfiguredEncoder",message:"Cannot encode samples using an unconfigured encoder"});const{sampleRate:i,numberOfChannels:r}=this.config,l=Math.floor(i/1e3*20);let s=0;const d=l/i*1e6;for(;s<t;){const c=a.subarray(s*r,(s+l)*r),u=this.opus._malloc(c.length*2);this.opus.HEAP16.set(c,u>>1);const m=4e3,p=this.opus._malloc(m),f=this.opus._opus_encode(this.encoder,u,l,p,m);if(f>0){const h=new Uint8Array(this.opus.HEAPU8.subarray(p,p+f));this.output({data:h,timestamp:n,type:"key",duration:d},this.meta)}else this.error(new DOMException("PCM chunk could not be encoded"));this.opus._free(u),this.opus._free(p),s+=l,n+=d}}}function qy(o){const a=Vs;let t=48e3;for(const n of a)Math.abs(o-n)<Math.abs(o-t)&&(t=n);return t}class Yy{constructor(a,t){ae(this,"canvas");ae(this,"muxer");ae(this,"videoEncoder");ae(this,"frame",0);ae(this,"sampleRate");ae(this,"numberOfChannels");ae(this,"videoBitrate");ae(this,"gpuBatchSize");ae(this,"fps");ae(this,"height");ae(this,"width");ae(this,"audio");this.canvas=a,this.width=a.width,this.height=a.height,this.fps=(t==null?void 0:t.fps)??30,this.sampleRate=qy((t==null?void 0:t.sampleRate)??48e3),this.numberOfChannels=(t==null?void 0:t.numberOfChannels)??2,this.videoBitrate=(t==null?void 0:t.videoBitrate)??1e7,this.gpuBatchSize=(t==null?void 0:t.gpuBatchSize)??5,this.audio=(t==null?void 0:t.audio)??!1}async init(){const a=await W0({height:Math.round(this.height),width:Math.round(this.width),bitrate:this.videoBitrate,fps:this.fps});this.muxer=new Nm({target:new ld,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 zr({code:"initializationError",message:"Encoder must be initialized using {audio: true} to use this method"});this.muxer||await this.init();const t=j0(a,this.sampleRate,this.numberOfChannels),n=new Jy({output:(i,r)=>{var l;(l=this.muxer)==null||l.addAudioChunkRaw(i.data,i.type,i.timestamp,i.duration,r)},error:console.error});await n.configure({numberOfChannels:this.numberOfChannels,sampleRate:this.sampleRate}),n.encode({data:z0(t),numberOfFrames:t.length})}async blob(){var t,n,i;await((t=this.videoEncoder)==null?void 0:t.flush()),(n=this.muxer)==null||n.finalize();const a=(i=this.muxer)==null?void 0:i.target.buffer;if(!a)throw new zr({code:"unexpectedRenderError",message:"Muxer could not be finalized because the target buffer is not defined"});return new Blob([a],{type:"video/mp4"})}async export(){return this.blob()}}async function Qy(o){var n,i;const a=(n=o.metadata)==null?void 0:n.source_url;if(a)return a;const t=(i=o.source)==null?void 0:i.media_uuid;if(t){if(typeof window<"u"){const r=window;if(r.MEDIABLES_MEDIA_URLS&&r.MEDIABLES_MEDIA_URLS[t])return r.MEDIABLES_MEDIA_URLS[t]}if(!t.startsWith("temp-"))try{if(typeof fetch<"u"){const r=await fetch(`/api/media/${t}`);if(r.ok){const l=await r.json();return l.playback_url||l.url||void 0}}}catch{}}}const Vi=class Vi{constructor(a){this.transitions=new Map,this.nextId=0,this.composition=a}async applyTransition(a,t,n){const i=`transition-${this.nextId++}`,r=Math.round(n.duration*30),l=n.easing||"linear",s=this.findTrackForClip(a),d=this.findTrackForClip(t);if(!s||!d)throw new Error("Clips must be added to composition before applying transitions");const c=a.stop.frames-r,u=a.stop.frames;switch(n.type){case"fade":await this.applyFadeTransition(a,t,c,u,l);break;case"dissolve":case"cross-fade":await this.applyCrossFadeTransition(a,t,c,u,l);break;case"wipe-left":case"wipe-right":case"wipe-up":case"wipe-down":await this.applyWipeTransition(a,t,n.type,c,u,l);break;case"slide-left":case"slide-right":case"slide-up":case"slide-down":await this.applySlideTransition(a,t,n.type,c,u,l);break;case"zoom-in":case"zoom-out":await this.applyZoomTransition(a,t,n.type,c,u,l);break;case"dip-to-black":case"dip-to-white":await this.applyDipTransition(a,t,n.type,c,u,l);break}return this.transitions.set(i,n),i}async applyFadeTransition(a,t,n,i,r){if(!this.isVideoClip(a)||!this.isVideoClip(t))throw new Error("Fade transitions require VideoClip instances");a.alpha=new Ge([n,i],[1,0],{easing:r}),t.alpha=new Ge([n,i],[0,1],{easing:r}),t.start=je.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 Ge([n,i],[1,0],{easing:r}),t.alpha=new Ge([n,i],[0,1],{easing:r}),t.start=je.fromFrames(n)}async applyWipeTransition(a,t,n,i,r,l){if(!this.isVideoClip(a)||!this.isVideoClip(t))throw new Error("Wipe transitions require VideoClip instances");const s={x:0,y:0},d={x:0,y:0};switch(n){case"wipe-left":s.x=new Ge([i,r],[0,-1920],{easing:l}),d.x=new Ge([i,r],[1920,0],{easing:l});break;case"wipe-right":s.x=new Ge([i,r],[0,1920],{easing:l}),d.x=new Ge([i,r],[-1920,0],{easing:l});break;case"wipe-up":s.y=new Ge([i,r],[0,-1080],{easing:l}),d.y=new Ge([i,r],[1080,0],{easing:l});break;case"wipe-down":s.y=new Ge([i,r],[0,1080],{easing:l}),d.y=new Ge([i,r],[-1080,0],{easing:l});break}a.translate=s,t.translate=d,t.start=je.fromFrames(i)}async applySlideTransition(a,t,n,i,r,l){if(!this.isVideoClip(a)||!this.isVideoClip(t))throw new Error("Slide transitions require VideoClip instances");const s={x:0,y:0},d={x:0,y:0};switch(n){case"slide-left":s.x=new Ge([i,r],[0,-1920],{easing:l}),d.x=new Ge([i,r],[1920,0],{easing:l});break;case"slide-right":s.x=new Ge([i,r],[0,1920],{easing:l}),d.x=new Ge([i,r],[-1920,0],{easing:l});break;case"slide-up":s.y=new Ge([i,r],[0,-1080],{easing:l}),d.y=new Ge([i,r],[1080,0],{easing:l});break;case"slide-down":s.y=new Ge([i,r],[0,1080],{easing:l}),d.y=new Ge([i,r],[-1080,0],{easing:l});break}a.translate=s,t.translate=d,t.start=je.fromFrames(i)}async applyZoomTransition(a,t,n,i,r,l){if(!this.isVideoClip(a)||!this.isVideoClip(t))throw new Error("Zoom transitions require VideoClip instances");n==="zoom-in"?(a.scale=new Ge([i,r],[1,2],{easing:l}),a.alpha=new Ge([i,r],[1,0],{easing:l}),t.scale=new Ge([i,r],[.5,1],{easing:l}),t.alpha=new Ge([i,r],[0,1],{easing:l})):(a.scale=new Ge([i,r],[1,.5],{easing:l}),a.alpha=new Ge([i,r],[1,0],{easing:l}),t.scale=new Ge([i,r],[2,1],{easing:l}),t.alpha=new Ge([i,r],[0,1],{easing:l})),t.start=je.fromFrames(i)}async applyDipTransition(a,t,n,i,r,l){if(!this.isVideoClip(a)||!this.isVideoClip(t))throw new Error("Dip transitions require VideoClip instances");const s=Math.round((i+r)/2),d=n==="dip-to-black"?"#000000":"#ffffff",c=await Ss.fromColor(d),u=new cy(c,{start:je.fromFrames(i),stop:je.fromFrames(r)});a.alpha=new Ge([i,s],[1,0],{easing:l}),u.alpha=new Ge([i,s,r],[0,1,0],{easing:l}),t.alpha=new Ge([s,r],[0,1],{easing:l}),await this.composition.add(u),t.start=je.fromFrames(s)}findTrackForClip(a){for(const t of this.composition.tracks)if(t.clips.includes(a))return t}removeTransition(a){this.transitions.delete(a)}getTransitions(){return new Map(this.transitions)}static getAvailableTransitions(){return[...Vi.TRANSITIONS]}static previewTransition(a){return Vi.TRANSITIONS.find(t=>t.type===a)}isVideoClip(a){return"alpha"in a&&"scale"in a&&"translate"in a}};Vi.TRANSITIONS=[{type:"fade",name:"Fade",description:"Simple fade transition"},{type:"dissolve",name:"Dissolve",description:"Cross-dissolve between clips"},{type:"wipe-left",name:"Wipe Left",description:"Wipe from right to left"},{type:"wipe-right",name:"Wipe Right",description:"Wipe from left to right"},{type:"wipe-up",name:"Wipe Up",description:"Wipe from bottom to top"},{type:"wipe-down",name:"Wipe Down",description:"Wipe from top to bottom"},{type:"slide-left",name:"Slide Left",description:"Slide out to the left"},{type:"slide-right",name:"Slide Right",description:"Slide out to the right"},{type:"slide-up",name:"Slide Up",description:"Slide out upward"},{type:"slide-down",name:"Slide Down",description:"Slide out downward"},{type:"zoom-in",name:"Zoom In",description:"Zoom into the next clip"},{type:"zoom-out",name:"Zoom Out",description:"Zoom out to the next clip"},{type:"cross-fade",name:"Cross Fade",description:"Cross-fade between clips"},{type:"dip-to-black",name:"Dip to Black",description:"Fade through black"},{type:"dip-to-white",name:"Dip to White",description:"Fade through white"}];let Ii=Vi;function Ba(o,a){if(typeof o=="number"&&Number.isFinite(o))return o;if(typeof o=="string"){const t=Number(o);if(Number.isFinite(t))return t}return a}function Ei(o){return o>5?o/100:o}function e1(o){if(o.value!==void 0){const a=Ba(o.value,0);return a>=-1&&a<=1?1+a:Ei(a)}return Ei(Ba(o.brightness,1))}function Aa(o,a,t){return Math.min(t,Math.max(a,o))}function ga(){return new Jt.ColorMatrixFilter}function t1(o,a){switch(o){case"brightness":{const t=ga();return t.brightness(Aa(e1(a),0,5),!1),t}case"contrast":{const t=ga(),n=Ba(a.value??a.contrast,1);return t.contrast(Aa(Ei(n),0,5),!1),t}case"saturation":{const t=ga(),n=Ba(a.value??a.saturation,1);return t.saturate(Aa(Ei(n),0,5),!1),t}case"hue":{const t=ga(),n=Ba(a.degrees??a.value,0);return t.hue(Aa(n,-180,180),!1),t}case"blur":case"softFocus":{const t=o==="softFocus"?1:0,n=Ba(a.radius??a.blur??a.value,t);return new Jt.BlurFilter({strength:Aa(n,0,32),quality:4})}case"grayscale":{const t=ga(),n=Aa(Ba(a.amount,100),0,100);return n<=0?null:(n>=100?t.desaturate():t.saturate(1-n/100,!1),t)}case"sepia":{if(Aa(Ba(a.amount,100),0,100)<=0)return null;const n=ga();return n.sepia(!1),n}case"invert":{if(Aa(Ba(a.amount,100),0,100)<=0)return null;const n=ga();return n.negative(!1),n}case"warmth":{const t=ga(),n=Aa(Ba(a.value,0),-50,50);return n>0?(t.sepia(!1),t.saturate(1+n/100,!1)):n<0&&t.hue(Math.abs(n)/50*-20,!1),t}case"tint":{const t=ga(),n=Aa(Ba(a.intensity,.3),0,1),i=typeof a.color=="string"?a.color:"#ff0000",r=i.startsWith("#")?i.slice(1):i;if(r.length===6){const l=parseInt(r.slice(0,2),16)/255,s=parseInt(r.slice(2,4),16)/255,d=parseInt(r.slice(4,6),16)/255;t.matrix=[1-n+n*l,0,0,0,0,0,1-n+n*s,0,0,0,0,0,1-n+n*d,0,0,0,0,0,1,0]}return t}case"vintage":{const t=ga();return t.sepia(!1),t.saturate(1.4,!1),t.contrast(1.1,!1),t}case"blackAndWhite":{const t=ga(),n=Aa(Ei(Ba(a.contrast,120)),.5,3);return t.desaturate(),t.contrast(n,!1),t}case"cinematic":{const t=ga();return t.contrast(1.2,!1),t.brightness(.95,!1),t.saturate(.85,!1),t}case"dramatic":{const t=ga();return t.contrast(1.4,!1),t.brightness(.9,!1),t.saturate(1.1,!1),t.sepia(!1),t}case"dreamy":{const t=ga();return t.brightness(1.05,!1),t.saturate(.9,!1),t.contrast(.95,!1),t}default:return null}}typeof window<"u"&&!window.PIXI&&(window.PIXI=Jt);class zm{constructor(a=1920,t=1080,n=30,i){this.player=null,this.clips=new Map,this.clipTimelineStart=new Map,this.resizeObserver=null,this.recipeSourceDimensions=null,this.filterCache=new Map,this.animationFrameId=null,this.lastRenderedFrame=-1,this.fps=n,this.fitMode=(i==null?void 0:i.fitMode)??"contain",this.composition=new Zy({width:a,height:t,background:"#000000"}),this.initPromise=new Promise(r=>{const l=()=>{this.isDebug()&&this.dbg("init:renderer-ready"),r()};this.composition.on("init",l),queueMicrotask(()=>{var d,c,u,m;const s=this.composition;((c=(d=s==null?void 0:s.app)==null?void 0:d.renderer)!=null&&c.view||(u=s==null?void 0:s.renderer)!=null&&u.view||(m=s==null?void 0:s.renderer)!=null&&m.canvas)&&l()})}),this.setupEventHandlers()}isDebug(){try{if(typeof window<"u"&&window.MEDIABLES_DEBUG===1||typeof localStorage<"u"&&localStorage.getItem("mediables.debug")==="1")return!0}catch{}return!1}dbg(...a){this.isDebug()}setupEventHandlers(){this.composition.on("play",()=>this.onPlay()),this.composition.on("pause",()=>this.onPause()),this.composition.on("currentframe",()=>this.onFrameUpdate())}onPlay(){}onPause(){}onFrameUpdate(){}async attachPlayer(a){this.player=a,this.isDebug()&&this.dbg("attachPlayer:begin",{w:a.clientWidth,h:a.clientHeight}),this.composition.attachPlayer(a),await this.initPromise;const t=this.composition;this.isDebug()&&this.dbg("attachPlayer:ready",{hasRenderer:!!(t!=null&&t.renderer),hasCanvas:!!(t!=null&&t.canvas),canvasSize:t!=null&&t.canvas?{w:t.canvas.width,h:t.canvas.height}:null}),this.setupResponsiveScaling(),this.composition.seek(0),this.startRenderLoop()}setupResponsiveScaling(){this.player&&(this.player.style.position="absolute",this.player.style.top="50%",this.player.style.left="50%",this.resizeObserver=new ResizeObserver(()=>{var n;const a=(n=this.player)==null?void 0:n.parentElement;if(!this.player||!a)return;const t=Math.min(a.clientWidth/this.composition.width,a.clientHeight/this.composition.height);this.player.style.width=`${this.composition.width}px`,this.player.style.height=`${this.composition.height}px`,this.player.style.transform=`translate(-50%, -50%) scale(${t})`,this.player.style.transformOrigin="center"}),this.resizeObserver.observe(this.player.parentElement??this.player))}async loadFromRecipe(a){var n,i,r;await this.initPromise,this.clips.clear(),this.recipeSourceDimensions=Number.isFinite((n=a.source)==null?void 0:n.original_width)&&a.source.original_width>0&&Number.isFinite((i=a.source)==null?void 0:i.original_height)&&a.source.original_height>0?{width:a.source.original_width,height:a.source.original_height}:null;const t=await Qy(a);for(const l of a.timeline)await this.addTimelineClip(l,t);if(a.textOverlays)for(const l of a.textOverlays)await this.addTextOverlay(l);await new Promise(l=>requestAnimationFrame(l));for(const l of a.timeline)(r=l.filters)!=null&&r.length&&this.applyFiltersToClip(l.id,l.filters);a.transitions&&a.transitions.length>0&&await this.applyTransitionsToClips(a.transitions),this.composition.seek(0),this.applyFitModeToClips(),this.composition.computeFrame()}async applyTransitionsToClips(a){const t=new Ii(this.composition);for(const n of a){if(n.type==="cut")continue;const i=this.clips.get(n.fromClipId),r=this.clips.get(n.toClipId),l=this.mapTransitionType(n.type);if(!i||!r||!l)continue;const s={type:l,duration:n.duration,easing:this.mapTransitionEasing(n.easing)};try{await t.applyTransition(i,r,s)}catch{}}}mapTransitionType(a){switch(a){case"fade":return"fade";case"crossfade":return"cross-fade";case"dip-to-black":return"dip-to-black";case"wipe-left":return"wipe-left";case"wipe-right":return"wipe-right";case"slide-left":return"slide-left";case"slide-right":return"slide-right";case"zoom":return"zoom-in";case"cut":return null}}mapTransitionEasing(a){switch(a){case"ease-in":return"easeIn";case"ease-out":return"easeOut";case"ease-in-out":return"easeInOut";case"linear":return"linear"}}async addTimelineClip(a,t){var n,i;try{const r=a.url||t;if(!r)throw new Error("No video source URL available for clip");if(!r.startsWith("blob:")){if(!/^https?:/i.test(String(r)))return}const l=await((n=Xn.from)==null?void 0:n.call(Xn,r,{crossOrigin:"anonymous"}))??await Xn.from(r),s=new xs(l,{muted:a.muted||!1,scale:a.scale||1,position:"center"});let d=0,c=null;if(a.sourceIn!==void 0||a.sourceOut!==void 0){const p=Math.max(0,Math.floor((a.sourceIn||0)*this.fps)),f=a.sourceOut!==void 0?Math.max(p+1,Math.floor(a.sourceOut*this.fps)):null;d=p,c=f;try{if(s.offset=s.offset||{frames:0},s.offset.frames=p,f!==null){const h=Math.max(1,f-p);s.duration=s.duration||{frames:h},s.duration.frames=h}}catch{}}const u=await this.composition.add(s);if(c!==null&&d>=0)try{const p=Math.max(1,c-d);u.offset=u.offset||{frames:0},u.offset.frames=d,u.duration=u.duration||{frames:p},u.duration.frames=p}catch{}const m=Math.floor(a.timelineStart*this.fps);m>0&&u.offsetBy(m),this.clipTimelineStart.set(a.id,a.timelineStart),this.applyFitToClip(u),this.clips.set(a.id,u),(i=a.filters)!=null&&i.length&&(await new Promise(p=>requestAnimationFrame(p)),this.applyFiltersToClip(a.id,a.filters))}catch{}}async addTextOverlay(a){try{const t=ua.fromFamily({family:a.fontFamily||"Arial",weight:a.fontWeight||"400"}),n=new Uo({text:a.content,font:t,fontSize:a.fontSize||34,position:a.position||"center",fillStyle:a.color||"#FFFFFF",textAlign:a.textAlign||"center",textBaseline:a.textBaseline||"middle"});if(a.animation){const r=a.animation.duration||1,l=0,s=r*this.fps,d=a.animation.easing||"linear";a.animation.type==="rotate"&&a.animation.rotation?n.rotation=new Ge([l,s],[a.animation.rotation.from,a.animation.rotation.to],{easing:d}):a.animation.type==="scale"&&a.animation.scale&&(n.scale=new Ge([l,s],[a.animation.scale.from,a.animation.scale.to],{easing:d}))}a.startTime&&a.startTime>0&&n.offsetBy(a.startTime*this.fps),a.duration&&n.subclip(0,a.duration*this.fps);const i=await this.composition.add(n);this.clips.set(a.id||`text-${Date.now()}`,i)}catch{}}applyFiltersToClip(a,t){const n=this.clips.get(a);if(!n)return;const i=this.filterCache.get(a)??new Map,r=new Set(t.map(d=>d.id));for(const[d,c]of i.entries())if(!r.has(d)){try{typeof c.instance.destroy=="function"&&c.instance.destroy()}catch{}i.delete(d)}const l=[];for(const d of t){const c=this.buildFilterSignature(d),u=i.get(d.id);let m=null;if(u&&u.signature===c)m=u.instance;else{if(u)try{u.instance.destroy()}catch{}m=this.createPixiFilter(d),m?i.set(d.id,{instance:m,signature:c}):i.delete(d.id)}m&&l.push(m)}this.filterCache.set(a,i);const s=n.view??n.sprite??n.displayObject??null;if("filters"in n)try{n.filters=l}catch{}if(s&&"filters"in s)try{s.filters=l}catch{}typeof n.enter=="function"&&n.enter()}buildFilterSignature(a){const t=typeof a.params=="object"&&a.params!==null?a.params:{},n=Object.keys(t).sort((i,r)=>i.localeCompare(r)).map(i=>[i,t[i]]);return JSON.stringify({filterId:a.filterId,intensity:a.intensity??1,params:n})}setClipFilters(a,t){this.applyFiltersToClip(a,t),this.composition.computeFrame()}createPixiFilter(a){const t=a.intensity??1,n=a.params||{};if(te.getFilter(a.filterId)&&!te.isFilterCompatibleWithMedia(a.filterId,"video"))return null;let r=Dh(a.filterId,n);return r||(r=t1(a.filterId,n)),r?(t!==1&&r&&(a.filterId==="colorOverlay"||a.filterId==="alpha"||("alpha"in r&&!n.alpha&&(r.alpha*=t),"strength"in r&&(r.strength*=t))),r):null}play(){this.composition.play(),this.startRenderLoop()}pause(){this.composition.pause(),this.composition.computeFrame()}seek(a){this.composition.seek(a)}seekToTime(a){this.composition.seek(a*this.fps)}get currentFrame(){return this.composition.frame}get currentTime(){return this.composition.time().seconds.toFixed(2)}get currentTimeInSeconds(){return this.composition.frame/this.fps}get duration(){return this.composition.duration.frames}get durationInSeconds(){return this.composition.duration.frames/this.fps}async export(a={}){var l,s,d,c,u,m,p,f,h;const t=a.fps??this.fps,n=this.composition.canvas??((s=(l=this.composition)==null?void 0:l.renderer)==null?void 0:s.view)??((u=(c=(d=this.composition)==null?void 0:d.app)==null?void 0:c.renderer)==null?void 0:u.view)??((p=(m=this.composition)==null?void 0:m.renderer)==null?void 0:p.canvas);if(!n)throw new Error("Export failed: composition canvas is not initialized");(f=a.onProgress)==null||f.call(a,0);const i=new Yy(n,{fps:t});await i.init();const r=await i.export();return(h=a.onProgress)==null||h.call(a,100),r}destroy(){if(this.stopRenderLoop(),this.composition.pause(),this.clips.clear(),this.clipTimelineStart.clear(),this.filterCache.clear(),this.player&&this.composition.detachPlayer(this.player),this.resizeObserver){try{this.resizeObserver.disconnect()}catch{}this.resizeObserver=null}this.player=null}startRenderLoop(){this.stopRenderLoop(),this.isDebug()&&this.dbg("renderLoop:start");const a=()=>{(this.composition.state==="PLAY"||this.composition.frame!==this.lastRenderedFrame)&&(this.composition.computeFrame(),this.lastRenderedFrame=this.composition.frame),this.animationFrameId=requestAnimationFrame(a)};a()}stopRenderLoop(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null,this.isDebug()&&this.dbg("renderLoop:stop"))}moveClip(a,t){const n=this.clips.get(a);if(!n)return;const i=this.clipTimelineStart.get(a)||0,r=t-i;r!==0&&(n.offsetBy(r*this.fps),this.clipTimelineStart.set(a,t),this.composition.computeFrame())}setFitMode(a){this.fitMode=a,this.applyFitModeToClips()}applyFitModeToClips(){for(const a of this.clips.values())"scale"in a&&typeof a.scale<"u"&&this.applyFitToClip(a);this.composition.computeFrame()}applyFitToClip(a){var t,n;if(this.fitMode!=="none")try{const i=this.composition.width,r=this.composition.height,l=a.source,s=(l==null?void 0:l.width)??(l==null?void 0:l.videoWidth)??((t=this.recipeSourceDimensions)==null?void 0:t.width),d=(l==null?void 0:l.height)??(l==null?void 0:l.videoHeight)??((n=this.recipeSourceDimensions)==null?void 0:n.height);if(!s||!d)return;const c=Math.min(i/s,r/d),u=Math.max(i/s,r/d),m=this.fitMode==="contain"?c:u;a.scale=m}catch{}}trimClip(a,t,n){const i=this.clips.get(a);if(!i)return;const r=Math.max(0,Math.floor(t*this.fps)),l=Math.max(r+1,Math.floor(n*this.fps));try{i.offset=i.offset||{frames:0},i.offset.frames=r,i.duration=i.duration||{frames:l-r},i.duration.frames=l-r,this.composition.computeFrame()}catch{}}resolveSourceFrame(a){var t,n;for(const[i,r]of this.clips.entries()){const l=this.clipTimelineStart.get(i)||0,s=Math.floor(l*this.fps),d=((t=r.duration)==null?void 0:t.frames)??Math.round(r.duration.seconds*this.fps),c=s+d;if(a>=s&&a<c){const u=a-s;return{sourceFrame:(((n=r.offset)==null?void 0:n.frames)??0)+u,clipId:i}}}return{sourceFrame:0,clipId:null}}}const a1=["src"],n1={class:"preview-controls"},o1=["aria-label"],i1={class:"time-display"},r1={class:"current-time"},l1={class:"total-time"},s1={key:2,class:"loading-overlay"},d1={key:3,class:"error-overlay"},c1=e.defineComponent({__name:"VideoPreviewEngine",props:{mediaUuid:{},recipe:{},media:{},autoPlay:{type:Boolean,default:!1},enableEngine:{type:Boolean,default:!0},fitMode:{default:"contain"}},emits:["time-update","duration-change","play-state-change","error","engine-ready"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(),r=e.ref(),l=e.ref(),s=e.ref(!1),d=e.ref("Initializing..."),c=e.ref(null),u=e.ref(!1),m=e.ref(0),p=e.ref(0);let f=null;const h=e.computed(()=>!!t.enableEngine&&!!t.recipe),v=e.computed(()=>{switch(t.fitMode){case"cover":return"cover";case"none":return"none";default:return"contain"}}),k=e.computed(()=>{var S,B;return(S=t.media)!=null&&S.url?t.media.url:(((B=t.media)==null?void 0:B.file)instanceof File,"")});async function y(){var S,B,_;if(!(!r.value||!t.recipe))try{s.value=!0,d.value="Initializing video engine...";const A=((S=t.recipe.source)==null?void 0:S.original_width)||1920,P=((B=t.recipe.source)==null?void 0:B.original_height)||1080,D=((_=t.recipe.output)==null?void 0:_.fps)||30;f=new zm(A,P,D,{fitMode:t.fitMode}),f.attachPlayer(r.value),d.value="Loading composition...",await f.loadFromRecipe(t.recipe),p.value=f.durationInSeconds,n("duration-change",p.value),w(),s.value=!1,n("engine-ready",f),t.autoPlay&&(f.play(),u.value=!0)}catch(A){const P=A instanceof Error?A.message:String(A);c.value=`Failed to initialize: ${P}`,s.value=!1}}function w(){if(!f)return;const S=setInterval(()=>{f&&u.value&&(m.value=f.currentTimeInSeconds,n("time-update",m.value))},100);$.value=S}function g(){h.value&&f?(u.value?f.pause():f.play(),u.value=!u.value,n("play-state-change",u.value)):l.value&&(u.value?l.value.pause():l.value.play(),u.value=!u.value,n("play-state-change",u.value))}function b(S){const B=Math.floor(S/60),_=Math.floor(S%60);return`${B}:${_.toString().padStart(2,"0")}`}function R(){c.value=null,h.value&&y()}function V(){!h.value&&l.value&&(p.value=l.value.duration,n("duration-change",p.value))}function I(){!h.value&&l.value&&(m.value=l.value.currentTime,n("time-update",m.value))}function x(){u.value=!1,n("play-state-change",!1)}function T(S){c.value="Failed to load video",n("error",c.value)}e.onMounted(()=>{h.value&&t.recipe&&y()}),e.onUnmounted(()=>{f&&(f.destroy(),f=null),$.value&&(clearInterval($.value),$.value=null),l.value&&(l.value.pause(),l.value.removeAttribute("src"),l.value.load())}),e.watch(()=>t.recipe,async S=>{if(h.value&&S)if(S.timeline,f)try{await f.loadFromRecipe(S),p.value=f.durationInSeconds,n("duration-change",p.value)}catch{}else await y()}),e.watch(()=>t.enableEngine,async S=>{S?(await e.nextTick(),await y()):f&&($.value&&(clearInterval($.value),$.value=null),f.destroy(),f=null)}),e.watch(()=>t.fitMode,async S=>{if(!(!h.value||!f))try{f.setFitMode(S||"contain")}catch{}});const $=e.ref(null);return(S,B)=>(e.openBlock(),e.createElementBlock("div",{class:"video-preview-engine",ref_key:"containerRef",ref:i},[h.value?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"videoEnginePlayer",ref:r,class:"video-engine-player",style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"}},null,512)):(e.openBlock(),e.createElementBlock("video",{key:1,ref_key:"videoRef",ref:l,src:k.value,onLoadedmetadata:V,onTimeupdate:I,onEnded:x,onError:T,style:e.normalizeStyle({width:"100%",height:"100%",objectFit:v.value}),playsinline:"",controls:""},null,44,a1)),e.createElementVNode("div",n1,[e.createElementVNode("button",{class:"play-button",onClick:g,"aria-label":u.value?"Pause":"Play"},[e.createVNode(e.unref(H.IonIcon),{icon:u.value?e.unref(lm):e.unref(sm)},null,8,["icon"])],8,o1),e.createElementVNode("div",i1,[e.createElementVNode("span",r1,e.toDisplayString(b(m.value)),1),B[0]||(B[0]=e.createElementVNode("span",{class:"separator"},"/",-1)),e.createElementVNode("span",l1,e.toDisplayString(b(p.value)),1)])]),s.value?(e.openBlock(),e.createElementBlock("div",s1,[e.createVNode(e.unref(H.IonSpinner),{name:"crescent"}),e.createElementVNode("p",null,e.toDisplayString(d.value),1)])):e.createCommentVNode("",!0),c.value?(e.openBlock(),e.createElementBlock("div",d1,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(td)},null,8,["icon"]),e.createElementVNode("p",null,e.toDisplayString(c.value),1),e.createElementVNode("button",{onClick:R},"Retry")])):e.createCommentVNode("",!0)],512))}}),Ts=$e(c1,[["__scopeId","data-v-e199ac48"]]),u1=["aria-label"],m1=["aria-label"],p1={class:"clip-content"},f1={key:0,class:"clip-thumbnail"},h1=["src","alt"],v1=["src"],g1=["data-visual-mode"],b1={class:"clip-info"},y1={class:"clip-label"},w1={class:"clip-duration"},k1={key:3,class:"filter-indicators"},_1={key:4,class:"speed-indicator"},E1=["aria-label","data-testid"],S1={key:1,class:"selection-overlay"},C1=420,x1=8,N1=48,V1=32,Dc=1,T1=e.defineComponent({__name:"TimelineClip",props:{clip:{},scale:{},scrollOffset:{default:0},selected:{type:Boolean,default:!1},isMobile:{type:Boolean,default:!1},canDelete:{type:Boolean,default:!1}},emits:["select","delete","long-press","trim-start","trim-end","drag","trim-start-abs","trim-end-abs","drag-abs"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(null),r=e.ref(!1),l=e.ref(null),s=e.ref(0),d=e.ref(0),c=e.ref(0),u=e.ref(0),m=e.ref(!1),p=e.ref(!1),f=e.ref(null),h=e.computed(()=>{const U=(t.clip.timelineEnd-t.clip.timelineStart)*t.scale;return{left:`${t.clip.timelineStart*t.scale-t.scrollOffset}px`,width:`${U}px`}}),v=e.computed(()=>t.clip.label||`Clip ${t.clip.id.slice(-4)}`),k=e.computed(()=>{const C=t.clip.timelineEnd-t.clip.timelineStart;return I(C)}),y=e.computed(()=>t.clip.filters&&t.clip.filters.length>0),w=e.computed(()=>t.clip.filters||[]),g=e.computed(()=>t.clip.waveformSamples??[]),b=e.computed(()=>t.clip.filmstripFrames??[]),R=e.computed(()=>g.value.length>0),V=e.computed(()=>b.value.length>0);function I(C){if(C<1)return`${Math.round(C*30)}f`;if(C<60)return`${C.toFixed(1)}s`;{const U=Math.floor(C/60),j=Math.floor(C%60);return`${U}:${j.toString().padStart(2,"0")}`}}function x(C){return!C||typeof C!="string"?fc:C.includes("color")||C.includes("brightness")?Cn:C.includes("blur")?uv:C.includes("style")?ui:C.includes("effect")?Sn:fc}function T(){r.value||n("select")}function $(C){C.button===0&&(_("move",C.clientX),C.preventDefault())}function S(C){if(C.touches.length!==1)return;const U=C.touches[0];if(!t.isMobile){_("move",U.clientX),C.preventDefault();return}c.value=U.clientX,u.value=U.clientY,m.value=!1,p.value=!1,A(),P(),f.value=window.setTimeout(()=>{p.value=!0,P(),t.selected||n("select"),n("long-press")},C1),document.addEventListener("touchmove",D),document.addEventListener("touchend",z),document.addEventListener("touchcancel",z),C.preventDefault()}function B(C,U){const j="touches"in U?U.touches[0].clientX:U.clientX;l.value=C==="start"?"trim-start":"trim-end",_(l.value,j),U.preventDefault(),U.stopPropagation()}function _(C,U){A(),P(),r.value=!0,l.value=C,s.value=U,C==="move"?d.value=t.clip.timelineStart:C==="trim-start"?d.value=t.clip.sourceIn:C==="trim-end"&&(d.value=t.clip.sourceOut),document.addEventListener("mousemove",M),document.addEventListener("mouseup",O),document.addEventListener("touchmove",Z),document.addEventListener("touchend",O),t.selected||n("select")}function A(){f.value!==null&&(window.clearTimeout(f.value),f.value=null)}function P(){document.removeEventListener("touchmove",D),document.removeEventListener("touchend",z),document.removeEventListener("touchcancel",z)}function D(C){if(C.touches.length!==1)return;const U=C.touches[0],j=U.clientX-c.value,re=U.clientY-u.value;Math.hypot(j,re)<x1||(m.value=!0,A(),P(),_("move",U.clientX),M(C),C.preventDefault())}function z(){const C=!m.value&&!p.value&&!r.value;A(),P(),m.value=!1,p.value=!1,C&&n("select")}function M(C){if(!r.value||!l.value)return;const U="touches"in C?C.touches[0].clientX:C.clientX,j="touches"in C?C.touches[0].clientY:C.clientY,ue=U-s.value;l.value==="move"?(n("drag",ue),n("drag-abs",U,j)):l.value==="trim-start"?(n("trim-start",ue),n("trim-start-abs",U)):l.value==="trim-end"&&(n("trim-end",ue),n("trim-end-abs",U))}function Z(C){M(C)}function O(){r.value=!1,l.value=null,document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",O),document.removeEventListener("touchmove",Z),document.removeEventListener("touchend",O)}function K(){e.nextTick(()=>{Ne()})}function de(C){var be,Ee;const U=Math.max(0,t.clip.timelineEnd-t.clip.timelineStart),j=Math.max(1,Math.round(U*t.scale)),re=t.isMobile?V1:N1,ue=Math.max(1,Math.round(C.clientWidth||((be=C.parentElement)==null?void 0:be.clientWidth)||j)),Xe=Math.max(1,Math.round(C.clientHeight||((Ee=C.parentElement)==null?void 0:Ee.clientHeight)||re));return{width:ue,height:Xe}}function Ne(){if(V.value||!i.value)return;const C=i.value,U=C.getContext("2d");if(!U)return;const{width:j,height:re}=de(C),ue=window.devicePixelRatio||1;if(C.width=Math.max(1,Math.round(j*ue)),C.height=Math.max(1,Math.round(re*ue)),U.setTransform(ue,0,0,ue,0,0),U.clearRect(0,0,j,re),g.value.length>0){le(U,j,re,g.value);return}ce(U,j,re)}function ce(C,U,j){const re=j/2;C.strokeStyle="rgba(255, 255, 255, 0.3)",C.lineWidth=1,C.beginPath(),C.moveTo(0,re),C.lineTo(U,re);for(let ue=0;ue<U;ue+=4){const Xe=Math.sin(ue*.05)*(j*.3);C.moveTo(ue,re-Xe),C.lineTo(ue,re+Xe)}C.stroke()}function le(C,U,j,re){const ue=t.clip.sourceIn,Xe=t.clip.sourceOut,be=Math.max(.001,Xe-ue),Ee=re.filter(Re=>Re.endTime>=ue&&Re.time<=Xe);if(Ee.length===0){ce(C,U,j);return}const ye=j/2,xe=j*.44,Ce=j*.32;C.fillStyle="rgba(255, 255, 255, 0.26)",Ee.forEach(Re=>{const ze=Math.max(Re.time,ue),rt=Math.min(Re.endTime,Xe),at=(ze-ue)/be*U,Dt=Math.max(Dc,(rt-ze)/be*U),ht=W(Re.rms)*Ce;C.fillRect(at,ye-ht,Dt,ht*2)}),C.fillStyle="rgba(255, 255, 255, 0.72)",Ee.forEach(Re=>{const ze=Math.max(Re.time,ue),rt=Math.min(Re.endTime,Xe),at=(ze-ue)/be*U,Dt=Math.max(Dc,(rt-ze)/be*U),ht=W(Re.peak)*xe;C.fillRect(at,ye-ht,Dt,ht*2)})}function W(C){return Math.min(1,Math.max(0,C))}return e.watch(()=>[t.clip.id,t.clip.timelineStart,t.clip.timelineEnd,t.clip.sourceIn,t.clip.sourceOut,t.clip.waveformSamples,t.clip.filmstripFrames,t.scale,t.isMobile],K,{deep:!0,flush:"post"}),e.onMounted(()=>{K(),window.addEventListener("resize",Ne)}),e.onUnmounted(()=>{O(),A(),P(),window.removeEventListener("resize",Ne)}),(C,U)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["timeline-clip",{selected:C.selected,mobile:C.isMobile,"has-filters":y.value}]),style:e.normalizeStyle(h.value),onClick:T,onMousedown:$,onTouchstart:S},[e.createElementVNode("div",{class:"trim-handle trim-start",onMousedown:U[0]||(U[0]=e.withModifiers(j=>B("start",j),["stop"])),onTouchstart:U[1]||(U[1]=e.withModifiers(j=>B("start",j),["stop"])),"aria-label":`Trim start of ${C.clip.label||"clip"}`},[...U[7]||(U[7]=[e.createElementVNode("div",{class:"trim-grip"},null,-1)])],40,u1),e.createElementVNode("div",{class:"trim-handle trim-end",onMousedown:U[2]||(U[2]=e.withModifiers(j=>B("end",j),["stop"])),onTouchstart:U[3]||(U[3]=e.withModifiers(j=>B("end",j),["stop"])),"aria-label":`Trim end of ${C.clip.label||"clip"}`},[...U[8]||(U[8]=[e.createElementVNode("div",{class:"trim-grip"},null,-1)])],40,m1),e.createElementVNode("div",p1,[C.clip.thumbnail?(e.openBlock(),e.createElementBlock("div",f1,[e.createElementVNode("img",{src:C.clip.thumbnail,alt:C.clip.label||"Video clip"},null,8,h1)])):e.createCommentVNode("",!0),V.value?(e.openBlock(),e.createElementBlock("div",{key:1,class:e.normalizeClass(["clip-analysis-strip clip-filmstrip",{compact:C.isMobile}]),"aria-hidden":"true"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(b.value,j=>(e.openBlock(),e.createElementBlock("img",{key:j.id,class:"clip-filmstrip-frame",src:j.uri,alt:"",draggable:"false"},null,8,v1))),128))],2)):(e.openBlock(),e.createElementBlock("div",{key:2,class:e.normalizeClass(["clip-analysis-strip clip-waveform",{compact:C.isMobile}]),"data-visual-mode":R.value?"waveform":"placeholder","aria-hidden":"true"},[e.createElementVNode("canvas",{ref_key:"waveformCanvas",ref:i},null,512)],10,g1)),e.createElementVNode("div",b1,[e.createElementVNode("span",y1,e.toDisplayString(v.value),1),e.createElementVNode("span",w1,e.toDisplayString(k.value),1)]),y.value?(e.openBlock(),e.createElementBlock("div",k1,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(w.value,j=>(e.openBlock(),e.createBlock(e.unref(H.IonIcon),{key:j.id||j.filterId,icon:x(j.filterId||j.id),title:`Filter: ${j.filterId||j.id}`},null,8,["icon","title"]))),128))])):e.createCommentVNode("",!0),C.clip.speed&&C.clip.speed!==1?(e.openBlock(),e.createElementBlock("div",_1,e.toDisplayString(C.clip.speed)+"x ",1)):e.createCommentVNode("",!0)]),C.selected&&C.canDelete?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"clip-delete-button","aria-label":`Delete ${C.clip.label||"clip"}`,"data-testid":`timeline-clip-delete-${C.clip.id}`,title:"Delete clip",onClick:U[4]||(U[4]=e.withModifiers(j=>n("delete"),["stop"])),onMousedown:U[5]||(U[5]=e.withModifiers(()=>{},["stop"])),onTouchstart:U[6]||(U[6]=e.withModifiers(()=>{},["stop"]))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Dr)},null,8,["icon"])],40,E1)):e.createCommentVNode("",!0),C.selected?(e.openBlock(),e.createElementBlock("div",S1)):e.createCommentVNode("",!0)],38))}}),Ac=$e(T1,[["__scopeId","data-v-deeaa999"]]),B1={class:"timeline-track-header__meta"},I1=["data-testid"],M1=["data-testid","value","aria-label","onKeydown"],$1={class:"timeline-track-header__type"},F1=["aria-label"],D1=["aria-pressed","aria-label"],A1=["aria-pressed","aria-label"],R1=["aria-pressed","aria-label"],L1=["aria-pressed","aria-label"],P1={class:"timeline-track-header__menu-row"},U1=["data-testid","aria-label","aria-expanded"],O1=["aria-label"],z1=["data-testid"],j1=["data-testid"],W1=["data-testid"],H1=["data-testid"],Z1=e.defineComponent({__name:"TimelineTrackHeader",props:{track:{}},emits:["toggle-lock","toggle-hidden","toggle-muted","toggle-solo","rename-track","delete-track","reorder-track"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!1),r=e.ref(!1),l=e.ref(""),s=e.ref(null);function d(){i.value=!i.value}function c(){i.value=!1}function u(){c(),m()}async function m(){var y,w;l.value=t.track.name,r.value=!0,await e.nextTick(),(y=s.value)==null||y.focus(),(w=s.value)==null||w.select()}function p(y){const w=y.target;w&&(l.value=w.value)}function f(){if(!r.value)return;const y=l.value.trim();r.value=!1,!(y===""||y===t.track.name)&&n("rename-track",t.track.id,y)}function h(){r.value=!1}function v(y){c(),n("reorder-track",t.track.id,y)}function k(){c(),n("delete-track",t.track.id)}return(y,w)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["timeline-track-header",{"is-hidden":y.track.hidden===!0}])},[e.createElementVNode("div",B1,[r.value?(e.openBlock(),e.createElementBlock("input",{key:1,ref_key:"renameInput",ref:s,class:"timeline-track-header__rename-input","data-testid":`timeline-track-rename-${y.track.id}`,value:l.value,"aria-label":`Rename ${y.track.name}`,onInput:p,onKeydown:[e.withKeys(e.withModifiers(f,["prevent"]),["enter"]),e.withKeys(e.withModifiers(h,["prevent"]),["escape"])],onBlur:f},null,40,M1)):(e.openBlock(),e.createElementBlock("span",{key:0,class:"timeline-track-header__name","data-testid":`timeline-track-name-${y.track.id}`,onDblclick:m},e.toDisplayString(y.track.name),41,I1)),e.createElementVNode("span",$1,e.toDisplayString(y.track.type),1)]),e.createElementVNode("div",{class:"timeline-track-header__actions","aria-label":`Track controls for ${y.track.name}`},[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["timeline-track-header__button",{"is-active":y.track.locked===!0}]),"aria-pressed":y.track.locked===!0,"aria-label":y.track.locked===!0?`Unlock ${y.track.name}`:`Lock ${y.track.name}`,title:"Lock",onClick:w[0]||(w[0]=g=>n("toggle-lock",y.track.id))}," Lock ",10,D1),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["timeline-track-header__button",{"is-active":y.track.hidden===!0}]),"aria-pressed":y.track.hidden===!0,"aria-label":y.track.hidden===!0?`Show ${y.track.name}`:`Hide ${y.track.name}`,title:"Hide",onClick:w[1]||(w[1]=g=>n("toggle-hidden",y.track.id))}," Hide ",10,A1),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["timeline-track-header__button",{"is-active":y.track.muted===!0}]),"aria-pressed":y.track.muted===!0,"aria-label":y.track.muted===!0?`Unmute ${y.track.name}`:`Mute ${y.track.name}`,title:"Mute",onClick:w[2]||(w[2]=g=>n("toggle-muted",y.track.id))}," Mute ",10,R1),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["timeline-track-header__button",{"is-active":y.track.solo===!0}]),"aria-pressed":y.track.solo===!0,"aria-label":y.track.solo===!0?`Disable solo for ${y.track.name}`:`Solo ${y.track.name}`,title:"Solo",onClick:w[3]||(w[3]=g=>n("toggle-solo",y.track.id))}," Solo ",10,L1)],8,F1),e.createElementVNode("div",P1,[e.createElementVNode("button",{type:"button",class:"timeline-track-header__menu-button","data-testid":`timeline-track-menu-${y.track.id}`,"aria-label":`More actions for ${y.track.name}`,"aria-expanded":i.value,"aria-haspopup":!0,onClick:d}," ⋯ ",8,U1),i.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"timeline-track-header__menu",role:"menu","aria-label":`${y.track.name} actions`},[e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":`timeline-track-rename-action-${y.track.id}`,onClick:u}," Rename ",8,z1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":`timeline-track-move-up-${y.track.id}`,onClick:w[4]||(w[4]=g=>v("up"))}," Move up ",8,j1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":`timeline-track-move-down-${y.track.id}`,onClick:w[5]||(w[5]=g=>v("down"))}," Move down ",8,W1),e.createElementVNode("button",{type:"button",role:"menuitem",class:"timeline-track-header__menu-button--danger","data-testid":`timeline-track-delete-${y.track.id}`,onClick:k}," Delete track ",8,H1)],8,O1)):e.createCommentVNode("",!0)])],2))}}),G1=$e(Z1,[["__scopeId","data-v-54e2bc6a"]]);class jm{constructor(a=30){this.fps=30,this.fps=a}setFps(a){this.fps=a}async convertTimelineClipToEngine(a,t){const n=new xs(t,{muted:a.muted||!1,scale:a.scale||1,position:"center"});if(a.sourceIn!==void 0||a.sourceOut!==void 0){const i=this.secondsToFrames(a.sourceIn||0),r=a.sourceOut?this.secondsToFrames(a.sourceOut):n.duration.frames;n.subclip(i,r)}return a.timelineStart&&a.timelineStart>0&&n.offsetBy(this.secondsToFrames(a.timelineStart)),a.transform&&this.applyTransformations(n,a.transform),n}convertEngineClipToTimeline(a,t,n){const i=this.framesToSeconds(a.duration.frames),r=a.offset?this.framesToSeconds(a.offset.frames):0;return{id:t,url:n,type:"video",timelineStart:r,timelineEnd:r+i,sourceIn:0,sourceOut:i,duration:i,muted:a.muted||!1,scale:a.scale.x||1}}async buildCompositionFromRecipe(a,t){var n;(n=t.clear)==null||n.call(t);for(const i of a.timeline)try{if(!i.url)continue;const r=await Xn.from(i.url),l=await this.convertTimelineClipToEngine(i,r);await t.add(l)}catch{}a.duration&&(t.duration=je.fromFrames(this.secondsToFrames(a.duration)))}extractTimelineFromComposition(a){const t=[];return(a.clips||[]).forEach((i,r)=>{var l,s;i instanceof xs&&t.push(this.convertEngineClipToTimeline(i,`clip-${r}`,((l=i.source)==null?void 0:l.externalURL)||((s=i.source)==null?void 0:s.objectURL)||""))}),t}applyTransformations(a,t){(t.x!==void 0||t.y!==void 0)&&(a.x=t.x||0,a.y=t.y||0),t.rotation!==void 0&&(a.rotation=t.rotation),t.opacity!==void 0&&(a.alpha=t.opacity),t.scale!==void 0&&(a.scale={x:t.scale,y:t.scale})}secondsToFrames(a){return Math.round(a*this.fps)}framesToSeconds(a){return a/this.fps}framesToTime(a){const t=this.framesToSeconds(a),n=Math.floor(t/60),i=Math.floor(t%60),r=Math.floor(t%1*1e3);return`${n.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}.${r.toString().padStart(3,"0")}`}formatTime(a){const t=Math.floor(a/3600),n=Math.floor(a%3600/60),i=Math.floor(a%60);return`${t.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}`}parseTime(a){const t=a.split(":");let n=0;if(t.length===2){const[i,r]=t;n=parseInt(i)*60+parseFloat(r)}else if(t.length===3){const[i,r,l]=t;n=parseInt(i)*3600+parseInt(r)*60+parseFloat(l)}else n=parseFloat(a);return n}timeToFrames(a){const t=a.split(":");let n=0;if(t.length===2){const[i,r]=t;n=parseInt(i)*60+parseFloat(r)}else if(t.length===3){const[i,r,l]=t;n=parseInt(i)*3600+parseInt(r)*60+parseFloat(l)}else n=parseFloat(a);return this.secondsToFrames(n)}}const X1={class:"time-markers"},K1=["data-track-id"],J1=["data-track-id"],q1=["aria-label","title"],Y1={key:0,class:"timeline-scrollbar"},Rc=152,Lc=80,Q1=e.defineComponent({__name:"VideoTimeline",props:{playhead:{},clips:{},tracks:{},duration:{},zoomLevel:{default:50},isMobile:{type:Boolean,default:!1},snapEnabled:{type:Boolean,default:!0},selectedClipId:{},fps:{default:30},useFrameMode:{type:Boolean,default:!1},sensitivity:{default:.25}},emits:["update:playhead","trim","split","clip-select","clip-delete","clip-move","clip-long-press","snap-state-change","toggle-frame-mode","toggle-lock","toggle-hidden","toggle-muted","toggle-solo","rename-track","delete-track","reorder-track"],setup(o,{expose:a,emit:t}){const n=o,i=e.computed(()=>n.isMobile===!0),r=t,l=e.ref(),s=e.ref(n.selectedClipId||null),d=e.ref(!1),c=e.ref(0),u=e.ref(),m=e.ref(0),p=e.computed(()=>n.selectedClipId??s.value);e.watch(()=>n.selectedClipId,Q=>{Q!==void 0&&(s.value=Q)});const f=new jm(n.fps);e.watch(()=>n.fps,Q=>{f.setFps(Q)});const h=e.ref(!1),v=e.ref(null),k=e.ref(0),y=e.ref(0),w=e.ref(null),g=e.ref(null),b=e.ref(0),R=e.ref(0),V=e.ref(0),I=e.ref(!1),x=e.ref(0),T=e.ref(n.zoomLevel),$=e.computed(()=>n.zoomLevel),S=e.computed(()=>n.tracks!==void 0&&n.tracks.length>0&&!i.value),B=e.computed(()=>S.value?Rc:0),_=e.computed(()=>Math.max(0,W.value-B.value));function A(Q){return Q.trackId??`legacy-track-${Q.track??0}`}function P(Q,ge){return{id:Q,type:"video",name:`Track ${ge+1}`,order:ge}}const D=e.computed(()=>{const Q=new Map;for(const ge of n.clips){const me=A(ge),se=Q.get(me);if(se){se.push(ge);continue}Q.set(me,[ge])}return Q}),z=e.computed(()=>{if(!S.value)return[];const Q=[...n.tracks??[]].sort((se,Ve)=>se.order-Ve.order),ge=new Set(Q.map(se=>se.id)),me=[];for(const se of D.value.keys())ge.has(se)||me.push(P(se,Q.length+me.length));return[...Q,...me].map(se=>({track:se,clips:D.value.get(se.id)??[],height:se.height??Lc}))}),M=e.computed(()=>new Set(z.value.filter(Q=>Q.track.locked===!0).map(Q=>Q.track.id)));function Z(Q){const ge=n.clips.find(me=>me.id===Q);return ge?!M.value.has(A(ge)):!1}function O(Q){const ge=n.clips.find(Ve=>Ve.id===Q);if(!ge)return null;const me=A(ge),se=n.clips.filter(Ve=>Ve.id!==Q&&A(Ve)===me&&Ve.timelineStart>=ge.timelineEnd-1e-9).map(Ve=>Ve.timelineStart);return se.length?Math.min(...se):null}function K(Q){const ge=Q.sourceMaxOut??n.duration,me=Q.timelineStart+(ge-Q.sourceIn),se=O(Q.id),Ve=se!=null?Math.max(Q.timelineStart,se):1/0;return Math.min(me,Ve)}function de(Q,ge=Lc){const me=Q.sourceMinIn??0,Ve=(Q.sourceMaxOut??n.duration)-me,Pe=Q.sourceIn-me;return{left:`${(Q.timelineStart-Pe)*$.value-c.value}px`,width:`${Ve*$.value}px`,top:"0px",height:`${ge}px`,opacity:p.value===Q.id?.25:.15}}const Ne=e.computed(()=>n.useFrameMode?n.zoomLevel:n.zoomLevel/n.fps),ce=e.computed(()=>f.secondsToFrames(n.duration)),le=e.computed(()=>n.useFrameMode?ce.value*Ne.value:n.duration*$.value),W=e.computed(()=>{var Q;return m.value||((Q=l.value)==null?void 0:Q.clientWidth)||800}),C=e.computed(()=>le.value>_.value),U=e.computed(()=>Math.max(0,le.value-_.value)),j=e.computed(()=>c.value>0),re=e.computed(()=>c.value<U.value),ue=e.computed(()=>n.useFrameMode?f.secondsToFrames(n.playhead)*Ne.value-c.value:n.playhead*$.value-c.value),Xe=e.computed(()=>w.value===null?null:n.useFrameMode?f.secondsToFrames(w.value)*Ne.value-c.value:w.value*$.value-c.value),be=e.computed(()=>{const Q=_.value,ge=Math.max(50,Q/le.value*Q),me=c.value/U.value*(Q-ge);return{width:`${ge}px`,left:`${me}px`}}),Ee=e.computed(()=>{const Q=[],ge=ye();for(let me=0;me<=n.duration;me+=ge){const se=me*$.value-c.value;se>=-50&&se<=_.value+50&&Q.push({position:se+B.value,label:xe(me),time:me})}return Q});function ye(){const ge=80/$.value;return ge<=1?1:ge<=5?5:ge<=10?10:ge<=30?30:ge<=60?60:Math.ceil(ge/60)*60}function xe(Q){if(n.useFrameMode)return`F${f.secondsToFrames(Q)}`;{const ge=Math.floor(Q/60),me=Math.floor(Q%60),se=Math.floor(Q%1*n.fps);return $.value>100?`${ge}:${me.toString().padStart(2,"0")}:${se.toString().padStart(2,"0")}`:`${ge}:${me.toString().padStart(2,"0")}`}}function Ce(Q){const ge=l.value.getBoundingClientRect();let se=(Q.clientX-ge.left-B.value+c.value)/$.value;const Ve=n.clips.find(Pe=>se>=Pe.timelineStart&&se<=Pe.timelineEnd);if(Ve)se=Math.max(Ve.timelineStart,Math.min(Ve.timelineEnd,se));else if(n.selectedClipId){const Pe=n.clips.find(et=>et.id===n.selectedClipId);if(Pe){const et=Math.abs(se-Pe.timelineStart),gt=Math.abs(se-Pe.timelineEnd);se=et<gt?Pe.timelineStart:Pe.timelineEnd}}else se=Math.max(0,Math.min(se,n.duration));r("update:playhead",se)}function Re(Q){if(!C.value)return;const ge=Math.abs(Q.deltaX)>Math.abs(Q.deltaY)?Q.deltaX:Q.deltaY;ge!==0&&(Q.preventDefault(),c.value=Math.max(0,Math.min(U.value,c.value+ge)))}function ze(Q){return[...Q===void 0?n.clips:n.clips.filter(me=>A(me)===Q)].sort((me,se)=>me.timelineStart-se.timelineStart)}function rt(Q){const ge=n.clips.find(Ve=>Ve.id===Q),me=ze(ge?A(ge):void 0),se=me.findIndex(Ve=>Ve.id===Q);return{previous:se>0?me[se-1]:null,next:se!==-1&&se<me.length-1?me[se+1]:null}}function at(Q){const ge=Q.timelineEnd-Q.timelineStart,{previous:me,next:se}=rt(Q.id),Ve=me?me.timelineEnd:0,Pe=se?se.timelineStart-ge:Math.max(Q.timelineStart,n.duration-ge);return{minStart:Ve,maxStart:Math.max(Ve,Pe)}}function Dt(){return 12/Math.max($.value,1)}function ht(Q){return Array.from(new Set(Q.filter(ge=>typeof ge=="number"&&Number.isFinite(ge))))}function St(Q,ge,me,se){const Ve=Math.max(me,Math.min(Q,se));if(!n.snapEnabled)return{value:Ve,guideTime:null};const Pe=Dt();let et=Ve,gt=null,Tt=Number.POSITIVE_INFINITY;for(const xt of ht(ge)){if(xt<me||xt>se)continue;const _t=Math.abs(xt-Ve);_t<=Pe&&_t<Tt&&(et=xt,gt=xt,Tt=_t)}return{value:et,guideTime:gt}}function ut(Q){if(Q.touches.length===2){I.value=!0;const ge=Q.touches[0],me=Q.touches[1];x.value=Math.hypot(me.clientX-ge.clientX,me.clientY-ge.clientY),T.value=n.zoomLevel}else Q.touches.length===1&&(b.value=Q.touches[0].clientX,R.value=Q.touches[0].clientY,V.value=b.value)}function lt(Q){if(I.value&&Q.touches.length===2){const ge=Q.touches[0],me=Q.touches[1],Ve=Math.hypot(me.clientX-ge.clientX,me.clientY-ge.clientY)/x.value;Math.max(10,Math.min(200,T.value*Ve)),r("update:playhead",n.playhead)}else if(Q.touches.length===1&&!I.value){const ge=Q.touches[0],me=V.value-ge.clientX;Math.abs(me)>Math.abs(ge.clientY-R.value)&&(Q.preventDefault(),c.value=Math.max(0,Math.min(U.value,c.value+me)),V.value=ge.clientX)}}function Ct(){I.value=!1}function Se(Q){const ge=Q.target;if(ge.closest(".playhead-handle"))return;const me=Q.button===1,se=!!ge.closest(".video-track");(me||!se&&C.value)&&J(Q)}function J(Q){h.value=!0,v.value="pan",k.value=Q.clientX,y.value=c.value,document.addEventListener("mousemove",fe),document.addEventListener("mouseup",Ae)}function oe(Q){Q.preventDefault(),Q.stopPropagation(),h.value=!0,v.value="playhead";const ge="touches"in Q?Q.touches[0].clientX:Q.clientX;k.value=ge,y.value=n.playhead,"touches"in Q?(document.addEventListener("touchmove",fe),document.addEventListener("touchend",Ae)):(document.addEventListener("mousemove",fe),document.addEventListener("mouseup",Ae))}function De(Q){Q.preventDefault(),Q.stopPropagation(),h.value=!0,v.value="scrollbar";const ge="touches"in Q?Q.touches[0].clientX:Q.clientX;k.value=ge,y.value=c.value,"touches"in Q?(document.addEventListener("touchmove",fe),document.addEventListener("touchend",Ae)):(document.addEventListener("mousemove",fe),document.addEventListener("mouseup",Ae))}function fe(Q){if(!h.value)return;const me=("touches"in Q?Q.touches[0].clientX:Q.clientX)-k.value;if(v.value==="playhead"){const se=me/$.value;let Ve=y.value+se;if(n.selectedClipId){const Pe=n.clips.find(et=>et.id===n.selectedClipId);Pe?Ve=Math.max(Pe.timelineStart,Math.min(Pe.timelineEnd,Ve)):Ve=Math.max(0,Math.min(n.duration,Ve))}else{const Pe=n.clips.find(et=>n.playhead>=et.timelineStart&&n.playhead<=et.timelineEnd);Pe?Ve=Math.max(Pe.timelineStart,Math.min(Pe.timelineEnd,Ve)):Ve=Math.max(0,Math.min(n.duration,Ve))}r("update:playhead",Ve)}else if(v.value==="scrollbar"){const se=me/_.value*le.value;c.value=Math.max(0,Math.min(U.value,y.value+se))}else if(v.value==="pan"){const se=y.value-me;c.value=Math.max(0,Math.min(U.value,se))}}function Ae(){h.value=!1,v.value=null,w.value=null,g.value=null,document.removeEventListener("mousemove",fe),document.removeEventListener("mouseup",Ae),document.removeEventListener("touchmove",fe),document.removeEventListener("touchend",Ae)}function Ye(Q){s.value=s.value===Q?null:Q,r("clip-select",s.value)}function st(Q){Z(Q)&&(s.value=Q,r("clip-select",Q),r("clip-long-press",Q))}function Bt(Q){!Z(Q)||n.clips.length<=1||(s.value=Q,r("clip-select",Q),r("clip-delete",Q))}function Vt(Q,ge){if(!Z(Q))return;const me=n.clips.find(Ve=>Ve.id===Q);if(!me||Math.abs(ge)<2)return;const se=ge/$.value*n.sensitivity;if(n.useFrameMode){const Ve=f.secondsToFrames(me.sourceIn),Pe=f.secondsToFrames(se),et=Math.max(0,Ve+Pe),gt=f.framesToSeconds(et);r("trim",Q,"start",gt)}else{const Ve=Math.max(0,me.sourceIn+se);r("trim",Q,"start",Ve)}}function Lt(Q,ge){if(!Z(Q))return;const me=n.clips.find(X=>X.id===Q);if(!me||!l.value)return;const se=l.value.getBoundingClientRect(),Ve=ge-se.left-B.value,Pe=80;Ve<Pe?c.value=Math.max(0,c.value-8):Ve>se.width-B.value-Pe&&(c.value=Math.min(U.value,c.value+8));const et=Ve+c.value,gt=1/n.fps;let Tt=et/$.value;const{previous:xt}=rt(me.id),_t=St(Tt,[0,xt==null?void 0:xt.timelineEnd,n.playhead],0,me.timelineEnd-gt);Tt=_t.value,w.value=_t.guideTime;let Xt=me.sourceIn+(Tt-me.timelineStart);Xt=Math.round(Xt*n.fps)/n.fps,r("trim",Q,"start",Xt)}function Pt(Q,ge){if(!Z(Q))return;const me=n.clips.find(we=>we.id===Q);if(!me||!l.value)return;const se=l.value.getBoundingClientRect(),Ve=ge-se.left-B.value,Pe=80;Ve<Pe?c.value=Math.max(0,c.value-8):Ve>se.width-B.value-Pe&&(c.value=Math.min(U.value,c.value+8));const et=Ve+c.value,gt=1/n.fps,Tt=K(me);let xt=et/$.value;const{next:_t}=rt(me.id),Xt=St(xt,[_t==null?void 0:_t.timelineStart,n.playhead],me.timelineStart+gt,Tt);xt=Xt.value,w.value=Xt.guideTime;let X=me.sourceIn+(xt-me.timelineStart);X=Math.round(X*n.fps)/n.fps,r("trim",Q,"end",X)}function zt(Q){var me;if(!S.value||!l.value)return null;const ge=Array.from(l.value.querySelectorAll(".timeline-track-lane__body"));for(const se of ge){const Ve=se.getBoundingClientRect();if(Q>=Ve.top&&Q<=Ve.bottom){const Pe=se.getAttribute("data-track-id");if(!Pe)continue;return((me=n.tracks)==null?void 0:me.find(gt=>gt.id===Pe))??null}}return null}function Ot(Q,ge,me){if(!Z(Q))return;const se=n.clips.find(we=>we.id===Q);if(!se||!l.value)return;const Ve=l.value.getBoundingClientRect(),Pe=ge-Ve.left-B.value,et=80;Pe<et?c.value=Math.max(0,c.value-8):Pe>Ve.width-B.value-et&&(c.value=Math.min(U.value,c.value+8));const gt=Pe+c.value,Tt=se.timelineEnd-se.timelineStart,xt=at(se);let _t=gt/$.value;const Xt=St(_t,[xt.minStart,xt.maxStart,n.playhead,n.playhead-Tt],xt.minStart,xt.maxStart);_t=Xt.value,w.value=Xt.guideTime,_t=Math.round(_t*n.fps)/n.fps;let X;if(typeof me=="number"){const we=zt(me);g.value=(we==null?void 0:we.id)??null,we&&we.id!==(se.trackId??null)&&we.locked!==!0&&(X=we.id)}X!==void 0?r("clip-move",Q,_t,X):r("clip-move",Q,_t)}function jt(Q,ge){if(!Z(Q))return;const me=n.clips.find(Pe=>Pe.id===Q);if(!me||Math.abs(ge)<2)return;const se=ge/$.value*n.sensitivity,Ve=Pe=>Math.max(0,Math.round(Pe*n.fps)/n.fps);if(n.useFrameMode){const Pe=f.secondsToFrames(me.sourceOut),et=f.secondsToFrames(se),gt=K(me),Tt=me.sourceIn+(gt-me.timelineStart),xt=f.secondsToFrames(Tt),_t=Math.min(xt,Pe+et),Xt=f.framesToSeconds(_t);r("trim",Q,"end",Xt)}else{const Pe=K(me),et=me.sourceIn+(Pe-me.timelineStart),gt=Math.min(et,me.sourceOut+se),Tt=Ve(gt);r("trim",Q,"end",Tt)}}function oa(Q,ge){if(!Z(Q))return;const me=n.clips.find(Pe=>Pe.id===Q);if(!me||Math.abs(ge)<2)return;const se=ge/$.value*n.sensitivity,Ve=Pe=>Math.max(0,Math.round(Pe*n.fps)/n.fps);if(n.useFrameMode){const Pe=f.secondsToFrames(me.timelineStart),et=f.secondsToFrames(se),gt=Math.max(0,Pe+et),Tt=f.framesToSeconds(gt);r("clip-move",Q,Tt)}else{const Pe=Math.max(0,me.timelineStart+se),et=Ve(Pe);r("clip-move",Q,et)}}return a({handleTrimStart:Vt,handleTrimEnd:jt,handleClipDrag:oa,handleTrimStartAbs:Lt,handleTrimEndAbs:Pt,handleClipDragAbs:Ot,handleClipLongPress:st}),e.watch(()=>n.playhead,Q=>{const ge=Q*$.value;ge<c.value+50?c.value=Math.max(0,ge-50):ge>c.value+_.value-50&&(c.value=Math.min(U.value,ge-_.value+50))}),e.onMounted(()=>{const Q=new ResizeObserver(ge=>{ge[0]&&(m.value=Math.round(ge[0].contentRect.width))});l.value&&Q.observe(l.value),e.onUnmounted(()=>Q.disconnect())}),e.onUnmounted(()=>{Ae()}),e.watch([le,W],()=>{c.value>U.value&&(c.value=U.value)}),e.watch(w,(Q,ge)=>{const me=Q!==null;me!==(ge!==null)&&r("snap-state-change",me)}),(Q,ge)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-timeline",{mobile:i.value}]),ref_key:"timelineRef",ref:l,onWheel:Re},[e.createElementVNode("div",{class:"timeline-ruler",onClick:Ce},[e.createElementVNode("div",X1,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Ee.value,me=>(e.openBlock(),e.createElementBlock("span",{key:me.position,class:"time-marker",style:e.normalizeStyle({left:`${me.position}px`})},e.toDisplayString(me.label),5))),128))])]),e.createElementVNode("div",{class:e.normalizeClass(["timeline-content",{"is-pannable":C.value,"is-panning":h.value&&v.value==="pan","overflow-left":j.value,"overflow-right":re.value}]),onTouchstart:ut,onTouchmove:lt,onTouchend:Ct,onMousedown:Se},[S.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"timeline-track-lanes",style:e.normalizeStyle({"--timeline-track-header-width":`${Rc}px`})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(z.value,me=>(e.openBlock(),e.createElementBlock("div",{key:me.track.id,class:e.normalizeClass(["timeline-track-lane",{"timeline-track-lane--locked":me.track.locked,"timeline-track-lane--hidden":me.track.hidden,"timeline-track-lane--drop-target":g.value===me.track.id&&me.track.locked!==!0,"timeline-track-lane--drop-rejected":g.value===me.track.id&&me.track.locked===!0}]),style:e.normalizeStyle({height:`${me.height}px`}),"data-track-id":me.track.id},[e.createVNode(G1,{class:"timeline-track-lane__header",track:me.track,onToggleLock:ge[0]||(ge[0]=se=>r("toggle-lock",se)),onToggleHidden:ge[1]||(ge[1]=se=>r("toggle-hidden",se)),onToggleMuted:ge[2]||(ge[2]=se=>r("toggle-muted",se)),onToggleSolo:ge[3]||(ge[3]=se=>r("toggle-solo",se)),onRenameTrack:ge[4]||(ge[4]=(se,Ve)=>r("rename-track",se,Ve)),onDeleteTrack:ge[5]||(ge[5]=se=>r("delete-track",se)),onReorderTrack:ge[6]||(ge[6]=(se,Ve)=>r("reorder-track",se,Ve))},null,8,["track"]),e.createElementVNode("div",{class:"video-track timeline-track-lane__body","data-track-id":me.track.id},[me.track.hidden?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(me.clips,se=>(e.openBlock(),e.createElementBlock("div",{key:`${se.id}-extent`,class:"clip-extent",style:e.normalizeStyle(de(se,me.height)),"aria-hidden":"true"},null,4))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(me.clips,se=>(e.openBlock(),e.createBlock(Ac,{key:se.id,clip:se,scale:$.value,"scroll-offset":c.value,selected:p.value===se.id,"is-mobile":i.value,"can-delete":n.clips.length>1&&Z(se.id),"data-locked":me.track.locked===!0?"true":void 0,onSelect:Ve=>Ye(se.id),onDelete:Ve=>Bt(se.id),onLongPress:Ve=>st(se.id),onTrimStartAbs:Ve=>Lt(se.id,Ve),onTrimEndAbs:Ve=>Pt(se.id,Ve),onDragAbs:(Ve,Pe)=>Ot(se.id,Ve,Pe)},null,8,["clip","scale","scroll-offset","selected","is-mobile","can-delete","data-locked","onSelect","onDelete","onLongPress","onTrimStartAbs","onTrimEndAbs","onDragAbs"]))),128))],64))],8,J1)],14,K1))),128))],4)):(e.openBlock(),e.createElementBlock("div",{key:1,class:"video-track",ref_key:"trackRef",ref:u},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Q.clips,me=>(e.openBlock(),e.createElementBlock("div",{key:`${me.id}-extent`,class:"clip-extent",style:e.normalizeStyle(de(me)),"aria-hidden":"true"},null,4))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Q.clips,me=>(e.openBlock(),e.createBlock(Ac,{key:me.id,clip:me,scale:$.value,"scroll-offset":c.value,selected:p.value===me.id,"is-mobile":i.value,"can-delete":n.clips.length>1&&Z(me.id),onSelect:se=>Ye(me.id),onDelete:se=>Bt(me.id),onLongPress:se=>st(me.id),onTrimStartAbs:se=>Lt(me.id,se),onTrimEndAbs:se=>Pt(me.id,se),onDragAbs:(se,Ve)=>Ot(me.id,se,Ve)},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:`${B.value+ue.value}px`}),onMousedown:oe,onTouchstart:oe},[...ge[8]||(ge[8]=[e.createElementVNode("div",{class:"playhead-handle"},[e.createElementVNode("div",{class:"playhead-line"})],-1)])],36),d.value?(e.openBlock(),e.createElementBlock("div",{key:2,class:"split-indicator",style:e.normalizeStyle({left:`${B.value+ue.value}px`})},null,4)):e.createCommentVNode("",!0),Xe.value!==null?(e.openBlock(),e.createElementBlock("div",{key:3,class:"snap-guide",style:e.normalizeStyle({left:`${B.value+Xe.value}px`}),"aria-hidden":"true"},null,4)):e.createCommentVNode("",!0),i.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("button",{key:4,class:"frame-mode-toggle",onClick:ge[7]||(ge[7]=me=>Q.$emit("toggle-frame-mode")),"aria-label":Q.useFrameMode?"Switch to time mode":"Switch to frame mode",title:Q.useFrameMode?"Switch to time mode":"Switch to frame mode"},e.toDisplayString(Q.useFrameMode?"F":"T"),9,q1))],34),C.value?(e.openBlock(),e.createElementBlock("div",Y1,[e.createElementVNode("div",{class:"scrollbar-thumb",style:e.normalizeStyle(be.value),onMousedown:De,onTouchstart:De},null,36)])):e.createCommentVNode("",!0)],34))}}),Bs=$e(Q1,[["__scopeId","data-v-2484f443"]]),ew={key:0,class:"control-group primary-controls"},tw=["disabled"],aw=["disabled"],nw=["disabled"],ow=["disabled"],iw=["disabled"],rw=["disabled"],lw={key:1,class:"control-group mobile-action-controls"},sw=["aria-expanded"],dw={key:0,class:"mobile-action-menu",role:"menu","aria-label":"Clip actions","data-testid":"timeline-mobile-action-menu"},cw=["disabled"],uw=["disabled"],mw=["disabled"],pw=["disabled"],fw=["disabled"],hw=["disabled"],vw={class:"control-group zoom-controls"},gw={class:"zoom-slider"},bw=["value"],yw={class:"control-group playback-controls"},ww=["aria-label"],kw={key:2,class:"control-group speed-control"},_w=["value"],Ew=e.defineComponent({__name:"TimelineControls",props:{selectedClip:{},canSplit:{type:Boolean,default:!1},canDelete:{type:Boolean,default:!1},canAddTrack:{type:Boolean,default:!0},showAddTrack:{type:Boolean,default:!1},canUndo:{type:Boolean,default:!1},canRedo:{type:Boolean,default:!1},isPlaying:{type:Boolean,default:!1},zoomLevel:{default:50},playbackSpeed:{default:1},isMobile:{type:Boolean,default:!1}},emits:["split","delete","duplicate","add-track","undo","redo","zoom-in","zoom-out","zoom-change","fit-to-window","play-pause","frame-forward","frame-backward","skip-to-start","skip-to-end","speed-change"],setup(o,{emit:a}){const t=a,n=e.ref(!1);function i(p){switch(p){case"split":t("split");break;case"delete":t("delete");break;case"duplicate":t("duplicate");break;case"add-track":t("add-track");break;case"undo":t("undo");break;case"redo":t("redo");break}n.value=!1}function r(p){const f=p.target;t("zoom-change",Number(f.value))}function l(){t("fit-to-window")}function s(){t("frame-forward")}function d(){t("frame-backward")}function c(){t("skip-to-start")}function u(){t("skip-to-end")}function m(p){const f=p.target;t("speed-change",Number(f.value))}return(p,f)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["timeline-controls",{mobile:p.isMobile}])},[p.isMobile?(e.openBlock(),e.createElementBlock("div",lw,[e.createElementVNode("button",{class:"control-button","data-testid":"timeline-btn-mobile-actions","aria-expanded":n.value?"true":"false","aria-label":"Clip actions",onClick:f[6]||(f[6]=h=>n.value=!n.value)},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(sv)},null,8,["icon"]),f[20]||(f[20]=e.createElementVNode("span",{class:"control-label"},"Actions",-1))],8,sw),n.value?(e.openBlock(),e.createElementBlock("div",dw,[p.showAddTrack?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",role:"menuitem",disabled:!p.canAddTrack,"data-testid":"timeline-mobile-btn-add-track",onClick:f[7]||(f[7]=h=>i("add-track"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(kr)},null,8,["icon"]),f[21]||(f[21]=e.createTextVNode(" Add Track ",-1))],8,cw)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",role:"menuitem",disabled:!p.canUndo,"data-testid":"timeline-mobile-btn-undo",onClick:f[8]||(f[8]=h=>i("undo"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(sc)},null,8,["icon"]),f[22]||(f[22]=e.createTextVNode(" Undo ",-1))],8,uw),e.createElementVNode("button",{type:"button",role:"menuitem",disabled:!p.canRedo,"data-testid":"timeline-mobile-btn-redo",onClick:f[9]||(f[9]=h=>i("redo"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(lc)},null,8,["icon"]),f[23]||(f[23]=e.createTextVNode(" Redo ",-1))],8,mw),e.createElementVNode("button",{type:"button",role:"menuitem",disabled:!p.canSplit,"data-testid":"timeline-mobile-btn-split",onClick:f[10]||(f[10]=h=>i("split"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Fr)},null,8,["icon"]),f[24]||(f[24]=e.createTextVNode(" Split ",-1))],8,pw),e.createElementVNode("button",{type:"button",role:"menuitem",disabled:!p.selectedClip,"data-testid":"timeline-mobile-btn-duplicate",onClick:f[11]||(f[11]=h=>i("duplicate"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(ms)},null,8,["icon"]),f[25]||(f[25]=e.createTextVNode(" Duplicate ",-1))],8,fw),e.createElementVNode("button",{type:"button",role:"menuitem",class:"danger-menu-item",disabled:!p.canDelete,"data-testid":"timeline-mobile-btn-delete",onClick:f[12]||(f[12]=h=>i("delete"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Dr)},null,8,["icon"]),f[26]||(f[26]=e.createTextVNode(" Delete ",-1))],8,hw)])):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("div",ew,[p.showAddTrack?(e.openBlock(),e.createElementBlock("button",{key:0,class:"control-button",disabled:!p.canAddTrack,"data-testid":"timeline-btn-add-track","aria-label":"Add video track",title:"Add Track",onClick:f[0]||(f[0]=h=>p.$emit("add-track"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(kr)},null,8,["icon"]),f[16]||(f[16]=e.createElementVNode("span",{class:"control-label"},"Add Track",-1))],8,tw)):e.createCommentVNode("",!0),e.createElementVNode("button",{class:"control-button",disabled:!p.canUndo,"data-testid":"timeline-btn-undo","aria-label":"Undo",title:"Undo",onClick:f[1]||(f[1]=h=>p.$emit("undo"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(sc)},null,8,["icon"])],8,aw),e.createElementVNode("button",{class:"control-button",disabled:!p.canRedo,"data-testid":"timeline-btn-redo","aria-label":"Redo",title:"Redo",onClick:f[2]||(f[2]=h=>p.$emit("redo"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(lc)},null,8,["icon"])],8,nw),e.createElementVNode("button",{class:"control-button",disabled:!p.canSplit,"data-testid":"timeline-btn-split","aria-label":"Split selected clip at playhead",title:"Split",onClick:f[3]||(f[3]=h=>p.$emit("split"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Fr)},null,8,["icon"]),f[17]||(f[17]=e.createElementVNode("span",{class:"control-label"},"Split",-1))],8,ow),e.createElementVNode("button",{class:"control-button",disabled:!p.selectedClip,"data-testid":"timeline-btn-duplicate","aria-label":"Duplicate selected clip",title:"Duplicate",onClick:f[4]||(f[4]=h=>p.$emit("duplicate"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(ms)},null,8,["icon"]),f[18]||(f[18]=e.createElementVNode("span",{class:"control-label"},"Duplicate",-1))],8,iw),e.createElementVNode("button",{class:"control-button danger-button",disabled:!p.canDelete,"data-testid":"timeline-btn-delete","aria-label":"Delete selected clip",title:"Delete",onClick:f[5]||(f[5]=h=>p.$emit("delete"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Dr)},null,8,["icon"]),f[19]||(f[19]=e.createElementVNode("span",{class:"control-label"},"Delete",-1))],8,rw)])),e.createElementVNode("div",vw,[e.createElementVNode("button",{class:"control-button zoom-button",onClick:f[13]||(f[13]=h=>p.$emit("zoom-out")),"aria-label":"Zoom out"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(xv)},null,8,["icon"])]),e.createElementVNode("div",gw,[e.createElementVNode("input",{type:"range",value:p.zoomLevel,onInput:r,min:"10",max:"200",step:"5","aria-label":"Timeline zoom"},null,40,bw)]),e.createElementVNode("button",{class:"control-button zoom-button",onClick:f[14]||(f[14]=h=>p.$emit("zoom-in")),"aria-label":"Zoom in"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(kr)},null,8,["icon"])]),e.createElementVNode("button",{class:"control-button",onClick:l,"aria-label":"Fit timeline to window"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(cv)},null,8,["icon"]),f[27]||(f[27]=e.createElementVNode("span",{class:"control-label"},"Fit",-1))])]),e.createElementVNode("div",yw,[e.createElementVNode("button",{class:"control-button",onClick:c,"aria-label":"Skip to start"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Sv)},null,8,["icon"])]),e.createElementVNode("button",{class:"control-button",onClick:d,"aria-label":"Previous frame"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(wv)},null,8,["icon"])]),e.createElementVNode("button",{class:"control-button play-button",onClick:f[15]||(f[15]=h=>p.$emit("play-pause")),"aria-label":p.isPlaying?"Pause":"Play"},[e.createVNode(e.unref(H.IonIcon),{icon:p.isPlaying?e.unref(ad):e.unref(nd)},null,8,["icon"])],8,ww),e.createElementVNode("button",{class:"control-button",onClick:s,"aria-label":"Next frame"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Ev)},null,8,["icon"])]),e.createElementVNode("button",{class:"control-button",onClick:u,"aria-label":"Skip to end"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Cv)},null,8,["icon"])])]),p.isMobile?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",kw,[f[29]||(f[29]=e.createElementVNode("label",{class:"speed-label"},"Speed:",-1)),e.createElementVNode("select",{value:p.playbackSpeed,onChange:m,class:"speed-select","aria-label":"Playback speed"},[...f[28]||(f[28]=[e.createStaticVNode('<option value="0.25" data-v-c7b0395a>0.25x</option><option value="0.5" data-v-c7b0395a>0.5x</option><option value="1" data-v-c7b0395a>1x</option><option value="1.5" data-v-c7b0395a>1.5x</option><option value="2" data-v-c7b0395a>2x</option>',5)])],40,_w)]))],2))}}),Is=$e(Ew,[["__scopeId","data-v-c7b0395a"]]),Sw={key:0,class:"category-section"},Cw={class:"category-carousel-wrapper"},xw=["disabled"],Nw=["onClick","data-testid","aria-label"],Vw={class:"category-name"},Tw=["disabled"],Bw={class:"filter-section"},Iw={class:"filter-carousel-wrapper"},Mw=["disabled"],$w=["onClick","onKeydown","data-testid","aria-label"],Fw=["onClick"],Dw={class:"filter-preview"},Aw={class:"filter-placeholder"},Rw={class:"filter-name"},Lw=["disabled"],Pw={class:"carousel-pagination"},Uw=["onClick"],Ow={key:1,class:"filter-adjustments"},zw={class:"adjustment-header"},jw={class:"adjustment-actions"},Ww={key:0},Hw={key:0,class:"slider-control"},Zw={class:"control-label"},Gw={class:"slider-wrapper"},Xw={class:"slider-value"},Kw={key:1,class:"color-control"},Jw={class:"control-label"},qw={class:"color-wrapper"},Yw=["value","onInput","disabled"],Qw={class:"color-value"},ek={key:2,class:"toggle-control"},tk={class:"control-label"},ak={key:3,class:"select-control"},nk={class:"control-label"},ok=["value","onChange","disabled"],ik=["value"],rk={key:1,class:"no-params"},lk=e.defineComponent({__name:"VideoFilterCarousel",props:{filters:{},activeFilters:{},thumbnailUrl:{},showCategories:{type:Boolean,default:!0},compact:{type:Boolean,default:!1}},emits:["apply-filter","remove-filter","update-param","preview-filter"],setup(o,{emit:a}){const t=o,n=a,i=e.ref("all"),r=e.ref(null),l=e.ref(0),s=e.ref(0),d=e.ref(new Map),c=e.ref(),u=e.ref(),m={all:Sn,adjust:ai,color:Cn,blur:lr,light:ni,effects:zl,stylize:ui,advanced:Sn,distortion:mi,transform:mi};function p(M){return M.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function f(M){return M.replace(/[-_]/g," ").replace(/\b\w/g,Z=>Z.toUpperCase())}function h(M){return m[M.toLowerCase()]??Sn}const v=e.computed(()=>{const M=Array.from(new Set(t.filters.map(Z=>Z.category).filter(Z=>typeof Z=="string"&&Z.length>0))).sort((Z,O)=>Z.localeCompare(O));return[{id:"all",name:"All",icon:Sn},...M.map(Z=>({id:Z,name:f(Z),icon:h(Z)}))]}),k=e.computed(()=>i.value==="all"?t.filters:t.filters.filter(M=>M.category===i.value));e.watch(v,M=>{new Set(M.map(K=>K.id)).has(i.value)||(i.value="all");const O=Math.max(0,M.length-3);l.value>O&&(l.value=O)},{immediate:!0});function y(M){var Z;return((Z=t.activeFilters)==null?void 0:Z.has(M))||!1}function w(M){if(r.value=M,!y(M.id)&&(n("apply-filter",M),M.params&&M.params.length>0)){const Z=new Map;M.params.forEach(O=>{Z.set(O.id,O.default)}),d.value.set(M.id,Z)}n("preview-filter",M)}function g(M){var Z;n("remove-filter",M),d.value.delete(M),((Z=r.value)==null?void 0:Z.id)===M&&(r.value=null)}function b(M){if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){const Z=Number(M);return Number.isFinite(Z)?Z:null}return null}function R(M,Z){var W;const O=t.filters.find(C=>C.id===M),K=O==null?void 0:O.params.find(C=>C.id===Z),de=(K==null?void 0:K.default)??0,Ne=C=>typeof de=="number"?b(C)??de:typeof de=="boolean"?typeof C=="boolean"?C:de:typeof C=="string"?C:de,ce=(W=t.activeFilters)==null?void 0:W.get(M);if(ce&&ce.params){const C=ce.params[Z];if(C!=null)return Ne(C)}const le=d.value.get(M);if(le){const C=le.get(Z);if(C!=null)return Ne(C)}return de}function V(M,Z,O){var K;d.value.has(M)||d.value.set(M,new Map),(K=d.value.get(M))==null||K.set(Z,O),n("update-param",M,Z,O)}function I(M){if(typeof M=="boolean")return M?"On":"Off";if(typeof M=="string"){const O=b(M);return O===null?"0":Number.isInteger(O)?O.toString():O.toFixed(2)}const Z=b(M);return Z===null?"0":Number.isInteger(Z)?Z.toString():Z.toFixed(2)}function x(){if(r.value&&(n("apply-filter",r.value),r.value.params&&r.value.params.length>0)){const M=new Map;r.value.params.forEach(Z=>{M.set(Z.id,Z.default)}),d.value.set(r.value.id,M)}}function T(M){const Z=t.filters.find(O=>O.id===M);Z&&Z.params&&Z.params.forEach(O=>{V(M,O.id,O.default)})}function $(M){return{basic:ai,color:Cn,blur:lr,light:ni,effects:zl,stylize:ui,adjustment:ai,"color-matrix":Cn,glow:Sn,distortion:mi}[M]||Sn}function S(M){return{adjustment:ai,brightness:ni,contrast:ai,saturation:Cn,blur:lr,"gaussian-blur":lr,"color-matrix":Cn,grayscale:ui,sepia:ui,vignette:mi,glow:Sn,glitch:zl,godray:ni,lightmap:ni}[M.id]||$(M.category)}function B(){l.value>0&&(l.value--,z(c.value,l.value))}function _(){l.value<v.value.length-3&&(l.value++,z(c.value,l.value))}function A(){s.value>0&&(s.value--,z(u.value,s.value))}function P(){s.value<k.value.length-4&&(s.value++,z(u.value,s.value))}function D(M){s.value=M*4,z(u.value,s.value)}function z(M,Z){var O;if(M){const K=((O=M.querySelector(".category-chip, .filter-card"))==null?void 0:O.clientWidth)||100;M.scrollTo({left:Z*(K+8),behavior:"smooth"})}}return(M,Z)=>{var O;return e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-filter-carousel-container",{compact:M.compact}])},[M.showCategories?(e.openBlock(),e.createElementBlock("div",Sw,[e.createElementVNode("div",Cw,[e.createElementVNode("button",{onClick:B,class:"carousel-nav carousel-nav-left",disabled:l.value===0,"aria-label":"Previous categories","data-testid":"btn-filter-category-prev"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(dc)},null,8,["icon"])],8,xw),e.createElementVNode("div",{ref_key:"categoryCarouselRef",ref:c,class:"category-carousel"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(v.value,K=>(e.openBlock(),e.createElementBlock("button",{key:K.id,onClick:de=>i.value=K.id,class:e.normalizeClass(["category-chip",{active:i.value===K.id}]),"data-testid":`btn-filter-category-${p(K.id)}`,"aria-label":`Filter category ${K.name}`},[e.createVNode(e.unref(H.IonIcon),{icon:K.icon,class:"category-icon"},null,8,["icon"]),e.createElementVNode("span",Vw,e.toDisplayString(K.name),1)],10,Nw))),128))],512),e.createElementVNode("button",{onClick:_,class:"carousel-nav carousel-nav-right",disabled:l.value>=v.value.length-3,"aria-label":"Next categories","data-testid":"btn-filter-category-next"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(cc)},null,8,["icon"])],8,Tw)])])):e.createCommentVNode("",!0),e.createElementVNode("div",Bw,[e.createElementVNode("div",Iw,[e.createElementVNode("button",{onClick:A,class:"carousel-nav carousel-nav-left",disabled:s.value===0,"aria-label":"Previous filters","data-testid":"btn-filter-carousel-prev"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(dc)},null,8,["icon"])],8,Mw),e.createElementVNode("div",{ref_key:"filterCarouselRef",ref:u,class:"filter-carousel"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(k.value,K=>{var de;return e.openBlock(),e.createElementBlock("div",{key:K.id,class:e.normalizeClass(["filter-card",{active:y(K.id),selected:((de=r.value)==null?void 0:de.id)===K.id}]),onClick:Ne=>w(K),onKeydown:[e.withKeys(Ne=>w(K),["enter"]),e.withKeys(e.withModifiers(Ne=>w(K),["prevent"]),["space"])],role:"button",tabindex:"0","data-testid":`btn-video-filter-${p(K.id)}`,"aria-label":`Select filter ${K.name}`},[y(K.id)?(e.openBlock(),e.createElementBlock("div",{key:0,class:"filter-checkmark",onClick:e.withModifiers(Ne=>g(K.id),["stop"])},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(im)},null,8,["icon"])],8,Fw)):e.createCommentVNode("",!0),e.createElementVNode("div",Dw,[e.createElementVNode("div",Aw,[e.createVNode(e.unref(H.IonIcon),{icon:S(K),class:"filter-icon"},null,8,["icon"])])]),e.createElementVNode("span",Rw,e.toDisplayString(K.name),1)],42,$w)}),128))],512),e.createElementVNode("button",{onClick:P,class:"carousel-nav carousel-nav-right",disabled:s.value>=Math.max(0,k.value.length-4),"aria-label":"Next filters","data-testid":"btn-filter-carousel-next"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(cc)},null,8,["icon"])],8,Lw)]),e.createElementVNode("div",Pw,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Math.ceil(k.value.length/4),(K,de)=>(e.openBlock(),e.createElementBlock("span",{key:de,class:e.normalizeClass(["pagination-dot",{active:Math.floor(s.value/4)===de}]),onClick:Ne=>D(de)},null,10,Uw))),128))])]),r.value?(e.openBlock(),e.createElementBlock("div",Ow,[e.createElementVNode("div",zw,[e.createElementVNode("h4",null,e.toDisplayString(r.value.name),1),e.createElementVNode("div",jw,[y(r.value.id)?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("button",{key:0,onClick:x,class:"apply-btn","data-testid":"btn-apply-selected-filter"}," Apply Filter ")),y(r.value.id)?(e.openBlock(),e.createElementBlock("button",{key:1,onClick:Z[0]||(Z[0]=K=>g(r.value.id)),class:"remove-btn","data-testid":"btn-remove-selected-filter"}," Remove Filter ")):e.createCommentVNode("",!0),y(r.value.id)&&((O=r.value.params)==null?void 0:O.length)>0?(e.openBlock(),e.createElementBlock("button",{key:2,onClick:Z[1]||(Z[1]=K=>T(r.value.id)),class:"reset-btn","data-testid":"btn-reset-selected-filter"}," Reset ")):e.createCommentVNode("",!0)])]),r.value.params&&r.value.params.length>0?(e.openBlock(),e.createElementBlock("div",Ww,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.value.params,K=>(e.openBlock(),e.createElementBlock("div",{key:K.id,class:"adjustment-control"},[!K.type||K.type==="slider"?(e.openBlock(),e.createElementBlock("div",Hw,[e.createElementVNode("label",Zw,e.toDisplayString(K.label||K.id),1),e.createElementVNode("div",Gw,[e.createVNode(e.unref(H.IonRange),{value:R(r.value.id,K.id),onIonChange:de=>V(r.value.id,K.id,de.detail.value),min:K.min,max:K.max,step:K.step||.01,color:"primary",class:"compact-slider",disabled:!y(r.value.id),"data-testid":`range-filter-${p(r.value.id)}-${p(K.id)}`,"aria-label":`Adjust ${K.label||K.id} for ${r.value.name}`},null,8,["value","onIonChange","min","max","step","disabled","data-testid","aria-label"]),e.createElementVNode("span",Xw,e.toDisplayString(I(R(r.value.id,K.id))),1)])])):K.type==="color"?(e.openBlock(),e.createElementBlock("div",Kw,[e.createElementVNode("label",Jw,e.toDisplayString(K.label||K.id),1),e.createElementVNode("div",qw,[e.createElementVNode("input",{type:"color",value:R(r.value.id,K.id),onInput:de=>V(r.value.id,K.id,de.target.value),disabled:!y(r.value.id),class:"color-input"},null,40,Yw),e.createElementVNode("span",Qw,e.toDisplayString(R(r.value.id,K.id)),1)])])):K.type==="toggle"?(e.openBlock(),e.createElementBlock("div",ek,[e.createElementVNode("label",tk,e.toDisplayString(K.label||K.id),1),e.createVNode(e.unref(H.IonToggle),{checked:!!R(r.value.id,K.id),onIonChange:de=>V(r.value.id,K.id,de.detail.checked),disabled:!y(r.value.id),color:"primary"},null,8,["checked","onIonChange","disabled"])])):K.type==="select"?(e.openBlock(),e.createElementBlock("div",ak,[e.createElementVNode("label",nk,e.toDisplayString(K.label||K.id),1),e.createElementVNode("select",{value:R(r.value.id,K.id),onChange:de=>V(r.value.id,K.id,de.target.value),disabled:!y(r.value.id),class:"select-input"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(K.options,de=>(e.openBlock(),e.createElementBlock("option",{key:String(de.value),value:de.value},e.toDisplayString(de.label),9,ik))),128))],40,ok)])):e.createCommentVNode("",!0)]))),128))])):(e.openBlock(),e.createElementBlock("div",rk," This filter has no adjustable parameters "))])):e.createCommentVNode("",!0)],2)}}}),Ms=$e(lk,[["__scopeId","data-v-9efd15d9"]]);class sk{constructor(a){this.pixiFilters=new Map,this.filterParams=new Map,this.filterTypes=new Map,this.filterIntensity=new Map,this.composition=a}setComposition(a){this.composition=a}mapMediablesToPIXI(a){switch(a.filterId){case"blur":return this.createBlurFilter(a.params);case"brightness":return this.createBrightnessFilter(a.params);case"contrast":return this.createContrastFilter(a.params);case"saturation":return this.createSaturationFilter(a.params);case"hue":return this.createHueFilter(a.params);case"vintage":return this.createVintageFilter(a.params);case"grayscale":return this.createGrayscaleFilter();case"sepia":return this.createSepiaFilter();default:return null}}createBlurFilter(a){var t,n;try{const i=(n=(t=window.PIXI)==null?void 0:t.filters)==null?void 0:n.BlurFilter;if(!i)return null;const r=new i;return r.blur=a.intensity||5,r.quality=a.quality||4,r}catch{return null}}createBrightnessFilter(a){var t,n;try{const i=(n=(t=window.PIXI)==null?void 0:t.filters)==null?void 0:n.ColorMatrixFilter;if(!i)return null;const r=new i;return r.brightness(a.value||1,!1),r}catch{return null}}createContrastFilter(a){var t,n;try{const i=(n=(t=window.PIXI)==null?void 0:t.filters)==null?void 0:n.ColorMatrixFilter;if(!i)return null;const r=new i;return r.contrast(a.value||1,!1),r}catch{return null}}createSaturationFilter(a){var t,n;try{const i=(n=(t=window.PIXI)==null?void 0:t.filters)==null?void 0:n.ColorMatrixFilter;if(!i)return null;const r=new i;return r.saturate(a.value||1,!1),r}catch{return null}}createHueFilter(a){var t,n;try{const i=(n=(t=window.PIXI)==null?void 0:t.filters)==null?void 0:n.ColorMatrixFilter;if(!i)return null;const r=new i;return r.hue(a.rotation||0,!1),r}catch{return null}}createVintageFilter(a){var t,n;try{const i=(n=(t=window.PIXI)==null?void 0:t.filters)==null?void 0:n.ColorMatrixFilter;if(!i)return null;const r=new i;return r.vintage(!1),a.intensity&&(r.contrast(1.2,!1),r.saturate(.8,!1)),r}catch{return null}}createGrayscaleFilter(){var a,t;try{const n=(t=(a=window.PIXI)==null?void 0:a.filters)==null?void 0:t.ColorMatrixFilter;if(!n)return null;const i=new n;return i.desaturate(),i}catch{return null}}createSepiaFilter(){var a,t;try{const n=(t=(a=window.PIXI)==null?void 0:a.filters)==null?void 0:t.ColorMatrixFilter;if(!n)return null;const i=new n;return i.sepia(!1),i}catch{return null}}async applyFilters(a){if(this.composition){this.clearFilters();for(const t of a){const n=this.mapMediablesToPIXI(t);n&&(this.pixiFilters.set(t.id,n),this.filterParams.set(t.id,t.params),this.filterTypes.set(t.id,t.filterId),this.filterIntensity.set(t.id,t.intensity),await this.applyToComposition(t.id,n))}}}async applyToComposition(a,t){try{this.composition.applyFilter&&await this.composition.applyFilter(a,t)}catch{}}updateFilterParams(a,t){var i;const n=this.pixiFilters.get(a);n&&(this.filterParams.set(a,t),"blur"in n&&(n.blur=t.intensity||n.blur),"brightness"in n&&n.brightness(t.value||1,!1),"contrast"in n&&n.contrast(t.value||1,!1),"saturate"in n&&n.saturate(t.value||1,!1),"hue"in n&&n.hue(t.rotation||0,!1),(i=this.composition)!=null&&i.update&&this.composition.update())}getFilterParams(a){return this.filterParams.get(a)||{}}removeFilter(a){var t;this.pixiFilters.delete(a),this.filterParams.delete(a),this.filterTypes.delete(a),this.filterIntensity.delete(a),(t=this.composition)!=null&&t.removeFilter&&this.composition.removeFilter(a)}clearFilters(){var a;this.pixiFilters.clear(),this.filterParams.clear(),this.filterTypes.clear(),this.filterIntensity.clear(),(a=this.composition)!=null&&a.clearFilters&&this.composition.clearFilters()}getActiveFilters(){return Array.from(this.pixiFilters.values())}exportFilterConfig(){const a=[];return this.pixiFilters.forEach((t,n)=>{const i=this.filterParams.get(n)??{},r=this.filterTypes.get(n)??"unknown",l=this.filterIntensity.get(n)??1;a.push({id:n,filterId:r,params:i,intensity:l})}),a}async importFilterConfig(a){await this.applyFilters(a)}destroy(){this.clearFilters(),this.composition=null}}const dk={class:"video-filter-preview"},ck={class:"preview-title"},uk={class:"filter-controls"},mk={class:"control-input"},pk=["value","onInput","min","max","step"],fk={class:"param-value"},hk={class:"preview-container"},vk={key:0,class:"filter-presets"},gk=["onClick"],bk={class:"preview-actions"},yk=e.defineComponent({__name:"VideoFilterPreview",props:{filter:{},currentFrame:{},useVideoEngine:{type:Boolean,default:!1},composition:{}},emits:["update-params","apply"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(),r=e.ref(!1),l=e.ref({});let s,d,c=null,u=null;const m=e.computed(()=>{var x;return((x=t.filter)==null?void 0:x.paramRanges)||{}}),p=e.computed(()=>f.value.length>0),f=e.computed(()=>t.filter?{brightness:[{name:"Subtle",params:{value:.1}},{name:"Medium",params:{value:.3}},{name:"Strong",params:{value:.5}}],contrast:[{name:"Low",params:{value:.8}},{name:"Normal",params:{value:1}},{name:"High",params:{value:1.5}}],"gaussian-blur":[{name:"Subtle",params:{value:1}},{name:"Medium",params:{value:3}},{name:"Strong",params:{value:5}}]}[t.filter.id]||[]:[]);async function h(){var x;if(i.value){t.useVideoEngine&&t.composition&&(u=new sk(t.composition));try{if(s=new Jt.Application,await s.init({width:i.value.clientWidth,height:i.value.clientHeight,background:0,resolution:window.devicePixelRatio||1,autoDensity:!0,canvas:i.value}),(x=t.currentFrame)!=null&&x.dataUrl){const T=await Jt.Assets.load(t.currentFrame.dataUrl);d=new Jt.Sprite(T);const $=Math.min(s.screen.width/d.texture.width,s.screen.height/d.texture.height);d.scale.set($),d.anchor.set(.5),d.position.set(s.screen.width/2,s.screen.height/2),s.stage.addChild(d)}v()}catch{}}}function v(){if(!(!d||!t.filter))if(t.useVideoEngine&&u){const x={id:t.filter.id,filterId:t.filter.id,params:l.value,intensity:l.value.value??l.value.intensity??1};u.applyFilters([x]).then(()=>{}).catch(T=>{}),c&&(c.destroy(),c=null),c=k(t.filter.id,l.value),c&&(d.filters=r.value?null:[c])}else c&&(c.destroy(),c=null),c=k(t.filter.id,l.value),c&&(d.filters=r.value?null:[c])}function k(x,T){switch(x){case"brightness":{const $=new Jt.ColorMatrixFilter,S=1+(T.value??0);return typeof $.brightness=="function"&&$.brightness(S,!1),$}case"contrast":{const $=new Jt.ColorMatrixFilter,S=T.value??1;return typeof $.contrast=="function"&&$.contrast(S,!1),$}case"saturation":{const $=new Jt.ColorMatrixFilter,S=T.value??1;return typeof $.saturate=="function"&&$.saturate(S,!1),$}case"hue":{const $=new Jt.ColorMatrixFilter,S=T.value??0;return typeof $.hue=="function"&&$.hue(S,!1),$}case"gaussian-blur":{const $=T.value??5;return new Jt.BlurFilter({strength:$,quality:4})}case"sepia":{const $=new Jt.ColorMatrixFilter;return typeof $.sepia=="function"&&$.sepia(!1),$}case"grayscale":{const $=new Jt.ColorMatrixFilter;return typeof $.desaturate=="function"&&$.desaturate(),$}default:return null}}function y(x,T){const $=T.target,S=Number.parseFloat($.value),B=Number.isFinite(S)?S:0;l.value={...l.value,[x]:B},t.useVideoEngine&&u&&t.filter&&u.updateFilterParams(t.filter.id,l.value),n("update-params",l.value),v()}function w(x){return x.charAt(0).toUpperCase()+x.slice(1).replace(/_/g," ")}function g(x,T){var S;const $=typeof x=="number"?x:Number(x);return Number.isFinite($)?T==="hue"||T==="angle"?`${$}°`:T==="value"&&((S=t.filter)==null?void 0:S.id)==="brightness"?`${Math.round((1+$)*100)}%`:Number.isInteger($)?$.toString():$.toFixed(2):"0"}function b(){var x;l.value=((x=t.filter)==null?void 0:x.defaultParams)||{},n("update-params",l.value),v()}function R(x){l.value={...x.params},n("update-params",l.value),v()}function V(x){return JSON.stringify(x.params)===JSON.stringify(l.value)}function I(){n("apply")}return e.watch(()=>t.filter,x=>{x&&(l.value={...x.defaultParams},v())}),e.watch(()=>t.currentFrame,async x=>{if(x!=null&&x.dataUrl&&d){const T=await Jt.Assets.load(x.dataUrl);d.texture=T}}),e.watch(r,v),e.onMounted(()=>{t.filter&&(l.value={...t.filter.defaultParams}),h()}),e.onUnmounted(()=>{s&&s.destroy(!0,{children:!0,texture:!0}),c&&c.destroy(),u&&u.destroy()}),(x,T)=>{var $;return e.openBlock(),e.createElementBlock("div",dk,[e.createElementVNode("h4",ck,e.toDisplayString(($=x.filter)==null?void 0:$.name)+" Settings",1),e.createElementVNode("div",uk,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(m.value,(S,B)=>(e.openBlock(),e.createElementBlock("div",{key:B,class:"control-group"},[e.createElementVNode("label",null,e.toDisplayString(w(B)),1),e.createElementVNode("div",mk,[e.createElementVNode("input",{type:"range",value:l.value[B],onInput:_=>y(B,_),min:S.min,max:S.max,step:S.step,class:"param-slider"},null,40,pk),e.createElementVNode("span",fk,e.toDisplayString(g(l.value[B],B)),1)])]))),128))]),e.createElementVNode("div",hk,[e.createElementVNode("canvas",{ref_key:"previewCanvas",ref:i,class:"preview-canvas"},null,512),e.createElementVNode("button",{class:"compare-button",onMousedown:T[0]||(T[0]=S=>r.value=!0),onMouseup:T[1]||(T[1]=S=>r.value=!1),onTouchstart:T[2]||(T[2]=S=>r.value=!0),onTouchend:T[3]||(T[3]=S=>r.value=!1)},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(mi)},null,8,["icon"]),T[4]||(T[4]=e.createTextVNode(" Hold to compare ",-1))],32)]),p.value?(e.openBlock(),e.createElementBlock("div",vk,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(f.value,S=>(e.openBlock(),e.createElementBlock("button",{key:S.name,class:e.normalizeClass(["preset-button",{active:V(S)}]),onClick:B=>R(S)},e.toDisplayString(S.name),11,gk))),128))])):e.createCommentVNode("",!0),e.createElementVNode("div",bk,[e.createElementVNode("button",{class:"action-button",onClick:b},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(io)},null,8,["icon"]),T[5]||(T[5]=e.createTextVNode(" Reset ",-1))]),e.createElementVNode("button",{class:"action-button primary",onClick:I},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(rm)},null,8,["icon"]),T[6]||(T[6]=e.createTextVNode(" Apply Filter ",-1))])])])}}}),$s=$e(yk,[["__scopeId","data-v-3de3dd04"]]),Wm={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"}},Hm={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"}},Zm={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"}},Gm={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"}},Xm=[Wm,Hm,Zm,Gm],kd={"mobile-share":Wm,"hd-web":Hm,original:Zm,"server-master":Gm},wk=["mobile-share","hd-web"],kk=["hd-web","original","mobile-share"],_k=["server-master","hd-web","original","mobile-share"];function vl(o){return typeof o=="string"?kd[o]:o}function Ek(o){const{bitrate:a,codec:t,format:n,fps:i,quality:r}=vl(o).settings,l={format:n,codec:t,quality:r,fps:i};return typeof a=="number"&&(l.bitrate=a),l}function Sk(o){const a=vl(o);return a.settings.mobileSuitable&&a.settings.advancedVisibility==="standard"}function Ck(o=Xm){return o.filter(a=>Sk(a))}function xk(o,a){const t=vl(o).settings.maxClientDurationSeconds;return t!==null&&Number.isFinite(a)&&a>=0&&a<=t}function Nk(o,a){const t=vl(o),n=a.endpoints.client&&xk(t,a.durationSeconds),i=a.endpoints.server;return t.settings.routePreference==="client"?n?"client":i?"server":null:t.settings.routePreference==="server"?i?"server":n?"client":null:n?"client":i?"server":null}function Vk(o,a){return Nk(o,a)!==null}function Tk(o){const a=Bk(o);for(const t of a){const n=kd[t];if(Ik(n,o.includeAdvanced===!0)&&!(o.device==="mobile"&&!n.settings.mobileSuitable)&&Vk(n,o))return n}return null}function Bk(o){return o.device==="mobile"?wk:o.includeAdvanced===!0?_k:kk}function Ik(o,a){return o.settings.advancedVisibility==="hidden"?!1:o.settings.advancedVisibility==="standard"||a}const Mk={class:"export-settings"},$k={class:"setting-group preset-setting"},Fk={class:"setting-copy"},Dk={class:"setting-description"},Ak=["value"],Rk={key:0,class:"advanced-toggle","data-testid":"export-advanced-toggle"},Lk={class:"preset-summary","data-testid":"export-preset-summary"},Pk={class:"estimated-size"},Uk={key:0,class:"export-progress"},Ok={class:"progress-header"},zk={class:"progress-percentage"},jk={class:"progress-time"},Wk={class:"action-buttons"},Hk=["disabled"],Zk=["disabled"],Gk=["disabled"],Xk={class:"export-options"},Kk="hd-web",Jk=e.defineComponent({__name:"EditorControls",props:{canExport:{type:Boolean,default:!1},isExporting:{type:Boolean,default:!1},exportProgress:{default:0},isMobile:{type:Boolean,default:!1},duration:{default:0}},emits:["export","save-draft","reset","cancel-export"],setup(o,{emit:a}){const t=o,n=a,i={client:!0,server:!0},r=Xm,l={"360p":1,"480p":2.5,"720p":5,"1080p":8,"1440p":16,"2160p":35},s=e.ref(!1),d=e.ref(b()),c=e.ref(!0),u=e.ref(!1),m=e.ref(0),p=e.ref(0),f=e.ref(0);let h=null;const v=e.computed(()=>t.isMobile?Ck():r.filter(S=>S.settings.advancedVisibility==="hidden"?!1:S.settings.advancedVisibility==="standard"||s.value)),k=e.computed(()=>v.value.find(S=>S.id===d.value)??kd[b()]),y=e.computed(()=>Ek(k.value)),w=e.computed(()=>{const S=y.value,B=[S.quality,S.format.toUpperCase(),S.codec.toUpperCase(),`${S.fps} fps`],_=R(S.bitrate);return _!==null&&B.push(_),B.join(" / ")}),g=e.computed(()=>{const S=y.value,_=(typeof S.bitrate=="number"?S.bitrate/1e6:l[S.quality])*t.duration/8;return _<1e3?`~${Math.round(_)} MB`:`~${(_/1e3).toFixed(1)} GB`});function b(){var S;return((S=Tk({durationSeconds:t.duration,device:t.isMobile?"mobile":"desktop",endpoints:i,includeAdvanced:s.value}))==null?void 0:S.id)??Kk}function R(S){return typeof S!="number"?null:`${Number((S/1e6).toFixed(1))} Mbps`}function V(){t.isExporting?(n("cancel-export"),T()):I()}function I(){const S=y.value,B={quality:S.quality,format:S.format,optimizeForWeb:c.value,includeWatermark:u.value,presetId:k.value.id,codec:S.codec,fps:S.fps};typeof S.bitrate=="number"&&(B.bitrate=S.bitrate),n("export",B),x()}function x(){m.value=Date.now(),p.value=0,h=window.setInterval(()=>{if(p.value=Math.floor((Date.now()-m.value)/1e3),t.exportProgress>0){const S=p.value/t.exportProgress*100;f.value=Math.max(0,S-p.value)}},1e3)}function T(){h&&(clearInterval(h),h=null)}function $(S){const B=Math.floor(S/60),_=Math.floor(S%60);return`${B}:${_.toString().padStart(2,"0")}`}return e.watch([()=>t.isMobile,()=>s.value],()=>{v.value.some(B=>B.id===d.value)||(d.value=b())},{immediate:!0}),e.watch(()=>t.isExporting,S=>{S||T()}),e.onUnmounted(()=>{T()}),(S,B)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["editor-controls",{mobile:S.isMobile}])},[e.createElementVNode("div",Mk,[B[8]||(B[8]=e.createElementVNode("h3",{class:"section-title"},"Export Settings",-1)),e.createElementVNode("div",$k,[e.createElementVNode("div",Fk,[B[6]||(B[6]=e.createElementVNode("label",{for:"export-preset-select"},"Preset",-1)),e.createElementVNode("span",Dk,e.toDisplayString(k.value.description),1)]),e.withDirectives(e.createElementVNode("select",{id:"export-preset-select","onUpdate:modelValue":B[0]||(B[0]=_=>d.value=_),class:"setting-select preset-select","data-testid":"export-preset-select"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(v.value,_=>(e.openBlock(),e.createElementBlock("option",{key:_.id,value:_.id},e.toDisplayString(_.label),9,Ak))),128))],512),[[e.vModelSelect,d.value]])]),S.isMobile?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("label",Rk,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":B[1]||(B[1]=_=>s.value=_),type:"checkbox","data-testid":"export-advanced-toggle-input"},null,512),[[e.vModelCheckbox,s.value]]),B[7]||(B[7]=e.createElementVNode("span",null,"Advanced presets",-1))])),e.createElementVNode("div",Lk,e.toDisplayString(w.value),1),e.createElementVNode("div",Pk,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(fv)},null,8,["icon"]),e.createElementVNode("span",null,"Estimated size: "+e.toDisplayString(g.value),1)])]),S.isExporting?(e.openBlock(),e.createElementBlock("div",Uk,[e.createElementVNode("div",Ok,[B[9]||(B[9]=e.createElementVNode("span",null,"Exporting...",-1)),e.createElementVNode("span",zk,e.toDisplayString(S.exportProgress??0)+"%",1)]),e.createVNode(e.unref(H.IonProgressBar),{value:(S.exportProgress??0)/100},null,8,["value"]),e.createElementVNode("div",jk,[e.createElementVNode("span",null,e.toDisplayString($(p.value))+" elapsed",1),e.createElementVNode("span",null,e.toDisplayString($(f.value))+" remaining",1)])])):e.createCommentVNode("",!0),e.createElementVNode("div",Wk,[e.createElementVNode("button",{class:"control-button secondary",onClick:B[2]||(B[2]=_=>S.$emit("save-draft")),disabled:!S.canExport||S.isExporting},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(el)},null,8,["icon"]),B[10]||(B[10]=e.createTextVNode(" Save Draft ",-1))],8,Hk),e.createElementVNode("button",{class:"control-button secondary",onClick:B[3]||(B[3]=_=>S.$emit("reset")),disabled:S.isExporting},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(io)},null,8,["icon"]),B[11]||(B[11]=e.createTextVNode(" Reset ",-1))],8,Zk),e.createElementVNode("button",{class:"control-button primary",onClick:V,disabled:!S.canExport&&!S.isExporting,"data-testid":"video-export-button"},[e.createVNode(e.unref(H.IonIcon),{icon:S.isExporting?e.unref(Yn):e.unref(Fo)},null,8,["icon"]),e.createTextVNode(" "+e.toDisplayString(S.isExporting?"Cancel":"Export Video"),1)],8,Gk)]),e.createElementVNode("div",Xk,[e.createVNode(e.unref(H.IonItem),{lines:"none"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonCheckbox),{modelValue:c.value,"onUpdate:modelValue":B[4]||(B[4]=_=>c.value=_)},null,8,["modelValue"]),e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...B[12]||(B[12]=[e.createTextVNode("Optimize for web streaming",-1)])]),_:1})]),_:1}),e.createVNode(e.unref(H.IonItem),{lines:"none"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonCheckbox),{modelValue:u.value,"onUpdate:modelValue":B[5]||(B[5]=_=>u.value=_)},null,8,["modelValue"]),e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...B[13]||(B[13]=[e.createTextVNode("Include watermark",-1)])]),_:1})]),_:1})])],2))}}),Fs=$e(Jk,[["__scopeId","data-v-d26ca1bc"]]),qk={class:"thumbnail-picker"},Yk={class:"thumbnail-grid"},Qk=["onClick"],e_=["src","alt"],t_={key:1,class:"thumbnail-placeholder"},a_={class:"thumbnail-time"},n_={class:"custom-selector"},o_={class:"time-input-group"},i_=["max"],r_={class:"time-value"},l_=["disabled"],s_={class:"picker-actions"},d_=["disabled"],c_=e.defineComponent({__name:"ThumbnailPicker",props:{mediaUuid:{},duration:{},currentTime:{default:0}},emits:["select","cancel"],setup(o,{emit:a}){const t=o,n=a,i=e.ref([]),r=e.ref(-1),l=e.ref(t.currentTime),s=e.ref(!1);function d(){const y=[];if(t.duration<=10)for(let g=0;g<Math.min(9,t.duration);g++)y.push(g);else{const g=t.duration/10;for(let b=1;b<=9;b++)y.push(g*b)}return y}async function c(y){try{const w=document.createElement("video");return w.crossOrigin="anonymous",w.src=await u(),new Promise(g=>{w.addEventListener("loadedmetadata",()=>{w.currentTime=y}),w.addEventListener("seeked",()=>{const b=document.createElement("canvas");b.width=w.videoWidth,b.height=w.videoHeight;const R=b.getContext("2d");R?(R.drawImage(w,0,0),g(b.toDataURL("image/jpeg",.8))):g(null),w.remove()}),w.addEventListener("error",()=>{g(null),w.remove()})})}catch{return null}}async function u(){try{return(await(await fetch(`/api/media/${t.mediaUuid}/playback`)).json()).playback_url}catch{return`/media/${t.mediaUuid}/video`}}async function m(){const y=d();i.value=y.map(g=>({time:g,loading:!0}));const w=3;for(let g=0;g<i.value.length;g+=w){const b=i.value.slice(g,g+w);await Promise.all(b.map(async R=>{const V=await c(R.time);V&&(R.dataUrl=V),R.loading=!1}))}}function p(y){r.value=y,l.value=i.value[y].time}function f(){r.value=-1}async function h(){s.value=!0;try{const y=await c(l.value);if(y){const w=i.value.findIndex(g=>Math.abs(g.time-l.value)<.1);w>=0?(i.value[w].dataUrl=y,r.value=w):(i.value.push({time:l.value,dataUrl:y}),r.value=i.value.length-1,i.value.sort((g,b)=>g.time-b.time),r.value=i.value.findIndex(g=>g.time===l.value))}}finally{s.value=!1}}function v(){const y=r.value>=0?i.value[r.value].time:l.value;n("select",y)}function k(y){const w=Math.floor(y/60),g=Math.floor(y%60),b=Math.floor(y%1*100);return w>0?`${w}:${g.toString().padStart(2,"0")}.${b.toString().padStart(2,"0")}`:`${g}.${b.toString().padStart(2,"0")}s`}return e.onMounted(()=>{m()}),(y,w)=>(e.openBlock(),e.createElementBlock("div",qk,[w[5]||(w[5]=e.createElementVNode("h4",{class:"picker-title"},"Select Video Thumbnail",-1)),e.createElementVNode("div",Yk,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,(g,b)=>(e.openBlock(),e.createElementBlock("div",{key:b,class:e.normalizeClass(["thumbnail-item",{selected:r.value===b}]),onClick:R=>p(b)},[g.dataUrl?(e.openBlock(),e.createElementBlock("img",{key:0,src:g.dataUrl,alt:`Frame at ${k(g.time)}`},null,8,e_)):(e.openBlock(),e.createElementBlock("div",t_,[e.createVNode(e.unref(H.IonSpinner),{name:"crescent"})])),e.createElementVNode("div",a_,e.toDisplayString(k(g.time)),1)],10,Qk))),128))]),e.createElementVNode("div",n_,[w[3]||(w[3]=e.createElementVNode("label",null,"Custom time:",-1)),e.createElementVNode("div",o_,[e.withDirectives(e.createElementVNode("input",{type:"range","onUpdate:modelValue":w[0]||(w[0]=g=>l.value=g),min:0,max:y.duration,step:.1,onInput:f,class:"time-slider"},null,40,i_),[[e.vModelText,l.value]]),e.createElementVNode("span",r_,e.toDisplayString(k(l.value)),1)]),e.createElementVNode("button",{class:"capture-button",onClick:h,disabled:s.value},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(av)},null,8,["icon"]),w[2]||(w[2]=e.createTextVNode(" Capture Frame ",-1))],8,l_)]),e.createElementVNode("div",s_,[e.createElementVNode("button",{class:"action-button",onClick:w[1]||(w[1]=g=>y.$emit("cancel"))}," Cancel "),e.createElementVNode("button",{class:"action-button primary",onClick:v,disabled:r.value===-1},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(rm)},null,8,["icon"]),w[4]||(w[4]=e.createTextVNode(" Set Thumbnail ",-1))],8,d_)])]))}}),u_=$e(c_,[["__scopeId","data-v-336c322c"]]),m_={class:"text-overlay-panel p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg"},p_={class:"mb-4"},f_={class:"space-y-2 max-h-64 overflow-y-auto"},h_={class:"flex items-center justify-between"},v_={class:"flex-1"},g_={class:"font-medium text-gray-900 dark:text-white"},b_={class:"text-sm text-gray-500 dark:text-gray-400"},y_={class:"flex items-center space-x-2"},w_=["onClick"],k_=["onClick"],__={key:0,class:"text-center py-8 text-gray-500 dark:text-gray-400"},E_={class:"bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 w-full max-w-lg mx-4"},S_={class:"text-lg font-semibold text-gray-900 dark:text-white mb-4"},C_={class:"space-y-4"},x_={class:"grid grid-cols-2 gap-4"},N_={class:"grid grid-cols-2 gap-4"},V_={key:0,class:"p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"},T_={class:"grid grid-cols-2 gap-3"},B_={class:"flex justify-end space-x-3 mt-6"},I_=e.defineComponent({__name:"TextOverlayPanel",props:{overlays:{}},emits:["add-overlay","update-overlay","remove-overlay"],setup(o,{emit:a}){const t=a,n=e.ref(!1),i=e.ref(null),r=()=>({id:"",text:"",fontSize:24,color:"#ffffff",position:"center",startTime:0,duration:5,animationType:"",animationDuration:1,animationEasing:"linear"}),l=e.reactive(r());function s(p){Object.assign(l,p),i.value=p}function d(){n.value=!1,i.value=null,Object.assign(l,r())}function c(){const p={text:l.text,fontSize:l.fontSize,color:l.color,position:l.position,startTime:l.startTime,duration:l.duration};if(l.animationType&&(p.animation={type:l.animationType},l.animationDuration!==void 0&&(p.animation.duration=l.animationDuration),l.animationEasing&&(p.animation.easing=l.animationEasing),p.animation))switch(l.animationType){case"rotate":p.animation.rotation={from:0,to:360};break;case"scale":p.animation.scale={from:.5,to:1};break;case"slide":p.animation.translate={fromX:-100,toX:0,fromY:0,toY:0};break}i.value?t("update-overlay",i.value.id,p):t("add-overlay",p),d()}function u(p){confirm("Are you sure you want to remove this text overlay?")&&t("remove-overlay",p)}function m(p){const f=Math.floor(p/60),h=Math.floor(p%60);return`${f}:${h.toString().padStart(2,"0")}`}return(p,f)=>(e.openBlock(),e.createElementBlock("div",m_,[e.createElementVNode("div",p_,[f[11]||(f[11]=e.createElementVNode("h3",{class:"text-lg font-semibold text-gray-900 dark:text-white mb-2"}," Text Overlays ",-1)),e.createElementVNode("button",{onClick:f[0]||(f[0]=h=>n.value=!0),class:"w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"},[...f[10]||(f[10]=[e.createElementVNode("svg",{class:"w-5 h-5 inline-block mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 4v16m8-8H4"})],-1),e.createTextVNode(" Add Text Overlay ",-1)])])]),e.createElementVNode("div",f_,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(p.overlays,h=>(e.openBlock(),e.createElementBlock("div",{key:h.id,class:"p-3 border border-gray-200 dark:border-gray-700 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"},[e.createElementVNode("div",h_,[e.createElementVNode("div",v_,[e.createElementVNode("div",g_,e.toDisplayString(h.text.substring(0,30))+e.toDisplayString(h.text.length>30?"...":""),1),e.createElementVNode("div",b_,e.toDisplayString(m(h.startTime??0))+" - "+e.toDisplayString(m((h.startTime||0)+(h.duration||5))),1)]),e.createElementVNode("div",y_,[e.createElementVNode("button",{onClick:v=>s(h),class:"p-1 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900 rounded",title:"Edit"},[...f[12]||(f[12]=[e.createElementVNode("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})],-1)])],8,w_),e.createElementVNode("button",{onClick:v=>u(h.id),class:"p-1 text-red-600 hover:bg-red-50 dark:hover:bg-red-900 rounded",title:"Remove"},[...f[13]||(f[13]=[e.createElementVNode("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})],-1)])],8,k_)])])]))),128)),p.overlays.length===0?(e.openBlock(),e.createElementBlock("div",__," No text overlays added yet ")):e.createCommentVNode("",!0)]),n.value||i.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",onClick:e.withModifiers(d,["self"])},[e.createElementVNode("div",E_,[e.createElementVNode("h4",S_,e.toDisplayString(i.value?"Edit":"Add")+" Text Overlay ",1),e.createElementVNode("div",C_,[e.createElementVNode("div",null,[f[14]||(f[14]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Text ",-1)),e.withDirectives(e.createElementVNode("textarea",{"onUpdate:modelValue":f[1]||(f[1]=h=>l.text=h),rows:"3",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white",placeholder:"Enter your text..."},null,512),[[e.vModelText,l.text]])]),e.createElementVNode("div",x_,[e.createElementVNode("div",null,[f[15]||(f[15]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Font Size ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":f[2]||(f[2]=h=>l.fontSize=h),type:"number",min:"10",max:"200",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,l.fontSize,void 0,{number:!0}]])]),e.createElementVNode("div",null,[f[16]||(f[16]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Color ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":f[3]||(f[3]=h=>l.color=h),type:"color",class:"w-full h-10 border border-gray-300 dark:border-gray-600 rounded-lg cursor-pointer"},null,512),[[e.vModelText,l.color]])])]),e.createElementVNode("div",null,[f[18]||(f[18]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Position ",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":f[4]||(f[4]=h=>l.position=h),class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},[...f[17]||(f[17]=[e.createStaticVNode('<option value="center" data-v-f86e688c>Center</option><option value="top" data-v-f86e688c>Top</option><option value="bottom" data-v-f86e688c>Bottom</option><option value="left" data-v-f86e688c>Left</option><option value="right" data-v-f86e688c>Right</option>',5)])],512),[[e.vModelSelect,l.position]])]),e.createElementVNode("div",N_,[e.createElementVNode("div",null,[f[19]||(f[19]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Start Time (seconds) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":f[5]||(f[5]=h=>l.startTime=h),type:"number",min:"0",step:"0.1",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,l.startTime,void 0,{number:!0}]])]),e.createElementVNode("div",null,[f[20]||(f[20]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Duration (seconds) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":f[6]||(f[6]=h=>l.duration=h),type:"number",min:"0.1",step:"0.1",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,l.duration,void 0,{number:!0}]])])]),e.createElementVNode("div",null,[f[22]||(f[22]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Animation ",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":f[7]||(f[7]=h=>l.animationType=h),class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},[...f[21]||(f[21]=[e.createStaticVNode('<option value="" data-v-f86e688c>None</option><option value="fade-in" data-v-f86e688c>Fade In</option><option value="fade-out" data-v-f86e688c>Fade Out</option><option value="slide" data-v-f86e688c>Slide</option><option value="scale" data-v-f86e688c>Scale</option><option value="rotate" data-v-f86e688c>Rotate</option><option value="typewriter" data-v-f86e688c>Typewriter</option>',7)])],512),[[e.vModelSelect,l.animationType]])]),l.animationType?(e.openBlock(),e.createElementBlock("div",V_,[f[26]||(f[26]=e.createElementVNode("div",{class:"text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"}," Animation Settings ",-1)),e.createElementVNode("div",T_,[e.createElementVNode("div",null,[f[23]||(f[23]=e.createElementVNode("label",{class:"block text-xs text-gray-600 dark:text-gray-400 mb-1"}," Duration (s) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":f[8]||(f[8]=h=>l.animationDuration=h),type:"number",min:"0.1",step:"0.1",class:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded focus:ring-2 focus:ring-blue-500 dark:bg-gray-600 dark:text-white"},null,512),[[e.vModelText,l.animationDuration,void 0,{number:!0}]])]),e.createElementVNode("div",null,[f[25]||(f[25]=e.createElementVNode("label",{class:"block text-xs text-gray-600 dark:text-gray-400 mb-1"}," Easing ",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":f[9]||(f[9]=h=>l.animationEasing=h),class:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded focus:ring-2 focus:ring-blue-500 dark:bg-gray-600 dark:text-white"},[...f[24]||(f[24]=[e.createElementVNode("option",{value:"linear"},"Linear",-1),e.createElementVNode("option",{value:"easeIn"},"Ease In",-1),e.createElementVNode("option",{value:"easeOut"},"Ease Out",-1),e.createElementVNode("option",{value:"easeInOut"},"Ease In Out",-1)])],512),[[e.vModelSelect,l.animationEasing]])])])])):e.createCommentVNode("",!0)]),e.createElementVNode("div",B_,[e.createElementVNode("button",{onClick:d,class:"px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"}," Cancel "),e.createElementVNode("button",{onClick:c,class:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"},e.toDisplayString(i.value?"Save":"Add"),1)])])])):e.createCommentVNode("",!0)]))}}),Ds=$e(I_,[["__scopeId","data-v-f86e688c"]]),M_={class:"transition-selector p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg"},$_={class:"grid grid-cols-3 gap-3 max-h-96 overflow-y-auto"},F_=["onClick"],D_={class:"w-full h-16 bg-gradient-to-r from-gray-300 to-gray-400 dark:from-gray-600 dark:to-gray-700 rounded mb-2 flex items-center justify-center"},A_={key:0,class:"w-8 h-8 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},R_={key:0,"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"},L_={key:1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M14 5l7 7m0 0l-7 7m7-7H3"},P_={key:2,"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4"},U_={key:3,"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"},O_={key:4,"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 5a1 1 0 011-1h14a1 1 0 011 1v14a1 1 0 01-1 1H5a1 1 0 01-1-1V5z"},z_={class:"text-sm font-medium text-gray-900 dark:text-white text-center"},j_={key:0,class:"mt-4 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"},W_={class:"space-y-3"},H_={class:"flex items-center space-x-2"},Z_=["disabled"],G_=["disabled"],X_={key:1,class:"mt-4"},K_={class:"space-y-2 max-h-32 overflow-y-auto"},J_={class:"text-sm text-gray-700 dark:text-gray-300"},q_=["onClick"],Y_=e.defineComponent({__name:"TransitionSelector",props:{selectedClips:{},appliedTransitions:{}},emits:["apply-transition","remove-transition","preview-transition"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(Ii.getAvailableTransitions()),r=e.ref(null),l=e.ref(.5),s=e.ref("linear"),d=e.computed(()=>r.value&&t.selectedClips&&t.selectedClips.length>=2);function c(h){r.value=h}function u(){if(!r.value||!d.value)return;const h={type:r.value.type,duration:l.value,easing:s.value};n("apply-transition",h),r.value=null}function m(){if(!r.value)return;const h={type:r.value.type,duration:l.value,easing:s.value};n("preview-transition",h)}function p(h){n("remove-transition",h)}function f(h){return["fade","wipe","slide","zoom"].some(v=>h.includes(v))}return(h,v)=>(e.openBlock(),e.createElementBlock("div",M_,[v[9]||(v[9]=e.createElementVNode("h3",{class:"text-lg font-semibold text-gray-900 dark:text-white mb-4"}," Transitions ",-1)),e.createElementVNode("div",$_,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,k=>{var y;return e.openBlock(),e.createElementBlock("div",{key:k.type,onClick:w=>c(k),class:e.normalizeClass(["transition-item cursor-pointer rounded-lg p-3 border-2 transition-all",((y=r.value)==null?void 0:y.type)===k.type?"border-blue-500 bg-blue-50 dark:bg-blue-900":"border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600"])},[e.createElementVNode("div",D_,[f(k.type)?(e.openBlock(),e.createElementBlock("svg",A_,[k.type.includes("fade")?(e.openBlock(),e.createElementBlock("path",R_)):k.type.includes("wipe")?(e.openBlock(),e.createElementBlock("path",L_)):k.type.includes("slide")?(e.openBlock(),e.createElementBlock("path",P_)):k.type.includes("zoom")?(e.openBlock(),e.createElementBlock("path",U_)):(e.openBlock(),e.createElementBlock("path",O_))])):e.createCommentVNode("",!0)]),e.createElementVNode("div",z_,e.toDisplayString(k.name),1)],10,F_)}),128))]),r.value?(e.openBlock(),e.createElementBlock("div",j_,[v[6]||(v[6]=e.createElementVNode("h4",{class:"text-sm font-medium text-gray-700 dark:text-gray-300 mb-3"}," Transition Settings ",-1)),e.createElementVNode("div",W_,[e.createElementVNode("div",null,[v[3]||(v[3]=e.createElementVNode("label",{class:"block text-xs text-gray-600 dark:text-gray-400 mb-1"}," Duration (seconds) ",-1)),e.createElementVNode("div",H_,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":v[0]||(v[0]=k=>l.value=k),type:"range",min:"0.1",max:"3",step:"0.1",class:"flex-1"},null,512),[[e.vModelText,l.value,void 0,{number:!0}]]),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":v[1]||(v[1]=k=>l.value=k),type:"number",min:"0.1",max:"3",step:"0.1",class:"w-16 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded focus:ring-2 focus:ring-blue-500 dark:bg-gray-600 dark:text-white"},null,512),[[e.vModelText,l.value,void 0,{number:!0}]])])]),e.createElementVNode("div",null,[v[5]||(v[5]=e.createElementVNode("label",{class:"block text-xs text-gray-600 dark:text-gray-400 mb-1"}," Easing ",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":v[2]||(v[2]=k=>s.value=k),class:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded focus:ring-2 focus:ring-blue-500 dark:bg-gray-600 dark:text-white"},[...v[4]||(v[4]=[e.createElementVNode("option",{value:"linear"},"Linear",-1),e.createElementVNode("option",{value:"easeIn"},"Ease In",-1),e.createElementVNode("option",{value:"easeOut"},"Ease Out",-1),e.createElementVNode("option",{value:"easeInOut"},"Ease In Out",-1)])],512),[[e.vModelSelect,s.value]])]),e.createElementVNode("button",{onClick:u,disabled:!d.value,class:e.normalizeClass(["w-full px-3 py-2 rounded-lg font-medium transition-colors",d.value?"bg-blue-600 text-white hover:bg-blue-700":"bg-gray-300 dark:bg-gray-600 text-gray-500 dark:text-gray-400 cursor-not-allowed"])}," Apply Transition ",10,Z_),e.createElementVNode("button",{onClick:m,disabled:!r.value,class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors"}," Preview ",8,G_)])])):e.createCommentVNode("",!0),h.appliedTransitions.length>0?(e.openBlock(),e.createElementBlock("div",X_,[v[8]||(v[8]=e.createElementVNode("h4",{class:"text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"}," Applied Transitions ",-1)),e.createElementVNode("div",K_,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(h.appliedTransitions,(k,y)=>(e.openBlock(),e.createElementBlock("div",{key:y,class:"flex items-center justify-between p-2 bg-gray-50 dark:bg-gray-700 rounded"},[e.createElementVNode("div",J_,e.toDisplayString(k.name)+" ("+e.toDisplayString(k.duration)+"s) ",1),e.createElementVNode("button",{onClick:w=>p(y),class:"p-1 text-red-600 hover:bg-red-50 dark:hover:bg-red-900 rounded"},[...v[7]||(v[7]=[e.createElementVNode("svg",{class:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M6 18L18 6M6 6l12 12"})],-1)])],8,q_)]))),128))])])):e.createCommentVNode("",!0),v[10]||(v[10]=e.createElementVNode("div",{class:"mt-4 text-xs text-gray-500 dark:text-gray-400"},[e.createElementVNode("p",null,"Select clips in the timeline, then choose a transition to apply between them.")],-1))]))}}),As=$e(Y_,[["__scopeId","data-v-ffcc612d"]]),Q_={class:"audio-track-manager p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg"},e2={class:"mb-4"},t2={class:"mb-4 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"},a2={class:"flex items-center justify-between mb-2"},n2={class:"text-sm text-gray-600 dark:text-gray-400"},o2={class:"flex items-center space-x-2"},i2={class:"space-y-3 max-h-64 overflow-y-auto"},r2={class:"flex items-center justify-between mb-2"},l2={class:"font-medium text-gray-900 dark:text-white"},s2={class:"flex items-center space-x-2"},d2=["onClick","title"],c2={key:0,class:"w-5 h-5",fill:"currentColor",viewBox:"0 0 20 20"},u2={key:1,class:"w-5 h-5",fill:"currentColor",viewBox:"0 0 20 20"},m2=["onClick"],p2=["onClick"],f2={class:"flex items-center space-x-2"},h2={class:"text-xs text-gray-500 dark:text-gray-400 w-10"},v2=["value","onInput","disabled"],g2={class:"mt-2 text-xs text-gray-500 dark:text-gray-400"},b2={key:0,class:"ml-2"},y2={key:1,class:"ml-2"},w2={key:0,class:"text-center py-8 text-gray-500 dark:text-gray-400"},k2={class:"bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 w-full max-w-lg mx-4"},_2={class:"text-lg font-semibold text-gray-900 dark:text-white mb-4"},E2={class:"space-y-4"},S2={class:"space-y-2"},C2={class:"flex items-center"},x2={class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"},N2={class:"grid grid-cols-2 gap-4"},V2={class:"grid grid-cols-2 gap-4"},T2={class:"flex items-center"},B2={class:"flex justify-end space-x-3 mt-6"},I2=["disabled"],M2=e.defineComponent({__name:"AudioTrackManager",props:{audioLayers:{},masterVolume:{}},emits:["add-track","update-track","remove-track","update-volume","toggle-mute","update-master-volume"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!1),r=e.ref(null),l=e.ref(t.masterVolume),s=()=>({id:"",source:"",sourceUrl:"",name:"Background Music",volume:.7,startTime:0,fadeIn:0,fadeOut:0,loop:!1}),d=e.reactive(s()),c=e.computed(()=>d.sourceUrl||d.sourceFile);function u(g){const b=g.target;b.files&&b.files[0]&&(d.sourceFile=b.files[0],d.name=d.name||b.files[0].name.replace(/\.[^/.]+$/,""))}function m(g){Object.assign(d,g),r.value=g}function p(){i.value=!1,r.value=null,Object.assign(d,s())}function f(){if(!c.value)return;const g={source:d.sourceFile??d.sourceUrl??"",name:d.name,volume:d.volume,startTime:d.startTime,loop:d.loop};d.duration!==void 0&&(g.duration=d.duration),d.fadeIn>0&&(g.fadeIn=d.fadeIn),d.fadeOut>0&&(g.fadeOut=d.fadeOut),r.value?n("update-track",r.value.id,g):n("add-track",g),p()}function h(g){confirm("Are you sure you want to remove this audio track?")&&n("remove-track",g)}function v(g,b){const R=b.target,V=parseFloat(R.value);n("update-volume",g.id,V)}function k(g){n("toggle-mute",g.id,!g.muted)}function y(){n("update-master-volume",l.value)}function w(g){const b=Math.floor(g/60),R=Math.floor(g%60);return`${b}:${R.toString().padStart(2,"0")}`}return(g,b)=>(e.openBlock(),e.createElementBlock("div",Q_,[e.createElementVNode("div",e2,[b[11]||(b[11]=e.createElementVNode("h3",{class:"text-lg font-semibold text-gray-900 dark:text-white mb-2"}," Audio Tracks ",-1)),e.createElementVNode("button",{onClick:b[0]||(b[0]=R=>i.value=!0),class:"w-full px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"},[...b[10]||(b[10]=[e.createElementVNode("svg",{class:"w-5 h-5 inline-block mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 4v16m8-8H4"})],-1),e.createTextVNode(" Add Audio Track ",-1)])])]),e.createElementVNode("div",t2,[e.createElementVNode("div",a2,[b[12]||(b[12]=e.createElementVNode("label",{class:"text-sm font-medium text-gray-700 dark:text-gray-300"}," Master Volume ",-1)),e.createElementVNode("span",n2,e.toDisplayString(Math.round(l.value*100))+"% ",1)]),e.createElementVNode("div",o2,[b[13]||(b[13]=e.createElementVNode("svg",{class:"w-4 h-4 text-gray-500",fill:"currentColor",viewBox:"0 0 20 20"},[e.createElementVNode("path",{"fill-rule":"evenodd",d:"M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM12.293 7.293a1 1 0 011.414 0L15 8.586l1.293-1.293a1 1 0 111.414 1.414L16.414 10l1.293 1.293a1 1 0 01-1.414 1.414L15 11.414l-1.293 1.293a1 1 0 01-1.414-1.414L13.586 10l-1.293-1.293a1 1 0 010-1.414z","clip-rule":"evenodd"})],-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":b[1]||(b[1]=R=>l.value=R),onInput:y,type:"range",min:"0",max:"1",step:"0.01",class:"flex-1"},null,544),[[e.vModelText,l.value,void 0,{number:!0}]]),b[14]||(b[14]=e.createElementVNode("svg",{class:"w-4 h-4 text-gray-500",fill:"currentColor",viewBox:"0 0 20 20"},[e.createElementVNode("path",{"fill-rule":"evenodd",d:"M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM14.657 2.929a1 1 0 011.414 0l3 3a1 1 0 010 1.414l-3 3a1 1 0 01-1.414-1.414L16.586 7l-1.929-1.929a1 1 0 010-1.414z","clip-rule":"evenodd"})],-1))])]),e.createElementVNode("div",i2,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(g.audioLayers,R=>(e.openBlock(),e.createElementBlock("div",{key:R.id,class:"p-3 border border-gray-200 dark:border-gray-700 rounded-lg"},[e.createElementVNode("div",r2,[e.createElementVNode("div",l2,e.toDisplayString(R.name),1),e.createElementVNode("div",s2,[e.createElementVNode("button",{onClick:V=>k(R),class:e.normalizeClass(["p-1 rounded",R.muted?"text-red-600 bg-red-50 dark:bg-red-900":"text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700"]),title:R.muted?"Unmute":"Mute"},[R.muted?(e.openBlock(),e.createElementBlock("svg",u2,[...b[16]||(b[16]=[e.createElementVNode("path",{"fill-rule":"evenodd",d:"M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM12.293 7.293a1 1 0 011.414 0L15 8.586l1.293-1.293a1 1 0 111.414 1.414L16.414 10l1.293 1.293a1 1 0 01-1.414 1.414L15 11.414l-1.293 1.293a1 1 0 01-1.414-1.414L13.586 10l-1.293-1.293a1 1 0 010-1.414z","clip-rule":"evenodd"},null,-1)])])):(e.openBlock(),e.createElementBlock("svg",c2,[...b[15]||(b[15]=[e.createElementVNode("path",{"fill-rule":"evenodd",d:"M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM14.657 2.929a1 1 0 011.414 0l3 3a1 1 0 010 1.414l-3 3a1 1 0 01-1.414-1.414L16.586 7l-1.929-1.929a1 1 0 010-1.414z","clip-rule":"evenodd"},null,-1)])]))],10,d2),e.createElementVNode("button",{onClick:V=>m(R),class:"p-1 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900 rounded",title:"Settings"},[...b[17]||(b[17]=[e.createElementVNode("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})],-1)])],8,m2),e.createElementVNode("button",{onClick:V=>h(R.id),class:"p-1 text-red-600 hover:bg-red-50 dark:hover:bg-red-900 rounded",title:"Remove"},[...b[18]||(b[18]=[e.createElementVNode("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})],-1)])],8,p2)])]),e.createElementVNode("div",f2,[e.createElementVNode("span",h2,e.toDisplayString(Math.round((R.volume||1)*100))+"% ",1),e.createElementVNode("input",{value:R.volume||1,onInput:V=>v(R,V),type:"range",min:"0",max:"1",step:"0.01",class:"flex-1",disabled:R.muted},null,40,v2)]),e.createElementVNode("div",g2,[e.createTextVNode(e.toDisplayString(w(R.startTime||0))+" - "+e.toDisplayString(w((R.startTime||0)+(R.duration||0)))+" ",1),R.fadeIn?(e.openBlock(),e.createElementBlock("span",b2,"Fade In: "+e.toDisplayString(R.fadeIn)+"s",1)):e.createCommentVNode("",!0),R.fadeOut?(e.openBlock(),e.createElementBlock("span",y2,"Fade Out: "+e.toDisplayString(R.fadeOut)+"s",1)):e.createCommentVNode("",!0)])]))),128)),g.audioLayers.length===0?(e.openBlock(),e.createElementBlock("div",w2," No audio tracks added yet ")):e.createCommentVNode("",!0)]),i.value||r.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",onClick:e.withModifiers(p,["self"])},[e.createElementVNode("div",k2,[e.createElementVNode("h4",_2,e.toDisplayString(r.value?"Edit":"Add")+" Audio Track ",1),e.createElementVNode("div",E2,[e.createElementVNode("div",null,[b[20]||(b[20]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Audio Source ",-1)),e.createElementVNode("div",S2,[e.createElementVNode("input",{type:"file",accept:"audio/*",onChange:u,class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,32),e.createElementVNode("div",C2,[b[19]||(b[19]=e.createElementVNode("span",{class:"text-sm text-gray-500 dark:text-gray-400 mr-2"},"or URL:",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":b[2]||(b[2]=R=>d.sourceUrl=R),type:"url",placeholder:"https://example.com/audio.mp3",class:"flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,d.sourceUrl]])])])]),e.createElementVNode("div",null,[b[21]||(b[21]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Track Name ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":b[3]||(b[3]=R=>d.name=R),type:"text",placeholder:"Background Music",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,d.name]])]),e.createElementVNode("div",null,[e.createElementVNode("label",x2," Volume: "+e.toDisplayString(Math.round(d.volume*100))+"% ",1),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":b[4]||(b[4]=R=>d.volume=R),type:"range",min:"0",max:"1",step:"0.01",class:"w-full"},null,512),[[e.vModelText,d.volume,void 0,{number:!0}]])]),e.createElementVNode("div",N2,[e.createElementVNode("div",null,[b[22]||(b[22]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Start Time (seconds) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":b[5]||(b[5]=R=>d.startTime=R),type:"number",min:"0",step:"0.1",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,d.startTime,void 0,{number:!0}]])]),e.createElementVNode("div",null,[b[23]||(b[23]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Duration (seconds) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":b[6]||(b[6]=R=>d.duration=R),type:"number",min:"0.1",step:"0.1",placeholder:"Auto",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,d.duration,void 0,{number:!0}]])])]),e.createElementVNode("div",V2,[e.createElementVNode("div",null,[b[24]||(b[24]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Fade In (seconds) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":b[7]||(b[7]=R=>d.fadeIn=R),type:"number",min:"0",max:"10",step:"0.1",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,d.fadeIn,void 0,{number:!0}]])]),e.createElementVNode("div",null,[b[25]||(b[25]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Fade Out (seconds) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":b[8]||(b[8]=R=>d.fadeOut=R),type:"number",min:"0",max:"10",step:"0.1",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,d.fadeOut,void 0,{number:!0}]])])]),e.createElementVNode("div",T2,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":b[9]||(b[9]=R=>d.loop=R),type:"checkbox",id:"loop-checkbox",class:"mr-2 rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500"},null,512),[[e.vModelCheckbox,d.loop]]),b[26]||(b[26]=e.createElementVNode("label",{for:"loop-checkbox",class:"text-sm text-gray-700 dark:text-gray-300"}," Loop audio track ",-1))])]),e.createElementVNode("div",B2,[e.createElementVNode("button",{onClick:p,class:"px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"}," Cancel "),e.createElementVNode("button",{onClick:f,disabled:!c.value,class:e.normalizeClass(["px-4 py-2 rounded-lg transition-colors",c.value?"bg-green-600 text-white hover:bg-green-700":"bg-gray-300 dark:bg-gray-600 text-gray-500 dark:text-gray-400 cursor-not-allowed"])},e.toDisplayString(r.value?"Save":"Add"),11,I2)])])])):e.createCommentVNode("",!0)]))}}),Rs=$e(M2,[["__scopeId","data-v-593719ac"]]);function bt(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 Pc(o){return typeof o=="boolean"?o?"On":"Off":typeof o=="number"?Number.isInteger(o)?String(o):o.toFixed(2):String(o??"")}let Uc=!1;function $2(){if(Uc)return;Uc=!0;const o=`
34
- /* ── MobileVideoFilterPanel — global (not scoped) ── */
35
- .mvfp {
36
- display: flex;
37
- flex-direction: column;
38
- width: 100%;
39
- position: relative;
40
- background: var(--app-surface, var(--ion-background-color, #1a1a1a));
41
- }
42
-
43
- /* ── Horizontal scroll rows ── */
44
- .mvfp-row {
45
- display: flex;
46
- gap: 8px;
47
- padding: 8px 12px;
48
- overflow-x: auto;
49
- -webkit-overflow-scrolling: touch;
50
- scrollbar-width: none;
51
- flex-shrink: 0;
52
- }
53
- .mvfp-row::-webkit-scrollbar { display: none; }
54
-
55
- /* ── Category chips ── */
56
- .mvfp-cat {
57
- display: flex;
58
- align-items: center;
59
- gap: 6px;
60
- min-height: 36px;
61
- padding: 8px 14px;
62
- border-radius: 20px;
63
- border: 1.5px solid var(--app-border, var(--ion-color-step-300, #444));
64
- background: var(--app-surface-variant, var(--ion-color-step-50, #222));
65
- color: var(--app-text, var(--ion-text-color, #eee));
66
- font-size: 13px;
67
- font-weight: 500;
68
- white-space: nowrap;
69
- cursor: pointer;
70
- flex-shrink: 0;
71
- transition: all 0.15s;
72
- -webkit-tap-highlight-color: transparent;
73
- }
74
- .mvfp-cat.active {
75
- background: var(--app-accent, var(--ion-color-primary, #3880ff));
76
- border-color: var(--app-accent, var(--ion-color-primary, #3880ff));
77
- color: #fff;
78
- }
79
-
80
- /* ── Filter cards ── */
81
- .mvfp-filter {
82
- display: flex;
83
- flex-direction: column;
84
- align-items: center;
85
- justify-content: center;
86
- min-width: 72px;
87
- max-width: 100px;
88
- min-height: 48px;
89
- padding: 10px 12px;
90
- border-radius: 12px;
91
- border: 2px solid var(--app-border, var(--ion-color-step-300, #444));
92
- background: var(--app-surface-variant, var(--ion-color-step-50, #222));
93
- color: var(--app-text, var(--ion-text-color, #eee));
94
- font-size: 12px;
95
- text-align: center;
96
- line-height: 1.3;
97
- cursor: pointer;
98
- flex-shrink: 0;
99
- position: relative;
100
- transition: all 0.15s;
101
- -webkit-tap-highlight-color: transparent;
102
- }
103
- .mvfp-filter.active {
104
- border-color: var(--app-success, var(--ion-color-success, #2dd36f));
105
- }
106
- .mvfp-filter.selected {
107
- background: rgba(var(--ion-color-primary-rgb, 56, 128, 255), 0.15);
108
- border-color: var(--app-accent, var(--ion-color-primary, #3880ff));
109
- }
110
- .mvfp-filter .mvfp-check {
111
- position: absolute;
112
- top: -5px;
113
- right: -5px;
114
- width: 18px;
115
- height: 18px;
116
- border-radius: 50%;
117
- background: var(--app-success, var(--ion-color-success, #2dd36f));
118
- color: #fff;
119
- display: flex;
120
- align-items: center;
121
- justify-content: center;
122
- font-size: 11px;
123
- cursor: pointer;
124
- }
125
-
126
- /* ── Active filter chips ── */
127
- .mvfp-active-row {
128
- display: flex;
129
- gap: 6px;
130
- padding: 6px 12px;
131
- overflow-x: auto;
132
- -webkit-overflow-scrolling: touch;
133
- scrollbar-width: none;
134
- flex-shrink: 0;
135
- }
136
- .mvfp-active-row::-webkit-scrollbar { display: none; }
137
-
138
- .mvfp-achip {
139
- display: flex;
140
- align-items: center;
141
- gap: 6px;
142
- padding: 6px 10px 6px 12px;
143
- background: rgba(var(--ion-color-primary-rgb, 56, 128, 255), 0.12);
144
- border: 1px solid var(--app-accent, var(--ion-color-primary, #3880ff));
145
- border-radius: 20px;
146
- white-space: nowrap;
147
- flex-shrink: 0;
148
- font-size: 12px;
149
- color: var(--app-text, var(--ion-text-color, #eee));
150
- cursor: pointer;
151
- transition: all 0.15s;
152
- }
153
- .mvfp-achip.selected {
154
- background: var(--app-accent, var(--ion-color-primary, #3880ff));
155
- color: #fff;
156
- }
157
- .mvfp-achip-x {
158
- width: 20px;
159
- height: 20px;
160
- border-radius: 50%;
161
- border: 1.5px solid currentColor;
162
- background: transparent;
163
- color: inherit;
164
- display: flex;
165
- align-items: center;
166
- justify-content: center;
167
- cursor: pointer;
168
- padding: 0;
169
- opacity: 0.7;
170
- flex-shrink: 0;
171
- }
172
- .mvfp-achip-x:hover, .mvfp-achip-x:active {
173
- background: var(--ion-color-danger, #ef4444);
174
- border-color: var(--ion-color-danger, #ef4444);
175
- color: #fff;
176
- opacity: 1;
177
- }
178
-
179
- .mvfp-placeholder {
180
- font-size: 12px;
181
- color: var(--app-text-secondary, var(--ion-color-medium, #888));
182
- padding: 6px 12px;
183
- }
184
-
185
- /* ── Drawer ── */
186
- .mvfp-drawer {
187
- position: absolute;
188
- bottom: 0;
189
- left: 0;
190
- right: 0;
191
- background: var(--app-surface, var(--ion-background-color, #1a1a1a));
192
- border-top: 1px solid var(--app-border, var(--ion-color-step-300, #444));
193
- transform: translateY(100%);
194
- z-index: 20;
195
- display: flex;
196
- flex-direction: column;
197
- overflow: hidden;
198
- border-radius: 14px 14px 0 0;
199
- }
200
- .mvfp-drawer-hdr {
201
- display: flex;
202
- justify-content: space-between;
203
- align-items: center;
204
- padding: 8px 14px;
205
- border-bottom: 1px solid var(--app-border, var(--ion-color-step-200, #333));
206
- flex-shrink: 0;
207
- }
208
- .mvfp-drawer-title {
209
- font-weight: 600;
210
- font-size: 14px;
211
- color: var(--app-text, var(--ion-text-color, #eee));
212
- }
213
- .mvfp-drawer-actions {
214
- display: flex;
215
- align-items: center;
216
- gap: 10px;
217
- }
218
- .mvfp-drawer-btn {
219
- background: none;
220
- border: none;
221
- font-size: 13px;
222
- font-weight: 500;
223
- cursor: pointer;
224
- padding: 4px 6px;
225
- color: var(--app-accent, var(--ion-color-primary, #3880ff));
226
- }
227
- .mvfp-drawer-btn.danger {
228
- color: var(--ion-color-danger, #ef4444);
229
- }
230
- .mvfp-drawer-close {
231
- width: 28px;
232
- height: 28px;
233
- border: none;
234
- border-radius: 50%;
235
- background: var(--app-surface-sunken, var(--ion-color-step-100, #2a2a2a));
236
- color: var(--app-text-secondary, var(--ion-color-medium, #888));
237
- display: flex;
238
- align-items: center;
239
- justify-content: center;
240
- cursor: pointer;
241
- padding: 0;
242
- }
243
- .mvfp-drawer-body {
244
- flex: 1 1 auto;
245
- overflow-y: auto;
246
- -webkit-overflow-scrolling: touch;
247
- padding: 10px 14px 16px;
248
- }
249
-
250
- /* ── Drawer slider controls ── */
251
- .mvfp-ctl {
252
- margin-bottom: 12px;
253
- }
254
- .mvfp-ctl-label {
255
- display: block;
256
- font-size: 11px;
257
- font-weight: 600;
258
- color: var(--app-text-secondary, var(--ion-color-medium, #888));
259
- text-transform: uppercase;
260
- letter-spacing: 0.5px;
261
- margin-bottom: 4px;
262
- }
263
- .mvfp-slider-row {
264
- display: flex;
265
- align-items: center;
266
- gap: 10px;
267
- }
268
- .mvfp-range {
269
- flex: 1;
270
- height: 6px;
271
- -webkit-appearance: none;
272
- appearance: none;
273
- background: var(--app-border, var(--ion-color-step-200, #333));
274
- border-radius: 3px;
275
- outline: none;
276
- }
277
- .mvfp-range::-webkit-slider-thumb {
278
- -webkit-appearance: none;
279
- width: 22px;
280
- height: 22px;
281
- border-radius: 50%;
282
- background: var(--app-accent, var(--ion-color-primary, #3880ff));
283
- cursor: pointer;
284
- border: 2px solid #fff;
285
- box-shadow: 0 1px 4px rgba(0,0,0,0.3);
286
- }
287
- .mvfp-range-val {
288
- min-width: 3rem;
289
- text-align: right;
290
- font-size: 12px;
291
- font-weight: 500;
292
- color: var(--app-text-secondary, var(--ion-color-medium, #888));
293
- }
294
- .mvfp-toggle-row {
295
- display: flex;
296
- align-items: center;
297
- justify-content: space-between;
298
- gap: 10px;
299
- }
300
- .mvfp-color-row {
301
- display: flex;
302
- align-items: center;
303
- justify-content: space-between;
304
- gap: 10px;
305
- }
306
- .mvfp-color-input {
307
- width: 36px;
308
- height: 36px;
309
- border: 1px solid var(--app-border, var(--ion-color-step-300, #444));
310
- border-radius: 8px;
311
- padding: 2px;
312
- cursor: pointer;
313
- background: transparent;
314
- }
315
- .mvfp-select-row {
316
- display: flex;
317
- align-items: center;
318
- justify-content: space-between;
319
- gap: 10px;
320
- }
321
- .mvfp-select {
322
- padding: 6px 10px;
323
- border: 1px solid var(--app-border, var(--ion-color-step-300, #444));
324
- border-radius: 8px;
325
- background: var(--app-surface, var(--ion-background-color, #1a1a1a));
326
- color: var(--app-text, var(--ion-text-color, #eee));
327
- font-size: 13px;
328
- }
329
- .mvfp-no-params {
330
- text-align: center;
331
- color: var(--app-text-secondary, var(--ion-color-medium, #888));
332
- font-style: italic;
333
- font-size: 13px;
334
- padding: 12px 0;
335
- }
336
- `,a=document.createElement("style");a.textContent=o,document.head.appendChild(a)}class F2{constructor({filters:a=[],callbacks:t={}}){$2(),this._filters=a,this._cb=t,this._selectedCategory="all",this._selectedFilterId=null,this._activeFilters=new Map,this._drawerOpen=!1,this._drawerFilterId=null,this._root=null,this._catRow=null,this._filterRow=null,this._activeRow=null,this._drawer=null,this._drawerTitle=null,this._drawerBody=null}mount(a){return this._root=bt("div",{className:"mvfp"}),this._catRow=bt("div",{className:"mvfp-row"}),this._root.appendChild(this._catRow),this._filterRow=bt("div",{className:"mvfp-row"}),this._root.appendChild(this._filterRow),this._activeRow=bt("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=bt("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=bt("div",{className:`mvfp-filter${t?" active":""}${n?" selected":""}`,onClick:()=>this._selectFilter(a)});if(t){const r=bt("div",{className:"mvfp-check",onClick:l=>{l.stopPropagation(),this._removeFilter(a.id)}});r.innerHTML="✓",i.appendChild(r)}i.appendChild(bt("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(bt("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=bt("div",{className:`mvfp-achip${i?" selected":""}`}),l=bt("span",{style:{cursor:"pointer"},onClick:()=>{this._selectedFilterId=t,this._renderFilters(),n.params&&n.params.length>0&&this.openDrawer(t)}},n.name),s=bt("button",{className:"mvfp-achip-x","aria-label":`Remove ${n.name}`,onClick:d=>{d.stopPropagation(),this._removeFilter(t)}});s.innerHTML='<svg width="10" height="10" viewBox="0 0 12 12"><path d="M3 3l6 6M9 3l-6 6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',r.appendChild(l),r.appendChild(s),this._activeRow.appendChild(r)})}_buildDrawer(){this._drawer=bt("div",{className:"mvfp-drawer"});const a=bt("div",{className:"mvfp-drawer-hdr"});this._drawerTitle=bt("span",{className:"mvfp-drawer-title"},"Filter");const t=bt("div",{className:"mvfp-drawer-actions"});t.appendChild(bt("button",{className:"mvfp-drawer-btn",onClick:()=>this._resetDrawerFilter()},"Reset")),t.appendChild(bt("button",{className:"mvfp-drawer-btn danger",onClick:()=>{this._drawerFilterId&&(this._removeFilter(this._drawerFilterId),this.closeDrawer())}},"Remove"));const n=bt("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=bt("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(bt("div",{className:"mvfp-no-params"},"No adjustable parameters"));return}const t=this._activeFilters.get(a.id),n=(t==null?void 0:t.params)||{};for(const i of a.params){const r=n[i.id]??i.default,l=bt("div",{className:"mvfp-ctl"}),s=bt("label",{className:"mvfp-ctl-label"},i.label||i.id);l.appendChild(s);const d=i.type||"slider";if(d==="slider"||d==="range"){const c=bt("div",{className:"mvfp-slider-row"}),u=bt("span",{className:"mvfp-range-val"},Pc(r)),m=bt("input",{type:"range",className:"mvfp-range",min:String(i.min??0),max:String(i.max??1),step:String(i.step??.01),value:String(typeof r=="number"?r:i.default??0),onInput:p=>{var h,v;const f=parseFloat(p.target.value);u.textContent=Pc(f),(v=(h=this._cb).onUpdateParam)==null||v.call(h,a.id,i.id,f)}});c.appendChild(m),c.appendChild(u),l.appendChild(c)}else if(d==="toggle"||d==="checkbox"){const c=bt("div",{className:"mvfp-toggle-row"}),u=bt("input",{type:"checkbox",checked:r?"checked":void 0,onChange:m=>{var p,f;return(f=(p=this._cb).onUpdateParam)==null?void 0:f.call(p,a.id,i.id,m.target.checked)}});c.appendChild(u),l.appendChild(c)}else if(d==="color"){const c=bt("div",{className:"mvfp-color-row"}),u=bt("input",{type:"color",className:"mvfp-color-input",value:typeof r=="string"?r:"#000000",onInput:m=>{var p,f;return(f=(p=this._cb).onUpdateParam)==null?void 0:f.call(p,a.id,i.id,m.target.value)}});c.appendChild(u),l.appendChild(c)}else if(d==="select"||d==="dropdown"){const c=bt("div",{className:"mvfp-select-row"}),u=bt("select",{className:"mvfp-select",onChange:m=>{var p,f;return(f=(p=this._cb).onUpdateParam)==null?void 0:f.call(p,a.id,i.id,m.target.value)}});for(const m of i.options||[]){const p=bt("option",{value:m.value},m.label||String(m.value));m.value===r&&(p.selected=!0),u.appendChild(p)}c.appendChild(u),l.appendChild(c)}this._drawerBody.appendChild(l)}}_resetDrawerFilter(){var t,n;if(!this._drawerFilterId)return;const a=this._filters.find(i=>i.id===this._drawerFilterId);if(a!=null&&a.params){for(const i of a.params)(n=(t=this._cb).onUpdateParam)==null||n.call(t,this._drawerFilterId,i.id,i.default);this._renderDrawerControls(a)}}}const D2=[200,500,1e3];function A2(o){return{"360p":[640,360],"480p":[854,480],"720p":[1280,720],"1080p":[1920,1080],"1440p":[2560,1440],"2160p":[3840,2160]}[o??""]??[1920,1080]}function Oc(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 R2(o){return new Promise(a=>{window.setTimeout(a,o)})}async function zc(){return await Promise.resolve().then(()=>require("./PixiFrameExporter-DhAJGzIK.cjs"))}function jc(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 Km(o){let a=null;return{canExportClientSide:async()=>{try{const{isWebCodecsSupported:i}=await zc();return i()}catch{return!1}},renderRecipeWithPixi:async(i,r,l)=>{var f,h,v,k;const s=i.timeline[0],d=s?Math.max(0,s.sourceIn):0,c=s?s.sourceOut:void 0,[u,m]=A2((r==null?void 0:r.quality)??((f=i.output)==null?void 0:f.quality)),p=((h=i.output)==null?void 0:h.fps)||30;o.setPlaying(!1),o.forcePixiPreview.value=!0,await e.nextTick();try{let y=!1;for(const A of D2){await R2(A);const P=o.getPreviewRef();if(!(!P||typeof P.captureFrameAt!="function")){if(typeof P.ensureReadyForCapture=="function"){if(y=await P.ensureReadyForCapture(),y)break;continue}y=!0;break}}const w=o.getPreviewRef();if(!w||typeof w.captureFrameAt!="function")throw new Error("PIXI preview not available for export. Ensure the preview is mounted.");if(!y)throw new Error("PIXI preview not ready for frame capture after retries. The video may still be loading.");const{exportWithPixiFrames:g,isWebCodecsSupported:b}=await zc();if(!b())throw new Error("WebCodecs is not supported in this browser. Export requires Chrome 94+ or equivalent.");a=new AbortController;const R={width:u,height:m,fps:p,trimStart:d,signal:a.signal};c!==void 0&&(R.trimEnd=c),l&&(R.onProgress=l);const V=o.getSourceUrl();V!==""&&(R.sourceUrl=V);const I=Oc(w)??((v=i.source)==null?void 0:v.duration)??c??0,x=await g({captureFrameAt:A=>{var P;return((P=w.captureFrameAt)==null?void 0:P.call(w,A))??Promise.resolve(null)},duration:{value:I}},R),T=new File([x],`edited-video-${Date.now()}.mp4`,{type:"video/mp4"}),$=Oc(w),S=((k=i.source)==null?void 0:k.duration)??0,_=Math.max(0,(c??$??S)-d);return{file:T,recipe:i,meta:{duration:_,width:u,height:m,format:"mp4",sizeBytes:T.size,size_bytes:T.size}}}finally{o.forcePixiPreview.value=!1,a=null}},cancelClientExport:()=>{a==null||a.abort(),a=null},resetClientExport:()=>{a=null}}}const Lo="default-video-track",Nn="default-media-source";function Jm(o){var r,l;const a=P2(o),t=U2(o),n=O2(o.timeline,((r=t[0])==null?void 0:r.id)??Lo,((l=a[0])==null?void 0:l.id)??Nn),i={version:o.version,source:{...o.source},mediaSources:a,tracks:z2(t,n),clips:n,markers:o.markers?o.markers.map(s=>({...s})):[],transitions:o.transitions?o.transitions.map(Qm):[],filters:o.filters.map(s=>({...s,params:{...s.params}})),audio:{...o.audio},output:{...o.output}};return typeof o.duration=="number"&&(i.duration=o.duration),o.snapSettings&&(i.snapSettings={...o.snapSettings}),o.textOverlays&&(i.textOverlays=[...o.textOverlays]),o.captionTracks&&(i.captionTracks=o.captionTracks.map(ep)),o.visualLayers&&(i.visualLayers=o.visualLayers.map(tp)),o.audioTracks&&(i.audioTracks=[...o.audioTracks]),o.posterFrame&&(i.posterFrame=o.posterFrame),o.metadata&&(i.metadata={...o.metadata}),i}function L2(o){const a={version:"1.0",source:{...o.source},timeline:o.clips.map(t=>({...t})),mediaSources:o.mediaSources.map(qm),tracks:o.tracks.map(Ym),markers:o.markers.map(t=>({...t})),transitions:o.transitions.map(Qm),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(ep)),o.visualLayers&&(a.visualLayers=o.visualLayers.map(tp)),o.audioTracks&&(a.audioTracks=[...o.audioTracks]),o.posterFrame&&(a.posterFrame=o.posterFrame),o.metadata&&(a.metadata={...o.metadata}),a}function P2(o){var t,n;if(o.mediaSources&&o.mediaSources.length>0)return o.mediaSources.map(qm);const a={id:((t=o.timeline.find(i=>i.sourceRefId))==null?void 0:t.sourceRefId)??Nn,type:"media",mediaUuid:o.source.media_uuid,duration:o.source.duration,width:o.source.original_width,height:o.source.original_height};return(n=o.metadata)!=null&&n.source_url&&(a.url=o.metadata.source_url),[a]}function U2(o){var a;return o.tracks&&o.tracks.length>0?o.tracks.map(Ym):[{id:((a=o.timeline.find(t=>t.trackId))==null?void 0:a.trackId)??Lo,type:"video",name:"Video",order:0}]}function O2(o,a,t){return o.map(n=>{const i={...n,trackId:n.trackId??a,sourceRefId:n.sourceRefId??t};return n.filters&&(i.filters=n.filters.map(r=>({...r,params:{...r.params}}))),n.transform&&(i.transform={...n.transform}),n.keyframes&&(i.keyframes=n.keyframes.map(r=>({...r}))),i})}function z2(o,a){return o.map(t=>{const n=a.filter(i=>i.trackId===t.id).map(i=>i.id);return{...t,clipIds:n}})}function qm(o){const a={...o};return o.metadata&&(a.metadata={...o.metadata}),a}function Ym(o){const a={...o};return o.clipIds&&(a.clipIds=[...o.clipIds]),a}function Qm(o){const a={...o};return o.params&&(a.params={...o.params}),a}function ep(o){return{...o,segments:o.segments.map(t=>{const n={...t};return t.words&&(n.words=t.words.map(i=>({...i}))),n})}}function tp(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 ap="video-project-draft-snapshot:v1",Ls="mediables:video-project-drafts",j2=(o,a={})=>{var p,f;const t=pn(a.now)??Date.now(),n=pn(a.createdAt)??t,i=pn(a.updatedAt)??t,r=tE(o),l={id:Ma(a.id)??iE(i),payloadKind:r,createdAt:new Date(n).toISOString(),updatedAt:new Date(i).toISOString(),deviceKind:a.deviceKind??"unknown"},s=Ma(a.projectId),d=Ma(a.sourceMediaUuid)??Ma(o.source.media_uuid),c=Ps(a.durationSeconds)??aE(o),u=Ma(a.editorVersion)??Ma((p=o.metadata)==null?void 0:p.editor_version),m=Ma(a.title)??Ma((f=o.metadata)==null?void 0:f.title);return s!==null&&(l.projectId=s),d!==null&&(l.sourceMediaUuid=d),c!==null&&(l.durationSeconds=c),u!==null&&(l.editorVersion=u),m!==null&&(l.title=m),a.saveReason!==void 0&&(l.saveReason=a.saveReason),{schemaVersion:ap,metadata:l,payload:o}},np=(o,a=Ls)=>{const t=Ma(a)??Ls,n=Xc(o.metadata.projectId??"unsaved-project"),i=Xc(o.metadata.id);return`${t}:${n}:${i}`},W2=o=>JSON.stringify(o),H2=o=>{if(typeof o!="string"||o.trim().length===0)return null;try{const a=JSON.parse(o);return Y2(a)?a:null}catch{return null}},Z2=o=>{const a=[];for(const t of o){const n=Ma(t.key),i=H2(t.value);n===null||i===null||a.push({key:n,snapshot:i})}return Si(a)},G2=(o,a)=>{const t=oE(a.maxCount),n=pn(a.now)??Date.now(),i=sp(a.maxAgeMs),r=[],l=[];let s=0;for(const d of Si(o)){if(!rp(d,a.projectId)){r.push(d);continue}if(lp(d.snapshot,n,i)||s>=t){l.push(d);continue}r.push(d),s+=1}return{retained:Si(r),removed:Si(l)}},X2=(o,a={})=>{const t={key:np(o),snapshot:o};if(!rp(t,a.projectId))return!1;const n=pn(a.now)??Date.now(),i=sp(a.maxAgeMs);if(lp(o,n,i))return!1;const r=a.savedAt===null?null:pn(a.savedAt);return r===null?!0:jr(o)>r},K2=(o,a={})=>Si(o).filter(t=>X2(t.snapshot,a)),J2=(o,a,t={})=>{const n=K2(o,t);if(a==="mobile"){const i=n[0]??null;return i===null?[]:[i]}return n},q2=async(o,a,t=np(a))=>(await o.setItem(t,W2(a)),{key:t,snapshot:a}),Wc=async(o,a=Ls)=>{const t=await o.listKeys(a),n=[];for(const i of t)n.push({key:i,value:await o.getItem(i)});return Z2(n)},Hc=async(o,a)=>{for(const t of a)await o.removeItem(t.key)},Y2=o=>!fn(o)||o.schemaVersion!==ap||!Q2(o.metadata)?!1:o.metadata.payloadKind==="project"?op(o.payload):eE(o.payload),Q2=o=>fn(o)?_d(o.id)&&lE(o.payloadKind)&&Gc(o.createdAt)&&Gc(o.updatedAt)&&sE(o.deviceKind)&&mr(o.projectId)&&mr(o.sourceMediaUuid)&&rE(o.durationSeconds)&&mr(o.editorVersion)&&mr(o.title)&&dE(o.saveReason):!1,eE=o=>fn(o)?o.version==="1.0"&&ip(o.source)&&Array.isArray(o.timeline)&&Array.isArray(o.filters)&&fn(o.audio)&&fn(o.output):!1,op=o=>fn(o)?o.version==="1.0"&&ip(o.source)&&Array.isArray(o.mediaSources)&&Array.isArray(o.tracks)&&Array.isArray(o.clips)&&Array.isArray(o.markers)&&Array.isArray(o.filters)&&fn(o.audio)&&fn(o.output):!1,ip=o=>fn(o)?_d(o.media_uuid)&&Ci(o.duration)&&Ci(o.original_width)&&Ci(o.original_height):!1,tE=o=>op(o)?"project":"recipe",aE=o=>Ps(o.duration)??Ps(o.source.duration),rp=(o,a)=>{const t=Ma(a);return t===null?!0:o.snapshot.metadata.projectId===t},lp=(o,a,t)=>t===null?!1:a-jr(o)>t,Si=o=>[...o].sort(nE),nE=(o,a)=>{const t=jr(a.snapshot)-jr(o.snapshot);if(t!==0)return t;const n=Zc(a.snapshot)-Zc(o.snapshot);return n!==0?n:o.snapshot.metadata.id.localeCompare(a.snapshot.metadata.id)},jr=o=>pn(o.metadata.updatedAt)??0,Zc=o=>pn(o.metadata.createdAt)??0,oE=o=>!Number.isFinite(o)||o<0?0:Math.floor(o),sp=o=>o===void 0||!Number.isFinite(o)||o<0?null:Math.floor(o),pn=o=>{if(o==null)return null;if(o instanceof Date)return Number.isFinite(o.getTime())?o.getTime():null;if(typeof o=="number")return Number.isFinite(o)?o:null;const a=o.trim();if(a.length===0)return null;const t=Date.parse(a);return Number.isFinite(t)?t:null},Gc=o=>typeof o=="string"&&pn(o)!==null,iE=o=>{var t;const a=typeof((t=globalThis.crypto)==null?void 0:t.randomUUID)=="function"?globalThis.crypto.randomUUID():Math.random().toString(36).slice(2,12);return`draft-${o}-${a}`},Xc=o=>encodeURIComponent(o.trim()),Ma=o=>{if(typeof o!="string")return null;const a=o.trim();return a.length>0?a:null},_d=o=>Ma(o)!==null,mr=o=>o===void 0||_d(o),Ps=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,rE=o=>o===void 0||Ci(o),lE=o=>o==="recipe"||o==="project",sE=o=>o==="desktop"||o==="mobile"||o==="tablet"||o==="unknown",dE=o=>o===void 0||o==="autosave"||o==="manual"||o==="before-export"||o==="before-close",fn=o=>typeof o=="object"&&o!==null&&!Array.isArray(o),cE=1,uE="master",Mi=-60,Us=12,Ed=0,Vn=-90,Wr=6,mE=4,dp=8;function cp(){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:dp}}}function pE(o,a=cp()){return zs(a[o])}function up(o){return Number.isNaN(o)?Ed:o<=0||o===Number.NEGATIVE_INFINITY?Mi:$i(20*Math.log10(o))}function Os(o){const a=$i(o);return a<=Mi?0:Bn(Math.pow(10,a/20),6)}function $i(o){return Number.isNaN(o)?Ed:o===Number.NEGATIVE_INFINITY?Mi:o===Number.POSITIVE_INFINITY?Us:Bn(Wi(o,Mi,Us),3)}function mp(o){return Number.isFinite(o)?Bn(Wi(o,-1,1),3):0}function fE(o,a=!1){const t=o.some(n=>n.controls.solo);return o.map(n=>{const i=n.controls.muted,r=t&&!n.controls.solo,l=a||i||r,s=l?0:n.controls.fader.linearGain;return{trackId:n.id,soloed:n.controls.solo,mutedByTrack:i,mutedBySolo:r,mutedByMaster:a,effectivelyMuted:l,audible:!l,effectiveGainLinear:s}})}function hE(o,a={}){const t=xE(a.effectSlotCount),n=new Set;return{schemaVersion:cE,capabilities:a.capabilities?BE(a.capabilities):cp(),tracks:o.map((i,r)=>gE(i,r,t,n)),master:bE(a.master,t)}}function pp(o){const a=$i(o);return{valueDb:a,minDb:Mi,maxDb:Us,unityDb:Ed,linearGain:Os(a)}}function vE(o,a="constant-power"){return{value:mp(o),mode:a}}function fp(o=Vn,a=Vn,t=o){const n=ql(o),i=ql(a),r=ql(t);return{peakDb:n,rmsDb:i,peakHoldDb:r,clipping:n>=0||r>=0}}function hp(o){const a=bp(o);return{id:`empty-effect-slot-${a}`,index:a,kind:"empty",label:"Empty",enabled:!1,bypassed:!0,wetMix:0,parameters:{}}}function gE(o,a,t,n){const i=gp(o.id),l={id:CE(i??`legacy-audio-track-${a+1}`,n),kind:"legacy-url",name:_E(o.name,a),order:a,source:yE(o.source),controls:{fader:pp(o.faderDb??up(o.volume??1)),pan:vE(o.pan??0),muted:o.muted??!1,solo:o.solo??!1,meter:fp(o.peakDb,o.rmsDb,o.peakHoldDb)},timeline:wE(o),effectSlots:vp(o.effectSlots,t)};return i!==void 0&&(l.legacyTrackId=i),l}function bE(o,a){return{id:uE,name:EE(o==null?void 0:o.name),fader:pp((o==null?void 0:o.faderDb)??up((o==null?void 0:o.volume)??1)),muted:(o==null?void 0:o.muted)??!1,meter:fp(o==null?void 0:o.peakDb,o==null?void 0:o.rmsDb,o==null?void 0:o.peakHoldDb),effectSlots:vp(o==null?void 0:o.effectSlots,a)}}function yE(o){const a=o.trim();return a===""?{type:"missing"}:{type:"url",url:a}}function wE(o){const a={startTime:VE(o.startTime??0),loop:o.loop??!1},t=NE(o.duration);t!==void 0&&(a.duration=t);const n=Kc(o.fadeIn);n!==void 0&&(a.fadeIn=n);const i=Kc(o.fadeOut);return i!==void 0&&(a.fadeOut=i),a}function vp(o,a){const t=new Map;for(const n of o??[]){const i=kE(n,a);t.set(i.index,i)}return Array.from({length:a},(n,i)=>t.get(i)??hp(i))}function kE(o,a){const t=bp(o.index),n=a>0?Math.min(t,a-1):0,i=o.kind;return i==="empty"?hp(n):{id:gp(o.id)??`${i}-effect-slot-${n}`,index:n,kind:i,label:SE(o.label,i),enabled:o.enabled,bypassed:o.bypassed,wetMix:TE(o.wetMix),parameters:{...o.parameters}}}function _E(o,a){const t=o==null?void 0:o.trim();return t&&t!==""?t:`Audio ${a+1}`}function EE(o){const a=o==null?void 0:o.trim();return a&&a!==""?a:"Master"}function SE(o,a){const t=o.trim();return t!==""?t:a}function CE(o,a){if(!a.has(o))return a.add(o),o;let t=2,n=`${o}-${t}`;for(;a.has(n);)t+=1,n=`${o}-${t}`;return a.add(n),n}function gp(o){const a=o==null?void 0:o.trim();if(!(!a||a===""))return a}function xE(o){return o===void 0||!Number.isFinite(o)?mE:Math.trunc(Wi(o,0,dp))}function bp(o){return!Number.isFinite(o)||o<0?0:Math.trunc(o)}function NE(o){if(!(o===void 0||!Number.isFinite(o)||o<=0))return Bn(o,3)}function Kc(o){if(!(o===void 0||!Number.isFinite(o)||o<0))return Bn(o,3)}function VE(o){return!Number.isFinite(o)||o<0?0:Bn(o,3)}function TE(o){return Number.isFinite(o)?Bn(Wi(o,0,1),3):1}function ql(o){return Number.isNaN(o)||o===Number.NEGATIVE_INFINITY?Vn:o===Number.POSITIVE_INFINITY?Wr:Bn(Wi(o,Vn,Wr),3)}function BE(o){return{mobile:zs(o.mobile),desktop:zs(o.desktop)}}function zs(o){return{...o}}function Wi(o,a,t){return Math.min(t,Math.max(a,o))}function Bn(o,a){const t=10**a;return Math.round(o*t)/t}const IE=/^(\d{2,}:[0-5]\d:[0-5]\d,\d{3})\s+-->\s+(\d{2,}:[0-5]\d:[0-5]\d,\d{3})$/,ME=/^(\d{2,}):([0-5]\d):([0-5]\d),(\d{3})$/,$E="srt-cue";class Tn extends Error{constructor(a,t,n={}){super(t),this.name="CaptionSrtError",this.code=a,this.context=n}}function FE(o,a={}){var l,s;const t=DE(a.idPrefix),n=o.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
337
- `).split(`
338
- `),i=[];let r=0;for(;r<n.length;){for(;r<n.length&&eu(n[r]);)r+=1;if(r>=n.length)break;const d=r+1,c=AE(((l=n[r])==null?void 0:l.trim())??"",d);if(r+=1,r>=n.length)throw new Tn("missing-timing",`Cue ${c} is missing its timing line.`,{cueIndex:i.length,cueNumber:c,lineNumber:d});const u=r+1,m=RE(((s=n[r])==null?void 0:s.trim())??"",c,u);r+=1;const p=[];for(;r<n.length&&!eu(n[r]);)p.push(n[r]??""),r+=1;i.push({cueNumber:c,id:`${t}-${i.length+1}`,startTime:m.startTime,endTime:m.endTime,text:p.join(`
339
- `)})}return yp(i),i}function Jc(o){return yp(o),o.length===0?"":`${o.map((a,t)=>PE(a,t+1)).join(`
340
-
341
- `)}
342
- `}function yp(o){const a=o.map((t,n)=>{const i=Qc(t,n),r=js(t.startTime,"startTime",i),l=js(t.endTime,"endTime",i);if(l<=r)throw new Tn("invalid-duration",`Caption cue "${t.id}" must end after it starts.`,i);return{cue:t,cueIndex:n,startMilliseconds:r,endMilliseconds:l}}).sort((t,n)=>t.startMilliseconds-n.startMilliseconds||t.cueIndex-n.cueIndex);for(let t=1;t<a.length;t+=1){const n=a[t-1],i=a[t];if(!(n===void 0||i===void 0)&&i.startMilliseconds<n.endMilliseconds)throw new Tn("overlapping-cues",`Caption cue "${i.cue.id}" overlaps cue "${n.cue.id}".`,Qc(i.cue,i.cueIndex))}}function qc(o){const a=js(o,"timestamp",{}),t=Math.floor(a/36e5),n=Math.floor(a%36e5/6e4),i=Math.floor(a%6e4/1e3),r=a%1e3;return[t.toString().padStart(2,"0"),n.toString().padStart(2,"0"),i.toString().padStart(2,"0")].join(":")+`,${r.toString().padStart(3,"0")}`}function DE(o){return o===void 0||o.trim()===""?$E:o.trim()}function AE(o,a){if(!/^[1-9]\d*$/.test(o))throw new Tn("invalid-cue-number",`Invalid SRT cue number at line ${a}.`,{lineNumber:a});return Number.parseInt(o,10)}function RE(o,a,t){const n=IE.exec(o),i=n==null?void 0:n[1],r=n==null?void 0:n[2];if(i===void 0||r===void 0)throw new Tn("invalid-timing",`Invalid SRT timing line for cue ${a} at line ${t}.`,{cueNumber:a,lineNumber:t});return{startTime:Yc(i,a,t),endTime:Yc(r,a,t)}}function Yc(o,a,t){const n=ME.exec(o),i=n==null?void 0:n[1],r=n==null?void 0:n[2],l=n==null?void 0:n[3],s=n==null?void 0:n[4];if(i===void 0||r===void 0||l===void 0||s===void 0)throw new Tn("invalid-time",`Invalid SRT timestamp for cue ${a} at line ${t}.`,{cueNumber:a,lineNumber:t});const d=Number.parseInt(i,10),c=Number.parseInt(r,10),u=Number.parseInt(l,10),m=Number.parseInt(s,10);return d*60*60+c*60+u+m/1e3}function js(o,a,t){if(!Number.isFinite(o)||o<0)throw new Tn("invalid-time",`Caption cue ${a} must be a finite, non-negative number.`,t);return Math.round(o*1e3)}function Qc(o,a){const t={cueIndex:a,segmentId:o.id},n=LE(o);return n!==void 0&&(t.cueNumber=n),t}function LE(o){if(!(!("cueNumber"in o)||typeof o.cueNumber!="number"))return o.cueNumber}function PE(o,a){return[a.toString(),`${qc(o.startTime)} --> ${qc(o.endTime)}`,UE(o.text)].join(`
343
- `)}function UE(o){return o.replace(/\r\n?/g,`
344
- `)}function eu(o){return o===void 0||o.trim()===""}const OE=["linear","ease-in","ease-out","ease-in-out"];class Hr extends Error{constructor(a,t="Invalid keyframe automation."){super(t),this.name="KeyframeAutomationError",this.issues=a}}const zE={opacity:{min:0,max:1},scale:{min:0,max:10},x:{min:0,max:1},y:{min:0,max:1},rotation:{},audioVolume:{min:0,max:1}};function jE(o){return typeof o=="string"&&OE.includes(o)}function WE(o){return o==="mobile"?{platform:o,editingMode:"preset-only",canApplyPresets:!0,canEditKeyframes:!1}:{platform:o,editingMode:"detailed",canApplyPresets:!0,canEditKeyframes:!0}}function HE(o){return[...o].sort((a,t)=>a.target!==t.target?a.target.localeCompare(t.target):a.time!==t.time?a.time-t.time:a.id.localeCompare(t.id))}function wp(o,a={}){const t=[],n=new Set,i={...zE,...a.ranges};return o.forEach((r,l)=>{if(r.id.trim()===""&&t.push({code:"empty-id",message:"Keyframe id cannot be empty.",index:l,target:r.target,time:r.time}),a.target!==void 0&&r.target!==a.target&&t.push({code:"target-mismatch",message:`Expected ${a.target} keyframe target but received ${r.target}.`,index:l,keyframeId:r.id,target:r.target,time:r.time}),!Number.isFinite(r.time)||r.time<(a.minTime??0))t.push({code:"invalid-time",message:"Keyframe time must be a finite non-negative number.",index:l,keyframeId:r.id,target:r.target,time:r.time});else if(a.maxTime!==void 0&&r.time>a.maxTime)t.push({code:"invalid-time",message:`Keyframe time must be less than or equal to ${a.maxTime}.`,index:l,keyframeId:r.id,target:r.target,time:r.time});else{const s=`${r.target}:${r.time}`;n.has(s)&&t.push({code:"duplicate-time",message:`Keyframe target ${r.target} already has a point at ${r.time}.`,index:l,keyframeId:r.id,target:r.target,time:r.time}),n.add(s)}if(!Number.isFinite(r.value))t.push({code:"invalid-value",message:"Keyframe value must be a finite number.",index:l,keyframeId:r.id,target:r.target,time:r.time});else{const s=i[r.target];s.min!==void 0&&r.value<s.min&&t.push({code:"invalid-value",message:`Keyframe value for ${r.target} must be greater than or equal to ${s.min}.`,index:l,keyframeId:r.id,target:r.target,time:r.time}),s.max!==void 0&&r.value>s.max&&t.push({code:"invalid-value",message:`Keyframe value for ${r.target} must be less than or equal to ${s.max}.`,index:l,keyframeId:r.id,target:r.target,time:r.time})}jE(r.easing)||t.push({code:"invalid-easing",message:`Unsupported keyframe easing "${String(r.easing)}".`,index:l,keyframeId:r.id,target:r.target,time:r.time})}),{valid:t.length===0,issues:t}}function ZE(o,a={}){const t=HE(o),n=wp(t,a);if(!n.valid)throw new Hr(n.issues);return t}function GE(o={}){return Sd({id:"fade-in",label:"Fade in",target:"opacity",startValue:o.fromOpacity??0,endValue:o.toOpacity??1,timing:Cd(o,"ease-out")})}function XE(o={}){return Sd({id:"fade-out",label:"Fade out",target:"opacity",startValue:o.fromOpacity??1,endValue:o.toOpacity??0,timing:Cd(o,"ease-in")})}function KE(o={}){return Sd({id:"zoom-in",label:"Zoom in",target:"scale",startValue:o.fromScale??1,endValue:o.toScale??1.1,timing:Cd(o,"ease-out")})}function Sd(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=wp(a,{target:o.target});if(!t.valid)throw new Hr(t.issues);return{id:o.id,label:o.label,target:o.target,editingMode:"preset-only",keyframes:a}}function Cd(o,a){const t=o.startTime??0,n=o.duration??1;if(!Number.isFinite(t)||t<0)throw new Hr([{code:"invalid-time",message:"Preset start time must be a finite non-negative number.",time:t}]);if(!Number.isFinite(n)||n<=0)throw new Hr([{code:"invalid-time",message:"Preset duration must be a finite number greater than zero."}]);return{startTime:t,endTime:t+n,easing:o.easing??a}}class eo extends Error{constructor(a,t){super(t),this.name="VisualLayerSchemaError",this.code=a}}function JE(o){Nd(o.id,"caption track id");const a={id:o.id,source:o.source,stylePreset:o.stylePreset??"default",animation:o.animation??"none",segments:qE(o.segments)};return o.language!==void 0&&(a.language=o.language),a}function qE(o){const a=o.map(t=>{Nd(t.id,"caption segment id");const n=xd(t.startTime,"caption segment startTime"),i=kp(t.endTime,"caption segment endTime");if(i<=n)throw new eo("invalid-caption-segment",`Caption segment "${t.id}" must end after it starts.`);const r={id:t.id,startTime:n,endTime:i,text:t.text};return t.words!==void 0&&(r.words=YE(t.id,t.words)),r}).sort((t,n)=>t.startTime-n.startTime);for(let t=1;t<a.length;t+=1){const n=a[t-1],i=a[t];if(!(n===void 0||i===void 0)&&i.startTime<n.endTime)throw new eo("invalid-caption-segment",`Caption segment "${i.id}" overlaps segment "${n.id}".`)}return a}function YE(o,a){return a.map(t=>{Nd(t.id,"caption word id");const n=xd(t.startTime,"caption word startTime"),i=kp(t.endTime,"caption word endTime");if(i<=n)throw new eo("invalid-caption-segment",`Caption word "${t.id}" in segment "${o}" must end after it starts.`);return{id:t.id,startTime:n,endTime:i,text:t.text}}).sort((t,n)=>t.startTime-n.startTime)}function xd(o,a){const t=QE(o,a);if(t<0)throw new eo("invalid-time",`${a} must be non-negative.`);return Math.round(t*1e3)/1e3}function kp(o,a){const t=xd(o,a);if(t<=0)throw new eo("invalid-duration",`${a} must be greater than zero.`);return t}function QE(o,a){if(!eS(o))throw new eo("invalid-time",`${a} must be a finite number.`);return o}function Nd(o,a){if(o.trim()==="")throw new eo("empty-id",`${a} cannot be empty.`)}function eS(o){return Number.isFinite(o)}function tu(o){var m,p,f,h;tS(o);const a=oS(o),t=iS(o),n=((m=a[0])==null?void 0:m.id)??Nn,i=((p=t[0])==null?void 0:p.id)??Lo,r=aS(o.clips,i,n),l=rS(t,r),s=[],d=cS(o),c=uS(o),u={version:"1.0",source:{media_uuid:o.mediaUuid,duration:o.originalDuration,original_width:((f=o.media)==null?void 0:f.width)||1920,original_height:((h=o.media)==null?void 0:h.height)||1080},timeline:r,mediaSources:a,tracks:l,filters:s,audio:d,output:c,metadata:{created_at:new Date().toISOString(),editor_version:"2.0.0"}};return o.textOverlays&&(u.textOverlays=o.textOverlays),o.captionTracks&&(u.captionTracks=o.captionTracks.map(v=>({...v,segments:v.segments.map(k=>{const y={...k};return k.words&&(y.words=k.words.map(w=>({...w}))),y})}))),o.visualLayers&&(u.visualLayers=o.visualLayers.map(v=>({...v}))),o.audioTracks&&(u.audioTracks=o.audioTracks.filter(v=>typeof v.source=="string")),o.transitions&&(u.transitions=o.transitions.map(dS)),u}function tS(o){if(!o.mediaUuid)throw new Error("Media UUID is required");if(!o.clips||o.clips.length===0)throw new Error("At least one clip is required");const a=new Map;for(const t of o.clips){const n=nS(t),i=a.get(n)??[];i.push(t),a.set(n,i)}for(const t of a.values()){t.sort((n,i)=>n.timelineStart-i.timelineStart);for(let n=1;n<t.length;n++){const i=t[n],r=t[n-1];if(i.timelineStart<r.timelineEnd)throw new Error(`Clips ${r.id} and ${i.id} overlap on timeline`)}}}function aS(o,a,t){return o.map(n=>{const i=n.speed||1,r=typeof n.sourceIn=="number"&&!Number.isNaN(n.sourceIn),l=typeof n.sourceOut=="number"&&!Number.isNaN(n.sourceOut),s=Math.max(0,n.timelineEnd-n.timelineStart),d=n,c=d.sourceOffset??d.trimStart??0;let u=Number(r?n.sourceIn:c),m=l?Number(n.sourceOut):Number(c)+s/i;m>u||(m=u+Math.max(.033,s/Math.max(1e-6,i)));const p={id:n.id,type:n.type??"clip",trackId:n.trackId??a,sourceRefId:n.sourceRefId??t,timelineStart:n.timelineStart,timelineEnd:n.timelineEnd,sourceIn:u,sourceOut:m,speed:i,filters:n.filters?[...n.filters]:[]};return n.keyframes&&(p.keyframes=n.keyframes.map(f=>({...f}))),p})}function nS(o){return o.trackId??`legacy-track-${o.track??0}`}function oS(o){var t,n,i,r,l,s,d,c;if(o.mediaSources&&o.mediaSources.length>0)return o.mediaSources.map(lS);const a={id:((t=o.clips.find(u=>u.sourceRefId))==null?void 0:t.sourceRefId)??Nn,type:"media",mediaUuid:o.mediaUuid,duration:o.originalDuration,width:((n=o.media)==null?void 0:n.width)??1920,height:((i=o.media)==null?void 0:i.height)??1080};return(r=o.media)!=null&&r.filename&&(a.filename=o.media.filename),(l=o.media)!=null&&l.mime_type&&(a.mimeType=o.media.mime_type),typeof((s=o.media)==null?void 0:s.frame_rate)=="number"&&(a.frameRate=o.media.frame_rate),typeof((d=o.media)==null?void 0:d.has_audio)=="boolean"&&(a.hasAudio=o.media.has_audio),(c=o.media)!=null&&c.thumbnail_url&&(a.thumbnailUrl=o.media.thumbnail_url),[a]}function iS(o){var a;return o.tracks&&o.tracks.length>0?o.tracks.map(sS):[{id:((a=o.clips.find(t=>t.trackId))==null?void 0:a.trackId)??Lo,type:"video",name:"Video",order:0}]}function rS(o,a){return o.map(t=>({...t,clipIds:a.filter(n=>n.trackId===t.id).map(n=>n.id)}))}function lS(o){const a={...o};return o.metadata&&(a.metadata={...o.metadata}),a}function sS(o){const a={...o};return o.clipIds&&(a.clipIds=[...o.clipIds]),a}function dS(o){const a={...o};return o.params&&(a.params={...o.params}),a}function cS(o){const a={volume:o.audioVolume,muted:o.audioVolume===0};return o.audioFadeIn>0&&(a.fadeIn=o.audioFadeIn),o.audioFadeOut>0&&(a.fadeOut=o.audioFadeOut),a}function uS(o){var r;const a={"360p":{bitrate:1e6},"480p":{bitrate:25e5},"720p":{bitrate:5e6},"1080p":{bitrate:8e6},"1440p":{bitrate:16e6},"2160p":{bitrate:35e6}},t=a[o.exportQuality]||a["1080p"],n=(r=o.media)==null?void 0:r.frame_rate,i=n&&Number.isFinite(n)&&n>0?n:30;return{format:o.exportFormat||"mp4",codec:"h264",quality:o.exportQuality||"1080p",fps:i,bitrate:t.bitrate}}function Ga(o){return arguments.length===0?{ok:!0,value:void 0}:{ok:!0,value:o}}function Zt(o,a){return{ok:!1,reason:o,message:a}}const mS={last_clip:"Can't delete the last clip — leave the timeline empty or use Reset.",no_selection:"Select a clip first.",track_locked:"Target track is locked. Unlock it or pick another track.",track_missing:"That track no longer exists.",track_type_mismatch:"Clip can't be placed on that track type.",overlap:"No room on this track. Move neighboring clips or use a different track.",asset_not_ready:"Asset is still uploading or processing.",invariant_violation:"Editor state would be invalid — change rejected.",source_not_found:"Asset source not found.",source_in_use:"This asset is in use on the timeline. Remove its clips before deleting."};function ca(o){return mS[o]}const xi=1e-6;function Yl(o){if(!Number.isFinite(o.desiredDuration)||o.desiredDuration<=0)return{ok:!1};const a=Math.max(0,o.preferredStart),t=[...o.trackClips].filter(i=>i.id!==o.ignoreClipId).sort((i,r)=>i.timelineStart-r.timelineStart);if(t.length===0)return{ok:!0,start:a};if(pS(a,o.desiredDuration,t))return{ok:!0,start:a};let n=a;for(const i of t)if(!(i.timelineEnd<=n+xi)){if(i.timelineStart-n>=o.desiredDuration-xi&&n+xi>=a)return{ok:!0,start:n};n=Math.max(n,i.timelineEnd)}return{ok:!0,start:n}}function pS(o,a,t){const n=o+a;for(const i of t)if(!(i.timelineEnd<=o+xi)&&!(i.timelineStart>=n-xi))return!1;return!0}const fS={video:new Set(["clip","video","image"]),image:new Set(["image"]),audio:new Set(["audio"]),text:new Set(["text"]),graphics:new Set(["graphics"]),caption:new Set([])};function au(o,a){return fS[a].has(o)}function hS(o){const a=new Set;for(const t of o.clips)typeof t.sourceRefId=="string"&&t.sourceRefId!==""&&a.add(t.sourceRefId);return a}function vS(o,a){return hS(o).has(a)}function pr(o,a=30){const t=typeof o=="number"?o:Number(o);return Number.isFinite(t)&&t>0?t:a}function _p(o,a,t){var yt,Wt,_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),l=e.ref([]),s=e.ref([]),d=e.ref(void 0);let c=typeof(t==null?void 0:t.duration)=="number"&&t.duration>0&&t.duration!==1;const u=e.ref(!1),m=pr(((yt=a==null?void 0:a.output)==null?void 0:yt.fps)??(t==null?void 0:t.frame_rate)),p=e.shallowRef(null),f=new jm(m),h=e.ref(m),v=e.ref(!1),k=e.ref(!1);a&&a.timeline&&a.timeline.length>0?(B(a),(Wt=a.output)!=null&&Wt.fps&&(h.value=pr(a.output.fps,h.value),f.setFps(h.value))):(R(),a&&((_a=a.output)!=null&&_a.fps&&(h.value=pr(a.output.fps,h.value),f.setFps(h.value)),a.audio&&(i.audioVolume=a.audio.volume||1,i.audioFadeIn=a.audio.fadeIn||0,i.audioFadeOut=a.audio.fadeOut||0),a.output&&(i.exportFormat=a.output.format||"mp4",i.exportQuality=a.output.quality||"1080p")));const y=e.ref(1),w=e.computed(()=>i.selectedClipId?i.clips.find(G=>G.id===i.selectedClipId)??null:null);e.watch(w,G=>{y.value=(G==null?void 0:G.speed)??1},{immediate:!0});const g=e.computed(()=>l.value.length>0),b=e.computed(()=>s.value.length>0);function R(){const G=typeof(t==null?void 0:t.duration)=="number"&&t.duration>0?t.duration:1;t&&(i.media=t),i.originalDuration=G,i.totalDuration=G;const q=zt();i.mediaSources=[V(G)],i.tracks=[I([q])];const pe={id:q,type:"clip",trackId:Lo,sourceRefId:Nn,timelineStart:0,timelineEnd:G,sourceIn:0,sourceOut:G,sourceMinIn:0,sourceMaxOut:G,speed:1};i.clips=[pe],i.selectedClipId=q,d.value=q,!(t||n.startsWith("temp-"))&&(async()=>{try{const he=await fetch(`/api/v1/video/${encodeURIComponent(n)}`);if(!he.ok)throw new Error(`Failed to fetch media: ${he.status}`);const Te=await he.json(),He=typeof Te=="object"&&Te!==null&&"data"in Te?Te.data:Te;if(!He||typeof He!="object")throw new Error("Failed to parse media payload");const ot=He;i.media=ot,a||(h.value=pr(ot.frame_rate,h.value),f.setFps(h.value));const Je=typeof ot.duration=="number"&&ot.duration>0?ot.duration:G;if(i.hasChanges||i.clips.length!==1||i.clips[0].id!==q)return;i.originalDuration=Je,i.totalDuration=Je,i.mediaSources=[V(Je,ot)],i.tracks=[I([q])];const Ze=i.clips[0];Ze.timelineStart=0,Ze.timelineEnd=Je,Ze.sourceIn=0,Ze.sourceOut=Je,Ze.sourceMinIn=0,Ze.sourceMaxOut=Je,J(),c=!0}catch{}})()}function V(G,q=t){const pe={id:Nn,type:"media",mediaUuid:n,duration:G,width:(q==null?void 0:q.width)??1920,height:(q==null?void 0:q.height)??1080};return q!=null&&q.filename&&(pe.filename=q.filename),q!=null&&q.mime_type&&(pe.mimeType=q.mime_type),typeof(q==null?void 0:q.frame_rate)=="number"&&(pe.frameRate=q.frame_rate),typeof(q==null?void 0:q.has_audio)=="boolean"&&(pe.hasAudio=q.has_audio),q!=null&&q.thumbnail_url&&(pe.thumbnailUrl=q.thumbnail_url),pe}function I(G){return{id:Lo,type:"video",name:"Video",order:0,clipIds:G}}function x(G){return`track-${G}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function T(G,q){const pe=G.charAt(0).toUpperCase()+G.slice(1),he=q.filter(Te=>Te.type===G).length;return he===0?pe:`${pe} ${he+1}`}function $(G,q){if(G.originalDuration!==1)return;G.originalDuration=q,G.totalDuration===1&&(G.totalDuration=q);const pe=G.clips[0],he=!a&&G.clips.length===1&&pe!==void 0&&pe.timelineStart===0&&pe.timelineEnd===1&&pe.sourceIn===0&&pe.sourceOut===1;for(const Te of G.clips)(Te.sourceMaxOut===1||Te.sourceMaxOut===void 0)&&(Te.sourceMaxOut=q);if(G.mediaSources)for(const Te of G.mediaSources)Te.id===Nn&&(Te.duration===1||Te.duration===void 0)&&(Te.duration=q);he&&pe!==void 0&&(pe.sourceOut=q,pe.timelineEnd=q)}function S(G){if(!Number.isFinite(G)||G<=0||c)return;const q=i.hasChanges;i.originalDuration=G,i.totalDuration=Math.max(i.totalDuration,G),i.media&&(i.media.duration=G);for(const Te of i.clips)Te.sourceMaxOut=G;if(i.mediaSources)for(const Te of i.mediaSources)(Te.id===Nn||Te.mediaUuid===n)&&(Te.duration=G);const pe=i.clips[0];!a&&i.clips.length===1&&pe!==void 0&&pe.timelineStart===0&&pe.timelineEnd===1&&pe.sourceIn===0&&pe.sourceOut===1&&pe!==void 0&&(pe.sourceOut=G,pe.timelineEnd=pe.timelineStart+(pe.sourceOut-pe.sourceIn)),J();for(const Te of l.value)$(Te,G);for(const Te of s.value)$(Te,G);c=!0,e.nextTick(()=>{q||(i.hasChanges=!1)})}function B(G){const q=Jm(G);i.mediaSources=q.mediaSources,i.tracks=q.tracks,i.transitions=q.transitions,i.clips=q.clips.map(pe=>({...pe,sourceMinIn:pe.sourceMinIn??0,sourceMaxOut:pe.sourceMaxOut??G.source.duration})),i.filters=[],i.audioVolume=G.audio.volume,i.audioFadeIn=G.audio.fadeIn||0,i.audioFadeOut=G.audio.fadeOut||0,i.exportFormat=G.output.format,i.exportQuality=G.output.quality,i.originalDuration=G.source.duration,i.textOverlays=G.textOverlays?[...G.textOverlays]:[],i.audioTracks=G.audioTracks?[...G.audioTracks]:[],i.captionTracks=G.captionTracks?G.captionTracks.map(ne):[],i.visualLayers=G.visualLayers?G.visualLayers.map(pe=>({...pe})):[],i.clips.length>0?(i.selectedClipId=i.clips[0].id,d.value=i.selectedClipId):(delete i.selectedClipId,d.value=void 0),J()}function _(){l.value.push(JSON.parse(JSON.stringify(i))),s.value=[],i.hasChanges=!0}function A(){if(!g.value)return;const G=l.value.pop();s.value.push(JSON.parse(JSON.stringify(i))),Object.assign(i,G)}function P(){if(!b.value)return;const G=s.value.pop();l.value.push(JSON.parse(JSON.stringify(i))),Object.assign(i,G)}function D(G,q,pe){_();const he=i.clips.find(Je=>Je.id===G);if(!he)return;const Te=1/h.value,He=he.sourceMinIn??0,ot=he.sourceMaxOut??i.originalDuration;if(q==="start"){const Je=he.sourceIn,Ze=Math.max(He,Math.min(pe,he.sourceOut-Te));he.sourceIn=Ze;const dt=Ze-Je;he.timelineStart+=dt}else{const Je=Math.max(he.sourceIn+Te,Math.min(pe,ot));he.sourceOut=Je;const Ze=he.sourceOut-he.sourceIn;he.timelineEnd=he.timelineStart+Ze}J(),p.value&&p.value.trimClip(G,he.sourceIn,he.sourceOut)}function z(G){_();const q=i.clips.find(ot=>G>ot.timelineStart&&G<ot.timelineEnd);if(!q)return;const pe=G-q.timelineStart,he=q.sourceIn+pe,Te={id:zt(),type:"clip",timelineStart:G,timelineEnd:q.timelineEnd,sourceIn:he,sourceOut:q.sourceOut,speed:q.speed??1,sourceMinIn:q.sourceMinIn??0,sourceMaxOut:q.sourceMaxOut??i.originalDuration,filters:[...q.filters||[]]};q.trackId&&(Te.trackId=q.trackId),q.sourceRefId&&(Te.sourceRefId=q.sourceRefId),q.timelineEnd=G,q.sourceOut=he;const He=i.clips.indexOf(q);i.clips.splice(He+1,0,Te),ce(),i.selectedClipId=Te.id}function M(){z(i.playheadPosition)}function Z(G){var pe;const q=G??i.selectedClipId??d.value??((pe=i.clips[0])==null?void 0:pe.id);q&&(i.selectedClipId=q,d.value=q)}function O(){return i.selectedClipId?K(i.selectedClipId):Zt("no_selection",ca("no_selection"))}function K(G){const q=i.clips.findIndex(pe=>pe.id===G);return q===-1?Zt("source_not_found","Clip not found."):(_(),i.clips.splice(q,1),ce(),de(q),J(),Ga())}function de(G){if(!i.clips.length){delete i.selectedClipId,d.value=void 0;return}const q=Math.max(0,Math.min(G,i.clips.length-1)),pe=i.clips[q];pe&&(i.selectedClipId=pe.id,d.value=pe.id)}function Ne(G){return G.trackId??`legacy-track-${G.track??0}`}function ce(){const G=i.tracks;if(G)for(const q of G)q.clipIds=i.clips.filter(pe=>Ne(pe)===q.id).map(pe=>pe.id)}function le(G="video"){_();const q=i.tracks??[],pe=q.reduce((Te,He)=>Math.max(Te,He.order),-1),he={id:x(G),type:G,name:T(G,q),order:pe+1,clipIds:[]};return i.tracks=[...q,he],i.hasChanges=!0,he}function W(G){if(G.length===0)return;const q=new Set(G),pe=i.clips.findIndex(he=>q.has(he.id));i.clips=i.clips.filter(he=>!q.has(he.id)),i.transitions&&i.transitions.length>0&&(i.transitions=i.transitions.filter(he=>!q.has(he.fromClipId)&&!q.has(he.toClipId))),ce(),i.selectedClipId!==void 0&&q.has(i.selectedClipId)&&de(pe>=0?pe:0),J()}function C(G){const q=i.tracks??[],pe=q.find(Te=>Te.id===G);if(!pe)return Zt("track_missing",ca("track_missing"));if(q.length<=1)return Zt("invariant_violation","Can't delete the last remaining track. Add another track first.");_();const he=i.clips.filter(Te=>Ne(Te)===pe.id).map(Te=>Te.id);return W(he),i.tracks=q.filter(Te=>Te.id!==pe.id),i.hasChanges=!0,Ga()}function U(G,q){const he=(i.tracks??[]).find(He=>He.id===G);if(!he)return Zt("track_missing",ca("track_missing"));const Te=q.trim();return Te===""?Zt("invariant_violation","Track name cannot be empty."):(he.name===Te||(_(),he.name=Te,i.hasChanges=!0),Ga())}function j(G,q){const pe=i.tracks??[],he=pe.find(dt=>dt.id===G);if(!he)return Zt("track_missing",ca("track_missing"));const Te=[...pe].sort((dt,ft)=>dt.order-ft.order),He=Te.findIndex(dt=>dt.id===he.id),ot=q==="up"?He+1:He-1,Je=Te[ot];if(!Je)return Zt("invariant_violation","Track is already at the edge.");_();const Ze=he.order;return he.order=Je.order,Je.order=Ze,i.hasChanges=!0,Ga()}function re(G){let q=i.tracks??[];if(q.length===0){const he=I([]);i.tracks=[he],q=i.tracks}if(G){const he=q.find(Te=>Te.id===G);return he?he.locked===!0?{ok:!1,reason:"track_locked"}:{ok:!0,track:he}:{ok:!1,reason:"track_missing"}}const pe=q.find(he=>he.type==="video"&&he.locked!==!0)??q.find(he=>he.locked!==!0);return pe?{ok:!0,track:pe}:{ok:!1,reason:"no_editable_track"}}function ue(G){const q=1/h.value;return typeof G.duration=="number"&&Number.isFinite(G.duration)&&G.duration>q?G.duration:i.originalDuration>q?i.originalDuration:Math.max(q,i.totalDuration)}function Xe(G){const q=i.clips.filter(pe=>Ne(pe)===G);return q.length>0?q.reduce((pe,he)=>Math.max(pe,he.timelineEnd),0):Math.max(0,Math.min(i.playheadPosition,i.totalDuration))}function be(G){const q=i.mediaSources??[],pe=q.find(he=>he.id===G.id);return pe||(i.mediaSources=[...q,G],i.hasChanges=!0,G)}function Ee(G,q){return xe(G,"clip",q)}function ye(G,q){if(!(i.mediaSources??[]).find(Te=>Te.id===G))return Zt("source_not_found",ca("source_not_found"));let he=q;if(!he){const Te=(i.tracks??[]).find(He=>He.type==="audio"&&He.locked!==!0);he=(Te==null?void 0:Te.id)??le("audio").id}return xe(G,"audio",he)}function xe(G,q,pe){const he=(i.mediaSources??[]).find(ea=>ea.id===G);if(!he)return Zt("source_not_found",ca("source_not_found"));const Te=re(pe);if(!Te.ok){const ea=Te.reason==="no_editable_track"?"track_missing":Te.reason;return Zt(ea,ca(ea))}const He=Te.track;if(!au(q,He.type))return Zt("track_type_mismatch",ca("track_type_mismatch"));const ot=i.clips.filter(ea=>Ne(ea)===He.id),Je=ue(he),Ze=Xe(He.id),dt=Yl({trackClips:ot,desiredDuration:Je,preferredStart:Ze});if(!dt.ok)return Zt("overlap",ca("overlap"));_();const ft=zt(),Qe={id:ft,type:q,trackId:He.id,sourceRefId:he.id,timelineStart:dt.start,timelineEnd:dt.start+Je,sourceIn:0,sourceOut:Je,sourceMinIn:0,sourceMaxOut:Je,speed:1};return i.clips.push(Qe),i.selectedClipId=ft,d.value=ft,ce(),J(),Ga(Qe)}function Ce(G){const q=w.value,pe=(i.mediaSources??[]).find(Je=>Je.id===G);if(!q||!pe)return!1;_();const he=1/h.value,Te=ue(pe),He=Math.max(he,q.timelineEnd-q.timelineStart),ot=Math.max(he,Math.min(He,Te));return q.sourceRefId=pe.id,q.sourceIn=0,q.sourceOut=ot,q.sourceMinIn=0,q.sourceMaxOut=Te,q.timelineEnd=q.timelineStart+ot,J(),!0}function Re(G){const q=i.mediaSources??[];return q.length<=1||vS({clips:i.clips},G)?!1:(_(),i.mediaSources=q.filter(pe=>pe.id!==G),!0)}function ze(G,q){const pe=(i.tracks??[]).find(he=>he.id===G);return pe?(_(),pe[q]=pe[q]!==!0,!0):!1}function rt(G){return ze(G,"locked")}function at(G){return ze(G,"hidden")}function Dt(G){return ze(G,"muted")}function ht(G){return ze(G,"solo")}function St(G){if(i.clips.length<=1)return!1;const q=i.clips.findIndex(He=>He.id===G),pe=q===-1?void 0:i.clips[q];if(!pe)return!1;const he=Math.max(0,pe.timelineEnd-pe.timelineStart),Te=Ne(pe);if(_(),i.clips.splice(q,1),ce(),he>0)for(const He of i.clips)Ne(He)!==Te||He.timelineStart<pe.timelineEnd||(He.timelineStart=Math.max(0,He.timelineStart-he),He.timelineEnd=Math.max(He.timelineStart,He.timelineEnd-he));return i.playheadPosition>=pe.timelineEnd?i.playheadPosition=Math.max(0,i.playheadPosition-he):i.playheadPosition>pe.timelineStart&&(i.playheadPosition=pe.timelineStart),de(q),J(),i.hasChanges=!0,!0}function ut(){return i.selectedClipId?St(i.selectedClipId):!1}function lt(){return[...i.clips].sort((G,q)=>G.timelineStart-q.timelineStart)}function Ct(G){const q=i.clips.find(Qe=>Qe.id===G);if(!q)return null;const pe=Ne(q),he=lt().filter(Qe=>Ne(Qe)===pe),Te=he.findIndex(Qe=>Qe.id===G);if(Te===-1)return null;const He=he[Te],ot=He.timelineEnd-He.timelineStart,Je=Te>0?he[Te-1]:null,Ze=Te<he.length-1?he[Te+1]:null,dt=Je?Je.timelineEnd:0,ft=Ze?Ze.timelineStart-ot:Math.max(He.timelineStart,i.totalDuration-ot);return{minStart:dt,maxStart:Math.max(dt,ft)}}function Se(G,q,pe){const he=i.clips.find(ft=>ft.id===G);if(!he)return Zt("source_not_found","Clip not found.");if(pe===void 0||pe===he.trackId){const ft=Ct(G),Qe=ft?Math.min(ft.maxStart,Math.max(ft.minStart,q)):Math.max(0,q);if(Qe===he.timelineStart)return Ga();_();const ea=Qe-he.timelineStart;return he.timelineStart=Qe,he.timelineEnd+=ea,J(),p.value&&p.value.moveClip(G,Qe),Ga()}const He=(i.tracks??[]).find(ft=>ft.id===pe);if(!He)return Zt("track_missing",ca("track_missing"));if(He.locked===!0)return Zt("track_locked",ca("track_locked"));if(!au(he.type,He.type))return Zt("track_type_mismatch",ca("track_type_mismatch"));const ot=i.clips.filter(ft=>Ne(ft)===He.id&&ft.id!==he.id),Je=he.timelineEnd-he.timelineStart,Ze=Yl({trackClips:ot,desiredDuration:Je,preferredStart:Math.max(0,q),ignoreClipId:he.id});if(!Ze.ok)return Zt("overlap",ca("overlap"));_(),he.trackId=He.id;const dt=he.timelineStart;return he.timelineStart=Ze.start,he.timelineEnd=Ze.start+Je,ce(),J(),p.value&&dt!==Ze.start&&p.value.moveClip(G,Ze.start),Ga()}function J(){if(i.clips.length===0){i.totalDuration=0;return}const G=i.clips.reduce((q,pe)=>pe.timelineEnd>q.timelineEnd?pe:q);i.totalDuration=G.timelineEnd}function oe(){i.zoomLevel=Math.min(200,i.zoomLevel*1.2)}function De(){i.zoomLevel=Math.max(10,i.zoomLevel/1.2)}function fe(G){i.zoomLevel=Math.max(10,Math.min(600,Math.round(G)))}function Ae(){i.isPlaying=!i.isPlaying}function Ye(G){i.isPlaying=G}function st(G){i.playheadPosition=Math.max(0,Math.min(G,i.totalDuration))}function Bt(){const G=tu(i);try{localStorage.setItem(`video-draft-${n}`,JSON.stringify(G))}catch{}return G}function Vt(){i.hasChanges=!1}function Lt(){return confirm("Are you sure you want to reset all changes?")?(_(),R(),i.hasChanges=!1,!0):!1}function Pt(){return tu(i)}function zt(){return`clip-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}async function Ot(G=1920,q=1080){if(u.value)try{p.value=new zm(G,q,h.value),await jt()}catch{p.value=null}}async function jt(){if(!(!p.value||k.value)){k.value=!0;try{const G=Pt();await p.value.loadFromRecipe(G);const q=f.secondsToFrames(i.playheadPosition);p.value.seek(q)}catch{}finally{k.value=!1}}}function oa(G){}function Q(G){return f.secondsToFrames(G)}function ge(G){return f.framesToSeconds(G)}function me(G){const q=ge(G);st(q),p.value&&p.value.seek(G)}function se(){v.value=!v.value}function Ve(){jt()}function Pe(G){u.value=!1,p.value=null}e.watch(()=>i.clips,()=>{i.hasChanges=!0,u.value&&p.value&&jt()},{deep:!0}),e.watch(()=>i.filters,()=>{i.hasChanges=!0,u.value&&p.value&&jt()},{deep:!0}),e.watch(()=>i.clips.map(G=>G.id),()=>{var q;if(!i.clips.length){delete i.selectedClipId,d.value=void 0;return}if(!i.clips.some(pe=>pe.id===i.selectedClipId)){const pe=d.value&&((q=i.clips.find(he=>he.id===d.value))==null?void 0:q.id);i.selectedClipId=pe??i.clips[0].id,d.value=i.selectedClipId}},{deep:!0});function et(G){const q=i.selectedClipId?i.clips.find(pe=>pe.id===i.selectedClipId):i.clips[0];q&&(q.filters=[...G],i.hasChanges=!0)}function gt(G){i.textOverlays=[...G]}function Tt(G){i.audioTracks=[...G]}function xt(G){i.captionTracks=G.map(ne),i.hasChanges=!0}function _t(G){i.visualLayers=G.map(q=>({...q})),i.hasChanges=!0}function Xt(G){i.transitions=G.map(q=>{const pe={...q};return q.params&&(pe.params={...q.params}),pe}),i.hasChanges=!0}function X(G,q){const pe=i.clips.find(he=>he.id===G);pe&&(pe.keyframes=q.map(he=>({...he})),i.hasChanges=!0)}function we(G){_(),B(G),i.hasChanges=!0}function ne(G){return{...G,segments:G.segments.map(q=>{const pe={...q};return q.words&&(pe.words=q.words.map(he=>({...he}))),pe})}}e.watch(u,G=>{G?Ot():p.value&&(p.value.destroy(),p.value=null)}),e.watch(v,()=>{}),e.watch(h,G=>{f.setFps(G)});function Fe(){if(!i.selectedClipId)return Zt("no_selection",ca("no_selection"));const G=i.clips.find(Je=>Je.id===i.selectedClipId);if(!G)return Zt("no_selection",ca("no_selection"));const q=Ne(G),pe=i.clips.filter(Je=>Ne(Je)===q),he=G.timelineEnd-G.timelineStart,Te=Yl({trackClips:pe,desiredDuration:he,preferredStart:G.timelineEnd});if(!Te.ok)return Zt("overlap",ca("overlap"));_();const He={...G,id:zt(),timelineStart:Te.start,timelineEnd:Te.start+he,filters:[...G.filters||[]]},ot=i.clips.indexOf(G);return i.clips.splice(ot+1,0,He),ce(),i.selectedClipId=He.id,i.hasChanges=!0,Ga(He)}function It(G){const q=G??800,pe=i.totalDuration;if(pe<=0){i.zoomLevel=50;return}const he=q*.8/pe;i.zoomLevel=Math.max(10,Math.min(600,Math.round(he)))}function At(){const G=1/h.value;st(Math.min(i.playheadPosition+G,i.totalDuration))}function Mt(){const G=1/h.value;st(Math.max(i.playheadPosition-G,0))}function mt(){st(0)}function pt(){st(i.totalDuration)}function Qt(G){if(!Number.isFinite(G)||G<=0)return;const q=w.value??i.clips[0];if(!q){y.value=G;return}const pe=q.speed??1;if(pe===G){y.value=G;return}_();const he=Math.max(1/h.value,q.sourceOut-q.sourceIn),Te=he/pe,He=he/G,ot=He-Te;q.speed=G,q.timelineEnd=q.timelineStart+He;const Je=i.clips.findIndex(Ze=>Ze.id===q.id);if(Je!==-1&&ot!==0)for(let Ze=Je+1;Ze<i.clips.length;Ze+=1){const dt=i.clips[Ze];dt.timelineStart+=ot,dt.timelineEnd+=ot}J(),i.playheadPosition=Math.max(0,Math.min(i.playheadPosition,i.totalDuration)),i.hasChanges=!0,y.value=G}return{currentFrame:r,playheadPosition:e.computed(()=>i.playheadPosition),timelineClips:e.computed(()=>i.clips),tracks:e.computed(()=>i.tracks??[]),mediaSources:e.computed(()=>i.mediaSources??[]),transitions:e.computed(()=>i.transitions??[]),totalDuration:e.computed(()=>i.totalDuration),hasChanges:e.computed(()=>i.hasChanges),isPlaying:e.computed(()=>i.isPlaying),selectedClip:w,zoomLevel:e.computed(()=>i.zoomLevel),playbackSpeed:y,useVideoEngine:u,compositionAdapter:e.computed(()=>p.value),fps:h,useFrameMode:v,handleTrim:D,handleSplit:z,handleClipSelect:Z,splitAtPlayhead:M,deleteSelectedClip:O,deleteClip:K,rippleDeleteClip:St,rippleDeleteSelectedClip:ut,duplicateSelectedClip:Fe,addTimelineTrack:le,deleteTimelineTrack:C,renameTimelineTrack:U,reorderTimelineTrack:j,appendMediaSourceToTimeline:Ee,appendAudioSourceToTimeline:ye,registerMediaSource:be,replaceSelectedClipSource:Ce,removeMediaSource:Re,toggleTrackLock:rt,toggleTrackHidden:at,toggleTrackMuted:Dt,toggleTrackSolo:ht,setFilters:et,setTextOverlays:gt,setAudioTracks:Tt,setCaptionTracks:xt,setVisualLayers:_t,setTransitions:Xt,setClipKeyframes:X,loadRecipe:we,moveClip:Se,saveDraft:Bt,clearHasChanges:Vt,resetChanges:Lt,generateRecipe:Pt,zoomIn:oe,zoomOut:De,setZoomLevel:fe,fitToWindow:It,togglePlayback:Ae,setPlaying:Ye,seekTo:st,frameForward:At,frameBackward:Mt,skipToStart:mt,skipToEnd:pt,setPlaybackSpeed:Qt,updateSourceDuration:S,undo:A,redo:P,canUndo:g,canRedo:b,initializeComposition:Ot,syncCompositionWithState:jt,syncWithComposition:oa,convertToFrames:Q,convertToSeconds:ge,seekToFrame:me,toggleFrameMode:se,onCompositionReady:Ve,onCompositionError:Pe}}const gS=[{id:"brightness",name:"Brightness",category:"color",ffmpeg:"eq=brightness={value}",pixiFilter:"AdjustmentFilter",defaultParams:{value:0},paramRanges:{value:{min:-1,max:1,step:.05}}},{id:"contrast",name:"Contrast",category:"color",ffmpeg:"eq=contrast={value}",pixiFilter:"AdjustmentFilter",defaultParams:{value:1},paramRanges:{value:{min:.5,max:2,step:.05}}},{id:"saturation",name:"Saturation",category:"color",ffmpeg:"eq=saturation={value}",pixiFilter:"AdjustmentFilter",defaultParams:{value:1},paramRanges:{value:{min:0,max:2,step:.05}}},{id:"hue",name:"Hue Shift",category:"color",ffmpeg:"hue=h={value}",pixiFilter:"HueRotateFilter",defaultParams:{value:0},paramRanges:{value:{min:-180,max:180,step:5}}},{id:"gaussian-blur",name:"Gaussian Blur",category:"blur",ffmpeg:"gblur=sigma={value}",pixiFilter:"BlurFilter",defaultParams:{value:2},paramRanges:{value:{min:0,max:10,step:.5}}},{id:"motion-blur",name:"Motion Blur",category:"blur",ffmpeg:"minterpolate=fps=60:mi_mode=mci:mc_mode=aobmc:me_mode=bidir:me=epzs:vsbmc=1",pixiFilter:"MotionBlurFilter",defaultParams:{velocity:5,angle:0},paramRanges:{velocity:{min:0,max:20,step:1},angle:{min:0,max:360,step:15}}},{id:"vintage",name:"Vintage",category:"stylize",ffmpeg:"curves=preset=vintage",pixiFilter:"ColorMatrixFilter",defaultParams:{preset:"vintage"},paramRanges:{}},{id:"sepia",name:"Sepia",category:"stylize",ffmpeg:"colorchannelmixer=.393:.769:.189:0:.349:.686:.168:0:.272:.534:.131",pixiFilter:"ColorMatrixFilter",defaultParams:{preset:"sepia"},paramRanges:{}},{id:"grayscale",name:"Black & White",category:"stylize",ffmpeg:"colorchannelmixer=0.3:0.59:0.11:0:0.3:0.59:0.11:0:0.3:0.59:0.11",pixiFilter:"ColorMatrixFilter",defaultParams:{preset:"grayscale"},paramRanges:{}},{id:"vignette",name:"Vignette",category:"effects",ffmpeg:"vignette=a={value}",pixiFilter:"VignetteFilter",defaultParams:{value:.3},paramRanges:{value:{min:0,max:1,step:.05}}},{id:"sharpen",name:"Sharpen",category:"effects",ffmpeg:"unsharp=5:5:{value}:5:5:0",pixiFilter:"SharpenFilter",defaultParams:{value:1},paramRanges:{value:{min:0,max:5,step:.25}}},{id:"denoise",name:"Noise Reduction",category:"effects",ffmpeg:"nlmeans=s={value}",pixiFilter:"NoiseFilter",defaultParams:{value:1},paramRanges:{value:{min:.1,max:5,step:.1}}},{id:"motion-blur",name:"Motion Blur",category:"effects",ffmpeg:"minterpolate=fps=30:mi_mode=blend",pixiFilter:"MotionBlurFilter",defaultParams:{velocity:[0,0],kernelSize:5},paramRanges:{velocityX:{min:-100,max:100,step:1},velocityY:{min:-100,max:100,step:1},kernelSize:{min:3,max:15,step:2}}},{id:"radial-blur",name:"Radial Blur",category:"effects",ffmpeg:"boxblur={radius}:{radius}",pixiFilter:"RadialBlurFilter",defaultParams:{radius:.1,angle:0,kernelSize:5},paramRanges:{radius:{min:0,max:1,step:.01},angle:{min:-180,max:180,step:1},kernelSize:{min:3,max:15,step:2}}},{id:"kawase-blur",name:"Kawase Blur",category:"effects",ffmpeg:"gblur=sigma={blur}:steps={quality}",pixiFilter:"KawaseBlurFilter",defaultParams:{blur:4,quality:3},paramRanges:{blur:{min:0,max:20,step:.5},quality:{min:1,max:10,step:1}}},{id:"flip-horizontal",name:"Flip Horizontal",category:"transform",ffmpeg:"hflip",pixiFilter:"FlipFilter",defaultParams:{horizontal:!0},paramRanges:{}},{id:"flip-vertical",name:"Flip Vertical",category:"transform",ffmpeg:"vflip",pixiFilter:"FlipFilter",defaultParams:{vertical:!0},paramRanges:{}},{id:"rotate",name:"Rotate",category:"transform",ffmpeg:"rotate={value}*PI/180",pixiFilter:"RotateFilter",defaultParams:{value:0},paramRanges:{value:{min:-180,max:180,step:15}}}],bS={dropShadow:"drop-shadow",softFocus:"blur",blackAndWhite:"grayscale",gaussianBlur:"blur","gaussian-blur":"blur"};function gl(o){return typeof o=="object"&&o!==null}function yS(o,a){if(typeof o=="number"&&Number.isFinite(o))return o;if(typeof o=="string"){const t=Number(o);if(Number.isFinite(t))return t}return a}function bl(o){if(typeof o=="number"||typeof o=="string"||typeof o=="boolean")return o}function wS(o){const a={id:o.id,type:o.type,label:o.label};o.property!==void 0&&(a.property=o.property),o.min!==void 0&&(a.min=o.min),o.max!==void 0&&(a.max=o.max),o.step!==void 0&&(a.step=o.step);const t=bl(o.default);return t!==void 0&&(a.default=t),o.options!==void 0&&(a.options=o.options),a}function Ep(o,a,t){const n=te.getFilter(o),i={},r=(n==null?void 0:n.defaultParams)??t;if(r&&gl(r))for(const[l,s]of Object.entries(r))i[l]=bl(s)??null;for(const l of a){const s=l.property??l.id;i[s]===void 0&&l.default!==void 0&&(i[s]=l.default)}return i}function Sp(o){const a={};for(const t of o){if(t.type!=="slider")continue;const n=t.property??t.id;a[n]={min:t.min??0,max:t.max??100,step:t.step??1}}return a}function kS(o,a,t,n){const i=n.map(wS);return{id:o,name:a,category:t,controls:i,params:i,defaultParams:Ep(o,i),paramRanges:Sp(i)}}function _S(o){const a=o.paramRanges??{},t=Object.entries(a).map(([n,i])=>{var s;const r={id:n,type:"slider",label:n.replace(/[-_]/g," ").replace(/\b\w/g,d=>d.toUpperCase()),property:n,min:i.min,max:i.max,step:i.step},l=bl((s=o.defaultParams)==null?void 0:s[n]);return l!==void 0&&(r.default=l),r});return{id:o.id,name:o.name,category:o.category,controls:t,params:t,defaultParams:Ep(o.id,t,o.defaultParams),paramRanges:Sp(t)}}function ES(o,a){return a.toLowerCase()==="unlisted"?!1:te.isFilterCompatibleWithMedia(o,"video")}function Ql(o){return bS[o]??o}function hi(o){const a=yS(o,1);return Math.max(0,Math.min(1,a))}function vi(o){if(!gl(o))return{};const a={};for(const[t,n]of Object.entries(o))a[t]=bl(n)??null;return a}function SS(o){return!gl(o)||typeof o.filterId!="string"?null:{filterId:o.filterId,params:vi(o.params),intensity:hi(o.intensity)}}function CS(o){if(!gl(o)||typeof o.id!="string"||typeof o.name!="string")return null;const t=(Array.isArray(o.filters)?o.filters:[]).map(i=>SS(i)).filter(i=>i!==null),n=typeof o.created_at=="string"?o.created_at:new Date().toISOString();return{id:o.id,name:o.name,filters:t,created_at:n}}function Cp(){te.initializeFilterRegistry();const o=e.ref([]),a=e.ref(null),t=e.ref(null),n=e.ref([]),i=e.ref(null),r=e.reactive({}),l=e.computed(()=>{const _=new Map,A=te.getRegisteredFilters();for(const P of A)ES(P.id,P.category)&&_.set(P.id,kS(P.id,P.name,P.category,P.controls));for(const P of gS)_.has(P.id)||_.set(P.id,_S(P));return Array.from(_.values())}),s=e.computed(()=>{const _=new Map;for(const A of l.value)_.set(A.id,A);return _}),d=e.computed(()=>o.value.length>0),c=e.computed(()=>{const _={};for(const A of l.value)_[A.category]||(_[A.category]=[]),_[A.category].push(A);return _});function u(_){const A=s.value.get(_);if(A)return A;const P=Ql(_);return s.value.get(P)??null}function m(_){const A=s.value.get(_);if(A)return A.id;const P=Ql(_),D=s.value.get(P);return D?D.id:null}function p(_){const A=_?u(_):a.value;if(!A)return;const P=A.defaultParams||{},D={id:T(),filterId:A.id,params:{...P},intensity:1};return o.value.push(D),i.value=D.id,a.value=A,Object.keys(r).forEach(z=>delete r[z]),Object.assign(r,D.params),t.value=null,D}function f(_){const A=u(_);if(!A)return;a.value=A;const P=A.defaultParams||S(_);Object.assign(r,P),t.value={id:"preview",filterId:A.id,params:{...P},intensity:1}}function h(_){if(Object.assign(r,_),t.value&&(t.value.params={...r}),i.value){const A=o.value.find(P=>P.id===i.value);A&&(A.params={...r})}}function v(_){const A=o.value.findIndex(P=>P.id===_);A!==-1&&o.value.splice(A,1)}function k(_,A){if(_<0||_>=o.value.length||A<0||A>=o.value.length)return;const[P]=o.value.splice(_,1);o.value.splice(A,0,P)}function y(_,A){const P=o.value.find(D=>D.id===_);P&&(P.intensity=Math.max(0,Math.min(1,A)))}function w(_){const A=o.value.find(P=>P.id===_);A&&(A.intensity=A.intensity>0?0:1)}function g(){o.value=[],t.value=null,a.value=null,i.value=null,Object.keys(r).forEach(_=>delete r[_])}function b(_){const A={id:$(),name:_,filters:o.value.map(D=>({filterId:D.filterId,params:vi(D.params),intensity:hi(D.intensity)})),created_at:new Date().toISOString()};n.value.push(A);const P=n.value.map(D=>({...D}));return localStorage.setItem("video-filter-presets",JSON.stringify(P)),A}function R(_){const A=n.value.find(P=>P.id===_);if(A){g();for(const P of A.filters){const D=u(P.filterId);D&&o.value.push({id:T(),filterId:D.id,params:{...P.params},intensity:hi(P.intensity)})}}}function V(_){const A=n.value.findIndex(P=>P.id===_);A!==-1&&(n.value.splice(A,1),localStorage.setItem("video-filter-presets",JSON.stringify(n.value)))}function I(){try{const _=localStorage.getItem("video-filter-presets");if(!_)return;const A=JSON.parse(_);if(!Array.isArray(A))return;n.value=A.map(P=>CS(P)).filter(P=>P!==null)}catch{}}function x(){if(o.value.length===0)return"No filters applied";const _=o.value.map(A=>{const P=B(A.filterId);return(P==null?void 0:P.name)||A.filterId});return _.length===1?_[0]:_.length===2?`${_[0]} + ${_[1]}`:`${_[0]} + ${_.length-1} more`}function T(){return`filter-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function $(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function S(_){const A=u(_);return A?A.defaultParams||{}:{}}function B(_){return u(_)}return I(),{videoCompatibleFilters:l,activeFilters:o,selectedFilter:a,previewFilter:t,filterPresets:n,filterParams:r,hasActiveFilters:d,filtersByCategory:c,applyFilter:p,previewFilterEffect:f,updateFilterParams:h,removeFilter:v,reorderFilters:k,updateFilterIntensity:y,toggleFilter:w,clearAllFilters:g,saveFilterPreset:b,loadFilterPreset:R,deleteFilterPreset:V,getFilterSummary:x,setActiveFilters(_){var P;const A=[];for(const D of _){const z=m(D.filterId);if(!z){const M=Ql(D.filterId);A.push({...D,filterId:M,params:vi(D.params),intensity:hi(D.intensity)});continue}A.push({...D,filterId:z,params:vi(D.params),intensity:hi(D.intensity)})}o.value=A,i.value=((P=o.value[0])==null?void 0:P.id)??null,Object.keys(r).forEach(D=>delete r[D]),o.value[0]&&Object.assign(r,vi(o.value[0].params))}}}class xp{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 ua({source:"https://fonts.googleapis.com/css2?family=Inter:wght@400",family:"Inter",weight:"400"})),this.fonts.set("bold",new ua({source:"https://fonts.googleapis.com/css2?family=Inter:wght@700",family:"Inter",weight:"700"})),this.fonts.set("serif",new ua({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 ua({source:t,family:n,weight:i});this.fonts.set(a,r)}loadLocalFont(a,t,n="400"){const i=new ua({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 Uo(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=je.fromSeconds(a.startTime)),a.duration!==void 0){const r=a.startTime||0;t.stop=je.fromSeconds(r+a.duration)}return a.animation&&this.applyAnimation(t,a.animation,a),t}applyPosition(a,t){if(!t){a.position="center";return}if(typeof t!="string"){a.x=t.x,a.y=t.y;return}switch(t){case"center":a.position="center";break;case"top":a.x="50%",a.y="10%";break;case"bottom":a.x="50%",a.y="90%";break;case"left":a.x="10%",a.y="50%";break;case"right":a.x="90%",a.y="50%";break}}applyAnimation(a,t,n){if(!t)return;const i=n.startTime?Math.round(n.startTime*30):0,r=t.duration||1,l=Math.round(r*30),s=i+l,d=t.easing||"linear";switch(t.type){case"fade-in":a.alpha=new Ge([i,s],[0,1],{easing:d});break;case"fade-out":a.alpha=new Ge([i,s],[1,0],{easing:d});break;case"rotate":t.rotation&&(a.rotation=new Ge([i,s],[t.rotation.from,t.rotation.to],{easing:d}));break;case"scale":t.scale&&(a.scale=new Ge([i,s],[t.scale.from,t.scale.to],{easing:d}));break;case"slide":t.translate&&(a.translate={x:new Ge([i,s],[t.translate.fromX,t.translate.toX],{easing:d}),y:new Ge([i,s],[t.translate.fromY,t.translate.toY],{easing:d})});break;case"typewriter":a.alpha=new Ge([i,s],[0,1],{easing:"linear"});break;case"custom":t.rotation&&(a.rotation=new Ge([i,s],[t.rotation.from,t.rotation.to],{easing:d})),t.scale&&(a.scale=new Ge([i,s],[t.scale.from,t.scale.to],{easing:d})),t.translate&&(a.translate={x:new Ge([i,s],[t.translate.fromX,t.translate.toX],{easing:d}),y:new Ge([i,s],[t.translate.fromY,t.translate.toY],{easing:d})});break}}async updateTextOverlay(a,t){const n=this.textClips.get(a);if(!n)throw new Error(`Text overlay with id ${a} not found`);const i=this.overlayConfigs.get(a);if(!i)throw new Error(`Text overlay with id ${a} is missing config`);const r={...i,...t};n.set(this.buildTextClipConfig(r)),this.overlayConfigs.set(a,r)}async removeTextOverlay(a){const t=this.textClips.get(a);if(!t)throw new Error(`Text overlay with id ${a} not found`);const n=this.composition.tracks;for(const i of n){const r=i.clips.indexOf(t);if(r!==-1){i.clips.splice(r,1);break}}this.textClips.delete(a),this.overlayConfigs.delete(a)}getTextOverlays(){return new Map(this.textClips)}async clearAllTextOverlays(){const a=Array.from(this.textClips.keys());for(const t of a)await this.removeTextOverlay(t)}getOverlays(){return Array.from(this.overlayConfigs.entries()).map(([a,t])=>({id:a,config:{...t}}))}async addCaptions(a,t="classic",n){var d;const r={classic:Oi,cascade:ul,guinea:cl,solar:ml,spotlight:zi,whisper:ji}[t],l=await this.composition.createTrack("caption"),s=new ol({transcript:a});if(await l.add(s),await((d=l.generate)==null?void 0:d.call(l,r)),n&&l.clips.length>0){const c=l.clips[0];c==null||c.set(n)}}}class Np{constructor(a){this.audioLayers=new Map,this.audioSources=new Map,this.nextId=0,this.masterVolume=1,this.composition=a}async loadAudioSource(a,t){try{const n=await xn.from(a),i=t||`audio-source-${this.nextId++}`;return this.audioSources.set(i,n),n}catch(n){throw n instanceof Error?n:new Error("Failed to load audio source")}}async addBackgroundMusic(a){return this.addAudioTrack({...a,name:a.name||"Background Music"})}async addAudioTrack(a){const t=`audio-track-${this.nextId++}`,n=await this.resolveAudioSource(a.source),i=this.createAudioClipConfig(a,n),r=new _i(i);let l=this.findAudioTrack();l||(l=await this.composition.createTrack("audio")),await l.add(r);const s={id:t,name:a.name||`Audio Track ${this.audioLayers.size+1}`,clip:r,track:l,config:a};return this.audioLayers.set(t,s),t}async resolveAudioSource(a){try{if(a instanceof xn)return a;if(typeof a=="string"&&a.trim()!=="")return await xn.from(a);if(a instanceof File)return await xn.from(URL.createObjectURL(a));throw new Error("Invalid audio source")}catch(t){throw t instanceof Error?t:new Error("Failed to create audio source")}}createAudioClipConfig(a,t){const n={source:t,volume:(a.volume??1)*this.masterVolume};if(a.startTime!==void 0&&(n.start=je.fromSeconds(a.startTime)),a.duration!==void 0){const i=a.startTime||0;n.stop=je.fromSeconds(i+a.duration)}return(a.fadeIn||a.fadeOut)&&(n.volume=this.createVolumeKeyframes(a)),n}findAudioTrack(){return this.composition.tracks.find(a=>a.kind==="audio")}removeClipFromTrack(a,t){const n=a.clips.indexOf(t);n!==-1&&a.clips.splice(n,1)}createVolumeKeyframes(a){const t=(a.volume??1)*this.masterVolume,n=a.startTime?Math.round(a.startTime*30):0,i=a.duration,r=[],l=[];if(a.fadeIn){const s=Math.round(a.fadeIn*30);r.push(n,n+s),l.push(0,t)}else r.push(n),l.push(t);if(a.fadeOut&&i){const s=n+Math.round(i*30),d=Math.round(a.fadeOut*30);a.fadeIn||(r.push(s-d),l.push(t)),r.push(s),l.push(0)}return new Ge(r,l,{easing:"linear"})}async updateVolume(a,t){const n=this.audioLayers.get(a);if(!n)throw new Error(`Audio track with id ${a} not found`);const i=Math.max(0,Math.min(1,t));n.config.volume=i,n.clip.set({volume:this.resolveLayerVolume(n.config)})}async updateAudioTrack(a,t){const n=this.audioLayers.get(a);if(!n)throw new Error(`Audio track with id ${a} not found`);const i={...n.config,...t,source:t.source??n.config.source},r=await this.resolveAudioSource(i.source),l=new _i(this.createAudioClipConfig(i,r));this.removeClipFromTrack(n.track,n.clip),await n.track.add(l),n.clip=l,n.config=i,n.name=i.name||n.name}async applyFadeIn(a,t){const n=this.audioLayers.get(a);if(!n)throw new Error(`Audio track with id ${a} not found`);n.config.fadeIn=t,n.clip.set({volume:this.resolveLayerVolume(n.config)})}async applyFadeOut(a,t){const n=this.audioLayers.get(a);if(!n)throw new Error(`Audio track with id ${a} not found`);n.config.fadeOut=t,n.clip.set({volume:this.resolveLayerVolume(n.config)})}async removeAudioTrack(a){const t=this.audioLayers.get(a);if(!t)throw new Error(`Audio track with id ${a} not found`);this.removeClipFromTrack(t.track,t.clip),this.audioLayers.delete(a)}async muteTrack(a,t){const n=this.audioLayers.get(a);if(!n)throw new Error(`Audio track with id ${a} not found`);t?n.clip.set({volume:0}):n.clip.set({volume:this.resolveLayerVolume(n.config)})}setMasterVolume(a){this.masterVolume=Math.max(0,Math.min(1,a));for(const t of this.audioLayers.values())t.clip.set({volume:this.resolveLayerVolume(t.config)})}resolveLayerVolume(a){return a.fadeIn||a.fadeOut?this.createVolumeKeyframes(a):(a.volume??1)*this.masterVolume}getMasterVolume(){return this.masterVolume}getAudioLayers(){return Array.from(this.audioLayers.values())}getAudioLayer(a){return this.audioLayers.get(a)}async clearAllAudioTracks(){const a=Array.from(this.audioLayers.keys());for(const t of a)await this.removeAudioTrack(t)}async syncWithVideo(a,t){for(const n of this.audioLayers.values()){const i=n.config.startTime||0,r=n.config.duration||t-a;if(i+r>t){n.config.duration=t-i;const l=new _i(this.createAudioClipConfig(n.config,n.clip.source)),s=n.track.clips.indexOf(n.clip);s!==-1&&(n.track.clips[s]=l,n.clip=l)}}}exportConfiguration(){return Array.from(this.audioLayers.values()).map(a=>({id:a.id,name:a.name,config:{...a.config,source:a.config.source&&typeof a.config.source=="object"&&"type"in a.config.source?"[AudioSource]":a.config.source}}))}async importConfiguration(a){for(const{name:t,config:n}of a)await this.addAudioTrack({...n,name:t})}}function Vp(o,a){return function(){return o.apply(a,arguments)}}const{toString:xS}=Object.prototype,{getPrototypeOf:Vd}=Object,{iterator:yl,toStringTag:Tp}=Symbol,wl=(o=>a=>{const t=xS.call(a);return o[t]||(o[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),La=o=>(o=o.toLowerCase(),a=>wl(a)===o),kl=o=>a=>typeof a===o,{isArray:jo}=Array,Fi=kl("undefined");function Hi(o){return o!==null&&!Fi(o)&&o.constructor!==null&&!Fi(o.constructor)&&ya(o.constructor.isBuffer)&&o.constructor.isBuffer(o)}const Bp=La("ArrayBuffer");function NS(o){let a;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?a=ArrayBuffer.isView(o):a=o&&o.buffer&&Bp(o.buffer),a}const VS=kl("string"),ya=kl("function"),Ip=kl("number"),Zi=o=>o!==null&&typeof o=="object",TS=o=>o===!0||o===!1,Tr=o=>{if(wl(o)!=="object")return!1;const a=Vd(o);return(a===null||a===Object.prototype||Object.getPrototypeOf(a)===null)&&!(Tp in o)&&!(yl in o)},BS=o=>{if(!Zi(o)||Hi(o))return!1;try{return Object.keys(o).length===0&&Object.getPrototypeOf(o)===Object.prototype}catch{return!1}},IS=La("Date"),MS=La("File"),$S=La("Blob"),FS=La("FileList"),DS=o=>Zi(o)&&ya(o.pipe),AS=o=>{let a;return o&&(typeof FormData=="function"&&o instanceof FormData||ya(o.append)&&((a=wl(o))==="formdata"||a==="object"&&ya(o.toString)&&o.toString()==="[object FormData]"))},RS=La("URLSearchParams"),[LS,PS,US,OS]=["ReadableStream","Request","Response","Headers"].map(La),zS=o=>o.trim?o.trim():o.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Gi(o,a,{allOwnKeys:t=!1}={}){if(o===null||typeof o>"u")return;let n,i;if(typeof o!="object"&&(o=[o]),jo(o))for(n=0,i=o.length;n<i;n++)a.call(null,o[n],n,o);else{if(Hi(o))return;const r=t?Object.getOwnPropertyNames(o):Object.keys(o),l=r.length;let s;for(n=0;n<l;n++)s=r[n],a.call(null,o[s],s,o)}}function Mp(o,a){if(Hi(o))return null;a=a.toLowerCase();const t=Object.keys(o);let n=t.length,i;for(;n-- >0;)if(i=t[n],a===i.toLowerCase())return i;return null}const Kn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,$p=o=>!Fi(o)&&o!==Kn;function Ws(){const{caseless:o}=$p(this)&&this||{},a={},t=(n,i)=>{const r=o&&Mp(a,i)||i;Tr(a[r])&&Tr(n)?a[r]=Ws(a[r],n):Tr(n)?a[r]=Ws({},n):jo(n)?a[r]=n.slice():a[r]=n};for(let n=0,i=arguments.length;n<i;n++)arguments[n]&&Gi(arguments[n],t);return a}const jS=(o,a,t,{allOwnKeys:n}={})=>(Gi(a,(i,r)=>{t&&ya(i)?o[r]=Vp(i,t):o[r]=i},{allOwnKeys:n}),o),WS=o=>(o.charCodeAt(0)===65279&&(o=o.slice(1)),o),HS=(o,a,t,n)=>{o.prototype=Object.create(a.prototype,n),o.prototype.constructor=o,Object.defineProperty(o,"super",{value:a.prototype}),t&&Object.assign(o.prototype,t)},ZS=(o,a,t,n)=>{let i,r,l;const s={};if(a=a||{},o==null)return a;do{for(i=Object.getOwnPropertyNames(o),r=i.length;r-- >0;)l=i[r],(!n||n(l,o,a))&&!s[l]&&(a[l]=o[l],s[l]=!0);o=t!==!1&&Vd(o)}while(o&&(!t||t(o,a))&&o!==Object.prototype);return a},GS=(o,a,t)=>{o=String(o),(t===void 0||t>o.length)&&(t=o.length),t-=a.length;const n=o.indexOf(a,t);return n!==-1&&n===t},XS=o=>{if(!o)return null;if(jo(o))return o;let a=o.length;if(!Ip(a))return null;const t=new Array(a);for(;a-- >0;)t[a]=o[a];return t},KS=(o=>a=>o&&a instanceof o)(typeof Uint8Array<"u"&&Vd(Uint8Array)),JS=(o,a)=>{const n=(o&&o[yl]).call(o);let i;for(;(i=n.next())&&!i.done;){const r=i.value;a.call(o,r[0],r[1])}},qS=(o,a)=>{let t;const n=[];for(;(t=o.exec(a))!==null;)n.push(t);return n},YS=La("HTMLFormElement"),QS=o=>o.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,n,i){return n.toUpperCase()+i}),nu=(({hasOwnProperty:o})=>(a,t)=>o.call(a,t))(Object.prototype),eC=La("RegExp"),Fp=(o,a)=>{const t=Object.getOwnPropertyDescriptors(o),n={};Gi(t,(i,r)=>{let l;(l=a(i,r,o))!==!1&&(n[r]=l||i)}),Object.defineProperties(o,n)},tC=o=>{Fp(o,(a,t)=>{if(ya(o)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const n=o[t];if(ya(n)){if(a.enumerable=!1,"writable"in a){a.writable=!1;return}a.set||(a.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},aC=(o,a)=>{const t={},n=i=>{i.forEach(r=>{t[r]=!0})};return jo(o)?n(o):n(String(o).split(a)),t},nC=()=>{},oC=(o,a)=>o!=null&&Number.isFinite(o=+o)?o:a;function iC(o){return!!(o&&ya(o.append)&&o[Tp]==="FormData"&&o[yl])}const rC=o=>{const a=new Array(10),t=(n,i)=>{if(Zi(n)){if(a.indexOf(n)>=0)return;if(Hi(n))return n;if(!("toJSON"in n)){a[i]=n;const r=jo(n)?[]:{};return Gi(n,(l,s)=>{const d=t(l,i+1);!Fi(d)&&(r[s]=d)}),a[i]=void 0,r}}return n};return t(o,0)},lC=La("AsyncFunction"),sC=o=>o&&(Zi(o)||ya(o))&&ya(o.then)&&ya(o.catch),Dp=((o,a)=>o?setImmediate:a?((t,n)=>(Kn.addEventListener("message",({source:i,data:r})=>{i===Kn&&r===t&&n.length&&n.shift()()},!1),i=>{n.push(i),Kn.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",ya(Kn.postMessage)),dC=typeof queueMicrotask<"u"?queueMicrotask.bind(Kn):typeof process<"u"&&process.nextTick||Dp,cC=o=>o!=null&&ya(o[yl]),ve={isArray:jo,isArrayBuffer:Bp,isBuffer:Hi,isFormData:AS,isArrayBufferView:NS,isString:VS,isNumber:Ip,isBoolean:TS,isObject:Zi,isPlainObject:Tr,isEmptyObject:BS,isReadableStream:LS,isRequest:PS,isResponse:US,isHeaders:OS,isUndefined:Fi,isDate:IS,isFile:MS,isBlob:$S,isRegExp:eC,isFunction:ya,isStream:DS,isURLSearchParams:RS,isTypedArray:KS,isFileList:FS,forEach:Gi,merge:Ws,extend:jS,trim:zS,stripBOM:WS,inherits:HS,toFlatObject:ZS,kindOf:wl,kindOfTest:La,endsWith:GS,toArray:XS,forEachEntry:JS,matchAll:qS,isHTMLForm:YS,hasOwnProperty:nu,hasOwnProp:nu,reduceDescriptors:Fp,freezeMethods:tC,toObjectSet:aC,toCamelCase:QS,noop:nC,toFiniteNumber:oC,findKey:Mp,global:Kn,isContextDefined:$p,isSpecCompliantForm:iC,toJSONObject:rC,isAsyncFn:lC,isThenable:sC,setImmediate:Dp,asap:dC,isIterable:cC};function tt(o,a,t,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=o,this.name="AxiosError",a&&(this.code=a),t&&(this.config=t),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}ve.inherits(tt,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ve.toJSONObject(this.config),code:this.code,status:this.status}}});const Ap=tt.prototype,Rp={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(o=>{Rp[o]={value:o}});Object.defineProperties(tt,Rp);Object.defineProperty(Ap,"isAxiosError",{value:!0});tt.from=(o,a,t,n,i,r)=>{const l=Object.create(Ap);return ve.toFlatObject(o,l,function(d){return d!==Error.prototype},s=>s!=="isAxiosError"),tt.call(l,o.message,a,t,n,i),l.cause=o,l.name=o.name,r&&Object.assign(l,r),l};const uC=null;function Hs(o){return ve.isPlainObject(o)||ve.isArray(o)}function Lp(o){return ve.endsWith(o,"[]")?o.slice(0,-2):o}function ou(o,a,t){return o?o.concat(a).map(function(i,r){return i=Lp(i),!t&&r?"["+i+"]":i}).join(t?".":""):a}function mC(o){return ve.isArray(o)&&!o.some(Hs)}const pC=ve.toFlatObject(ve,{},null,function(a){return/^is[A-Z]/.test(a)});function _l(o,a,t){if(!ve.isObject(o))throw new TypeError("target must be an object");a=a||new FormData,t=ve.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(v,k){return!ve.isUndefined(k[v])});const n=t.metaTokens,i=t.visitor||u,r=t.dots,l=t.indexes,d=(t.Blob||typeof Blob<"u"&&Blob)&&ve.isSpecCompliantForm(a);if(!ve.isFunction(i))throw new TypeError("visitor must be a function");function c(h){if(h===null)return"";if(ve.isDate(h))return h.toISOString();if(ve.isBoolean(h))return h.toString();if(!d&&ve.isBlob(h))throw new tt("Blob is not supported. Use a Buffer instead.");return ve.isArrayBuffer(h)||ve.isTypedArray(h)?d&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,v,k){let y=h;if(h&&!k&&typeof h=="object"){if(ve.endsWith(v,"{}"))v=n?v:v.slice(0,-2),h=JSON.stringify(h);else if(ve.isArray(h)&&mC(h)||(ve.isFileList(h)||ve.endsWith(v,"[]"))&&(y=ve.toArray(h)))return v=Lp(v),y.forEach(function(g,b){!(ve.isUndefined(g)||g===null)&&a.append(l===!0?ou([v],b,r):l===null?v:v+"[]",c(g))}),!1}return Hs(h)?!0:(a.append(ou(k,v,r),c(h)),!1)}const m=[],p=Object.assign(pC,{defaultVisitor:u,convertValue:c,isVisitable:Hs});function f(h,v){if(!ve.isUndefined(h)){if(m.indexOf(h)!==-1)throw Error("Circular reference detected in "+v.join("."));m.push(h),ve.forEach(h,function(y,w){(!(ve.isUndefined(y)||y===null)&&i.call(a,y,ve.isString(w)?w.trim():w,v,p))===!0&&f(y,v?v.concat(w):[w])}),m.pop()}}if(!ve.isObject(o))throw new TypeError("data must be an object");return f(o),a}function iu(o){const a={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(o).replace(/[!'()~]|%20|%00/g,function(n){return a[n]})}function Td(o,a){this._pairs=[],o&&_l(o,this,a)}const Pp=Td.prototype;Pp.append=function(a,t){this._pairs.push([a,t])};Pp.toString=function(a){const t=a?function(n){return a.call(this,n,iu)}:iu;return this._pairs.map(function(i){return t(i[0])+"="+t(i[1])},"").join("&")};function fC(o){return encodeURIComponent(o).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Up(o,a,t){if(!a)return o;const n=t&&t.encode||fC;ve.isFunction(t)&&(t={serialize:t});const i=t&&t.serialize;let r;if(i?r=i(a,t):r=ve.isURLSearchParams(a)?a.toString():new Td(a,t).toString(n),r){const l=o.indexOf("#");l!==-1&&(o=o.slice(0,l)),o+=(o.indexOf("?")===-1?"?":"&")+r}return o}class ru{constructor(){this.handlers=[]}use(a,t,n){return this.handlers.push({fulfilled:a,rejected:t,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(a){this.handlers[a]&&(this.handlers[a]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(a){ve.forEach(this.handlers,function(n){n!==null&&a(n)})}}const Op={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},hC=typeof URLSearchParams<"u"?URLSearchParams:Td,vC=typeof FormData<"u"?FormData:null,gC=typeof Blob<"u"?Blob:null,bC={isBrowser:!0,classes:{URLSearchParams:hC,FormData:vC,Blob:gC},protocols:["http","https","file","blob","url","data"]},Bd=typeof window<"u"&&typeof document<"u",Zs=typeof navigator=="object"&&navigator||void 0,yC=Bd&&(!Zs||["ReactNative","NativeScript","NS"].indexOf(Zs.product)<0),wC=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",kC=Bd&&window.location.href||"http://localhost",_C=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Bd,hasStandardBrowserEnv:yC,hasStandardBrowserWebWorkerEnv:wC,navigator:Zs,origin:kC},Symbol.toStringTag,{value:"Module"})),ma={..._C,...bC};function EC(o,a){return _l(o,new ma.classes.URLSearchParams,{visitor:function(t,n,i,r){return ma.isNode&&ve.isBuffer(t)?(this.append(n,t.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)},...a})}function SC(o){return ve.matchAll(/\w+|\[(\w*)]/g,o).map(a=>a[0]==="[]"?"":a[1]||a[0])}function CC(o){const a={},t=Object.keys(o);let n;const i=t.length;let r;for(n=0;n<i;n++)r=t[n],a[r]=o[r];return a}function zp(o){function a(t,n,i,r){let l=t[r++];if(l==="__proto__")return!0;const s=Number.isFinite(+l),d=r>=t.length;return l=!l&&ve.isArray(i)?i.length:l,d?(ve.hasOwnProp(i,l)?i[l]=[i[l],n]:i[l]=n,!s):((!i[l]||!ve.isObject(i[l]))&&(i[l]=[]),a(t,n,i[l],r)&&ve.isArray(i[l])&&(i[l]=CC(i[l])),!s)}if(ve.isFormData(o)&&ve.isFunction(o.entries)){const t={};return ve.forEachEntry(o,(n,i)=>{a(SC(n),i,t,0)}),t}return null}function xC(o,a,t){if(ve.isString(o))try{return(a||JSON.parse)(o),ve.trim(o)}catch(n){if(n.name!=="SyntaxError")throw n}return(t||JSON.stringify)(o)}const Xi={transitional:Op,adapter:["xhr","http","fetch"],transformRequest:[function(a,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=ve.isObject(a);if(r&&ve.isHTMLForm(a)&&(a=new FormData(a)),ve.isFormData(a))return i?JSON.stringify(zp(a)):a;if(ve.isArrayBuffer(a)||ve.isBuffer(a)||ve.isStream(a)||ve.isFile(a)||ve.isBlob(a)||ve.isReadableStream(a))return a;if(ve.isArrayBufferView(a))return a.buffer;if(ve.isURLSearchParams(a))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),a.toString();let s;if(r){if(n.indexOf("application/x-www-form-urlencoded")>-1)return EC(a,this.formSerializer).toString();if((s=ve.isFileList(a))||n.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return _l(s?{"files[]":a}:a,d&&new d,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),xC(a)):a}],transformResponse:[function(a){const t=this.transitional||Xi.transitional,n=t&&t.forcedJSONParsing,i=this.responseType==="json";if(ve.isResponse(a)||ve.isReadableStream(a))return a;if(a&&ve.isString(a)&&(n&&!this.responseType||i)){const l=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(a)}catch(s){if(l)throw s.name==="SyntaxError"?tt.from(s,tt.ERR_BAD_RESPONSE,this,null,this.response):s}}return a}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ma.classes.FormData,Blob:ma.classes.Blob},validateStatus:function(a){return a>=200&&a<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ve.forEach(["delete","get","head","post","put","patch"],o=>{Xi.headers[o]={}});const NC=ve.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),VC=o=>{const a={};let t,n,i;return o&&o.split(`
345
- `).forEach(function(l){i=l.indexOf(":"),t=l.substring(0,i).trim().toLowerCase(),n=l.substring(i+1).trim(),!(!t||a[t]&&NC[t])&&(t==="set-cookie"?a[t]?a[t].push(n):a[t]=[n]:a[t]=a[t]?a[t]+", "+n:n)}),a},lu=Symbol("internals");function ii(o){return o&&String(o).trim().toLowerCase()}function Br(o){return o===!1||o==null?o:ve.isArray(o)?o.map(Br):String(o)}function TC(o){const a=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=t.exec(o);)a[n[1]]=n[2];return a}const BC=o=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(o.trim());function es(o,a,t,n,i){if(ve.isFunction(n))return n.call(this,a,t);if(i&&(a=t),!!ve.isString(a)){if(ve.isString(n))return a.indexOf(n)!==-1;if(ve.isRegExp(n))return n.test(a)}}function IC(o){return o.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(a,t,n)=>t.toUpperCase()+n)}function MC(o,a){const t=ve.toCamelCase(" "+a);["get","set","has"].forEach(n=>{Object.defineProperty(o,n+t,{value:function(i,r,l){return this[n].call(this,a,i,r,l)},configurable:!0})})}let wa=class{constructor(a){a&&this.set(a)}set(a,t,n){const i=this;function r(s,d,c){const u=ii(d);if(!u)throw new Error("header name must be a non-empty string");const m=ve.findKey(i,u);(!m||i[m]===void 0||c===!0||c===void 0&&i[m]!==!1)&&(i[m||d]=Br(s))}const l=(s,d)=>ve.forEach(s,(c,u)=>r(c,u,d));if(ve.isPlainObject(a)||a instanceof this.constructor)l(a,t);else if(ve.isString(a)&&(a=a.trim())&&!BC(a))l(VC(a),t);else if(ve.isObject(a)&&ve.isIterable(a)){let s={},d,c;for(const u of a){if(!ve.isArray(u))throw TypeError("Object iterator must return a key-value pair");s[c=u[0]]=(d=s[c])?ve.isArray(d)?[...d,u[1]]:[d,u[1]]:u[1]}l(s,t)}else a!=null&&r(t,a,n);return this}get(a,t){if(a=ii(a),a){const n=ve.findKey(this,a);if(n){const i=this[n];if(!t)return i;if(t===!0)return TC(i);if(ve.isFunction(t))return t.call(this,i,n);if(ve.isRegExp(t))return t.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(a,t){if(a=ii(a),a){const n=ve.findKey(this,a);return!!(n&&this[n]!==void 0&&(!t||es(this,this[n],n,t)))}return!1}delete(a,t){const n=this;let i=!1;function r(l){if(l=ii(l),l){const s=ve.findKey(n,l);s&&(!t||es(n,n[s],s,t))&&(delete n[s],i=!0)}}return ve.isArray(a)?a.forEach(r):r(a),i}clear(a){const t=Object.keys(this);let n=t.length,i=!1;for(;n--;){const r=t[n];(!a||es(this,this[r],r,a,!0))&&(delete this[r],i=!0)}return i}normalize(a){const t=this,n={};return ve.forEach(this,(i,r)=>{const l=ve.findKey(n,r);if(l){t[l]=Br(i),delete t[r];return}const s=a?IC(r):String(r).trim();s!==r&&delete t[r],t[s]=Br(i),n[s]=!0}),this}concat(...a){return this.constructor.concat(this,...a)}toJSON(a){const t=Object.create(null);return ve.forEach(this,(n,i)=>{n!=null&&n!==!1&&(t[i]=a&&ve.isArray(n)?n.join(", "):n)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([a,t])=>a+": "+t).join(`
346
- `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(a){return a instanceof this?a:new this(a)}static concat(a,...t){const n=new this(a);return t.forEach(i=>n.set(i)),n}static accessor(a){const n=(this[lu]=this[lu]={accessors:{}}).accessors,i=this.prototype;function r(l){const s=ii(l);n[s]||(MC(i,l),n[s]=!0)}return ve.isArray(a)?a.forEach(r):r(a),this}};wa.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);ve.reduceDescriptors(wa.prototype,({value:o},a)=>{let t=a[0].toUpperCase()+a.slice(1);return{get:()=>o,set(n){this[t]=n}}});ve.freezeMethods(wa);function ts(o,a){const t=this||Xi,n=a||t,i=wa.from(n.headers);let r=n.data;return ve.forEach(o,function(s){r=s.call(t,r,i.normalize(),a?a.status:void 0)}),i.normalize(),r}function jp(o){return!!(o&&o.__CANCEL__)}function Wo(o,a,t){tt.call(this,o??"canceled",tt.ERR_CANCELED,a,t),this.name="CanceledError"}ve.inherits(Wo,tt,{__CANCEL__:!0});function Wp(o,a,t){const n=t.config.validateStatus;!t.status||!n||n(t.status)?o(t):a(new tt("Request failed with status code "+t.status,[tt.ERR_BAD_REQUEST,tt.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function $C(o){const a=/^([-+\w]{1,25})(:?\/\/|:)/.exec(o);return a&&a[1]||""}function FC(o,a){o=o||10;const t=new Array(o),n=new Array(o);let i=0,r=0,l;return a=a!==void 0?a:1e3,function(d){const c=Date.now(),u=n[r];l||(l=c),t[i]=d,n[i]=c;let m=r,p=0;for(;m!==i;)p+=t[m++],m=m%o;if(i=(i+1)%o,i===r&&(r=(r+1)%o),c-l<a)return;const f=u&&c-u;return f?Math.round(p*1e3/f):void 0}}function DC(o,a){let t=0,n=1e3/a,i,r;const l=(c,u=Date.now())=>{t=u,i=null,r&&(clearTimeout(r),r=null),o(...c)};return[(...c)=>{const u=Date.now(),m=u-t;m>=n?l(c,u):(i=c,r||(r=setTimeout(()=>{r=null,l(i)},n-m)))},()=>i&&l(i)]}const Zr=(o,a,t=3)=>{let n=0;const i=FC(50,250);return DC(r=>{const l=r.loaded,s=r.lengthComputable?r.total:void 0,d=l-n,c=i(d),u=l<=s;n=l;const m={loaded:l,total:s,progress:s?l/s:void 0,bytes:d,rate:c||void 0,estimated:c&&s&&u?(s-l)/c:void 0,event:r,lengthComputable:s!=null,[a?"download":"upload"]:!0};o(m)},t)},su=(o,a)=>{const t=o!=null;return[n=>a[0]({lengthComputable:t,total:o,loaded:n}),a[1]]},du=o=>(...a)=>ve.asap(()=>o(...a)),AC=ma.hasStandardBrowserEnv?((o,a)=>t=>(t=new URL(t,ma.origin),o.protocol===t.protocol&&o.host===t.host&&(a||o.port===t.port)))(new URL(ma.origin),ma.navigator&&/(msie|trident)/i.test(ma.navigator.userAgent)):()=>!0,RC=ma.hasStandardBrowserEnv?{write(o,a,t,n,i,r){const l=[o+"="+encodeURIComponent(a)];ve.isNumber(t)&&l.push("expires="+new Date(t).toGMTString()),ve.isString(n)&&l.push("path="+n),ve.isString(i)&&l.push("domain="+i),r===!0&&l.push("secure"),document.cookie=l.join("; ")},read(o){const a=document.cookie.match(new RegExp("(^|;\\s*)("+o+")=([^;]*)"));return a?decodeURIComponent(a[3]):null},remove(o){this.write(o,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function LC(o){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(o)}function PC(o,a){return a?o.replace(/\/?\/$/,"")+"/"+a.replace(/^\/+/,""):o}function Hp(o,a,t){let n=!LC(a);return o&&(n||t==!1)?PC(o,a):a}const cu=o=>o instanceof wa?{...o}:o;function to(o,a){a=a||{};const t={};function n(c,u,m,p){return ve.isPlainObject(c)&&ve.isPlainObject(u)?ve.merge.call({caseless:p},c,u):ve.isPlainObject(u)?ve.merge({},u):ve.isArray(u)?u.slice():u}function i(c,u,m,p){if(ve.isUndefined(u)){if(!ve.isUndefined(c))return n(void 0,c,m,p)}else return n(c,u,m,p)}function r(c,u){if(!ve.isUndefined(u))return n(void 0,u)}function l(c,u){if(ve.isUndefined(u)){if(!ve.isUndefined(c))return n(void 0,c)}else return n(void 0,u)}function s(c,u,m){if(m in a)return n(c,u);if(m in o)return n(void 0,c)}const d={url:r,method:r,data:r,baseURL:l,transformRequest:l,transformResponse:l,paramsSerializer:l,timeout:l,timeoutMessage:l,withCredentials:l,withXSRFToken:l,adapter:l,responseType:l,xsrfCookieName:l,xsrfHeaderName:l,onUploadProgress:l,onDownloadProgress:l,decompress:l,maxContentLength:l,maxBodyLength:l,beforeRedirect:l,transport:l,httpAgent:l,httpsAgent:l,cancelToken:l,socketPath:l,responseEncoding:l,validateStatus:s,headers:(c,u,m)=>i(cu(c),cu(u),m,!0)};return ve.forEach(Object.keys({...o,...a}),function(u){const m=d[u]||i,p=m(o[u],a[u],u);ve.isUndefined(p)&&m!==s||(t[u]=p)}),t}const Zp=o=>{const a=to({},o);let{data:t,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:r,headers:l,auth:s}=a;a.headers=l=wa.from(l),a.url=Up(Hp(a.baseURL,a.url,a.allowAbsoluteUrls),o.params,o.paramsSerializer),s&&l.set("Authorization","Basic "+btoa((s.username||"")+":"+(s.password?unescape(encodeURIComponent(s.password)):"")));let d;if(ve.isFormData(t)){if(ma.hasStandardBrowserEnv||ma.hasStandardBrowserWebWorkerEnv)l.setContentType(void 0);else if((d=l.getContentType())!==!1){const[c,...u]=d?d.split(";").map(m=>m.trim()).filter(Boolean):[];l.setContentType([c||"multipart/form-data",...u].join("; "))}}if(ma.hasStandardBrowserEnv&&(n&&ve.isFunction(n)&&(n=n(a)),n||n!==!1&&AC(a.url))){const c=i&&r&&RC.read(r);c&&l.set(i,c)}return a},UC=typeof XMLHttpRequest<"u",OC=UC&&function(o){return new Promise(function(t,n){const i=Zp(o);let r=i.data;const l=wa.from(i.headers).normalize();let{responseType:s,onUploadProgress:d,onDownloadProgress:c}=i,u,m,p,f,h;function v(){f&&f(),h&&h(),i.cancelToken&&i.cancelToken.unsubscribe(u),i.signal&&i.signal.removeEventListener("abort",u)}let k=new XMLHttpRequest;k.open(i.method.toUpperCase(),i.url,!0),k.timeout=i.timeout;function y(){if(!k)return;const g=wa.from("getAllResponseHeaders"in k&&k.getAllResponseHeaders()),R={data:!s||s==="text"||s==="json"?k.responseText:k.response,status:k.status,statusText:k.statusText,headers:g,config:o,request:k};Wp(function(I){t(I),v()},function(I){n(I),v()},R),k=null}"onloadend"in k?k.onloadend=y:k.onreadystatechange=function(){!k||k.readyState!==4||k.status===0&&!(k.responseURL&&k.responseURL.indexOf("file:")===0)||setTimeout(y)},k.onabort=function(){k&&(n(new tt("Request aborted",tt.ECONNABORTED,o,k)),k=null)},k.onerror=function(){n(new tt("Network Error",tt.ERR_NETWORK,o,k)),k=null},k.ontimeout=function(){let b=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const R=i.transitional||Op;i.timeoutErrorMessage&&(b=i.timeoutErrorMessage),n(new tt(b,R.clarifyTimeoutError?tt.ETIMEDOUT:tt.ECONNABORTED,o,k)),k=null},r===void 0&&l.setContentType(null),"setRequestHeader"in k&&ve.forEach(l.toJSON(),function(b,R){k.setRequestHeader(R,b)}),ve.isUndefined(i.withCredentials)||(k.withCredentials=!!i.withCredentials),s&&s!=="json"&&(k.responseType=i.responseType),c&&([p,h]=Zr(c,!0),k.addEventListener("progress",p)),d&&k.upload&&([m,f]=Zr(d),k.upload.addEventListener("progress",m),k.upload.addEventListener("loadend",f)),(i.cancelToken||i.signal)&&(u=g=>{k&&(n(!g||g.type?new Wo(null,o,k):g),k.abort(),k=null)},i.cancelToken&&i.cancelToken.subscribe(u),i.signal&&(i.signal.aborted?u():i.signal.addEventListener("abort",u)));const w=$C(i.url);if(w&&ma.protocols.indexOf(w)===-1){n(new tt("Unsupported protocol "+w+":",tt.ERR_BAD_REQUEST,o));return}k.send(r||null)})},zC=(o,a)=>{const{length:t}=o=o?o.filter(Boolean):[];if(a||t){let n=new AbortController,i;const r=function(c){if(!i){i=!0,s();const u=c instanceof Error?c:this.reason;n.abort(u instanceof tt?u:new Wo(u instanceof Error?u.message:u))}};let l=a&&setTimeout(()=>{l=null,r(new tt(`timeout ${a} of ms exceeded`,tt.ETIMEDOUT))},a);const s=()=>{o&&(l&&clearTimeout(l),l=null,o.forEach(c=>{c.unsubscribe?c.unsubscribe(r):c.removeEventListener("abort",r)}),o=null)};o.forEach(c=>c.addEventListener("abort",r));const{signal:d}=n;return d.unsubscribe=()=>ve.asap(s),d}},jC=function*(o,a){let t=o.byteLength;if(t<a){yield o;return}let n=0,i;for(;n<t;)i=n+a,yield o.slice(n,i),n=i},WC=async function*(o,a){for await(const t of HC(o))yield*jC(t,a)},HC=async function*(o){if(o[Symbol.asyncIterator]){yield*o;return}const a=o.getReader();try{for(;;){const{done:t,value:n}=await a.read();if(t)break;yield n}}finally{await a.cancel()}},uu=(o,a,t,n)=>{const i=WC(o,a);let r=0,l,s=d=>{l||(l=!0,n&&n(d))};return new ReadableStream({async pull(d){try{const{done:c,value:u}=await i.next();if(c){s(),d.close();return}let m=u.byteLength;if(t){let p=r+=m;t(p)}d.enqueue(new Uint8Array(u))}catch(c){throw s(c),c}},cancel(d){return s(d),i.return()}},{highWaterMark:2})},El=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Gp=El&&typeof ReadableStream=="function",ZC=El&&(typeof TextEncoder=="function"?(o=>a=>o.encode(a))(new TextEncoder):async o=>new Uint8Array(await new Response(o).arrayBuffer())),Xp=(o,...a)=>{try{return!!o(...a)}catch{return!1}},GC=Gp&&Xp(()=>{let o=!1;const a=new Request(ma.origin,{body:new ReadableStream,method:"POST",get duplex(){return o=!0,"half"}}).headers.has("Content-Type");return o&&!a}),mu=64*1024,Gs=Gp&&Xp(()=>ve.isReadableStream(new Response("").body)),Gr={stream:Gs&&(o=>o.body)};El&&(o=>{["text","arrayBuffer","blob","formData","stream"].forEach(a=>{!Gr[a]&&(Gr[a]=ve.isFunction(o[a])?t=>t[a]():(t,n)=>{throw new tt(`Response type '${a}' is not supported`,tt.ERR_NOT_SUPPORT,n)})})})(new Response);const XC=async o=>{if(o==null)return 0;if(ve.isBlob(o))return o.size;if(ve.isSpecCompliantForm(o))return(await new Request(ma.origin,{method:"POST",body:o}).arrayBuffer()).byteLength;if(ve.isArrayBufferView(o)||ve.isArrayBuffer(o))return o.byteLength;if(ve.isURLSearchParams(o)&&(o=o+""),ve.isString(o))return(await ZC(o)).byteLength},KC=async(o,a)=>{const t=ve.toFiniteNumber(o.getContentLength());return t??XC(a)},JC=El&&(async o=>{let{url:a,method:t,data:n,signal:i,cancelToken:r,timeout:l,onDownloadProgress:s,onUploadProgress:d,responseType:c,headers:u,withCredentials:m="same-origin",fetchOptions:p}=Zp(o);c=c?(c+"").toLowerCase():"text";let f=zC([i,r&&r.toAbortSignal()],l),h;const v=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let k;try{if(d&&GC&&t!=="get"&&t!=="head"&&(k=await KC(u,n))!==0){let R=new Request(a,{method:"POST",body:n,duplex:"half"}),V;if(ve.isFormData(n)&&(V=R.headers.get("content-type"))&&u.setContentType(V),R.body){const[I,x]=su(k,Zr(du(d)));n=uu(R.body,mu,I,x)}}ve.isString(m)||(m=m?"include":"omit");const y="credentials"in Request.prototype;h=new Request(a,{...p,signal:f,method:t.toUpperCase(),headers:u.normalize().toJSON(),body:n,duplex:"half",credentials:y?m:void 0});let w=await fetch(h,p);const g=Gs&&(c==="stream"||c==="response");if(Gs&&(s||g&&v)){const R={};["status","statusText","headers"].forEach(T=>{R[T]=w[T]});const V=ve.toFiniteNumber(w.headers.get("content-length")),[I,x]=s&&su(V,Zr(du(s),!0))||[];w=new Response(uu(w.body,mu,I,()=>{x&&x(),v&&v()}),R)}c=c||"text";let b=await Gr[ve.findKey(Gr,c)||"text"](w,o);return!g&&v&&v(),await new Promise((R,V)=>{Wp(R,V,{data:b,headers:wa.from(w.headers),status:w.status,statusText:w.statusText,config:o,request:h})})}catch(y){throw v&&v(),y&&y.name==="TypeError"&&/Load failed|fetch/i.test(y.message)?Object.assign(new tt("Network Error",tt.ERR_NETWORK,o,h),{cause:y.cause||y}):tt.from(y,y&&y.code,o,h)}}),Xs={http:uC,xhr:OC,fetch:JC};ve.forEach(Xs,(o,a)=>{if(o){try{Object.defineProperty(o,"name",{value:a})}catch{}Object.defineProperty(o,"adapterName",{value:a})}});const pu=o=>`- ${o}`,qC=o=>ve.isFunction(o)||o===null||o===!1,Kp={getAdapter:o=>{o=ve.isArray(o)?o:[o];const{length:a}=o;let t,n;const i={};for(let r=0;r<a;r++){t=o[r];let l;if(n=t,!qC(t)&&(n=Xs[(l=String(t)).toLowerCase()],n===void 0))throw new tt(`Unknown adapter '${l}'`);if(n)break;i[l||"#"+r]=n}if(!n){const r=Object.entries(i).map(([s,d])=>`adapter ${s} `+(d===!1?"is not supported by the environment":"is not available in the build"));let l=a?r.length>1?`since :
347
- `+r.map(pu).join(`
348
- `):" "+pu(r[0]):"as no adapter specified";throw new tt("There is no suitable adapter to dispatch the request "+l,"ERR_NOT_SUPPORT")}return n},adapters:Xs};function as(o){if(o.cancelToken&&o.cancelToken.throwIfRequested(),o.signal&&o.signal.aborted)throw new Wo(null,o)}function fu(o){return as(o),o.headers=wa.from(o.headers),o.data=ts.call(o,o.transformRequest),["post","put","patch"].indexOf(o.method)!==-1&&o.headers.setContentType("application/x-www-form-urlencoded",!1),Kp.getAdapter(o.adapter||Xi.adapter)(o).then(function(n){return as(o),n.data=ts.call(o,o.transformResponse,n),n.headers=wa.from(n.headers),n},function(n){return jp(n)||(as(o),n&&n.response&&(n.response.data=ts.call(o,o.transformResponse,n.response),n.response.headers=wa.from(n.response.headers))),Promise.reject(n)})}const Jp="1.11.0",Sl={};["object","boolean","number","function","string","symbol"].forEach((o,a)=>{Sl[o]=function(n){return typeof n===o||"a"+(a<1?"n ":" ")+o}});const hu={};Sl.transitional=function(a,t,n){function i(r,l){return"[Axios v"+Jp+"] Transitional option '"+r+"'"+l+(n?". "+n:"")}return(r,l,s)=>{if(a===!1)throw new tt(i(l," has been removed"+(t?" in "+t:"")),tt.ERR_DEPRECATED);return t&&!hu[l]&&(hu[l]=!0),a?a(r,l,s):!0}};Sl.spelling=function(a){return(t,n)=>!0};function YC(o,a,t){if(typeof o!="object")throw new tt("options must be an object",tt.ERR_BAD_OPTION_VALUE);const n=Object.keys(o);let i=n.length;for(;i-- >0;){const r=n[i],l=a[r];if(l){const s=o[r],d=s===void 0||l(s,r,o);if(d!==!0)throw new tt("option "+r+" must be "+d,tt.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new tt("Unknown option "+r,tt.ERR_BAD_OPTION)}}const Ir={assertOptions:YC,validators:Sl},Xa=Ir.validators;let qn=class{constructor(a){this.defaults=a||{},this.interceptors={request:new ru,response:new ru}}async request(a,t){try{return await this._request(a,t)}catch(n){if(n instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const r=i.stack?i.stack.replace(/^.+\n/,""):"";try{n.stack?r&&!String(n.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(n.stack+=`
349
- `+r):n.stack=r}catch{}}throw n}}_request(a,t){typeof a=="string"?(t=t||{},t.url=a):t=a||{},t=to(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;n!==void 0&&Ir.assertOptions(n,{silentJSONParsing:Xa.transitional(Xa.boolean),forcedJSONParsing:Xa.transitional(Xa.boolean),clarifyTimeoutError:Xa.transitional(Xa.boolean)},!1),i!=null&&(ve.isFunction(i)?t.paramsSerializer={serialize:i}:Ir.assertOptions(i,{encode:Xa.function,serialize:Xa.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Ir.assertOptions(t,{baseUrl:Xa.spelling("baseURL"),withXsrfToken:Xa.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let l=r&&ve.merge(r.common,r[t.method]);r&&ve.forEach(["delete","get","head","post","put","patch","common"],h=>{delete r[h]}),t.headers=wa.concat(l,r);const s=[];let d=!0;this.interceptors.request.forEach(function(v){typeof v.runWhen=="function"&&v.runWhen(t)===!1||(d=d&&v.synchronous,s.unshift(v.fulfilled,v.rejected))});const c=[];this.interceptors.response.forEach(function(v){c.push(v.fulfilled,v.rejected)});let u,m=0,p;if(!d){const h=[fu.bind(this),void 0];for(h.unshift(...s),h.push(...c),p=h.length,u=Promise.resolve(t);m<p;)u=u.then(h[m++],h[m++]);return u}p=s.length;let f=t;for(m=0;m<p;){const h=s[m++],v=s[m++];try{f=h(f)}catch(k){v.call(this,k);break}}try{u=fu.call(this,f)}catch(h){return Promise.reject(h)}for(m=0,p=c.length;m<p;)u=u.then(c[m++],c[m++]);return u}getUri(a){a=to(this.defaults,a);const t=Hp(a.baseURL,a.url,a.allowAbsoluteUrls);return Up(t,a.params,a.paramsSerializer)}};ve.forEach(["delete","get","head","options"],function(a){qn.prototype[a]=function(t,n){return this.request(to(n||{},{method:a,url:t,data:(n||{}).data}))}});ve.forEach(["post","put","patch"],function(a){function t(n){return function(r,l,s){return this.request(to(s||{},{method:a,headers:n?{"Content-Type":"multipart/form-data"}:{},url:r,data:l}))}}qn.prototype[a]=t(),qn.prototype[a+"Form"]=t(!0)});let QC=class qp{constructor(a){if(typeof a!="function")throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(r){t=r});const n=this;this.promise.then(i=>{if(!n._listeners)return;let r=n._listeners.length;for(;r-- >0;)n._listeners[r](i);n._listeners=null}),this.promise.then=i=>{let r;const l=new Promise(s=>{n.subscribe(s),r=s}).then(i);return l.cancel=function(){n.unsubscribe(r)},l},a(function(r,l,s){n.reason||(n.reason=new Wo(r,l,s),t(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(a){if(this.reason){a(this.reason);return}this._listeners?this._listeners.push(a):this._listeners=[a]}unsubscribe(a){if(!this._listeners)return;const t=this._listeners.indexOf(a);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const a=new AbortController,t=n=>{a.abort(n)};return this.subscribe(t),a.signal.unsubscribe=()=>this.unsubscribe(t),a.signal}static source(){let a;return{token:new qp(function(i){a=i}),cancel:a}}};function ex(o){return function(t){return o.apply(null,t)}}function tx(o){return ve.isObject(o)&&o.isAxiosError===!0}const Ks={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(Ks).forEach(([o,a])=>{Ks[a]=o});function Yp(o){const a=new qn(o),t=Vp(qn.prototype.request,a);return ve.extend(t,qn.prototype,a,{allOwnKeys:!0}),ve.extend(t,a,null,{allOwnKeys:!0}),t.create=function(i){return Yp(to(o,i))},t}const Gt=Yp(Xi);Gt.Axios=qn;Gt.CanceledError=Wo;Gt.CancelToken=QC;Gt.isCancel=jp;Gt.VERSION=Jp;Gt.toFormData=_l;Gt.AxiosError=tt;Gt.Cancel=Gt.CanceledError;Gt.all=function(a){return Promise.all(a)};Gt.spread=ex;Gt.isAxiosError=tx;Gt.mergeConfig=to;Gt.AxiosHeaders=wa;Gt.formToJSON=o=>zp(ve.isHTMLForm(o)?new FormData(o):o);Gt.getAdapter=Kp.getAdapter;Gt.HttpStatusCode=Ks;Gt.default=Gt;const{Axios:EU,AxiosError:SU,CanceledError:CU,isCancel:xU,CancelToken:NU,VERSION:VU,all:TU,Cancel:BU,isAxiosError:IU,spread:MU,toFormData:$U,AxiosHeaders:FU,HttpStatusCode:DU,formToJSON:AU,getAdapter:RU,mergeConfig:LU}=Gt;class Cl{constructor(a="/api/v1"){this.eventSource=null,this.progressCallbacks=new Map,this.api=Gt.create({baseURL:a,headers:{"Content-Type":"application/json",Accept:"application/json"}}),this.api.interceptors.request.use(t=>{const n=this.getAuthToken();return n&&(t.headers.Authorization=`Bearer ${n}`),t}),this.api.interceptors.response.use(t=>t,t=>{var n;return(n=t.response)==null||n.status,Promise.reject(t)})}async createJob(a){try{const t=await this.api.post("/video/jobs",a);return this.normalizeJob(t.data.data)}catch(t){throw t}}async createRenderJob(a){try{const t=await this.api.post("/video/jobs/render",a);return this.normalizeJob(t.data.data)}catch(t){throw t}}async pollRenderJob(a,t,n=3e3,i=6e5){const r=Date.now();return new Promise((l,s)=>{const d=setInterval(async()=>{try{const c=await this.getJob(a);t==null||t(c.progress,c.status),c.status==="completed"?(clearInterval(d),l(c)):c.status==="failed"?(clearInterval(d),s(new Error(c.error_message??"Render job failed"))):c.status==="cancelled"?(clearInterval(d),s(new Error("Render job cancelled"))):Date.now()-r>i&&(clearInterval(d),s(new Error("Render job timed out")))}catch(c){clearInterval(d),s(c)}},n)})}async getJob(a){try{const t=await this.api.get(`/video/jobs/${a}`);return this.normalizeJob(t.data.data)}catch(t){throw t}}async listJobs(a){try{return(await this.api.get("/video/jobs",{params:a})).data}catch(t){throw t}}async cancelJob(a){try{const t=await this.api.delete(`/video/jobs/${a}`);return this.unsubscribeFromProgress(a),this.normalizeJob(t.data.data)}catch(t){throw t}}async retryJob(a){try{const t=await this.api.post(`/video/jobs/${a}/retry`);return this.normalizeJob(t.data.data)}catch(t){throw t}}subscribeToProgress(a,t){this.progressCallbacks.set(a,t),this.eventSource||this.initializeEventSource(),this.eventSource||this.pollProgress(a)}unsubscribeFromProgress(a){this.progressCallbacks.delete(a),this.progressCallbacks.size===0&&this.eventSource&&(this.eventSource.close(),this.eventSource=null)}initializeEventSource(){try{const a=this.getAuthToken(),t=`/api/v1/video/jobs/events${a?`?token=${a}`:""}`;this.eventSource=new EventSource(t),this.eventSource.addEventListener("progress",n=>{const i=JSON.parse(n.data),r=this.progressCallbacks.get(i.jobId);r&&r(i.progress)}),this.eventSource.addEventListener("complete",n=>{const i=JSON.parse(n.data),r=this.progressCallbacks.get(i.jobId);r&&(r(100),this.unsubscribeFromProgress(i.jobId))}),this.eventSource.addEventListener("error",n=>{this.progressCallbacks.forEach((i,r)=>{this.pollProgress(r)})})}catch{}}async pollProgress(a){const t=setInterval(async()=>{try{const n=await this.getJob(a),i=this.progressCallbacks.get(a);i&&i(n.progress),(n.status==="completed"||n.status==="failed"||n.status==="cancelled")&&(clearInterval(t),this.unsubscribeFromProgress(a))}catch{clearInterval(t)}},2e3)}getAuthToken(){const a=localStorage.getItem("auth_token");if(a)return a;const t=document.cookie.split(";");for(const n of t){const[i,r]=n.trim().split("=");if(i==="auth_token")return decodeURIComponent(r)}return null}async downloadVideo(a){try{return(await this.api.get(`/video/jobs/${a}/download`,{responseType:"blob"})).data}catch(t){throw t}}async getThumbnail(a,t=0){try{const n=await this.api.get(`/video/jobs/${a}/thumbnail`,{params:{time:t},responseType:"blob"});return URL.createObjectURL(n.data)}catch(n){throw n}}normalizeJob(a){const t=a,n={...t,user_id:t.user_id??t.userId??"",source_media_id:t.source_media_id??t.sourceMediaId??"",created_at:t.created_at??t.createdAt??"",updated_at:t.updated_at??t.updatedAt??""},i=t.output_media_id??t.outputMediaId;typeof i=="string"&&i!==""&&(n.output_media_id=i);const r=t.error_message??t.errorMessage;typeof r=="string"&&r!==""&&(n.error_message=r);const l=t.progress_message??t.progressMessage;typeof l=="string"&&l!==""&&(n.progress_message=l);const s=t.progress_detail??t.progressDetail;s&&typeof s=="object"&&(n.progress_detail=s);const d=t.started_at??t.startedAt;typeof d=="string"&&d!==""&&(n.started_at=d);const c=t.completed_at??t.completedAt;typeof c=="string"&&c!==""&&(n.completed_at=c);const u=t.cancelled_at??t.cancelledAt;return typeof u=="string"&&u!==""&&(n.cancelled_at=u),n}}new Cl;const ax={key:0,class:"mobile-layout"},nx={class:"mobile-toolbar"},ox={class:"mobile-toolbar-left"},ix=["aria-label"],rx={class:"mobile-toolbar-right"},lx=["disabled"],sx=["disabled"],dx={class:"preview-section"},cx={key:0,class:"mobile-export-overlay"},ux={class:"mobile-export-progress"},mx={class:"mobile-export-bar"},px={class:"mobile-timeline-zoom"},fx={class:"mobile-edit-strip"},hx={class:"mobile-selection-summary"},vx={class:"mobile-selection-title"},gx={class:"mobile-selection-meta"},bx={class:"mobile-readout-row"},yx=["disabled"],wx={class:"mobile-readout-grid"},kx={class:"mobile-readout-chip","data-testid":"mobile-playhead-readout"},_x={class:"mobile-readout-chip","data-testid":"mobile-clip-in-readout"},Ex={class:"mobile-readout-chip","data-testid":"mobile-clip-out-readout"},Sx={class:"mobile-readout-chip","data-testid":"mobile-duration-readout"},Cx=["disabled"],xx={class:"mobile-speed-strip"},Nx={class:"mobile-speed-chips"},Vx=["data-testid","onClick"],Tx={class:"mobile-edit-actions"},Bx=["disabled"],Ix=["disabled"],Mx=["disabled"],$x=["disabled"],Fx=["disabled"],Dx={class:"mobile-action-sheet-header"},Ax={class:"mobile-action-sheet-title"},Rx={class:"mobile-action-sheet-subtitle"},Lx={class:"mobile-action-sheet-actions"},Px=["disabled"],Ux=["disabled"],Ox=["disabled"],zx=["disabled"],jx=["disabled"],Wx={key:1,class:"desktop-layout"},Hx={class:"desktop-main-row"},Zx={class:"preview-panel"},Gx={class:"fit-toggle"},Xx={class:"editor-content"},Kx={class:"editor-tabs"},Jx={class:"tab-header"},qx=["onClick"],Yx={class:"tab-content-area"},Qx={class:"filter-controls"},eN={class:"text-controls"},tN={class:"transition-controls"},aN={class:"audio-controls"},nN={class:"adjustments-controls"},oN={key:1,class:"no-filter-selected"},iN={class:"export-controls"},rN={key:0,"data-testid":"video-export-status-completed"},lN={key:1,"data-testid":"video-export-status-message",class:"export-status-message"},sN={class:"desktop-timeline-row"},dN={class:"timeline-zoom"},cN=["value"],uN={class:"zoom-readout"},mN={key:0,class:"dev-editor-controls","data-testid":"video-editor-dev-controls"},pN={class:"dev-editor-row"},fN={class:"dev-editor-field"},hN={class:"dev-editor-field"},vN=["disabled"],gN=["disabled"],bN=["disabled"],yN={class:"dev-editor-row"},wN={class:"dev-editor-field dev-editor-field--wide"},kN=["value"],_N=["disabled"],EN=["disabled"],SN=["disabled"],CN=["disabled"],xN=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 N=n.media.uuid??n.media.id;return typeof N=="string"&&N.trim()!==""?N.trim():void 0}),l=e.computed(()=>{const N=typeof n.mediaUuid=="string"?n.mediaUuid.trim():"";return N!==""?N:r.value??`temp-${Date.now()}`}),s=e.ref(typeof window<"u"?window.innerWidth<768:!1),d=e.ref("filters"),c=e.ref("filters"),u=e.computed(()=>{const N=n.workflowMode==="uploader"?{filters:!0,adjustments:!0,text:!1,transitions:!1,audio:!1,export:!1}:{filters:!0,adjustments:!0,text:!0,transitions:!0,audio:!0,export:!0},L=n.featureFlags;return L?{filters:typeof L.filters=="boolean"?L.filters:N.filters,adjustments:typeof L.adjustments=="boolean"?L.adjustments:N.adjustments,text:typeof L.text=="boolean"?L.text:N.text,transitions:typeof L.transitions=="boolean"?L.transitions:N.transitions,audio:typeof L.audio=="boolean"?L.audio:N.audio,export:typeof L.export=="boolean"?L.export:N.export}:N}),m=e.computed(()=>s.value?d.value:c.value),p=e.computed(()=>m.value==="filters"||k.value),f=e.computed(()=>m.value!=="filters"&&!k.value),h=e.ref(null),v=e.ref(null),k=e.ref(!1),y=e.computed(()=>s.value?h.value:v.value);function w(N){return N==="contain"||N==="cover"||N==="none"}function g(N){if(!(N!=null&&N.metadata))return null;const L=N.metadata.fit_mode;return w(L)?L:null}const b=e.shallowRef(null),R=e.ref(null),V=e.ref(g(n.initialRecipe)??"contain"),I=e.ref(null),x=e.ref(null),T=e.ref(null),$=e.ref(!1),S=new Map,B=e.ref([]),_=e.ref([]),A=e.ref([]),P=e.ref([]),D=e.ref(1),z=()=>{s.value=window.innerWidth<768},M=[{id:"filters",label:"Filters",icon:Cn},{id:"adjustments",label:"Adjust",icon:hv},{id:"text",label:"Text",icon:"text-outline"},{id:"transitions",label:"Transitions",icon:"swap-horizontal-outline"},{id:"audio",label:"Audio",icon:"musical-notes-outline"},{id:"export",label:"Export",icon:Fo}],Z=[{id:"filters",label:"Filters"},{id:"adjustments",label:"Adjustments"},{id:"text",label:"Text"},{id:"transitions",label:"Transitions"},{id:"audio",label:"Audio"},{id:"export",label:"Export"}],O=e.computed(()=>M.filter(N=>u.value[N.id])),K=e.computed(()=>Z.filter(N=>u.value[N.id])),de=e.computed(()=>{var N,L;return((N=K.value[0])==null?void 0:N.id)??((L=O.value[0])==null?void 0:L.id)??"filters"});e.watch(u,N=>{N[d.value]||(d.value=de.value),N[c.value]||(c.value=de.value)},{immediate:!0,deep:!0}),e.watch(de,N=>{u.value[d.value]||(d.value=N),u.value[c.value]||(c.value=N)},{immediate:!0}),e.watch(u,N=>{N.export||(d.value==="export"&&(d.value=de.value),c.value==="export"&&(c.value=de.value))},{immediate:!0,deep:!0});const Ne=e.computed(()=>typeof window>"u"?!1:window.__MEDIABLES_EDITOR_DEV__===!0),ce=um(),{currentFrame:le,playheadPosition:W,timelineClips:C,totalDuration:U,hasChanges:j,isPlaying:re,selectedClip:ue,zoomLevel:Xe,playbackSpeed:be,fps:Ee,handleTrim:ye,handleSplit:xe,handleClipSelect:Ce,splitAtPlayhead:Re,deleteSelectedClip:ze,duplicateSelectedClip:rt,setZoomLevel:at,moveClip:Dt,setFilters:ht,setTextOverlays:St,setAudioTracks:ut,saveDraft:lt,clearHasChanges:Ct,resetChanges:Se,generateRecipe:J,zoomIn:oe,zoomOut:De,fitToWindow:fe,togglePlayback:Ae,setPlaying:Ye,seekTo:st,frameForward:Bt,frameBackward:Vt,skipToStart:Lt,skipToEnd:Pt,setPlaybackSpeed:zt,updateSourceDuration:Ot,undo:jt,redo:oa,canUndo:Q,canRedo:ge}=_p(l.value,n.initialRecipe,n.media),{videoCompatibleFilters:me,activeFilters:se,selectedFilter:Ve,previewFilter:Pe,previewFilterEffect:et,applyFilter:gt,updateFilterParams:Tt,removeFilter:xt,clearAllFilters:_t,setActiveFilters:Xt}=Cp();function X(N){var ie,_e;const L=((ie=ue.value)==null?void 0:ie.id)??((_e=C.value[0])==null?void 0:_e.id);L&&($.value=!0,typeof N=="object"&&N.id?gt(N.id):typeof N=="string"&&gt(N),ht(se.value),b.value?b.value.setClipFilters(L,se.value):S.set(L,[...se.value]),Ce(L),$.value=!1,Za())}function we(){var L,ie;const N=((L=ue.value)==null?void 0:L.id)??((ie=C.value[0])==null?void 0:ie.id);N&&Ce(N)}function ne(N){const L=se.value.find(ie=>ie.filterId===N);L&&xt(L.id)}const Fe=e.computed(()=>me.value.map(L=>{var _e;const ie=[];if(L.controls&&L.controls.length>0)for(const Me of L.controls){const Be=Me.type;if(Be==="button"||Be==="text"||Be==="range")continue;const Ie={id:Me.property||Me.id,label:Me.label||Me.id,type:Be,default:Me.default??(Be==="toggle"?!1:Be==="color"?"#ffffff":0)};Be==="slider"&&(Ie.min=Me.min??0,Ie.max=Me.max??1,Ie.step=Me.step??.01),Be==="select"&&Me.options&&(Ie.options=Me.options),ie.push(Ie)}else if(L.paramRanges){const Me=Object.entries(L.paramRanges);for(const[Be,Ie]of Me){const Et=Be.replace(/[-_]/g," ").replace(/\b\w/g,Pn=>Pn.toUpperCase()),Sa=(_e=L.defaultParams)==null?void 0:_e[Be],Eo=(Ie.min+Ie.max)/2;ie.push({id:Be,label:Et,min:Ie.min,max:Ie.max,step:Ie.step??.01,default:typeof Sa=="number"?Sa:Eo})}}return{id:L.id,name:L.name,category:L.category,params:ie}})),It=e.ref("0.00"),At=e.ref("0.00"),Mt=e.ref("");e.watch(Fe,N=>{if(N.length===0){Mt.value="";return}N.some(ie=>ie.id===Mt.value)||(Mt.value=N[0].id)},{immediate:!0});const mt=e.ref(!1),pt=e.ref(0),Qt=e.ref(!1),yt=e.ref(null),Wt=e.ref(null);let _a=null,G=!1;const q=e.computed(()=>{const N=new Map;return se.value.forEach(L=>N.set(L.filterId,L)),N}),pe=e.computed(()=>{var N,L;return le.value?le.value:((N=n.media)==null?void 0:N.thumbnail_url)||((L=n.media)==null?void 0:L.url)}),he=e.ref("");e.watch(()=>{var N,L;return{file:(N=n.media)==null?void 0:N.file,url:(L=n.media)==null?void 0:L.url}},(N,L,ie)=>{var Me,Be;const _e=he.value;ie(()=>{_e&&_e.startsWith("blob:")&&URL.revokeObjectURL(_e)}),(Me=n.media)!=null&&Me.file?he.value=URL.createObjectURL(n.media.file):(Be=n.media)!=null&&Be.url?he.value=n.media.url:he.value=""},{immediate:!0}),e.onUnmounted(()=>{he.value&&he.value.startsWith("blob:")&&URL.revokeObjectURL(he.value)});const Te=e.computed(()=>he.value),He=Km({forcePixiPreview:k,getPreviewRef:()=>y.value,getSourceUrl:()=>he.value,setPlaying:Ye}),ot=e.computed(()=>{if(!n.media)return null;const{file:N,...L}=n.media;return{...L,url:he.value}}),Je=e.computed(()=>{var L;const N=(L=n.media)==null?void 0:L.url;return!!(N&&/^https?:/i.test(N))}),Ze=e.computed(()=>se.value),dt=e.computed(()=>W.value),ft=e.computed(()=>!!ue.value&&W.value>0),Qe=e.computed(()=>!!ue.value&&C.value.length>1),ea=e.computed(()=>!!ue.value),Ft=e.ref(!0),Pa=[.5,1,1.5,2],Fa=e.computed(()=>{const N=new Set([0,va.value]);for(const L of C.value)N.add(L.timelineStart),N.add(L.timelineEnd);return Array.from(N).filter(L=>Number.isFinite(L)).sort((L,ie)=>L-ie)}),co=e.computed(()=>Fa.value.some(N=>N<W.value-.001)),Da=e.computed(()=>Fa.value.some(N=>N>W.value+.001)),on=e.ref(!1),Ua=e.ref(null);function ha(N){if(!Number.isFinite(N)||N<0)return"0:00";const L=Math.floor(N/60),ie=Math.floor(N%60);return`${L}:${ie.toString().padStart(2,"0")}`}const In=e.computed(()=>{var ie;const N=ue.value??C.value[0];if(!N)return"No clip selected";const L=(ie=N.label)==null?void 0:ie.trim();return L&&L.length>0?L:`Clip ${N.id.slice(-4)}`}),uo=e.computed(()=>{const N=ue.value??C.value[0];if(!N)return"Tap a clip to start editing";const L=Math.max(0,N.timelineEnd-N.timelineStart);return`${ha(N.timelineStart)} - ${ha(N.timelineEnd)} • ${L.toFixed(1)}s`});function Mn(N){return!Number.isFinite(N)||N<0?"0.0s":N<60?`${N.toFixed(1)}s`:ha(N)}const mo=e.computed(()=>ha(W.value)),hn=e.computed(()=>{const N=ue.value??C.value[0];return N?ha(N.sourceIn):"0:00"}),Oa=e.computed(()=>{const N=ue.value??C.value[0];return N?ha(N.sourceOut):"0:00"}),Il=e.computed(()=>{const N=ue.value??C.value[0];return N?Mn(N.timelineEnd-N.timelineStart):"0.0s"}),Ho=e.computed(()=>Ua.value===null?ue.value??C.value[0]??null:C.value.find(N=>N.id===Ua.value)??null),Ml=e.computed(()=>{var ie;const N=Ho.value;if(!N)return"Clip actions";const L=(ie=N.label)==null?void 0:ie.trim();return L&&L.length>0?L:`Clip ${N.id.slice(-4)}`}),$l=e.computed(()=>{const N=Ho.value;return N?`${ha(N.timelineStart)} - ${ha(N.timelineEnd)} • ${Mn(N.timelineEnd-N.timelineStart)}`:"Choose an action"}),$n=e.ref(0),va=e.computed(()=>{try{const N=U.value??U;return N&&typeof N=="number"&&N>0?N:$n.value}catch{return $n.value}}),vn=e.ref(),Zo=e.ref(),Go=e.ref(),gn=e.ref(),po=e.ref(0),rn=e.ref(!1);let la=null,Ta=null;e.watch(va,N=>{var ie;if(rn.value||!N||N<=0)return;const L=po.value||((ie=vn.value)==null?void 0:ie.clientWidth)||0;L>0&&(rn.value=!0,fe(L))}),e.watch(po,N=>{if(rn.value||!N||N<=0)return;va.value>0&&(rn.value=!0,fe(N))}),e.watch(s,N=>{N||Wa()}),e.watch(()=>{var N;return(N=Ho.value)==null?void 0:N.id},N=>{on.value&&!N&&Wa()});function ln(N){return Number.isFinite(N)?N.toFixed(2):"0.00"}function Ki(N){const L=Number(N);return Number.isFinite(L)?L:null}function ia(N){N&&(It.value=ln(N.sourceIn),At.value=ln(N.sourceOut))}e.watch(()=>{var N,L,ie;return[(N=ue.value)==null?void 0:N.id,(L=ue.value)==null?void 0:L.sourceIn,(ie=ue.value)==null?void 0:ie.sourceOut]},()=>{ia(ue.value)},{immediate:!0});function bn(N){const L=ue.value;if(!L)return;const ie=1/30,_e=L.sourceMinIn??0,Me=L.sourceMaxOut??va.value,Be=L.sourceIn+(W.value-L.timelineStart);if(N==="start"){const Et=Math.max(_e,Math.min(Be,L.sourceOut-ie));It.value=ln(Et);return}const Ie=Math.max(L.sourceIn+ie,Math.min(Be,Me));At.value=ln(Ie)}function za(){const N=ue.value;if(!N)return;const L=Ki(It.value),ie=Ki(At.value);if(L===null||ie===null)return;const _e=1/30,Me=N.sourceMinIn??0,Be=N.sourceMaxOut??va.value,Ie=Math.max(Me,Math.min(L,Be-_e)),Et=Math.max(Ie+_e,Math.min(ie,Be));ye(N.id,"start",Ie),ye(N.id,"end",Et),It.value=ln(Ie),At.value=ln(Et),ue.value&&st(ue.value.timelineStart)}function Ut(){Mt.value.trim()!==""&&X(Mt.value)}function sn(){var N;_t(),ht(se.value),(N=ue.value)!=null&&N.id&&(b.value?b.value.setClipFilters(ue.value.id,se.value):S.set(ue.value.id,[...se.value])),Za()}function fo(N,L,ie){var Me,Be;const _e=se.value.find(Ie=>Ie.filterId===N);_e?(_e.params={..._e.params,[L]:ie},ht(se.value),b.value&&((Me=ue.value)!=null&&Me.id)?b.value.setClipFilters(ue.value.id,se.value):(Be=ue.value)!=null&&Be.id&&S.set(ue.value.id,[...se.value]),Za(),we()):Pe.value&&Pe.value.filterId===N&&(Pe.value.params={...Pe.value.params||{},[L]:ie})}function Fn(N){st(N)}function ja(N){!N||!Number.isFinite(N.timestamp)||st(N.timestamp)}function Xo(N){Ye(N)}function ho(N){!Number.isFinite(N)||N<=0||($n.value=N,Ot(N))}function Wa(){on.value=!1,Ua.value=null}function Ea(N){s.value&&(Ua.value=N,on.value=!0)}function Ko(N){var _e,Me,Be,Ie;const L=((_e=ue.value)==null?void 0:_e.id)??((Me=C.value[0])==null?void 0:Me.id)??null;Ce(N),(((Be=ue.value)==null?void 0:Be.id)??((Ie=C.value[0])==null?void 0:Ie.id)??null)!==L&&ce.selection()}function Ji(N){Ko(N),Ea(N)}function Dn(N){N&&ce.selection()}function vo(){Ft.value=!Ft.value,ce.selection()}function Ha(){const N=Fa.value.filter(ie=>ie<W.value-.001),L=N.length>0?N[N.length-1]:0;st(L)}function qi(){const N=Fa.value.find(L=>L>W.value+.001);st(N??va.value)}function go(){jt()}function bo(){oa()}function yn(){const N=C.value.length;Re(),C.value.length>N&&(ce.success(),Wa())}function Jo(N){const L=C.value.length;xe(N),C.value.length>L&&ce.success()}function An(){const N=C.value.length;rt(),C.value.length>N&&(ce.selection(),Wa())}function yo(){const N=C.value.length;ze(),C.value.length<N&&(ce.error(),Wa())}function Rn(N){const L=be.value;zt(N),be.value!==L&&ce.selection()}function wo(N){return N instanceof HTMLElement?N.closest('input, textarea, select, button, [contenteditable="true"]')!==null:!1}function wn(N){if(s.value||wo(N.target))return;const L=N.key.toLowerCase(),ie=N.metaKey||N.ctrlKey;if(N.code==="Space"){N.preventDefault(),Ae();return}if(!ie&&L==="s"){N.preventDefault(),yn();return}if(L==="arrowleft"){N.preventDefault(),Vt();return}if(L==="arrowright"){N.preventDefault(),Bt();return}if(L==="home"){N.preventDefault(),Lt();return}if(L==="end"){N.preventDefault(),Pt();return}if(!ie&&L==="["){N.preventDefault(),Ha();return}if(!ie&&L==="]"){N.preventDefault(),qi();return}if(ie&&L==="z"&&N.shiftKey){N.preventDefault(),bo();return}ie&&L==="z"&&(N.preventDefault(),go())}function Yi(){var L;const N=po.value||((L=vn.value)==null?void 0:L.clientWidth)||800;fe(N)}function qo(N){rn.value=!0,at(N)}function Gd(){rn.value=!0,oe()}function Xd(){rn.value=!0,De()}function ko(N){const L=N.target,ie=Number(L.value);qo(ie)}function Yo(N){const L=Math.min(600,Math.max(10,Xe.value+N));qo(L)}function Qo(){Ta==null||Ta(),Ta=null;const N=Go.value,L=gn.value;if(!s.value||!N||!L)return;const ie=()=>{Yo(-20)},_e=()=>{Yo(20)};N.addEventListener("click",ie),L.addEventListener("click",_e),Ta=()=>{N.removeEventListener("click",ie),L.removeEventListener("click",_e)}}e.watch([s,Go,gn],()=>{Qo()},{flush:"post"});function Qi(N){var L;b.value=N,(L=b.value)!=null&&L.composition&&(I.value=new xp(b.value.composition),x.value=new Ii(b.value.composition),T.value=new Np(b.value.composition));try{S.size&&(S.forEach((ie,_e)=>{b.value.setClipFilters(_e,ie)}),S.clear(),b.value.composition.computeFrame())}catch{}}function er(N){N!=null&&N.id&&et(N.id)}function tr(N){Tt(N),Za()}async function ar(N){if(!I.value)return;const L=await I.value.addTextOverlay(N);B.value.push({id:L,...N})}async function nr(N,L){if(!I.value)return;await I.value.updateTextOverlay(N,L);const ie=B.value.findIndex(_e=>_e.id===N);ie!==-1&&(B.value[ie]={...B.value[ie],...L})}async function E(N){I.value&&(await I.value.removeTextOverlay(N),B.value=B.value.filter(L=>L.id!==N))}async function F(N){if(!x.value||P.value.length<2)return;const[L,ie]=P.value,_e=await x.value.applyTransition(L,ie,N);_.value.push({id:_e,...N,name:N.type})}function ee(N){if(!x.value)return;const L=_.value[N];L&&(x.value.removeTransition(L.id),_.value.splice(N,1))}function ke(N){}async function Ue(N){if(!T.value)return;const L=await T.value.addAudioTrack(N);A.value.push({id:L,...N})}async function Oe(N,L){if(!T.value)return;const ie=A.value.findIndex(_e=>_e.id===N);ie!==-1&&(A.value[ie]={...A.value[ie],...L})}async function it(N){T.value&&(await T.value.removeAudioTrack(N),A.value=A.value.filter(L=>L.id!==N))}async function Nt(N,L){if(!T.value)return;await T.value.updateVolume(N,L);const ie=A.value.find(_e=>_e.id===N);ie&&(ie.volume=L)}async function Kt(N,L){if(!T.value)return;await T.value.muteTrack(N,L);const ie=A.value.find(_e=>_e.id===N);ie&&(ie.muted=L)}function pa(N){T.value&&(T.value.setMasterVolume(N),D.value=N)}function _o(N){i("thumbnail-selected",N)}function kn(){_a!==null&&(clearInterval(_a),_a=null)}function Zf(N,L){return L?{...N,output:{...N.output,format:L.format,quality:L.quality}}:N}function ei(N){var L;return N.metadata||(N.metadata={created_at:new Date().toISOString(),editor_version:"2.0.0"}),N.metadata.fit_mode=V.value,(L=n.media)!=null&&L.url&&/^https?:/i.test(n.media.url)?N.metadata.source_url=n.media.url:delete N.metadata.source_url,N}function Ht(N,L,ie){return Math.min(ie,Math.max(L,N))}function Fl(N,L){if(typeof N=="number"&&Number.isFinite(N))return N;if(typeof N=="string"){const ie=Number(N);if(Number.isFinite(ie))return ie}return L}function sa(N,L,ie){for(const _e of L)if(_e in N)return Fl(N[_e],ie);return ie}function Gf(N){const L=typeof N.params=="object"&&N.params!==null?N.params:{};switch(N.filterId.trim().toLowerCase()){case"brightness":return[{type:"brightness",value:Ht(sa(L,["value","brightness"],0),-1,1)}];case"contrast":return[{type:"contrast",value:Ht(sa(L,["value","contrast"],1),.1,3)}];case"saturation":return[{type:"saturation",value:Ht(sa(L,["value","saturation"],1),0,3)}];case"blur":case"gaussian-blur":case"kawase-blur":case"radial-blur":return[{type:"blur",value:Ht(sa(L,["value","blur","radius"],0),0,25)}];case"sharpen":return[{type:"sharpen",value:Ht(sa(L,["value","amount"],1),0,5)}];case"sepia":return[{type:"sepia",value:1}];case"grayscale":return[{type:"grayscale",value:1}];case"adjustment":{const _e=Ht(sa(L,["brightness"],1)-1,-1,1),Me=Ht(sa(L,["contrast"],1),.1,3),Be=Ht(sa(L,["saturation"],1),0,3);return[{type:"brightness",value:_e},{type:"contrast",value:Me},{type:"saturation",value:Be}]}default:return[]}}function Xf(N){const L=N.timeline[0],ie=Array.isArray(L==null?void 0:L.filters)?L.filters:[],_e=[];for(const Be of ie)if(_e.push(...Gf(Be)),_e.length>=12)break;const Me={...N,filters:_e.slice(0,12)};if(N.timeline.length===1&&L){const Be=Math.max(0,Fl(L.sourceIn,0)),Ie=Fl(L.sourceOut,Be);Ie>Be&&(Me.trim={start:Be,end:Ie})}return Me}async function Kd(N,L,ie){return He.renderRecipeWithPixi(N,L,ie)}async function Kf(N,L){var ti;kn(),G=!1,He.resetClientExport(),Wt.value=null,yt.value=null,Qt.value=!1,pt.value=0;const ie=ei(N??J()),_e=ac(ie),Me=Array.isArray(_e.filters)&&_e.filters.length>0,Be=Rl(_e);if(!(j.value||Me||Be))return Ct(),i("video-exported",null),null;const Et=_e.timeline[0],Sa=Et?Math.max(0,Et.sourceIn):0,Pn=((Et==null?void 0:Et.sourceOut)??((ti=_e.source)==null?void 0:ti.duration)??va.value)-Sa,Ul=n.serverRenderEndpoint!=null&&n.clientExportThreshold>0&&Pn>n.clientExportThreshold;if(Ul){mt.value=!0;try{return await Jf(_e),null}catch(da){const Ca=da instanceof Error?da.message:"Server render failed";throw yt.value=Ca,i("server-render-failed",Ca),da}finally{mt.value=!1}}if(n.maxDuration>0&&Pn>n.maxDuration&&!Ul){const da=`This video is too long for in-browser export (${Math.round(Pn)}s). Server rendering is not available. Try a shorter clip.`;return yt.value=da,i("video-exported",null),null}mt.value=!0;try{const da=await Kd(_e,L,Ca=>{G||(pt.value=Ca)});return G?(yt.value="Export canceled.",pt.value=0,i("video-exported",null),null):(Ct(),i("recipe-generated",_e),i("video-exported",da),pt.value=100,Qt.value=!0,da)}catch(da){if(G)return yt.value="Export canceled.",pt.value=0,i("video-exported",null),null;const Ca=da instanceof Error?da.message:"Local WebGL export failed.";throw yt.value=Ca,new Error(`Video export failed: ${Ca}`)}finally{mt.value=!1}}function or(){return new Cl(n.serverRenderEndpoint??"/api/v1")}async function Jf(N){const L=or();yt.value="Starting server render...",pt.value=0;const ie=await L.createRenderJob({source_media_uuid:l.value,recipe:N});Wt.value=ie.id,i("server-render-started",ie.id),i("export-started",ie.id),yt.value="Rendering on server...";const _e=await L.pollRenderJob(ie.id,(Be,Ie)=>{pt.value=Be,Ie==="processing"&&(yt.value=`Server rendering: ${Be}%`)},3e3,(n.maxDuration>0?n.maxDuration*3:1800)*1e3);pt.value=100,Qt.value=!0,yt.value="Server render complete!",Ct(),i("recipe-generated",N);const Me={id:_e.id};typeof _e.output_media_id=="string"&&_e.output_media_id!==""&&(Me.output_media_id=_e.output_media_id),i("server-render-completed",Me)}async function Jd(){if(!mt.value)return;G=!0,k.value=!1,He.cancelClientExport(),kn();const N=Wt.value;if(N)try{await or().cancelJob(N)}catch(L){const ie=L instanceof Error?L.message:"Failed to cancel export";yt.value=ie,mt.value=!1,Wt.value=null;return}mt.value=!1,pt.value=0,Qt.value=!1,Wt.value=null,yt.value="Export canceled."}async function qd(N){kn(),G=!1,He.resetClientExport(),Wt.value=null,yt.value=null,Qt.value=!1,mt.value=!0,pt.value=0;try{const L=ei(Zf(J(),N));i("recipe-generated",L);const ie=l.value.startsWith("temp-"),_e=L.timeline[0],Me=Array.isArray(_e==null?void 0:_e.filters)?_e.filters:[],Be=!0,Ie=typeof window<"u"&&window.MEDIABLES_ALLOW_SERVER_EXPORT_FALLBACK===1||typeof localStorage<"u"&&localStorage.getItem("mediables.export.allowServerFallback")==="1";if(Be)try{const Ca=await Kd(L,N,dh=>{G||(pt.value=dh)});if(G){yt.value="Export canceled.",mt.value=!1,pt.value=0;return}i("video-exported",Ca);const oc=URL.createObjectURL(Ca.file),Ol=document.createElement("a");Ol.href=oc,Ol.download=`edited-video-${Date.now()}.mp4`,Ol.click(),setTimeout(()=>URL.revokeObjectURL(oc),100),mt.value=!1,pt.value=100,Qt.value=!0;return}catch(Ca){if(G){yt.value="Export canceled.",mt.value=!1,pt.value=0;return}if(ie||!Ie)throw Ca;pt.value=0,yt.value="Local filter export failed, falling back to server render."}const Et={"360p":"low","480p":"low","720p":"medium","1080p":"high","1440p":"ultra","2160p":"ultra"},Sa=(N==null?void 0:N.quality)??L.output.quality,Eo=Et[Sa]??"high",Pn={...Xf(L),export:{format:(N==null?void 0:N.format)??L.output.format,quality:Eo,resolution:Sa,framerate:L.output.fps}},ti=await or().createJob({source_media_id:l.value,recipe:Pn}),da=typeof ti.id=="string"?ti.id:null;if(!da)throw new Error("Export failed: missing job id");Wt.value=da,i("export-started",da),lh(da)}catch(L){if(k.value=!1,He.resetClientExport(),G){yt.value="Export canceled.",mt.value=!1,pt.value=0,Wt.value=null;return}try{const ie=ei(J()),_e=new Blob([JSON.stringify(ie,null,2)],{type:"application/json"}),Me=URL.createObjectURL(_e),Be=document.createElement("a");Be.href=Me,Be.download=`video-recipe-${Date.now()}.json`,Be.click(),setTimeout(()=>URL.revokeObjectURL(Me),100)}finally{mt.value=!1,pt.value=0,Wt.value=null,yt.value=L instanceof Error?L.message:"Export failed"}}}const Dl=async N=>{await new Promise(L=>{window.setTimeout(L,N)})},Al=N=>{if(!N||N.width<=0||N.height<=0)return null;try{return N.toDataURL("image/jpeg",.85)}catch{return null}},qf=N=>{if(!N||typeof N!="object")return null;const ie=N.pixiCanvas;if(ie&&typeof ie=="object"&&"value"in ie){const _e=ie.value;return _e instanceof HTMLCanvasElement?_e:null}return ie instanceof HTMLCanvasElement?ie:null},Yf=N=>{if(!N||typeof N!="object")return null;const L=N.duration;if(typeof L=="number"&&Number.isFinite(L))return L;if(L&&typeof L=="object"&&"value"in L){const ie=L.value;if(typeof ie=="number"&&Number.isFinite(ie))return ie}return null},Qf=N=>{if(!N||typeof N!="object")return null;const ie=N.videoElement;if(ie&&typeof ie=="object"&&"value"in ie){const _e=ie.value;return _e instanceof HTMLVideoElement?_e:null}return ie instanceof HTMLVideoElement?ie:null},Yd=N=>typeof N.params=="object"&&N.params!==null?N.params:{},eh=N=>{const L=[];for(const ie of N){const _e=Yd(ie),Me=ie.filterId.trim().toLowerCase();if(Me==="brightness"){const Ie=(Ht(sa(_e,["value","brightness"],0),-1,1)+1)*100;L.push(`brightness(${Ie.toFixed(2)}%)`);continue}if(Me==="contrast"){const Be=Ht(sa(_e,["value","contrast"],1),.1,4);L.push(`contrast(${(Be*100).toFixed(2)}%)`);continue}if(Me==="saturation"||Me==="saturate"){const Be=Ht(sa(_e,["value","saturation"],1),0,4);L.push(`saturate(${(Be*100).toFixed(2)}%)`);continue}if(Me==="grayscale"){L.push("grayscale(100%)");continue}if(Me==="sepia"){L.push("sepia(100%)");continue}if(Me==="blur"||Me==="gaussian-blur"||Me==="kawase-blur"){const Be=Ht(sa(_e,["value","blur","radius"],0),0,30);Be>.01&&L.push(`blur(${Be.toFixed(2)}px)`);continue}if(Me==="adjustment"){const Be=sa(_e,["brightness"],1),Ie=sa(_e,["contrast"],1),Et=sa(_e,["saturation"],1);Math.abs(Be-1)>.01&&L.push(`brightness(${(Ht(Be,0,5)*100).toFixed(2)}%)`),Math.abs(Ie-1)>.01&&L.push(`contrast(${(Ht(Ie,.1,5)*100).toFixed(2)}%)`),Math.abs(Et-1)>.01&&L.push(`saturate(${(Ht(Et,0,5)*100).toFixed(2)}%)`);continue}if(Me==="cinematic"){L.push("contrast(120%) brightness(95%) saturate(85%)");continue}if(Me==="dramatic"){L.push("contrast(140%) brightness(90%) saturate(110%) sepia(10%)");continue}if(Me==="dreamy"){L.push("blur(0.5px) brightness(105%) saturate(90%) contrast(95%)");continue}}return L.join(" ")},th=N=>{const L=N.find(Me=>Me.filterId.trim().toLowerCase()==="noise");if(!L)return 0;const ie=Yd(L),_e=sa(ie,["noise","value","amount","intensity"],.2);return _e<=1?Ht(_e,0,1):Ht(_e/100,0,1)},ah=(N,L,ie,_e)=>{if(_e<=0)return;const Me=N.getImageData(0,0,L,ie),Be=255*_e;for(let Ie=0;Ie<Me.data.length;Ie+=4){const Et=(Math.random()*2-1)*Be;Me.data[Ie]=Ht(Me.data[Ie]+Et,0,255),Me.data[Ie+1]=Ht(Me.data[Ie+1]+Et,0,255),Me.data[Ie+2]=Ht(Me.data[Ie+2]+Et,0,255)}N.putImageData(Me,0,0)},Qd=async N=>{N.readyState>=2&&N.videoWidth>0&&N.videoHeight>0||await new Promise(L=>{let ie=!1,_e=0;const Me=()=>{ie||(ie=!0,N.removeEventListener("loadedmetadata",Be),N.removeEventListener("loadeddata",Be),N.removeEventListener("canplay",Be),window.clearTimeout(_e),L())},Be=()=>{Me()};N.addEventListener("loadedmetadata",Be),N.addEventListener("loadeddata",Be),N.addEventListener("canplay",Be),_e=window.setTimeout(()=>Me(),800),N.play().catch(()=>{})})},nh=async(N,L)=>{await new Promise(ie=>{let _e=!1,Me=0;const Be=()=>{_e||(_e=!0,N.removeEventListener("seeked",Ie),window.clearTimeout(Me),ie())},Ie=()=>{Be()};if(Math.abs(N.currentTime-L)<.016){requestAnimationFrame(()=>Be());return}N.addEventListener("seeked",Ie),Me=window.setTimeout(()=>Be(),700),N.currentTime=L})},ec=async(N,L)=>{await Qd(N);const ie=Math.floor(N.videoWidth),_e=Math.floor(N.videoHeight);if(ie<=0||_e<=0)return null;const Me=Number.isFinite(N.duration)&&N.duration>0?N.duration:0,Be=Me>0?Ht(L,0,Me):0;await nh(N,Be);const Ie=document.createElement("canvas");Ie.width=ie,Ie.height=_e;const Et=Ie.getContext("2d");if(!Et)return null;const Sa=eh(se.value);Sa!==""&&(Et.filter=Sa);try{Et.drawImage(N,0,0,ie,_e)}catch{return null}const Eo=th(se.value);return ah(Et,ie,_e,Eo),Al(Ie)},oh=async(N,L)=>{const ie=document.createElement("video");ie.src=N,ie.muted=!0,ie.playsInline=!0,ie.preload="auto",N.startsWith("blob:")||(ie.crossOrigin="anonymous");try{return await Qd(ie),await ec(ie,L)}catch{return null}finally{ie.pause(),ie.removeAttribute("src"),ie.load()}},ih=async N=>{const L=y.value,ie=Al(qf(L));if(ie)return ie;if(L!=null&&L.captureFrameAt)for(let Be=0;Be<4;Be+=1){const Ie=Yf(L);if(Ie!==null&&Ie<=0&&Be<2){await Dl(80);continue}const Et=await Promise.race([L.captureFrameAt(N),Dl(450).then(()=>null)]),Sa=Al(Et);if(Sa)return Sa;await Dl(80)}const _e=Qf(L);if(_e){const Be=await ec(_e,N);if(Be)return Be}const Me=Te.value.trim();if(Me!==""){const Be=await oh(Me,N);if(Be)return Be}return null},tc=N=>N.map(L=>({...L,params:L.params&&typeof L.params=="object"?{...L.params}:L.params}));function ac(N){const L=tc(se.value);if(!Rl(N)&&L.length>0&&Array.isArray(N.timeline)&&N.timeline.length>0){const _e=N.timeline[0];_e&&(N.timeline=[{..._e,filters:L},...N.timeline.slice(1)])}return N}const Rl=N=>Array.isArray(N.timeline)?N.timeline.some(L=>Array.isArray(L.filters)&&L.filters.length>0):!1,rh=N=>{if(!N||typeof N!="object")return null;const L=N.posterFrame;if(typeof L!="string")return null;const ie=L.trim();return ie!==""?ie:null};async function Ll(){const N=ei(ac(lt())),L=tc(se.value),ie=Rl(N)||L.length>0,_e=rh(n.initialRecipe);if(ie){const Me=W.value>0?W.value:.1;try{const Be=await ih(Me);Be?N.posterFrame=Be:_e&&(N.posterFrame=_e)}catch{_e&&(N.posterFrame=_e)}}else delete N.posterFrame;return Ct(),i("draft-saved",N),N}function nc(){Se()&&(_t(),Za())}async function lh(N){kn();const L=or();_a=window.setInterval(async()=>{try{if(G){kn();return}const ie=await L.getJob(N),_e=Number(ie.progress??0);if(pt.value=Number.isFinite(_e)?_e:0,ie.status==="completed"||ie.status==="failed"||ie.status==="cancelled")if(kn(),mt.value=!1,Wt.value=null,ie.status==="completed")pt.value=100,Qt.value=!0,yt.value=null;else{const Me=ie.status==="cancelled"||typeof ie.error_message=="string"&&/cancel/i.test(ie.error_message);yt.value=Me?"Export canceled.":typeof ie.error_message=="string"&&ie.error_message.trim()!==""?ie.error_message:"Export failed"}}catch(ie){kn(),mt.value=!1,Wt.value=null,yt.value=ie instanceof Error?ie.message:"Failed to check export progress"}},2e3)}function Pl(){const N=ei(J());try{const L=N.timeline??[]}catch{}R.value=N}let Ln=null;function Za(){Ln&&clearTimeout(Ln),Ln=setTimeout(()=>{Pl(),Ln=null},200)}e.watch(()=>C.value,Za,{deep:!0}),e.watch(()=>ue.value,N=>{if($.value||!N)return;const L=(N==null?void 0:N.filters)??[];Xt(L)},{immediate:!0}),e.watch(()=>se.value,N=>{ht(N),Za()},{deep:!0}),e.watch(()=>B.value,N=>{St(N),Za()},{deep:!0}),e.watch(()=>A.value,N=>{const L=N.map(ie=>({...ie,source:typeof ie.source=="string"?ie.source:void 0}));ut(L),Za()},{deep:!0}),e.watch(()=>W.value,Za),a({saveDraft:Ll,exportForUpload:Kf}),Pl(),e.onUnmounted(()=>{kn(),G=!0,He.cancelClientExport(),Ln&&(clearTimeout(Ln),Ln=null),b.value&&(b.value.destroy(),b.value=null),I.value=null,x.value=null,T.value=null});function sh(){la||!Zo.value||(la=new F2({filters:Fe.value,callbacks:{onApplyFilter:N=>{X(N.id)},onRemoveFilter:N=>{ne(N)},onUpdateParam:(N,L,ie)=>{fo(N,L,ie)},onPreviewFilter:N=>{et(N.id)}}}),la.mount(Zo.value),la.setActiveFilters(q.value))}e.watch(q,N=>{la==null||la.setActiveFilters(N)},{deep:!0}),e.watch(Fe,N=>{la==null||la.setFilters(N)});let _n=null;return e.onMounted(()=>{window.addEventListener("resize",z),window.addEventListener("keydown",wn);const N=()=>{!vn.value||_n||(_n=new ResizeObserver(L=>{L[0]&&(po.value=Math.round(L[0].contentRect.width))}),_n.observe(vn.value))};N(),_n||e.nextTick(N),s.value&&(Qo(),Ta||e.nextTick(Qo)),n.media&&Pl(),s.value&&e.nextTick(()=>{sh()}),e.nextTick(()=>{const L=document.querySelector(".video-editor");L&&L.getBoundingClientRect();const ie=document.querySelector(".mobile-layout");ie&&ie.getBoundingClientRect()})}),e.onUnmounted(()=>{window.removeEventListener("resize",z),window.removeEventListener("keydown",wn),_n==null||_n.disconnect(),_n=null,Ta==null||Ta(),Ta=null,la==null||la.destroy(),la=null}),(N,L)=>{var ie,_e,Me,Be;return e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-editor",{mobile:s.value}])},[s.value?(e.openBlock(),e.createElementBlock("div",ax,[e.createElementVNode("div",nx,[e.createElementVNode("div",ox,[e.createElementVNode("button",{class:e.normalizeClass(["mobile-toolbar-btn",{active:e.unref(re)}]),onClick:L[0]||(L[0]=(...Ie)=>e.unref(Ae)&&e.unref(Ae)(...Ie)),"aria-label":e.unref(re)?"Pause":"Play","data-testid":"btn-mobile-play"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(re)?e.unref(ad):e.unref(nd)},null,8,["icon"])],10,ix),e.createElementVNode("button",{class:"mobile-toolbar-btn",onClick:nc,"aria-label":"Reset all changes","data-testid":"btn-mobile-reset"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(io)},null,8,["icon"])])]),e.createElementVNode("div",rx,[e.createElementVNode("button",{class:"mobile-toolbar-btn mobile-toolbar-save",onClick:Ll,"aria-label":"Save","data-testid":"btn-mobile-save",disabled:!e.unref(j)},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(el)},null,8,["icon"]),L[13]||(L[13]=e.createElementVNode("span",null,"Save",-1))],8,lx),e.createElementVNode("button",{class:"mobile-toolbar-btn",onClick:L[1]||(L[1]=Ie=>qd()),"aria-label":"Export","data-testid":"btn-mobile-export",disabled:mt.value||!e.unref(j)},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Fo)},null,8,["icon"])],8,sx),e.createElementVNode("button",{class:"mobile-toolbar-btn",onClick:L[2]||(L[2]=Ie=>i("close")),"aria-label":"Close","data-testid":"btn-mobile-close"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Yn)},null,8,["icon"])])])]),e.createElementVNode("div",dx,[e.withDirectives(e.createVNode(ps,{ref_key:"pixiPreviewMobileRef",ref:h,"aria-hidden":!p.value,class:"preview-host-child",source:Te.value,"fallback-duration":va.value,filters:Ze.value,playhead:dt.value,"is-playing":e.unref(re),"fit-mode":V.value,active:p.value,onPlayPause:e.unref(Ae),onFrameUpdate:ja,onDurationChange:ho},null,8,["aria-hidden","source","fallback-duration","filters","playhead","is-playing","fit-mode","active","onPlayPause"]),[[e.vShow,p.value]]),e.withDirectives(e.createVNode(Ts,{"aria-hidden":!f.value,class:"preview-host-child","media-uuid":l.value,recipe:R.value,media:ot.value,"enable-engine":f.value&&Je.value,"fit-mode":V.value,onTimeUpdate:Fn,onPlayStateChange:Xo,onDurationChange:ho,onEngineReady:Qi},null,8,["aria-hidden","media-uuid","recipe","media","enable-engine","fit-mode"]),[[e.vShow,f.value]]),mt.value?(e.openBlock(),e.createElementBlock("div",cx,[e.createElementVNode("div",ux,[e.createElementVNode("span",null,"Exporting "+e.toDisplayString(pt.value)+"%",1),e.createElementVNode("div",mx,[e.createElementVNode("div",{class:"mobile-export-bar-fill",style:e.normalizeStyle({width:pt.value+"%"})},null,4)]),e.createElementVNode("button",{class:"mobile-export-cancel",onClick:Jd},"Cancel")])])):e.createCommentVNode("",!0)]),e.createElementVNode("div",{ref_key:"timelineContainerRef",ref:vn,class:"timeline-section"},[e.createElementVNode("div",px,[e.createElementVNode("button",{ref_key:"mobileZoomOutButtonRef",ref:Go,type:"button",class:"mobile-zoom-btn","aria-label":"Zoom out timeline","data-testid":"btn-timeline-zoom-out"},[...L[14]||(L[14]=[e.createElementVNode("svg",{width:"16",height:"16",viewBox:"0 0 16 16"},[e.createElementVNode("path",{d:"M4 8h8",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round"})],-1)])],512),e.createElementVNode("button",{ref_key:"mobileZoomInButtonRef",ref:gn,type:"button",class:"mobile-zoom-btn","aria-label":"Zoom in timeline","data-testid":"btn-timeline-zoom-in"},[...L[15]||(L[15]=[e.createElementVNode("svg",{width:"16",height:"16",viewBox:"0 0 16 16"},[e.createElementVNode("path",{d:"M4 8h8M8 4v8",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round"})],-1)])],512)]),e.createVNode(Bs,{playhead:e.unref(W),clips:e.unref(C),"selected-clip-id":((ie=e.unref(ue))==null?void 0:ie.id)??((_e=e.unref(C)[0])==null?void 0:_e.id)??null,duration:va.value,fps:e.unref(Ee),"zoom-level":e.unref(Xe),"snap-enabled":Ft.value,sensitivity:.25,"is-mobile":!0,"onUpdate:playhead":e.unref(st),onTrim:e.unref(ye),onSplit:Jo,onClipSelect:Ko,onClipMove:e.unref(Dt),onClipLongPress:Ji,onSnapStateChange:Dn},null,8,["playhead","clips","selected-clip-id","duration","fps","zoom-level","snap-enabled","onUpdate:playhead","onTrim","onClipMove"])],512),e.createElementVNode("div",fx,[e.createElementVNode("div",hx,[e.createElementVNode("span",vx,e.toDisplayString(In.value),1),e.createElementVNode("span",gx,e.toDisplayString(uo.value),1)]),e.createElementVNode("div",bx,[e.createElementVNode("button",{type:"button",class:"mobile-cut-nav-btn","data-testid":"btn-mobile-prev-cut","aria-label":"Jump to previous cut",disabled:!co.value,onClick:Ha}," Prev Cut ",8,yx),e.createElementVNode("div",wx,[e.createElementVNode("span",kx,"Playhead "+e.toDisplayString(mo.value),1),e.createElementVNode("span",_x,"In "+e.toDisplayString(hn.value),1),e.createElementVNode("span",Ex,"Out "+e.toDisplayString(Oa.value),1),e.createElementVNode("span",Sx,"Duration "+e.toDisplayString(Il.value),1)]),e.createElementVNode("button",{type:"button",class:"mobile-cut-nav-btn","data-testid":"btn-mobile-next-cut","aria-label":"Jump to next cut",disabled:!Da.value,onClick:qi}," Next Cut ",8,Cx)]),e.createElementVNode("div",xx,[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["mobile-snap-toggle",{active:Ft.value}]),"data-testid":"btn-mobile-snap-toggle",onClick:vo},e.toDisplayString(Ft.value?"Snap On":"Snap Off"),3),e.createElementVNode("div",Nx,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(Pa,Ie=>e.createElementVNode("button",{key:Ie,type:"button",class:e.normalizeClass(["mobile-speed-chip",{active:e.unref(be)===Ie}]),"data-testid":`btn-mobile-speed-${String(Ie).replace(".","-")}`,onClick:Et=>Rn(Ie)},e.toDisplayString(Ie)+"x ",11,Vx)),64))])]),e.createElementVNode("div",Tx,[e.createElementVNode("button",{type:"button",class:"mobile-edit-btn","data-testid":"btn-mobile-undo","aria-label":"Undo",disabled:!e.unref(Q),onClick:go}," Undo ",8,Bx),e.createElementVNode("button",{type:"button",class:"mobile-edit-btn","data-testid":"btn-mobile-redo","aria-label":"Redo",disabled:!e.unref(ge),onClick:bo}," Redo ",8,Ix),e.createElementVNode("button",{type:"button",class:"mobile-edit-btn","data-testid":"btn-mobile-split","aria-label":"Split at playhead",disabled:!ft.value,onClick:yn}," Split ",8,Mx),e.createElementVNode("button",{type:"button",class:"mobile-edit-btn","data-testid":"btn-mobile-duplicate","aria-label":"Duplicate selected clip",disabled:!ea.value,onClick:An}," Duplicate ",8,$x),e.createElementVNode("button",{type:"button",class:"mobile-edit-btn mobile-edit-btn--danger","data-testid":"btn-mobile-delete","aria-label":"Delete selected clip",disabled:!Qe.value,onClick:yo}," Delete ",8,Fx)])]),e.createElementVNode("div",{ref_key:"mobileControlsRef",ref:Zo,class:"controls-section mobile-controls"},null,512),on.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"mobile-action-sheet-backdrop","data-testid":"video-mobile-action-sheet",onClick:Wa},[e.createElementVNode("div",{class:"mobile-action-sheet",onClick:L[3]||(L[3]=e.withModifiers(()=>{},["stop"]))},[L[16]||(L[16]=e.createElementVNode("div",{class:"mobile-action-sheet-handle"},null,-1)),e.createElementVNode("div",Dx,[e.createElementVNode("span",Ax,e.toDisplayString(Ml.value),1),e.createElementVNode("span",Rx,e.toDisplayString($l.value),1)]),e.createElementVNode("div",Lx,[e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-undo",disabled:!e.unref(Q),onClick:go},"Undo",8,Px),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-redo",disabled:!e.unref(ge),onClick:bo},"Redo",8,Ux),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-split",disabled:!ft.value,onClick:yn},"Split",8,Ox),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-duplicate",disabled:!ea.value,onClick:An},"Duplicate",8,zx),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn mobile-action-sheet-btn--danger","data-testid":"btn-mobile-sheet-delete",disabled:!Qe.value,onClick:yo},"Delete",8,jx),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-close",onClick:Wa},"Close")])])])):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("div",Wx,[e.createElementVNode("div",Hx,[e.createElementVNode("div",Zx,[e.createElementVNode("div",Gx,[e.createElementVNode("label",null,[e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":L[4]||(L[4]=Ie=>V.value=Ie),"aria-label":"Fit mode","data-testid":"select-video-fit-mode"},[...L[17]||(L[17]=[e.createElementVNode("option",{value:"contain"},"Contain",-1),e.createElementVNode("option",{value:"cover"},"Cover",-1),e.createElementVNode("option",{value:"none"},"None",-1)])],512),[[e.vModelSelect,V.value]])])]),e.withDirectives(e.createVNode(ps,{ref_key:"pixiPreviewDesktopRef",ref:v,"aria-hidden":!p.value,class:"preview-host-child",source:Te.value,"fallback-duration":va.value,filters:Ze.value,playhead:dt.value,"is-playing":e.unref(re),"fit-mode":V.value,active:p.value,onPlayPause:e.unref(Ae),onFrameUpdate:ja,onDurationChange:ho},null,8,["aria-hidden","source","fallback-duration","filters","playhead","is-playing","fit-mode","active","onPlayPause"]),[[e.vShow,p.value]]),e.withDirectives(e.createVNode(Ts,{"aria-hidden":!f.value,class:"preview-host-child","media-uuid":l.value,recipe:R.value,media:ot.value,"enable-engine":f.value&&Je.value,"fit-mode":V.value,onTimeUpdate:Fn,onPlayStateChange:Xo,onDurationChange:ho,onEngineReady:Qi},null,8,["aria-hidden","media-uuid","recipe","media","enable-engine","fit-mode"]),[[e.vShow,f.value]]),N.showThumbnailPicker?(e.openBlock(),e.createBlock(u_,{key:0,"media-uuid":l.value,duration:va.value,onSelect:_o},null,8,["media-uuid","duration"])):e.createCommentVNode("",!0)]),e.createElementVNode("div",Xx,[e.createElementVNode("div",Kx,[e.createElementVNode("div",Jx,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(K.value,Ie=>(e.openBlock(),e.createElementBlock("button",{key:Ie.id,class:e.normalizeClass(["tab-btn",{active:c.value===Ie.id}]),onClick:Et=>c.value=Ie.id},e.toDisplayString(Ie.label),11,qx))),128))]),e.createElementVNode("div",Yx,[e.withDirectives(e.createElementVNode("div",Qx,[e.createVNode(Ms,{filters:Fe.value,"active-filters":q.value,"thumbnail-url":pe.value,onApplyFilter:X,onRemoveFilter:ne,onUpdateParam:fo,onPreviewFilter:er},null,8,["filters","active-filters","thumbnail-url"])],512),[[e.vShow,c.value==="filters"]]),e.withDirectives(e.createElementVNode("div",eN,[e.createVNode(Ds,{overlays:B.value,onAddOverlay:ar,onUpdateOverlay:nr,onRemoveOverlay:E},null,8,["overlays"])],512),[[e.vShow,c.value==="text"]]),e.withDirectives(e.createElementVNode("div",tN,[e.createVNode(As,{"selected-clips":P.value,"applied-transitions":_.value,onApplyTransition:F,onRemoveTransition:ee,onPreviewTransition:ke},null,8,["selected-clips","applied-transitions"])],512),[[e.vShow,c.value==="transitions"]]),e.withDirectives(e.createElementVNode("div",aN,[e.createVNode(Rs,{"audio-layers":A.value,"master-volume":D.value,onAddTrack:Ue,onUpdateTrack:Oe,onRemoveTrack:it,onUpdateVolume:Nt,onToggleMute:Kt,onUpdateMasterVolume:pa},null,8,["audio-layers","master-volume"])],512),[[e.vShow,c.value==="audio"]]),e.withDirectives(e.createElementVNode("div",nN,[e.unref(Ve)?(e.openBlock(),e.createBlock($s,{key:0,filter:e.unref(Ve),"current-frame":e.unref(le),onUpdateParams:tr},null,8,["filter","current-frame"])):(e.openBlock(),e.createElementBlock("div",oN,[...L[18]||(L[18]=[e.createElementVNode("p",null,"Select a filter from the Filters tab to adjust its parameters",-1)])]))],512),[[e.vShow,c.value==="adjustments"]]),e.withDirectives(e.createElementVNode("div",iN,[e.createVNode(Fs,{"can-export":e.unref(j),"is-exporting":mt.value,"export-progress":pt.value,onExport:qd,onCancelExport:Jd,onSaveDraft:Ll,onReset:nc},null,8,["can-export","is-exporting","export-progress"]),Qt.value?(e.openBlock(),e.createElementBlock("div",rN," Export complete ")):e.createCommentVNode("",!0),yt.value&&!Qt.value?(e.openBlock(),e.createElementBlock("div",lN,e.toDisplayString(yt.value),1)):e.createCommentVNode("",!0)],512),[[e.vShow,c.value==="export"]])])])])]),e.createElementVNode("div",sN,[e.createElementVNode("div",{ref_key:"timelineContainerRef",ref:vn,class:"timeline-container"},[e.createElementVNode("div",dN,[e.createElementVNode("label",null,[L[19]||(L[19]=e.createTextVNode(" Zoom ",-1)),e.createElementVNode("input",{type:"range",min:"10",max:"600",value:e.unref(Xe),onInput:L[5]||(L[5]=Ie=>ko(Ie))},null,40,cN)]),e.createElementVNode("span",uN,e.toDisplayString(Math.round(e.unref(Xe)))+" px/s",1),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["desktop-snap-toggle",{active:Ft.value}]),"data-testid":"btn-desktop-snap-toggle",onClick:vo},e.toDisplayString(Ft.value?"Snap On":"Snap Off"),3)]),e.createVNode(Bs,{playhead:e.unref(W),clips:e.unref(C),"selected-clip-id":((Me=e.unref(ue))==null?void 0:Me.id)??((Be=e.unref(C)[0])==null?void 0:Be.id)??null,duration:va.value,fps:e.unref(Ee),"zoom-level":e.unref(Xe),"snap-enabled":Ft.value,sensitivity:.25,"onUpdate:playhead":e.unref(st),onTrim:e.unref(ye),onSplit:Jo,onClipSelect:Ko,onClipMove:e.unref(Dt),onClipLongPress:Ji,onSnapStateChange:Dn},null,8,["playhead","clips","selected-clip-id","duration","fps","zoom-level","snap-enabled","onUpdate:playhead","onTrim","onClipMove"]),e.createVNode(Is,{"selected-clip":e.unref(ue),"can-split":ft.value,"can-delete":Qe.value,"is-playing":e.unref(re),"zoom-level":e.unref(Xe),"playback-speed":e.unref(be),onSplit:yn,onDelete:yo,onDuplicate:An,onZoomIn:Gd,onZoomOut:Xd,onZoomChange:qo,onFitToWindow:Yi,onPlayPause:e.unref(Ae),onFrameForward:e.unref(Bt),onFrameBackward:e.unref(Vt),onSkipToStart:e.unref(Lt),onSkipToEnd:e.unref(Pt),onSpeedChange:e.unref(zt)},null,8,["selected-clip","can-split","can-delete","is-playing","zoom-level","playback-speed","onPlayPause","onFrameForward","onFrameBackward","onSkipToStart","onSkipToEnd","onSpeedChange"]),Ne.value?(e.openBlock(),e.createElementBlock("div",mN,[e.createElementVNode("div",pN,[e.createElementVNode("label",fN,[L[20]||(L[20]=e.createElementVNode("span",null,"Trim start (s)",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":L[6]||(L[6]=Ie=>It.value=Ie),type:"number",step:"0.01",min:"0",inputmode:"decimal","data-testid":"video-dev-trim-start"},null,512),[[e.vModelText,It.value]])]),e.createElementVNode("label",hN,[L[21]||(L[21]=e.createElementVNode("span",null,"Trim end (s)",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":L[7]||(L[7]=Ie=>At.value=Ie),type:"number",step:"0.01",min:"0",inputmode:"decimal","data-testid":"video-dev-trim-end"},null,512),[[e.vModelText,At.value]])]),e.createElementVNode("button",{class:"dev-editor-button",type:"button","data-testid":"video-dev-trim-start-playhead",disabled:!e.unref(ue),onClick:L[8]||(L[8]=Ie=>bn("start"))}," Start = Playhead ",8,vN),e.createElementVNode("button",{class:"dev-editor-button",type:"button","data-testid":"video-dev-trim-end-playhead",disabled:!e.unref(ue),onClick:L[9]||(L[9]=Ie=>bn("end"))}," End = Playhead ",8,gN),e.createElementVNode("button",{class:"dev-editor-button dev-editor-button--primary",type:"button","data-testid":"video-dev-apply-trim",disabled:!e.unref(ue),onClick:za}," Apply Trim ",8,bN)]),e.createElementVNode("div",yN,[e.createElementVNode("label",wN,[L[22]||(L[22]=e.createElementVNode("span",null,"Quick filter",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":L[10]||(L[10]=Ie=>Mt.value=Ie),"data-testid":"video-dev-filter-select"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Fe.value,Ie=>(e.openBlock(),e.createElementBlock("option",{key:Ie.id,value:Ie.id},e.toDisplayString(Ie.name),9,kN))),128))],512),[[e.vModelSelect,Mt.value]])]),e.createElementVNode("button",{class:"dev-editor-button dev-editor-button--primary",type:"button","data-testid":"video-dev-apply-filter",disabled:!e.unref(ue)||Mt.value==="",onClick:Ut}," Apply Filter ",8,_N),e.createElementVNode("button",{class:"dev-editor-button",type:"button","data-testid":"video-dev-clear-filters",disabled:e.unref(se).length===0,onClick:sn}," Clear Filters ",8,EN),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(ue),onClick:L[11]||(L[11]=Ie=>X("noise"))}," QA: Noise ",8,SN),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(ue),onClick:L[12]||(L[12]=Ie=>X("grayscale"))}," QA: Grayscale ",8,CN)])])):e.createCommentVNode("",!0)],512)])]))],2)}}}),Qp=$e(xN,[["__scopeId","data-v-1bb4247b"]]),NN={key:0,class:"video-editor-v2-toolbar"},VN={class:"video-editor-v2-body"},TN={key:0,class:"video-editor-v2-assets","data-testid":"v2-assets-panel"},BN={class:"video-editor-v2-main"},IN={class:"video-editor-v2-canvas"},MN={key:1,class:"video-editor-v2-timeline"},$N=["aria-expanded"],FN=["aria-hidden","inert"],DN="(max-width: 900px)",AN=e.defineComponent({__name:"SplitPanelLayout",setup(o,{expose:a}){const t=e.ref(!1),n=e.ref(!1);let i=null,r=null;const l=c=>{t.value=c,c&&(n.value=!1)},s=()=>{n.value=!0},d=()=>{n.value=!1};return e.onMounted(()=>{typeof window>"u"||!window.matchMedia||(i=window.matchMedia(DN),l(i.matches),r=c=>l(c.matches),i.addEventListener?i.addEventListener("change",r):"addListener"in i&&i.addListener(r))}),e.onBeforeUnmount(()=>{!i||!r||(i.removeEventListener?i.removeEventListener("change",r):"removeListener"in i&&i.removeListener(r),i=null,r=null)}),a({isMobile:t}),(c,u)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-editor-v2",{"is-mobile":t.value,"is-desktop":!t.value}]),"data-testid":"video-editor-v2-shell"},[c.$slots.toolbar?(e.openBlock(),e.createElementBlock("div",NN,[e.renderSlot(c.$slots,"toolbar",{},void 0,!0)])):e.createCommentVNode("",!0),e.createElementVNode("div",VN,[!t.value&&c.$slots.assets?(e.openBlock(),e.createElementBlock("aside",TN,[e.renderSlot(c.$slots,"assets",{},void 0,!0)])):e.createCommentVNode("",!0),e.createElementVNode("div",BN,[e.createElementVNode("div",IN,[e.renderSlot(c.$slots,"canvas",{},void 0,!0)])])]),c.$slots.timeline?(e.openBlock(),e.createElementBlock("div",MN,[e.renderSlot(c.$slots,"timeline",{isMobile:t.value},void 0,!0)])):e.createCommentVNode("",!0),!t.value&&c.$slots.inspector?(e.openBlock(),e.createElementBlock(e.Fragment,{key:2},[n.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("button",{key:0,class:"video-editor-v2-tools-tab",type:"button","data-testid":"v2-tools-drawer-open","aria-label":"Open editor tools","aria-controls":"v2-editor-tools-drawer","aria-expanded":n.value?"true":"false",onClick:s}," Tools ",8,$N)),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,FN)],64)):e.createCommentVNode("",!0),t.value?e.renderSlot(c.$slots,"drawer",{key:3},void 0,!0):e.createCommentVNode("",!0)],2))}}),RN=$e(AN,[["__scopeId","data-v-ed83bde0"]]),LN=["aria-selected"],PN={class:"asset-rail-item__main"},UN={class:"asset-rail-item__type","data-testid":"asset-rail-item-type"},ON={class:"asset-rail-item__label","data-testid":"asset-rail-item-label"},zN={key:0,class:"asset-rail-item__details","data-testid":"asset-rail-item-details"},jN={class:"asset-rail-item__actions","aria-label":"Asset actions"},WN=e.defineComponent({__name:"AssetRailItem",props:{source:{},selected:{type:Boolean}},emits:["add","replaceSelected","remove"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>t.source.label??t.source.name??t.source.filename??t.source.id),r=e.computed(()=>{if(typeof t.source.duration!="number"||!Number.isFinite(t.source.duration))return null;const c=Math.max(0,Math.round(t.source.duration)),u=Math.floor(c/60),m=c%60;return`${u}:${m.toString().padStart(2,"0")}`}),l=e.computed(()=>typeof t.source.width!="number"||typeof t.source.height!="number"||!Number.isFinite(t.source.width)||!Number.isFinite(t.source.height)?null:`${Math.round(t.source.width)}x${Math.round(t.source.height)}`),s=e.computed(()=>[r.value,l.value].filter(c=>c!==null)),d=c=>{if(c==="add"){n("add",t.source.id);return}if(c==="replaceSelected"){n("replaceSelected",t.source.id);return}n("remove",t.source.id)};return(c,u)=>(e.openBlock(),e.createElementBlock("article",{class:e.normalizeClass(["asset-rail-item",{"is-selected":c.selected}]),"aria-selected":c.selected?"true":"false","data-testid":"asset-rail-item"},[e.createElementVNode("div",PN,[e.createElementVNode("span",UN,e.toDisplayString(c.source.type),1),e.createElementVNode("span",ON,e.toDisplayString(i.value),1),s.value.length>0?(e.openBlock(),e.createElementBlock("span",zN,e.toDisplayString(s.value.join(" / ")),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",jN,[e.createElementVNode("button",{class:"asset-rail-item__action",type:"button",title:"Add to timeline","aria-label":"Add to timeline","data-testid":"asset-rail-item-add",onClick:u[0]||(u[0]=m=>d("add"))}," + "),e.createElementVNode("button",{class:"asset-rail-item__action",type:"button",title:"Replace selected","aria-label":"Replace selected","data-testid":"asset-rail-item-replace",onClick:u[1]||(u[1]=m=>d("replaceSelected"))}," R "),e.createElementVNode("button",{class:"asset-rail-item__action asset-rail-item__action--danger",type:"button",title:"Remove asset","aria-label":"Remove asset","data-testid":"asset-rail-item-remove",onClick:u[2]||(u[2]=m=>d("remove"))}," - ")])],10,LN))}}),HN=$e(WN,[["__scopeId","data-v-3ba2fd25"]]),ZN={class:"asset-rail__header"},GN={key:0,class:"asset-rail__list","data-testid":"asset-rail-list"},XN={key:1,class:"asset-rail__empty","data-testid":"asset-rail-empty"},KN=e.defineComponent({__name:"AssetRail",props:{sources:{},selectedSourceId:{},uploadsEnabled:{type:Boolean}},emits:["add","replaceSelected","remove","importFiles"],setup(o,{emit:a}){const t=a,n=e.ref(null),i=e.ref(!1),r=(m,p)=>{if(m==="add"){t("add",p);return}if(m==="replaceSelected"){t("replaceSelected",p);return}t("remove",p)},l=()=>{var m;(m=n.value)==null||m.click()},s=m=>{const p=m.target;if(!(p!=null&&p.files)||p.files.length===0)return;const f=Array.from(p.files);t("importFiles",f),p.value=""},d=m=>{m.preventDefault(),m.dataTransfer&&(m.dataTransfer.dropEffect="copy"),i.value=!0},c=()=>{i.value=!1},u=m=>{var f;m.preventDefault(),i.value=!1;const p=Array.from(((f=m.dataTransfer)==null?void 0:f.files)??[]);p.length!==0&&t("importFiles",p)};return(m,p)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["asset-rail",{"asset-rail--drag-over":i.value&&m.uploadsEnabled}]),"aria-label":"Assets","data-testid":"asset-rail",onDragover:d,onDragleave:c,onDrop:u},[e.createElementVNode("div",ZN,[p[3]||(p[3]=e.createElementVNode("h2",{class:"asset-rail__title"},"Assets",-1)),m.uploadsEnabled?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"asset-rail__upload","data-testid":"asset-rail-upload","aria-label":"Upload media files",onClick:l}," Upload ")):e.createCommentVNode("",!0),m.uploadsEnabled?(e.openBlock(),e.createElementBlock("input",{key:1,ref_key:"fileInput",ref:n,class:"asset-rail__file-input",type:"file",accept:"video/mp4,video/webm,video/quicktime,image/png,image/jpeg,image/webp,audio/mpeg,audio/aac,audio/wav",multiple:"","data-testid":"asset-rail-file-input",onChange:s},null,544)):e.createCommentVNode("",!0)]),m.sources.length>0?(e.openBlock(),e.createElementBlock("div",GN,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(m.sources,f=>(e.openBlock(),e.createBlock(HN,{key:f.id,source:f,selected:f.id===m.selectedSourceId,onAdd:p[0]||(p[0]=h=>r("add",h)),onReplaceSelected:p[1]||(p[1]=h=>r("replaceSelected",h)),onRemove:p[2]||(p[2]=h=>r("remove",h))},null,8,["source","selected"]))),128))])):(e.openBlock(),e.createElementBlock("p",XN,e.toDisplayString(m.uploadsEnabled?"Drop files here or click Upload to add media.":"No assets"),1))],34))}}),JN=$e(KN,[["__scopeId","data-v-3db665c6"]]),qN={class:"audio-mixer-panel__tracks","data-testid":"audio-mixer-tracks"},YN={key:0,class:"audio-mixer-panel__empty","data-testid":"audio-mixer-empty"},QN=["data-testid"],eV={class:"audio-mixer-strip__header"},tV={class:"audio-mixer-strip__identity"},aV={class:"audio-mixer-strip__kind"},nV=["data-testid"],oV=["data-testid"],iV=["data-testid"],rV={class:"audio-mixer-meter__rail","aria-hidden":"true"},lV={class:"audio-mixer-meter__value"},sV={class:"audio-mixer-strip__controls"},dV=["for"],cV=["id","min","max","value","data-testid","onInput"],uV={class:"audio-mixer-control__value"},mV={class:"audio-mixer-buttons"},pV=["aria-pressed","aria-label","data-testid","onClick"],fV=["aria-pressed","aria-label","data-testid","onClick"],hV=["for"],vV=["id","value","data-testid","onInput"],gV={class:"audio-mixer-control__value"},bV=["data-testid"],yV={key:0},wV={key:1},kV=["data-testid"],_V=["data-testid"],EV=["data-testid"],SV={class:"audio-mixer-routing__target"},CV={class:"audio-mixer-strip__header"},xV={class:"audio-mixer-strip__identity"},NV={class:"audio-mixer-strip__name","data-testid":"audio-mixer-master-name"},VV={class:"audio-mixer-meter__rail","aria-hidden":"true"},TV={class:"audio-mixer-meter__value"},BV={class:"audio-mixer-strip__controls"},IV={key:0,class:"audio-mixer-control audio-mixer-control--fader",for:"audio-mixer-master-fader"},MV=["min","max","value"],$V={class:"audio-mixer-control__value"},FV={class:"audio-mixer-buttons"},DV=["aria-pressed","aria-label"],AV={key:1,class:"audio-mixer-effects","data-testid":"audio-mixer-master-effects"},RV=["data-testid"],LV=e.defineComponent({__name:"AudioMixerPanel",props:{state:{},deviceClass:{}},emits:["update"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>pE(t.deviceClass,t.state.capabilities)),r=e.computed(()=>t.deviceClass==="desktop"),l=e.computed(()=>[...t.state.tracks].sort((D,z)=>D.order-z.order)),s=e.computed(()=>{const D=new Map(fE(l.value,t.state.master.muted).map(z=>[z.trackId,z]));return l.value.map(z=>({track:z,effectiveState:D.get(z.id)??null}))}),d=e.computed(()=>i.value.canAdjustTrackFaders),c=e.computed(()=>i.value.canAdjustMasterFader),u=e.computed(()=>i.value.canMuteTracks),m=e.computed(()=>r.value&&i.value.canSoloTracks),p=e.computed(()=>r.value&&i.value.canAdjustPan),f=e.computed(()=>i.value.canViewMeters&&i.value.meterMode!=="off"),h=e.computed(()=>r.value&&i.value.canEditEffectSlots&&i.value.maxEffectSlots>0),v=e.computed(()=>r.value&&i.value.canEditRouting),k=D=>{if(!(D.target instanceof HTMLInputElement))return null;const z=Number(D.target.value);return Number.isFinite(z)?z:null},y=(D,z)=>{if(!d.value)return;const M=k(z);M!==null&&n("update",{type:"track-fader-db",trackId:D.id,valueDb:$i(M)})},w=D=>{u.value&&n("update",{type:"track-mute",trackId:D.id,muted:!D.controls.muted})},g=D=>{m.value&&n("update",{type:"track-solo",trackId:D.id,solo:!D.controls.solo})},b=(D,z)=>{if(!p.value)return;const M=k(z);M!==null&&n("update",{type:"track-pan",trackId:D.id,pan:mp(M)})},R=D=>{if(!c.value)return;const z=k(D);z!==null&&n("update",{type:"master-fader-db",valueDb:$i(z)})},V=D=>{u.value&&n("update",{type:"master-mute",muted:!D.muted})},I=D=>{const z=Math.round(D*10)/10;return z>0?`+${z.toFixed(z%1===0?0:1)} dB`:`${z.toFixed(z%1===0?0:1)} dB`},x=D=>D===0?"C":`${D<0?"L":"R"} ${Math.round(Math.abs(D)*100)}`,T=D=>{if(D===void 0)return"";const z=Math.round(D*10)/10;return`${z.toFixed(z%1===0?0:1)}s`},$=D=>I(D),S=D=>{if(!Number.isFinite(D))return 0;const z=Math.min(Wr,Math.max(Vn,D)),M=Wr-Vn;return Math.round((z-Vn)/M*100)},B=D=>D.slice(0,i.value.maxEffectSlots),_=D=>h.value&&B(D).length>0,A=D=>D.timeline.fadeIn!==void 0||D.timeline.fadeOut!==void 0,P=D=>D===null?"Unknown":D.mutedByMaster?"Master muted":D.mutedByTrack?"Muted":D.mutedBySolo?"Muted by solo":D.soloed?"Solo active":"Audible";return(D,z)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["audio-mixer-panel",`audio-mixer-panel--${D.deviceClass}`]),"data-testid":"audio-mixer-panel","aria-label":"Audio mixer"},[e.createElementVNode("div",qN,[s.value.length===0?(e.openBlock(),e.createElementBlock("p",YN," No audio tracks ")):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(s.value,({track:M,effectiveState:Z})=>(e.openBlock(),e.createElementBlock("article",{key:M.id,class:e.normalizeClass(["audio-mixer-strip",{"is-muted":(Z==null?void 0:Z.effectivelyMuted)===!0,"is-soloed":M.controls.solo}]),"data-testid":`audio-mixer-track-${M.id}`},[e.createElementVNode("header",eV,[e.createElementVNode("div",tV,[e.createElementVNode("span",aV,e.toDisplayString(M.kind),1),e.createElementVNode("h3",{class:"audio-mixer-strip__name","data-testid":`audio-mixer-track-name-${M.id}`},e.toDisplayString(M.name),9,nV)]),e.createElementVNode("span",{class:e.normalizeClass(["audio-mixer-strip__status",{"is-active":(Z==null?void 0:Z.audible)===!0}]),"data-testid":`audio-mixer-track-status-${M.id}`},e.toDisplayString(P(Z)),11,oV)]),f.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:e.normalizeClass(["audio-mixer-meter",{"is-clipping":M.controls.meter.clipping}]),"data-testid":`audio-mixer-track-meter-${M.id}`,"aria-label":"Track meter"},[e.createElementVNode("span",rV,[e.createElementVNode("span",{class:"audio-mixer-meter__fill",style:e.normalizeStyle({width:`${S(M.controls.meter.peakDb)}%`})},null,4)]),e.createElementVNode("span",lV,e.toDisplayString($(M.controls.meter.peakDb)),1)],10,iV)):e.createCommentVNode("",!0),e.createElementVNode("div",sV,[d.value?(e.openBlock(),e.createElementBlock("label",{key:0,class:"audio-mixer-control audio-mixer-control--fader",for:`audio-mixer-track-fader-${M.id}`},[z[2]||(z[2]=e.createElementVNode("span",{class:"audio-mixer-control__label"},"Level",-1)),e.createElementVNode("input",{id:`audio-mixer-track-fader-${M.id}`,type:"range",class:"audio-mixer-control__range",min:M.controls.fader.minDb,max:M.controls.fader.maxDb,value:M.controls.fader.valueDb,step:"0.5","data-testid":`audio-mixer-track-fader-${M.id}`,onInput:O=>y(M,O)},null,40,cV),e.createElementVNode("span",uV,e.toDisplayString(I(M.controls.fader.valueDb)),1)],8,dV)):e.createCommentVNode("",!0),e.createElementVNode("div",mV,[u.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:e.normalizeClass(["audio-mixer-button",{"is-active":M.controls.muted}]),"aria-pressed":M.controls.muted?"true":"false","aria-label":M.controls.muted?`Unmute ${M.name}`:`Mute ${M.name}`,"data-testid":`audio-mixer-track-mute-${M.id}`,onClick:O=>w(M)}," M ",10,pV)):e.createCommentVNode("",!0),m.value?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button",class:e.normalizeClass(["audio-mixer-button audio-mixer-button--solo",{"is-active":M.controls.solo}]),"aria-pressed":M.controls.solo?"true":"false","aria-label":M.controls.solo?`Clear solo on ${M.name}`:`Solo ${M.name}`,"data-testid":`audio-mixer-track-solo-${M.id}`,onClick:O=>g(M)}," S ",10,fV)):e.createCommentVNode("",!0)])]),p.value?(e.openBlock(),e.createElementBlock("label",{key:1,class:"audio-mixer-control audio-mixer-control--pan",for:`audio-mixer-track-pan-${M.id}`},[z[3]||(z[3]=e.createElementVNode("span",{class:"audio-mixer-control__label"},"Pan",-1)),e.createElementVNode("input",{id:`audio-mixer-track-pan-${M.id}`,type:"range",class:"audio-mixer-control__range",min:"-1",max:"1",step:"0.01",value:M.controls.pan.value,"data-testid":`audio-mixer-track-pan-${M.id}`,onInput:O=>b(M,O)},null,40,vV),e.createElementVNode("span",gV,e.toDisplayString(x(M.controls.pan.value)),1)],8,hV)):e.createCommentVNode("",!0),A(M)?(e.openBlock(),e.createElementBlock("div",{key:2,class:"audio-mixer-strip__fades","data-testid":`audio-mixer-track-fades-${M.id}`},[M.timeline.fadeIn!==void 0?(e.openBlock(),e.createElementBlock("span",yV," In "+e.toDisplayString(T(M.timeline.fadeIn)),1)):e.createCommentVNode("",!0),M.timeline.fadeOut!==void 0?(e.openBlock(),e.createElementBlock("span",wV," Out "+e.toDisplayString(T(M.timeline.fadeOut)),1)):e.createCommentVNode("",!0)],8,bV)):e.createCommentVNode("",!0),_(M.effectSlots)?(e.openBlock(),e.createElementBlock("div",{key:3,class:"audio-mixer-effects","data-testid":`audio-mixer-track-effects-${M.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(B(M.effectSlots),O=>(e.openBlock(),e.createElementBlock("span",{key:O.id,class:e.normalizeClass(["audio-mixer-effect",{"is-empty":O.kind==="empty","is-bypassed":O.bypassed,"is-enabled":O.enabled&&!O.bypassed}]),"data-testid":`audio-mixer-track-effect-${M.id}-${O.index}`},e.toDisplayString(O.label),11,_V))),128))],8,kV)):e.createCommentVNode("",!0),v.value?(e.openBlock(),e.createElementBlock("div",{key:4,class:"audio-mixer-routing","data-testid":`audio-mixer-track-routing-${M.id}`},[z[5]||(z[5]=e.createElementVNode("span",{class:"audio-mixer-routing__label"},"Route",-1)),e.createElementVNode("span",SV,e.toDisplayString(D.state.master.name),1)],8,EV)):e.createCommentVNode("",!0)],10,QN))),128))]),e.createElementVNode("article",{class:e.normalizeClass(["audio-mixer-strip audio-mixer-strip--master",{"is-muted":D.state.master.muted}]),"data-testid":"audio-mixer-master-strip"},[e.createElementVNode("header",CV,[e.createElementVNode("div",xV,[z[6]||(z[6]=e.createElementVNode("span",{class:"audio-mixer-strip__kind"},"master",-1)),e.createElementVNode("h3",NV,e.toDisplayString(D.state.master.name),1)]),e.createElementVNode("span",{class:e.normalizeClass(["audio-mixer-strip__status",{"is-active":!D.state.master.muted}]),"data-testid":"audio-mixer-master-status"},e.toDisplayString(D.state.master.muted?"Muted":"Active"),3)]),f.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:e.normalizeClass(["audio-mixer-meter",{"is-clipping":D.state.master.meter.clipping}]),"data-testid":"audio-mixer-master-meter","aria-label":"Master meter"},[e.createElementVNode("span",VV,[e.createElementVNode("span",{class:"audio-mixer-meter__fill",style:e.normalizeStyle({width:`${S(D.state.master.meter.peakDb)}%`})},null,4)]),e.createElementVNode("span",TV,e.toDisplayString($(D.state.master.meter.peakDb)),1)],2)):e.createCommentVNode("",!0),e.createElementVNode("div",BV,[c.value?(e.openBlock(),e.createElementBlock("label",IV,[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:D.state.master.fader.minDb,max:D.state.master.fader.maxDb,value:D.state.master.fader.valueDb,step:"0.5","data-testid":"audio-mixer-master-fader",onInput:z[0]||(z[0]=M=>R(M))},null,40,MV),e.createElementVNode("span",$V,e.toDisplayString(I(D.state.master.fader.valueDb)),1)])):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":D.state.master.muted}]),"aria-pressed":D.state.master.muted?"true":"false","aria-label":D.state.master.muted?`Unmute ${D.state.master.name}`:`Mute ${D.state.master.name}`,"data-testid":"audio-mixer-master-mute",onClick:z[1]||(z[1]=M=>V(D.state.master))}," M ",10,DV)):e.createCommentVNode("",!0)])]),_(D.state.master.effectSlots)?(e.openBlock(),e.createElementBlock("div",AV,[z[8]||(z[8]=e.createElementVNode("span",{class:"audio-mixer-effects__label"},"FX",-1)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(B(D.state.master.effectSlots),M=>(e.openBlock(),e.createElementBlock("span",{key:M.id,class:e.normalizeClass(["audio-mixer-effect",{"is-empty":M.kind==="empty","is-bypassed":M.bypassed,"is-enabled":M.enabled&&!M.bypassed}]),"data-testid":`audio-mixer-master-effect-${M.index}`},e.toDisplayString(M.label),11,RV))),128))])):e.createCommentVNode("",!0)],2)],2))}}),vu=$e(LV,[["__scopeId","data-v-e5c785e8"]]),PV={class:"caption-srt-panel__header"},UV={class:"caption-srt-panel__title-group"},OV={class:"caption-srt-panel__title"},zV=["id"],jV={key:0,class:"caption-srt-panel__stats","data-testid":"caption-srt-desktop-stats"},WV={key:0,class:"caption-srt-panel__desktop-controls","data-testid":"caption-srt-desktop-controls"},HV={class:"caption-srt-panel__field"},ZV={class:"caption-srt-panel__field"},GV=["for"],XV=["id","aria-describedby","aria-invalid"],KV=["id"],JV=["id"],qV={key:3,class:"caption-srt-panel__cue-summary","data-testid":"caption-srt-cue-summary","aria-label":"Current caption cue summary"},YV={key:0,class:"caption-srt-panel__cue-list"},QV={class:"caption-srt-panel__cue-time"},eT={class:"caption-srt-panel__cue-text"},tT={key:1,class:"caption-srt-panel__empty"},aT=e.defineComponent({__name:"CaptionSrtPanel",props:{captionTrack:{default:null},segments:{default:null},layout:{default:"desktop"},trackId:{default:"caption-track-srt"},idPrefix:{default:"srt-cue"},panelId:{default:"caption-srt-panel"},title:{default:"Caption SRT"},textareaLabel:{default:"SRT caption text"}},emits:["import","update:captionTrack","update:segments","export","clear"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(""),r=e.ref(null),l=e.ref(null),s=e.ref(""),d=e.ref(""),c=e.ref(!1),u=e.computed(()=>t.layout==="mobile"),m=e.computed(()=>`${t.panelId}-textarea`),p=e.computed(()=>`${t.panelId}-helper`),f=e.computed(()=>`${t.panelId}-error`),h=e.computed(()=>`${t.panelId}-status`),v=e.computed(()=>{const _=[p.value,h.value];return r.value!==null&&_.push(f.value),_.join(" ")}),k=e.computed(()=>t.captionTrack!==null?t.captionTrack.segments:t.segments??[]),y=e.computed(()=>{try{return{text:Jc(k.value),errorMessage:null}}catch(_){return{text:"",errorMessage:$(_)}}}),w=e.computed(()=>k.value.length),g=e.computed(()=>k.value.reduce((_,A)=>Math.max(_,A.endTime),0)),b=e.computed(()=>k.value.slice(0,5));e.watch(()=>{var _,A;return[(_=t.captionTrack)==null?void 0:_.id,(A=t.captionTrack)==null?void 0:A.language,t.trackId]},([_,A,P])=>{s.value=_??P,d.value=A??""},{immediate:!0}),e.watch(y,_=>{if(_.errorMessage!==null){r.value=_.errorMessage;return}c.value||(i.value=_.text)},{immediate:!0});const R=()=>{c.value=!0,l.value=null,r.value!==null&&(r.value=null)},V=()=>{const _=i.value;if(r.value=null,l.value=null,_.trim()===""){r.value="Paste SRT text before importing captions.";return}try{const A=FE(_,{idPrefix:t.idPrefix}),P=JE(T(A)),D=Jc(P.segments);i.value=D,c.value=!1,l.value=`Imported ${S(P.segments.length)}.`,n("update:captionTrack",P),n("update:segments",P.segments),n("import",{track:P,segments:P.segments,sourceText:_})}catch(A){r.value=$(A)}},I=()=>{const _=y.value;if(r.value=_.errorMessage,_.errorMessage!==null){l.value=null;return}i.value=_.text,c.value=!1,l.value=_.text===""?"No captions to export.":`Exported ${S(w.value)}.`,n("export",_.text)},x=()=>{i.value="",c.value=!0,r.value=null,l.value="SRT text cleared.",n("clear")};function T(_){var D,z;const A={id:s.value.trim(),source:"srt-import",stylePreset:((D=t.captionTrack)==null?void 0:D.stylePreset)??"default",animation:((z=t.captionTrack)==null?void 0:z.animation)??"none",segments:_},P=d.value.trim();return P!==""&&(A.language=P),A}function $(_){return _ instanceof Tn||_ instanceof Error?_.message:"Unable to process SRT captions."}function S(_){return _===1?"1 cue":`${_} cues`}function B(_){const A=Math.floor(_/60),P=Math.floor(_%60);return`${A}:${P.toString().padStart(2,"0")}`}return(_,A)=>(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",PV,[e.createElementVNode("div",UV,[e.createElementVNode("h2",OV,e.toDisplayString(_.title),1),e.createElementVNode("p",{id:p.value,class:"caption-srt-panel__helper"}," Paste SRT, import it as captions, or export the current caption track. ",8,zV)]),u.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",jV,[e.createElementVNode("span",null,e.toDisplayString(S(w.value)),1),e.createElementVNode("span",null,e.toDisplayString(B(g.value)),1)]))]),u.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",WV,[e.createElementVNode("label",HV,[A[3]||(A[3]=e.createElementVNode("span",null,"Track ID",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":A[0]||(A[0]=P=>s.value=P),class:"caption-srt-panel__input",type:"text",autocomplete:"off","data-testid":"caption-srt-track-id"},null,512),[[e.vModelText,s.value]])]),e.createElementVNode("label",ZV,[A[4]||(A[4]=e.createElementVNode("span",null,"Language",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":A[1]||(A[1]=P=>d.value=P),class:"caption-srt-panel__input",type:"text",autocomplete:"off",placeholder:"en","data-testid":"caption-srt-language"},null,512),[[e.vModelText,d.value]])])])),e.createElementVNode("label",{class:"caption-srt-panel__textarea-label",for:m.value},e.toDisplayString(_.textareaLabel),9,GV),e.withDirectives(e.createElementVNode("textarea",{id:m.value,"onUpdate:modelValue":A[2]||(A[2]=P=>i.value=P),class:e.normalizeClass(["caption-srt-panel__textarea",{"has-error":r.value!==null}]),spellcheck:"false","aria-describedby":v.value,"aria-invalid":r.value!==null?"true":"false","data-testid":"caption-srt-textarea",onInput:R},null,42,XV),[[e.vModelText,i.value]]),r.value!==null?(e.openBlock(),e.createElementBlock("p",{key:1,id:f.value,class:"caption-srt-panel__error",role:"alert","data-testid":"caption-srt-error"},e.toDisplayString(r.value),9,KV)):(e.openBlock(),e.createElementBlock("p",{key:2,id:h.value,class:"caption-srt-panel__status","aria-live":"polite","data-testid":"caption-srt-status"},e.toDisplayString(l.value??"Ready for caption import or export."),9,JV)),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:V}," Import "),e.createElementVNode("button",{type:"button",class:"caption-srt-panel__button","data-testid":"caption-srt-export",onClick:I}," Export "),e.createElementVNode("button",{type:"button",class:"caption-srt-panel__button","data-testid":"caption-srt-clear",onClick:x}," Clear ")]),u.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",qV,[A[5]||(A[5]=e.createElementVNode("p",{class:"caption-srt-panel__cue-summary-title"},"Cue summary",-1)),b.value.length>0?(e.openBlock(),e.createElementBlock("ol",YV,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(b.value,P=>(e.openBlock(),e.createElementBlock("li",{key:P.id,class:"caption-srt-panel__cue"},[e.createElementVNode("span",QV,e.toDisplayString(B(P.startTime))+"-"+e.toDisplayString(B(P.endTime)),1),e.createElementVNode("span",eT,e.toDisplayString(P.text),1)]))),128))])):(e.openBlock(),e.createElementBlock("p",tT," No captions loaded. "))]))],2))}}),gu=$e(aT,[["__scopeId","data-v-1d5fdb3b"]]),nT=["aria-label"],oT={class:"draft-recovery-banner__header"},iT={class:"draft-recovery-banner__heading"},rT={class:"draft-recovery-banner__title"},lT={class:"draft-recovery-banner__summary","data-testid":"draft-recovery-summary"},sT={key:0,class:"draft-recovery-banner__list","data-testid":"draft-recovery-list"},dT={class:"draft-recovery-banner__record-copy"},cT={class:"draft-recovery-banner__record-title","data-testid":"draft-recovery-record-title"},uT={class:"draft-recovery-banner__record-meta"},mT={"data-testid":"draft-recovery-record-updated"},pT={"data-testid":"draft-recovery-record-reason"},fT={class:"draft-recovery-banner__actions"},hT=["onClick"],vT=["onClick"],gT={key:1,class:"draft-recovery-banner__mobile-prompt","data-testid":"draft-recovery-mobile-prompt"},bT={class:"draft-recovery-banner__record-copy"},yT={class:"draft-recovery-banner__record-title","data-testid":"draft-recovery-record-title"},wT={class:"draft-recovery-banner__record-meta"},kT={"data-testid":"draft-recovery-record-updated"},_T={"data-testid":"draft-recovery-record-reason"},ET={class:"draft-recovery-banner__actions draft-recovery-banner__actions--mobile"},ST={key:2,class:"draft-recovery-banner__empty","data-testid":"draft-recovery-empty"},CT=e.defineComponent({__name:"DraftRecoveryBanner",props:{records:{},surface:{},projectId:{},savedAt:{},maxAgeMs:{},now:{},maxDesktopItems:{default:3}},emits:["restore","dismiss"],setup(o,{emit:a}){const t=o,n=a,i={autosave:"Autosaved",manual:"Manual save","before-export":"Before export","before-close":"Before close"},r=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}),l=e.computed(()=>{const V={};return t.projectId!==void 0&&(V.projectId=t.projectId),t.savedAt!==void 0&&(V.savedAt=t.savedAt),t.maxAgeMs!==void 0&&(V.maxAgeMs=t.maxAgeMs),t.now!==void 0&&(V.now=t.now),V}),s=e.computed(()=>{const V=t.maxDesktopItems;return!Number.isFinite(V)||V<1?1:Math.floor(V)}),d=e.computed(()=>J2(t.records,t.surface,l.value)),c=e.computed(()=>t.surface==="mobile"?d.value:d.value.slice(0,s.value)),u=e.computed(()=>t.surface==="mobile"),m=e.computed(()=>c.value.length>0),p=e.computed(()=>u.value?c.value[0]??null:null),f=e.computed(()=>u.value?"Unsaved video draft":"Unsaved video drafts"),h=e.computed(()=>m.value?u.value?"A newer draft is available on this device.":`${c.value.length} recoverable draft${c.value.length===1?"":"s"} found.`:"No recoverable video drafts"),v=V=>{var I;return((I=V.snapshot.metadata.title)==null?void 0:I.trim())||"Untitled video draft"},k=V=>{const I=V.snapshot.metadata.saveReason;return I===void 0?"Saved draft":i[I]},y=V=>{const I=new Date(V.snapshot.metadata.updatedAt);return Number.isFinite(I.getTime())?r.format(I):"Updated time unavailable"},w=V=>{n("restore",V)},g=V=>{V.length!==0&&n("dismiss",V)},b=V=>{g([V])},R=()=>{g(c.value)};return(V,I)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["draft-recovery-banner",{"draft-recovery-banner--mobile":u.value,"draft-recovery-banner--empty":!m.value}]),"data-testid":"draft-recovery-banner","aria-live":"polite","aria-label":f.value},[e.createElementVNode("header",oT,[e.createElementVNode("div",iT,[I[2]||(I[2]=e.createElementVNode("p",{class:"draft-recovery-banner__eyebrow"},"Draft recovery",-1)),e.createElementVNode("h2",rT,e.toDisplayString(f.value),1),e.createElementVNode("p",lT,e.toDisplayString(h.value),1)]),!u.value&&c.value.length>1?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"draft-recovery-banner__ghost-action","data-testid":"draft-recovery-dismiss-all",onClick:R}," Dismiss all ")):e.createCommentVNode("",!0)]),!u.value&&m.value?(e.openBlock(),e.createElementBlock("ul",sT,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.value,x=>(e.openBlock(),e.createElementBlock("li",{key:x.key,class:"draft-recovery-banner__record","data-testid":"draft-recovery-record"},[e.createElementVNode("div",dT,[e.createElementVNode("h3",cT,e.toDisplayString(v(x)),1),e.createElementVNode("p",uT,[e.createElementVNode("span",mT,"Updated "+e.toDisplayString(y(x)),1),I[3]||(I[3]=e.createElementVNode("span",{"aria-hidden":"true"},"·",-1)),e.createElementVNode("span",pT,e.toDisplayString(k(x)),1)])]),e.createElementVNode("div",fT,[e.createElementVNode("button",{type:"button",class:"draft-recovery-banner__primary-action","data-testid":"draft-recovery-restore",onClick:T=>w(x)}," Restore ",8,hT),e.createElementVNode("button",{type:"button",class:"draft-recovery-banner__secondary-action","data-testid":"draft-recovery-dismiss",onClick:T=>b(x)}," Dismiss ",8,vT)])]))),128))])):p.value?(e.openBlock(),e.createElementBlock("article",gT,[e.createElementVNode("div",bT,[e.createElementVNode("h3",yT,e.toDisplayString(v(p.value)),1),e.createElementVNode("p",wT,[e.createElementVNode("span",kT,"Updated "+e.toDisplayString(y(p.value)),1),I[4]||(I[4]=e.createElementVNode("span",{"aria-hidden":"true"},"·",-1)),e.createElementVNode("span",_T,e.toDisplayString(k(p.value)),1)])]),e.createElementVNode("div",ET,[e.createElementVNode("button",{type:"button",class:"draft-recovery-banner__primary-action","data-testid":"draft-recovery-restore",onClick:I[0]||(I[0]=x=>w(p.value))}," Restore "),e.createElementVNode("button",{type:"button",class:"draft-recovery-banner__secondary-action","data-testid":"draft-recovery-dismiss",onClick:I[1]||(I[1]=x=>b(p.value))}," Dismiss ")])])):(e.openBlock(),e.createElementBlock("p",ST," No recoverable drafts "))],10,nT))}}),bu=$e(CT,[["__scopeId","data-v-3ed3c273"]]),xT={class:"inspector-tabs",role:"tablist","aria-label":"Editor tools"},NT=["aria-selected","data-testid","onClick"],VT=["aria-labelledby"],TT={class:"inspector-placeholder","data-testid":"v2-inspector-placeholder"},BT=e.defineComponent({__name:"InspectorPanel",props:{activeTab:{},tabs:{},compact:{type:Boolean,default:!1}},emits:["update:activeTab"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>t.tabs.filter(l=>l.enabled)),r=l=>{l!==t.activeTab&&n("update:activeTab",l)};return(l,s)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["inspector-panel",{"inspector-panel--compact":l.compact}]),"data-testid":"v2-inspector-panel"},[e.createElementVNode("nav",xT,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,d=>(e.openBlock(),e.createElementBlock("button",{key:d.id,type:"button",role:"tab",class:e.normalizeClass(["inspector-tab",{"is-active":l.activeTab===d.id}]),"aria-selected":l.activeTab===d.id?"true":"false","data-testid":`v2-inspector-tab-${d.id}`,onClick:c=>r(d.id)},e.toDisplayString(d.label),11,NT))),128))]),e.createElementVNode("div",{class:"inspector-body",role:"tabpanel","aria-labelledby":`v2-inspector-tab-${l.activeTab}`},[e.renderSlot(l.$slots,l.activeTab,{},()=>[e.createElementVNode("div",TT,[e.createElementVNode("p",null,e.toDisplayString(l.activeTab)+" controls — coming soon",1)])],!0)],8,VT)],2))}}),IT=$e(BT,[["__scopeId","data-v-7f5b0e50"]]),MT={class:"keyframe-preset-panel__header"},$T={class:"keyframe-preset-panel__target","data-testid":"keyframe-preset-target"},FT={key:0,class:"keyframe-preset-panel__notice","data-testid":"keyframe-preset-invalid-duration"},DT={class:"keyframe-preset-panel__grid","data-testid":"keyframe-preset-buttons"},AT=["disabled","aria-disabled","data-testid","onClick"],RT={class:"keyframe-preset-panel__preset-label"},LT={class:"keyframe-preset-panel__preset-summary"},PT={key:1,class:"keyframe-preset-panel__compact-summary","data-testid":"keyframe-preset-mobile-summary"},UT={key:2,class:"keyframe-preset-panel__desktop-summary","data-testid":"keyframe-preset-desktop-summary"},OT={class:"keyframe-preset-panel__summary-list"},zT=["data-testid"],jT={key:0,class:"keyframe-preset-panel__summary-empty","data-testid":"keyframe-preset-summary-empty"},WT=e.defineComponent({__name:"KeyframePresetPanel",props:{duration:{},target:{},deviceClass:{}},emits:["apply-preset"],setup(o,{emit:a}){const t=o,n=a,i={all:"All targets",opacity:"Opacity",scale:"Scale",x:"Pan X",y:"Pan Y",rotation:"Rotation",audioVolume:"Audio"},r=[{id:"fade-in",label:"Fade in",target:"opacity",summary:"Opacity 0 -> 100%",create:V=>{const I=GE({duration:R(V)});return y("fade-in","Fade in",I,V)}},{id:"fade-out",label:"Fade out",target:"opacity",summary:"Opacity 100 -> 0%",create:V=>{const I=R(V),x=XE({startTime:V-I,duration:I});return y("fade-out","Fade out",x,V)}},{id:"push-in",label:"Push in",target:"scale",summary:"Scale 100 -> 108%",create:V=>{const I=KE({duration:V,fromScale:1,toScale:1.08,easing:"ease-out"});return y("push-in","Push in",I,V)}},{id:"push-out",label:"Push out",target:"scale",summary:"Scale 108 -> 100%",create:V=>g({id:"push-out",label:"Push out",target:"scale",duration:V,startValue:1.08,endValue:1,easing:"ease-in"})},{id:"pan-x-left",label:"Pan left",target:"x",summary:"X 55 -> 45%",create:V=>g({id:"pan-x-left",label:"Pan left",target:"x",duration:V,startValue:.55,endValue:.45,easing:"ease-in-out"})},{id:"pan-x-right",label:"Pan right",target:"x",summary:"X 45 -> 55%",create:V=>g({id:"pan-x-right",label:"Pan right",target:"x",duration:V,startValue:.45,endValue:.55,easing:"ease-in-out"})},{id:"pan-y-up",label:"Pan up",target:"y",summary:"Y 55 -> 45%",create:V=>g({id:"pan-y-up",label:"Pan up",target:"y",duration:V,startValue:.55,endValue:.45,easing:"ease-in-out"})},{id:"pan-y-down",label:"Pan down",target:"y",summary:"Y 45 -> 55%",create:V=>g({id:"pan-y-down",label:"Pan down",target:"y",duration:V,startValue:.45,endValue:.55,easing:"ease-in-out"})},{id:"audio-fade-in",label:"Audio fade in",target:"audioVolume",summary:"Volume 0 -> 100%",create:V=>g({id:"audio-fade-in",label:"Audio fade in",target:"audioVolume",duration:R(V),startValue:0,endValue:1,easing:"ease-out"})},{id:"audio-fade-out",label:"Audio fade out",target:"audioVolume",summary:"Volume 100 -> 0%",create:V=>{const I=R(V);return g({id:"audio-fade-out",label:"Audio fade out",target:"audioVolume",duration:I,startTime:V-I,startValue:1,endValue:0,easing:"ease-in"})}}],l=e.computed(()=>WE(t.deviceClass)),s=e.computed(()=>l.value.platform==="mobile"),d=e.computed(()=>Number.isFinite(t.duration)&&t.duration>0),c=e.computed(()=>t.target==="all"?r:r.filter(V=>V.target===t.target)),u=e.computed(()=>d.value?c.value.map(V=>({definition:V,automation:V.create(t.duration)})):[]),m=e.computed(()=>i[t.target]),p=e.computed(()=>{const V=c.value.length,I=V===1?"preset":"presets";return d.value?`${V} ${I} - ${h(t.duration)} clip.`:`${V} ${I} available when duration is set.`}),f=V=>{if(!d.value)return;const I=V.create(t.duration);n("apply-preset",{presetId:I.id,target:I.target,keyframes:I.keyframes,automation:I})},h=V=>{const I=Math.round(V*100)/100;return`${I.toFixed(I%1===0?0:2)}s`},v=(V,I)=>V==="opacity"||V==="audioVolume"?`${Math.round(I*100)}%`:V==="scale"?`${Math.round(I*100)}%`:V==="x"||V==="y"?`${Math.round(I*100)}%`:`${Math.round(I*100)/100}`,k=V=>{const[I,x]=V.keyframes;return`${h(I.time)} ${v(V.target,I.value)} -> ${h(x.time)} ${v(V.target,x.value)}`};function y(V,I,x,T){return w({id:V,label:I,target:x.target,duration:T,keyframes:x.keyframes})}function w(V){const I=ZE(V.keyframes,{target:V.target,minTime:0,maxTime:V.duration}),x=I[0],T=I[1];if(I.length!==2||x===void 0||T===void 0)throw new Error("Keyframe preset panel presets must generate exactly two keyframes.");return{id:V.id,label:V.label,target:V.target,editingMode:"preset-only",keyframes:[x,T]}}function g(V){const I=V.startTime??0,x=[b(`${V.id}:start`,V.target,I,V.startValue,"linear"),b(`${V.id}:end`,V.target,I+V.duration,V.endValue,V.easing)];return w({id:V.id,label:V.label,target:V.target,duration:I+V.duration,keyframes:x})}function b(V,I,x,T,$){return{id:V,target:I,time:x,value:T,easing:$}}function R(V){return Math.min(V,1)}return(V,I)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["keyframe-preset-panel",{"keyframe-preset-panel--mobile":s.value}]),"data-testid":"keyframe-preset-panel","aria-label":"Keyframe presets"},[e.createElementVNode("header",MT,[I[0]||(I[0]=e.createElementVNode("div",{class:"keyframe-preset-panel__heading"},[e.createElementVNode("p",{class:"keyframe-preset-panel__eyebrow"},"Presets"),e.createElementVNode("h3",{class:"keyframe-preset-panel__title"},"Keyframe automation")],-1)),e.createElementVNode("span",$T,e.toDisplayString(m.value),1)]),d.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("p",FT," Set a valid clip duration to apply automation presets. ")),e.createElementVNode("div",DT,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.value,x=>(e.openBlock(),e.createElementBlock("button",{key:x.id,type:"button",class:"keyframe-preset-panel__preset",disabled:!d.value,"aria-disabled":d.value?void 0:"true","data-testid":`keyframe-preset-button-${x.id}`,onClick:T=>f(x)},[e.createElementVNode("span",RT,e.toDisplayString(x.label),1),e.createElementVNode("span",LT,e.toDisplayString(x.summary),1)],8,AT))),128))]),s.value?(e.openBlock(),e.createElementBlock("p",PT,e.toDisplayString(p.value),1)):(e.openBlock(),e.createElementBlock("div",UT,[I[1]||(I[1]=e.createElementVNode("p",{class:"keyframe-preset-panel__summary-title"},"Generated keyframes",-1)),e.createElementVNode("ul",OT,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(u.value,x=>(e.openBlock(),e.createElementBlock("li",{key:x.definition.id,class:"keyframe-preset-panel__summary-row","data-testid":`keyframe-preset-summary-${x.definition.id}`},[e.createElementVNode("span",null,e.toDisplayString(x.definition.label),1),e.createElementVNode("span",null,e.toDisplayString(k(x.automation)),1)],8,zT))),128))]),u.value.length===0?(e.openBlock(),e.createElementBlock("p",jT," No generated keyframes until duration is valid. ")):e.createCommentVNode("",!0)]))],2))}}),yu=$e(WT,[["__scopeId","data-v-79615683"]]),HT={class:"mobile-clip-summary__main"},ZT={class:"mobile-clip-summary__title","data-testid":"v2-mobile-clip-label"},GT={class:"mobile-clip-summary__stats","aria-label":"Selected clip timing"},XT={class:"mobile-clip-summary__stat"},KT={"data-testid":"v2-mobile-clip-start"},JT={class:"mobile-clip-summary__stat"},qT={"data-testid":"v2-mobile-clip-end"},YT={class:"mobile-clip-summary__stat"},QT={"data-testid":"v2-mobile-clip-duration"},eB={key:1,class:"mobile-clip-summary__empty","data-testid":"v2-mobile-no-clip"},tB=e.defineComponent({__name:"MobileClipSummary",props:{selectedClip:{}},emits:["open-actions"],setup(o,{emit:a}){const t=o,n=a,i=m=>m===void 0||!Number.isFinite(m)?null:m,r=e.computed(()=>{var m,p,f;return((p=(m=t.selectedClip)==null?void 0:m.label)==null?void 0:p.trim())||((f=t.selectedClip)==null?void 0:f.id)||""}),l=e.computed(()=>t.selectedClip?i(t.selectedClip.timelineStart)??i(t.selectedClip.startTime):null),s=e.computed(()=>t.selectedClip?i(t.selectedClip.timelineEnd)??i(t.selectedClip.endTime):null),d=e.computed(()=>{const m=l.value,p=s.value;return m!==null&&p!==null?Math.max(0,p-m):t.selectedClip?i(t.selectedClip.duration):null}),c=m=>{if(m===null)return"--";const p=Math.round(m*100)/100;return`${p.toFixed(p%1===0?0:2)}s`},u=()=>{t.selectedClip&&n("open-actions",t.selectedClip.id)};return(m,p)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["mobile-clip-summary",{"mobile-clip-summary--empty":!m.selectedClip}]),"data-testid":"v2-mobile-clip-summary","aria-live":"polite"},[m.selectedClip?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("div",HT,[p[0]||(p[0]=e.createElementVNode("p",{class:"mobile-clip-summary__eyebrow"},"Selected clip",-1)),e.createElementVNode("h2",ZT,e.toDisplayString(r.value),1)]),e.createElementVNode("dl",GT,[e.createElementVNode("div",XT,[p[1]||(p[1]=e.createElementVNode("dt",null,"Start",-1)),e.createElementVNode("dd",KT,e.toDisplayString(c(l.value)),1)]),e.createElementVNode("div",JT,[p[2]||(p[2]=e.createElementVNode("dt",null,"End",-1)),e.createElementVNode("dd",qT,e.toDisplayString(c(s.value)),1)]),e.createElementVNode("div",YT,[p[3]||(p[3]=e.createElementVNode("dt",null,"Duration",-1)),e.createElementVNode("dd",QT,e.toDisplayString(c(d.value)),1)])]),e.createElementVNode("button",{type:"button",class:"mobile-clip-summary__actions","aria-label":"Open selected clip actions","data-testid":"v2-mobile-clip-actions",onClick:u}," Actions ")],64)):(e.openBlock(),e.createElementBlock("p",eB," No clip selected "))],2))}}),aB=$e(tB,[["__scopeId","data-v-433c7812"]]),nB=["aria-label"],oB=["aria-pressed","data-testid","onClick"],iB={class:"mobile-tool-picker__label"},rB=e.defineComponent({__name:"MobileToolPicker",props:{modelValue:{},ariaLabel:{default:"Mobile editor tools"}},emits:["update:modelValue"],setup(o,{emit:a}){const t=[{id:"look",label:"Look"},{id:"trim",label:"Trim"},{id:"text",label:"Text"},{id:"audio",label:"Audio"},{id:"export",label:"Export"},{id:"more",label:"More"}],n=o,i=a,r=l=>{l!==n.modelValue&&i("update:modelValue",l)};return(l,s)=>(e.openBlock(),e.createElementBlock("div",{class:"mobile-tool-picker",role:"group","aria-label":l.ariaLabel,"data-testid":"v2-mobile-tool-picker"},[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(t,d=>e.createElementVNode("button",{key:d.id,type:"button",class:e.normalizeClass(["mobile-tool-picker__button",{"is-active":l.modelValue===d.id}]),"aria-pressed":l.modelValue===d.id?"true":"false","data-testid":`v2-mobile-tool-${d.id}`,onClick:c=>r(d.id)},[e.createElementVNode("span",iB,e.toDisplayString(d.label),1)],10,oB)),64))],8,nB))}}),lB=$e(rB,[["__scopeId","data-v-ec597c70"]]),sB=["aria-label","data-snap"],dB=["aria-expanded"],cB={class:"drawer-header"},uB={class:"drawer-body"},mB=e.defineComponent({__name:"VideoBottomDrawer",props:{initialSnap:{default:"half"},ariaLabel:{default:"Editor controls drawer"},containerHeight:{default:0}},emits:["snap-change"],setup(o,{expose:a,emit:t}){const n=["collapsed","half","full"],i=o,r=t,l=e.ref(null),s=e.ref(null),d=e.ref(i.initialSnap);let c=!1,u=!1,m=null,p=0,f=0,h=0;const v=T=>{const $=h||(typeof window<"u"?window.innerHeight:600);switch(T){case"collapsed":return 80;case"half":return Math.round($*.45);case"full":return Math.round($*.85)}},k=(T,{animate:$=!0}={})=>{var _;if(!l.value)return;const S=d.value;d.value=T;const B=typeof window<"u"&&((_=window.matchMedia)==null?void 0:_.call(window,"(prefers-reduced-motion: reduce)").matches);l.value.style.transition=$&&!B?"height 0.25s cubic-bezier(0.33, 1, 0.68, 1)":"none",l.value.style.height=`${v(T)}px`,T!==S&&r("snap-change",T,S)},y=T=>{let $=n[0],S=1/0;for(const B of n){const _=Math.abs(v(B)-T);_<S&&(S=_,$=B)}return $},w=()=>{const T=n.indexOf(d.value);k(n[(T+1)%n.length])},g=T=>{if(u){u=!1,T.preventDefault();return}w()},b=T=>{var $,S,B;if(T.button===0){c=!0,u=!1,m=T.pointerId,p=T.clientY,f=(($=l.value)==null?void 0:$.offsetHeight)??0;try{(B=(S=s.value)==null?void 0:S.setPointerCapture)==null||B.call(S,T.pointerId)}catch{}l.value&&(l.value.style.transition="none")}},R=T=>{if(!c||T.pointerId!==m)return;const $=T.clientY-p,S=f-$,B=v("collapsed"),_=v("full"),A=Math.max(B,Math.min(_,S));l.value&&(l.value.style.height=`${A}px`),Math.abs($)>4&&(u=!0),T.preventDefault()},V=T=>{var S,B,_;if(!c)return;c=!1;try{(B=(S=s.value)==null?void 0:S.releasePointerCapture)==null||B.call(S,T.pointerId)}catch{}m=null;const $=((_=l.value)==null?void 0:_.offsetHeight)??0;k(y($))},I=(T,$={})=>{n.includes(T)&&k(T,{animate:$.animate!==!1})},x=T=>{h=Math.max(0,Number(T)||0),k(d.value,{animate:!1})};return e.watch(()=>i.containerHeight,T=>{T>0&&x(T)}),e.onMounted(()=>{i.containerHeight>0&&(h=i.containerHeight),k(d.value,{animate:!1})}),e.onBeforeUnmount(()=>{c=!1,m=null}),a({snapTo:I,updateContainerHeight:x,snap:d}),(T,$)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"rootEl",ref:l,class:"video-editor-v2-drawer",role:"dialog","aria-label":T.ariaLabel,"data-snap":d.value,"data-testid":"v2-video-bottom-drawer"},[e.createElementVNode("button",{ref_key:"handleEl",ref:s,type:"button",class:"drawer-handle","aria-label":"Drag to resize editor drawer","aria-expanded":d.value==="full"?"true":"false","data-testid":"v2-video-drawer-handle",onClick:g,onPointerdown:b,onPointermove:R,onPointerup:V,onPointercancel:V},[...$[0]||($[0]=[e.createElementVNode("span",{class:"drawer-handle-grip","aria-hidden":"true"},null,-1)])],40,dB),e.createElementVNode("div",cB,[e.renderSlot(T.$slots,"header",{},void 0,!0)]),e.createElementVNode("div",uB,[e.renderSlot(T.$slots,"default",{},void 0,!0)])],8,sB))}}),pB=$e(mB,[["__scopeId","data-v-4ebedbf7"]]),fB=new Set(["INPUT","TEXTAREA","SELECT"]);function hB(o){return o instanceof HTMLElement?!!(fB.has(o.tagName)||o.isContentEditable):!1}function vB(o,a={}){const t=n=>{var s,d,c,u,m,p,f,h,v,k,y,w,g,b,R,V,I;if(a.enabled&&a.enabled()===!1||hB(n.target))return;const i=n.ctrlKey||n.metaKey,r=n.shiftKey,l=n.key;if(i&&(l==="z"||l==="Z")){r?(s=o.redo)==null||s.call(o):(d=o.undo)==null||d.call(o),n.preventDefault();return}if(i&&(l==="s"||l==="S")){(c=o.save)==null||c.call(o),n.preventDefault();return}if(i&&(l==="e"||l==="E")){(u=o.exportNow)==null||u.call(o),n.preventDefault();return}switch(l){case" ":case"Spacebar":(m=o.playPause)==null||m.call(o),n.preventDefault();return;case"ArrowLeft":r?(p=o.secondBackward)==null||p.call(o):(f=o.frameBackward)==null||f.call(o),n.preventDefault();return;case"ArrowRight":r?(h=o.secondForward)==null||h.call(o):(v=o.frameForward)==null||v.call(o),n.preventDefault();return;case"Home":(k=o.skipToStart)==null||k.call(o),n.preventDefault();return;case"End":(y=o.skipToEnd)==null||y.call(o),n.preventDefault();return;case"[":(w=o.prevClip)==null||w.call(o),n.preventDefault();return;case"]":(g=o.nextClip)==null||g.call(o),n.preventDefault();return;case"s":case"S":i||((b=o.splitAtPlayhead)==null||b.call(o),n.preventDefault());return;case"Delete":case"Backspace":r?(R=o.rippleDeleteSelected)==null||R.call(o):(V=o.deleteSelected)==null||V.call(o),n.preventDefault();return;case"?":(I=o.showShortcutsOverlay)==null||I.call(o),n.preventDefault();return}};e.onMounted(()=>{window.addEventListener("keydown",t)}),e.onBeforeUnmount(()=>{window.removeEventListener("keydown",t)})}const ef=["video/mp4","video/webm","video/quicktime"],tf=["image/png","image/jpeg","image/jpg","image/webp"],gB=["audio/mpeg","audio/mp3","audio/aac","audio/wav","audio/x-wav","audio/wave"],bB=new Set([...ef,...tf,...gB]),yB=2*1024*1024*1024,wB=60*60;function wu(o,a){const t=o.type.toLowerCase();return bB.has(t)?o.size>yB?{ok:!1,reason:"oversize",message:`File is too large (${(o.size/(1024*1024*1024)).toFixed(2)} GiB). Limit is 2 GiB.`}:typeof a=="number"&&Number.isFinite(a)&&a>wB?{ok:!1,reason:"duration_exceeded",message:`Clip is too long (${Math.round(a)}s). Limit is 1 hour.`}:{ok:!0,kind:ef.includes(t)?"video":tf.includes(t)?"image":"audio"}:{ok:!1,reason:"unsupported_mime",message:`Unsupported file type: ${t||"unknown"}.`}}const kB="mediables-asset-blobs",Ka="blobs",_B=1;class EB{constructor(){this.dbPromise=null}openDb(){return this.dbPromise?this.dbPromise:(this.dbPromise=new Promise((a,t)=>{if(typeof indexedDB>"u"){t(new Error("IndexedDB is not available in this environment."));return}const n=indexedDB.open(kB,_B);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Ka)||i.createObjectStore(Ka)},n.onsuccess=()=>{a(n.result)},n.onerror=()=>{t(n.error??new Error("Failed to open IndexedDB."))}}),this.dbPromise)}async put(a,t){const n=await this.openDb();await new Promise((i,r)=>{const d=n.transaction(Ka,"readwrite").objectStore(Ka).put(t,a);d.onsuccess=()=>{i()},d.onerror=()=>{r(d.error??new Error("Failed to write blob."))}})}async get(a){const t=await this.openDb();return new Promise((n,i)=>{const s=t.transaction(Ka,"readonly").objectStore(Ka).get(a);s.onsuccess=()=>{const d=s.result;d==null?n(null):d instanceof Blob?n(d):n(null)},s.onerror=()=>{i(s.error??new Error("Failed to read blob."))}})}async delete(a){const t=await this.openDb();await new Promise((n,i)=>{const s=t.transaction(Ka,"readwrite").objectStore(Ka).delete(a);s.onsuccess=()=>{n()},s.onerror=()=>{i(s.error??new Error("Failed to delete blob."))}})}async clear(){const a=await this.openDb();await new Promise((t,n)=>{const l=a.transaction(Ka,"readwrite").objectStore(Ka).clear();l.onsuccess=()=>{t()},l.onerror=()=>{n(l.error??new Error("Failed to clear cache."))}})}}let ns=null;function SB(){return ns===null&&(ns=new EB),ns}class CB{constructor(){this.store=new Map}async put(a,t){this.store.set(a,t)}async get(a){return this.store.get(a)??null}async delete(a){this.store.delete(a)}async clear(){this.store.clear()}}function xB(){return`asset-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function NB(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 VB(o){const a=e.reactive(new Map),t=o.blobCache??TB();async function n(u,m){try{await t.put(u,m)}catch{}}async function i(u){try{await t.delete(u)}catch{}}async function r(u,m,p){var f,h,v;try{m.status="uploading",m.uploadProgress=0,a.set(m.assetId,m);const k=await o.uploader.upload({file:u},({assetId:y,progress:w,status:g})=>{if(y!==m.assetId)return;const b=a.get(y);b&&(b.uploadProgress=w,b.status=g,a.set(y,b))});return a.set(m.assetId,k),k.status==="ready"?(i(m.assetId),(f=o.onReady)==null||f.call(o,k)):k.status==="failed"&&((h=o.onFailure)==null||h.call(o,k)),{ok:!0,record:k}}catch(k){const y=k instanceof Error?k.message:"Upload failed.",w={...m,status:"failed",failureMessage:y};return a.set(m.assetId,w),(v=o.onFailure)==null||v.call(o,w),{ok:!1,reason:"upload",message:y}}}const l=o.probeTimeoutMs??1500;async function s(u){const m=await NB(u,l),p=wu(u,m.durationSeconds);if(!p.ok)return{ok:!1,reason:"preflight",message:p.message};const f=xB(),h={assetId:f,filename:u.name,mime:u.type,sizeBytes:u.size,status:"local-selected"};return m.durationSeconds!==void 0&&(h.durationSeconds=m.durationSeconds),m.width!==void 0&&(h.width=m.width),m.height!==void 0&&(h.height=m.height),a.set(f,h),await n(f,u),r(u,h)}async function d(u){const m=a.get(u);if(!m)return{ok:!1,reason:"unknown",message:"Unknown asset."};const p=await t.get(u);if(!p)return{ok:!1,reason:"unknown",message:"Original file is no longer cached."};const f=p instanceof File?p:new File([p],m.filename,{type:m.mime}),h=wu(f,m.durationSeconds);return h.ok?r(f,m):{ok:!1,reason:"preflight",message:h.message}}async function c(u){a.delete(u),await i(u)}return{records:e.readonly(a),importFile:s,retry:d,remove:c}}function TB(){return typeof indexedDB<"u"?SB():new CB}const BB={class:"v2-toolbar-group"},IB=["aria-label"],MB=["disabled"],$B={class:"v2-toolbar-group"},FB={class:"v2-toolbar-fit"},DB=["disabled"],AB=["aria-label","title","disabled"],RB={class:"v2-assets"},LB={key:0,class:"v2-asset-rail-status","data-testid":"v2-asset-rail-status",role:"status"},PB={class:"v2-preview-host"},UB={class:"v2-timeline-topbar"},OB={class:"v2-timeline-heading"},zB={class:"v2-timeline-meta","data-testid":"v2-timeline-meta"},jB={class:"v2-timeline-zoom"},WB=["value"],HB={class:"v2-timeline-zoom-readout"},ZB={key:0,class:"v2-timeline-track-actions"},GB={key:0,class:"v2-timeline-track-target"},XB=["value"],KB=["value"],JB=["aria-pressed"],qB={key:0,class:"v2-editor-status","data-testid":"v2-editor-status",role:"status","aria-live":"polite"},YB={key:1,class:"v2-timeline-empty","data-testid":"v2-timeline-empty"},QB={key:1,class:"v2-empty-state"},e4={key:0,"data-testid":"v2-export-status-completed",class:"v2-export-status"},t4={key:1,class:"v2-export-status","data-testid":"v2-export-status-message"},a4={key:1,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-look"},n4={class:"v2-mobile-panel-section"},o4={class:"v2-mobile-panel-section v2-mobile-panel-section--compact"},i4={key:1,class:"v2-empty-state"},r4={key:2,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-trim"},l4={key:3,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-text"},s4={key:4,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-audio"},d4={key:5,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-export"},c4={key:0,class:"v2-export-status"},u4={key:1,class:"v2-export-status"},m4={key:6,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-more"},p4={class:"v2-mobile-secondary-controls"},f4={class:"v2-mobile-secondary-field"},h4=["aria-pressed"],v4=["disabled"],g4=["disabled"],b4={key:0,class:"v2-mobile-secondary-details","data-testid":"v2-mobile-transitions"},y4={class:"v2-mobile-secondary-details","data-testid":"v2-mobile-keyframes"},w4={class:"v2-shortcuts-overlay__panel"},k4={class:"v2-shortcuts-overlay__header"},_4=e.defineComponent({__name:"VideoEditorV2",props:{mediaUuid:{},initialRecipe:{},media:{},showThumbnailPicker:{type:Boolean,default:!1},workflowMode:{default:"full"},featureFlags:{},clientExportThreshold:{default:20},maxDuration:{default:300},serverRenderEndpoint:{default:null},assetUploader:{default:null}},emits:["recipe-generated","export-started","draft-saved","video-exported","thumbnail-selected","server-render-started","server-render-progress","server-render-completed","server-render-failed","close"],setup(o,{expose:a,emit:t}){var er,tr,ar,nr;const n=o,i=t,r=e.computed(()=>{var ee;const E=typeof n.mediaUuid=="string"?n.mediaUuid.trim():"";if(E!=="")return E;const F=(ee=n.media)==null?void 0:ee.uuid;return typeof F=="string"&&F.trim()!==""?F.trim():`temp-${Date.now()}`}),l=_p(r.value,n.initialRecipe,n.media),s=Cp(),d=e.ref("filters"),c=e.ref("look"),u=e.ref(null),m=e.computed(()=>n.workflowMode==="uploader"?{filters:!0,adjustments:!0,text:!1,transitions:!1,audio:!1,export:!1}:{filters:!0,adjustments:!0,text:!0,transitions:!0,audio:!0,export:!0}),p=e.computed(()=>{const E=n.featureFlags??{},F=["filters","adjustments","text","transitions","audio","export"],ee={filters:"Filters",adjustments:"Adjust",text:"Text",transitions:"Transitions",audio:"Audio",export:"Export"};return F.map(ke=>({id:ke,label:ee[ke],enabled:typeof E[ke]=="boolean"?E[ke]:m.value[ke]}))}),f=E=>p.value.some(F=>F.id===E&&F.enabled),h={look:"filters",text:"text",audio:"audio",export:"export"},v=e.computed(()=>{var E;return((E=n.featureFlags)==null?void 0:E.transitions)===!0});e.watch(c,E=>{var F,ee;if(E!=="trim"&&E!=="more"){const ke=h[E];f(ke)&&(d.value=ke)}(ee=(F=u.value)==null?void 0:F.snapTo)==null||ee.call(F,"full"),e.nextTick(()=>{var Oe;if(typeof document>"u")return;const ke=document.querySelector(`[data-testid="v2-mobile-panel-${E}"]`);if(!ke||!(ke instanceof HTMLElement))return;const Ue=typeof window<"u"&&((Oe=window.matchMedia)==null?void 0:Oe.call(window,"(prefers-reduced-motion: reduce)").matches);ke.scrollIntoView({block:"start",behavior:Ue?"auto":"smooth"})})});const k=e.ref(!1),y=e.computed(()=>d.value),w=e.computed(()=>y.value==="filters"||k.value),g=e.computed(()=>y.value!=="filters"&&!k.value),b=e.ref(null),R=e.computed(()=>b.value),V=["contain","cover","none"],I=E=>typeof E=="string"&&V.includes(E),x=E=>{var ee;const F=(ee=E==null?void 0:E.metadata)==null?void 0:ee.fit_mode;return I(F)?F:null},T=e.ref(x(n.initialRecipe)??"contain"),$=e.ref("");e.watch(()=>{var E,F;return{file:(E=n.media)==null?void 0:E.file,url:(F=n.media)==null?void 0:F.url}},(E,F,ee)=>{var Ue,Oe;const ke=$.value;ee(()=>{ke&&ke.startsWith("blob:")&&URL.revokeObjectURL(ke)}),(Ue=n.media)!=null&&Ue.file?$.value=URL.createObjectURL(n.media.file):(Oe=n.media)!=null&&Oe.url?$.value=n.media.url:$.value=""},{immediate:!0});const S=e.computed(()=>$.value),B=e.computed(()=>s.activeFilters.value),_=e.computed(()=>l.playheadPosition.value),A=Km({forcePixiPreview:k,getPreviewRef:()=>R.value,getSourceUrl:()=>$.value,setPlaying:l.setPlaying}),P=e.computed(()=>{if(!n.media)return null;const{file:E,...F}=n.media;return{...F,url:$.value}}),D=e.computed(()=>{var F;const E=(F=n.media)==null?void 0:F.url;return!!(E&&/^https?:/i.test(E))}),z=e.ref(0),M=e.computed(()=>{var F;if(l.totalDuration.value>0)return l.totalDuration.value;if(z.value>0)return z.value;const E=Number((F=n.media)==null?void 0:F.duration);return Number.isFinite(E)&&E>0?E:0}),Z=E=>{!Number.isFinite(E)||E<=0||(z.value=E,l.updateSourceDuration(E))},O=E=>{E&&typeof E.time=="number"&&Number.isFinite(E.time)&&l.seekTo(E.time)},K=E=>{Number.isFinite(E)&&l.seekTo(E)},de=E=>{l.setPlaying(E)},Ne=e.computed(()=>s.videoCompatibleFilters.value.map(F=>{var ke;const ee=[];if(F.controls&&F.controls.length>0)for(const Ue of F.controls){const Oe=Ue.type;if(Oe==="button"||Oe==="text"||Oe==="range")continue;const it={id:Ue.property||Ue.id,label:Ue.label||Ue.id,type:Oe,default:Ue.default??(Oe==="toggle"?!1:Oe==="color"?"#ffffff":0)};Oe==="slider"&&(it.min=Ue.min??0,it.max=Ue.max??1,it.step=Ue.step??.01),Oe==="select"&&Ue.options&&(it.options=Ue.options),ee.push(it)}else if(F.paramRanges){const Ue=Object.entries(F.paramRanges);for(const[Oe,it]of Ue){const Nt=Oe.replace(/[-_]/g," ").replace(/\b\w/g,_o=>_o.toUpperCase()),Kt=(ke=F.defaultParams)==null?void 0:ke[Oe],pa=(it.min+it.max)/2;ee.push({id:Oe,label:Nt,min:it.min,max:it.max,step:it.step??.01,default:typeof Kt=="number"?Kt:pa})}}return{id:F.id,name:F.name,category:F.category,params:ee}})),ce=e.computed(()=>{const E=new Map;return s.activeFilters.value.forEach(F=>E.set(F.filterId,F)),E}),le=e.computed(()=>{if(l.currentFrame.value)return l.currentFrame.value;const E=n.media;return(E==null?void 0:E.thumbnail_url)??(E==null?void 0:E.url)}),W=e.shallowRef(null),C=e.ref(null),U=e.ref(null),j=e.ref(null),re=e.ref(!1),ue=new Map,Xe=(E,F)=>{const ee={id:E.id??`text-overlay-recipe-${F}`,text:E.content};return E.fontFamily!==void 0&&(ee.fontFamily=E.fontFamily),E.fontSize!==void 0&&(ee.fontSize=E.fontSize),E.fontWeight!==void 0&&(ee.fontWeight=E.fontWeight),E.color!==void 0&&(ee.color=E.color),E.position!==void 0&&(ee.position=E.position),E.startTime!==void 0&&(ee.startTime=E.startTime),E.duration!==void 0&&(ee.duration=E.duration),E.animation!==void 0&&(ee.animation=E.animation),E.textAlign!==void 0&&(ee.textAlign=E.textAlign),E.textBaseline!==void 0&&(ee.textBaseline=E.textBaseline),ee},be=E=>{const F={id:E.id,content:E.text};return E.fontFamily!==void 0&&(F.fontFamily=E.fontFamily),E.fontSize!==void 0&&(F.fontSize=E.fontSize),E.fontWeight!==void 0&&(F.fontWeight=E.fontWeight),E.color!==void 0&&(F.color=E.color),E.position!==void 0&&(F.position=E.position),E.startTime!==void 0&&(F.startTime=E.startTime),E.duration!==void 0&&(F.duration=E.duration),E.animation!==void 0&&(F.animation=E.animation),E.textAlign!==void 0&&(F.textAlign=E.textAlign),E.textBaseline!==void 0&&(F.textBaseline=E.textBaseline),F},Ee=(E,F)=>{const ee={id:E.id??`audio-track-recipe-${F}`,source:E.source};return E.volume!==void 0&&(ee.volume=E.volume),E.startTime!==void 0&&(ee.startTime=E.startTime),E.duration!==void 0&&(ee.duration=E.duration),E.fadeIn!==void 0&&(ee.fadeIn=E.fadeIn),E.fadeOut!==void 0&&(ee.fadeOut=E.fadeOut),E.loop!==void 0&&(ee.loop=E.loop),E.name!==void 0&&(ee.name=E.name),ee},ye=E=>{if(typeof E.source!="string")return null;const F={id:E.id,source:E.source};return E.volume!==void 0&&(F.volume=E.volume),E.startTime!==void 0&&(F.startTime=E.startTime),E.duration!==void 0&&(F.duration=E.duration),E.fadeIn!==void 0&&(F.fadeIn=E.fadeIn),E.fadeOut!==void 0&&(F.fadeOut=E.fadeOut),E.loop!==void 0&&(F.loop=E.loop),E.name!==void 0&&(F.name=E.name),F},xe=E=>{const F={id:E.id,source:typeof E.source=="string"?E.source:""};return E.volume!==void 0&&(F.volume=E.volume),E.startTime!==void 0&&(F.startTime=E.startTime),E.duration!==void 0&&(F.duration=E.duration),E.fadeIn!==void 0&&(F.fadeIn=E.fadeIn),E.fadeOut!==void 0&&(F.fadeOut=E.fadeOut),E.loop!==void 0&&(F.loop=E.loop),E.name!==void 0&&(F.name=E.name),E.muted!==void 0&&(F.muted=E.muted),E.solo!==void 0&&(F.solo=E.solo),E.pan!==void 0&&(F.pan=E.pan),E.faderDb!==void 0&&(F.faderDb=E.faderDb),F},Ce=E=>({...E,segments:E.segments.map(F=>{const ee={...F};return F.words&&(ee.words=F.words.map(ke=>({...ke}))),ee})}),Re=e.ref((((er=n.initialRecipe)==null?void 0:er.textOverlays)??[]).map(Xe)),ze=E=>{switch(E){case"crossfade":return"cross-fade";case"zoom":return"zoom-in";case"cut":return"fade";default:return E}},rt=E=>{switch(E){case"ease-in":return"easeIn";case"ease-out":return"easeOut";case"ease-in-out":return"easeInOut";case"linear":return"linear"}},at=E=>{switch(E){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 E}},Dt=E=>{switch(E){case"easeIn":return"ease-in";case"easeOut":return"ease-out";case"easeInOut":return"ease-in-out";case"linear":default:return"linear"}},ht=E=>({id:E.id,type:ze(E.type),duration:E.duration,easing:rt(E.easing),name:E.type,fromClipId:E.fromClipId,toClipId:E.toClipId,cutTime:E.cutTime??0}),St=E=>({id:E.id,type:at(E.type),fromClipId:E.fromClipId,toClipId:E.toClipId,duration:E.duration,easing:Dt(E.easing),cutTime:E.cutTime}),ut=e.ref((((tr=n.initialRecipe)==null?void 0:tr.transitions)??[]).map(ht)),lt=e.ref((((ar=n.initialRecipe)==null?void 0:ar.audioTracks)??[]).map(Ee)),Ct=e.ref(1),Se=e.ref(!1),J=e.ref((((nr=n.initialRecipe)==null?void 0:nr.captionTracks)??[]).map(Ce)),oe=e.ref([]),De=e.ref(null),fe=e.computed(()=>r.value),Ae=e.computed(()=>oe.value),Ye=e.computed(()=>J.value[0]??null),st=e.computed(()=>{const E=l.selectedClip.value??l.timelineClips.value[0];return E?Math.max(0,E.timelineEnd-E.timelineStart):M.value}),Bt=e.computed(()=>hE(lt.value.map(xe),{master:{volume:Ct.value,muted:Se.value}})),Vt=e.computed(()=>{const E=[...l.timelineClips.value].sort((it,Nt)=>it.timelineStart-Nt.timelineStart),F=l.selectedClip.value??E[0];if(!F)return[];const ee=E.findIndex(it=>it.id===F.id);if(ee===-1)return[];const ke=it=>(it.trackId??null)===(F.trackId??null),Ue=E.slice(ee+1).find(ke);if(Ue)return[F,Ue];const Oe=[...E.slice(0,ee)].reverse().find(ke);return Oe?[Oe,F]:[]}),Lt=E=>{W.value=E,E!=null&&E.composition&&(U.value=new xp(E.composition),j.value=new Np(E.composition));try{ue.size&&W.value&&(ue.forEach((F,ee)=>{W.value.setClipFilters(ee,F)}),ue.clear(),W.value.composition.computeFrame())}catch{}},Pt=E=>{W.value?W.value.setClipFilters(E,s.activeFilters.value):ue.set(E,[...s.activeFilters.value])},zt=E=>{var ee,ke;const F=((ee=l.selectedClip.value)==null?void 0:ee.id)??((ke=l.timelineClips.value[0])==null?void 0:ke.id);F&&(re.value=!0,typeof E=="object"&&E!==null&&"id"in E?s.applyFilter(E.id):typeof E=="string"&&s.applyFilter(E),l.setFilters(s.activeFilters.value),Pt(F),l.handleClipSelect(F),re.value=!1,Ze())},Ot=E=>{var ke,Ue;const F=s.activeFilters.value.find(Oe=>Oe.filterId===E);F&&s.removeFilter(F.id),l.setFilters(s.activeFilters.value);const ee=((ke=l.selectedClip.value)==null?void 0:ke.id)??((Ue=l.timelineClips.value[0])==null?void 0:Ue.id);ee&&Pt(ee),Ze()},jt=(E,F,ee)=>{var Oe,it;const ke=s.activeFilters.value.find(Nt=>Nt.filterId===E);if(ke){ke.params={...ke.params??{},[F]:ee},l.setFilters(s.activeFilters.value);const Nt=((Oe=l.selectedClip.value)==null?void 0:Oe.id)??((it=l.timelineClips.value[0])==null?void 0:it.id);Nt&&Pt(Nt),Ze();return}const Ue=s.previewFilter.value;Ue&&Ue.filterId===E&&(Ue.params={...Ue.params??{},[F]:ee})},oa=E=>{E&&typeof E.id=="string"&&E.id!==""&&s.previewFilterEffect(E.id)},Q=E=>{s.updateFilterParams(E),l.setFilters(s.activeFilters.value),Ze()},ge=async E=>{if(!U.value)return;const F=await U.value.addTextOverlay(E);Re.value.push({id:F,...E})},me=async(E,F)=>{if(!U.value)return;await U.value.updateTextOverlay(E,F);const ee=Re.value.findIndex(ke=>ke.id===E);ee!==-1&&(Re.value[ee]={...Re.value[ee],...F})},se=async E=>{U.value&&(await U.value.removeTextOverlay(E),Re.value=Re.value.filter(F=>F.id!==E))},Ve=async E=>{const[F,ee]=Vt.value;if(!F||!ee)return;const ke={id:`transition-${F.id}-${ee.id}-${Date.now()}`,...E,name:E.type,fromClipId:F.id,toClipId:ee.id,cutTime:F.timelineEnd};ut.value.push(ke),l.setTransitions(ut.value.map(St)),Ze()},Pe=E=>{ut.value[E]&&(ut.value.splice(E,1),l.setTransitions(ut.value.map(St)),Ze())},et=E=>{},gt=async E=>{if(!j.value)return;const F=await j.value.addAudioTrack(E);lt.value.push({id:F,...E});const ee=typeof E.source=="string"?E.source:E.source instanceof File?URL.createObjectURL(E.source):null;if(!ee)return;const ke={id:`audio-source-${F}`,type:"url",url:ee,duration:typeof E.duration=="number"&&E.duration>0?E.duration:0,width:0,height:0};typeof E.name=="string"&&(ke.filename=E.name),l.registerMediaSource(ke);const Ue=l.appendAudioSourceToTimeline(ke.id);if(!Ue.ok){Qe.value=Ue.message;return}Qe.value=`Audio added to ${Ue.value.trackId??"timeline"}.`,Ze()},Tt=async(E,F)=>{if(!j.value)return;await j.value.updateAudioTrack(E,F);const ee=lt.value.findIndex(ke=>ke.id===E);ee!==-1&&(lt.value[ee]={...lt.value[ee],...F})},xt=async E=>{j.value&&(await j.value.removeAudioTrack(E),lt.value=lt.value.filter(F=>F.id!==E))},_t=async(E,F)=>{if(!j.value)return;await j.value.updateVolume(E,F);const ee=lt.value.find(ke=>ke.id===E);ee&&(ee.volume=F)},Xt=async(E,F)=>{if(!j.value)return;await j.value.muteTrack(E,F);const ee=lt.value.find(ke=>ke.id===E);ee&&(ee.muted=F)},X=E=>{j.value&&(j.value.setMasterVolume(E),Ct.value=E)},we=(E,F)=>{const ee=lt.value.findIndex(Ue=>Ue.id===E);if(ee===-1)return null;const ke={...lt.value[ee],...F};return lt.value[ee]=ke,ke},ne=E=>{switch(E.type){case"track-fader-db":{const F=Os(E.valueDb);we(E.trackId,{faderDb:E.valueDb,volume:F}),j.value&&j.value.updateVolume(E.trackId,F);break}case"track-mute":we(E.trackId,{muted:E.muted}),j.value&&j.value.muteTrack(E.trackId,E.muted);break;case"track-solo":we(E.trackId,{solo:E.solo});break;case"track-pan":we(E.trackId,{pan:E.pan});break;case"master-fader-db":{Ct.value=Os(E.valueDb),j.value&&j.value.setMasterVolume(Se.value?0:Ct.value);break}case"master-mute":Se.value=E.muted,j.value&&j.value.setMasterVolume(Se.value?0:Ct.value);break}},Fe=E=>{J.value=[Ce(E.track)],l.setCaptionTracks(J.value),Ze()},It=E=>{J.value=[Ce(E)],l.setCaptionTracks(J.value),Ze()},At=()=>{J.value=[],l.setCaptionTracks([]),Ze()},Mt=E=>{const F=l.selectedClip.value??l.timelineClips.value[0];if(!F)return;const ke=[...(F.keyframes??[]).filter(Ue=>Ue.target!==E.target),...E.keyframes].sort((Ue,Oe)=>{const it=Ue.time-Oe.time;return it===0?Ue.id.localeCompare(Oe.id):it});l.setClipKeyframes(F.id,ke),Ze()},mt=E=>{var F;return E.metadata||(E.metadata={created_at:new Date().toISOString(),editor_version:"2.0.0"}),E.metadata.fit_mode=T.value,(F=n.media)!=null&&F.url&&/^https?:/i.test(n.media.url)?E.metadata.source_url=n.media.url:delete E.metadata.source_url,E.captionTracks=J.value.map(Ce),E},pt=(E,F)=>F?{...E,output:{...E.output,format:F.format,quality:F.quality,codec:F.codec??E.output.codec,fps:F.fps??E.output.fps,...typeof F.bitrate=="number"?{bitrate:F.bitrate}:{}}}:E,Qt=E=>E.map(F=>({...F,params:F.params&&typeof F.params=="object"?{...F.params}:F.params})),yt=E=>E.timeline.some(F=>Array.isArray(F.filters)&&F.filters.length>0),Wt=E=>{const F=Qt(s.activeFilters.value);if(!yt(E)&&F.length>0&&E.timeline.length>0){const ke=E.timeline[0];ke&&(E.timeline=[{...ke,filters:F},...E.timeline.slice(1)])}return E},_a=()=>{const E=Wt(mt(l.saveDraft()));try{localStorage.setItem(`video-draft-${r.value}`,JSON.stringify(E))}catch{}return pe(E,"manual",!0),E},G=()=>typeof localStorage>"u"?null:{getItem:E=>localStorage.getItem(E),setItem:(E,F)=>{localStorage.setItem(E,F)},removeItem:E=>{localStorage.removeItem(E)},listKeys:E=>{const F=[];for(let ee=0;ee<localStorage.length;ee+=1){const ke=localStorage.key(ee);ke!=null&&ke.startsWith(E)&&F.push(ke)}return F}},q=async()=>{const E=G();if(E===null){oe.value=[];return}oe.value=await Wc(E)},pe=async(E,F,ee)=>{var pa,_o;const ke=G();if(ke===null)return;const Ue=new Date().toISOString(),Oe={projectId:fe.value,sourceMediaUuid:r.value,durationSeconds:M.value,editorVersion:((pa=E.metadata)==null?void 0:pa.editor_version)??"2.0.0",saveReason:F,now:Ue};((_o=E.metadata)==null?void 0:_o.title)!==void 0&&(Oe.title=E.metadata.title);const it=j2(Jm(E),Oe);await q2(ke,it);const Nt=await Wc(ke),Kt=G2(Nt,{maxCount:5,projectId:fe.value,now:Ue});await Hc(ke,Kt.removed),oe.value=[...Kt.retained],ee&&(De.value=Ue)},he=E=>E.snapshot.metadata.payloadKind==="project"?L2(E.snapshot.payload):E.snapshot.payload,Te=E=>{const F=he(E);l.loadRecipe(F),Re.value=(F.textOverlays??[]).map(Xe),lt.value=(F.audioTracks??[]).map(Ee),J.value=(F.captionTracks??[]).map(Ce),ut.value=(F.transitions??[]).map(ht);const ee=x(F);ee!==null&&(T.value=ee),ot()},He=E=>{const F=G();oe.value=oe.value.filter(ee=>!E.some(ke=>ke.key===ee.key)),F!==null&&Hc(F,E)},ot=()=>{C.value=mt(l.generateRecipe())};let Je=null;const Ze=()=>{Je&&clearTimeout(Je),Je=setTimeout(()=>{ot(),Je=null},200)};if(e.watch(()=>l.timelineClips.value,Ze,{deep:!0}),e.watch(()=>l.selectedClip.value,E=>{if(re.value||!E)return;const F=(E==null?void 0:E.filters)??[];s.setActiveFilters(F)},{immediate:!0}),e.watch(()=>s.activeFilters.value,E=>{l.setFilters(E),Ze()},{deep:!0}),e.watch(()=>Re.value,E=>{l.setTextOverlays(E.map(be)),Ze()},{deep:!0}),e.watch(()=>lt.value,E=>{const F=E.map(ye).filter(ee=>ee!==null);l.setAudioTracks(F),Ze()},{deep:!0}),e.watch(()=>J.value,E=>{l.setCaptionTracks(E.map(Ce)),Ze()},{deep:!0}),Re.value.length>0&&l.setTextOverlays(Re.value.map(be)),lt.value.length>0){const E=lt.value.map(ye).filter(F=>F!==null);l.setAudioTracks(E)}J.value.length>0&&l.setCaptionTracks(J.value.map(Ce)),e.watch(()=>l.playheadPosition.value,Ze),ot();const dt=e.ref(!0),ft=e.ref(null),Qe=e.ref(null);let ea=null;e.watch(Qe,E=>{ea!==null&&(clearTimeout(ea),ea=null),!(E===null||E==="")&&(ea=setTimeout(()=>{Qe.value=null},4e3))});const Ft=e.ref(null),Pa=e.computed(()=>l.tracks.value),Fa=e.computed(()=>l.mediaSources.value),co=e.computed(()=>{var E,F;return((E=l.selectedClip.value)==null?void 0:E.sourceRefId)??((F=Fa.value[0])==null?void 0:F.id)}),Da=e.computed(()=>Pa.value.filter(E=>E.locked!==!0&&E.type==="video")),on=e.computed(()=>Ft.value?Pa.value.find(E=>E.id===Ft.value)??null:null),Ua=e.computed(()=>!!l.selectedClip.value&&l.playheadPosition.value>0),ha=e.computed(()=>!!l.selectedClip.value),In=e.computed(()=>l.timelineClips.value.length>0&&l.hasChanges.value),uo=e.computed(()=>l.selectedClip.value??l.timelineClips.value[0]??null),Mn=E=>{const F=Number.isFinite(E)&&E>0?Math.round(E):0,ee=Math.floor(F/60),ke=F%60;return`${ee}:${ke.toString().padStart(2,"0")}`},mo=e.computed(()=>{const E=l.timelineClips.value.length,F=Pa.value.length,ee=E===1?"1 clip":`${E} clips`,ke=F===1?"1 track":`${F} tracks`;return`${ee} / ${ke} / ${Mn(M.value)}`});e.watch(()=>Pa.value.map(E=>`${E.id}:${E.locked===!0?"locked":"open"}`).join("|"),()=>{var E;Ft.value&&Da.value.some(F=>F.id===Ft.value)||(Ft.value=((E=Da.value[0])==null?void 0:E.id)??null)},{immediate:!0}),e.watch(()=>{var E;return(E=l.selectedClip.value)==null?void 0:E.trackId},E=>{E&&Da.value.some(F=>F.id===E)&&(Ft.value=E)},{immediate:!0});const hn=E=>{const F=Fa.value.find(ee=>ee.id===E);return F?F.filename??F.mediaUuid??F.url??F.id:"Asset"},Oa=n.assetUploader?VB({uploader:n.assetUploader,onReady:E=>{if(!E.mediaUrl&&!E.mediaUuid)return;const F={id:`imported-${E.assetId}`,type:E.mediaUuid?"media":"url",filename:E.filename,mimeType:E.mime,duration:E.durationSeconds??0,width:E.width??0,height:E.height??0};E.mediaUuid!==void 0&&(F.mediaUuid=E.mediaUuid),E.mediaUrl!==void 0&&(F.url=E.mediaUrl),l.registerMediaSource(F),Qe.value=`${E.filename} ready.`},onFailure:E=>{Qe.value=E.failureMessage??`Upload of ${E.filename} failed.`}}):null,Il=async E=>{if(!Oa){Qe.value="Asset import is not configured for this editor host.";return}for(const F of E){const ee=await Oa.importFile(F);ee.ok||(Qe.value=ee.message)}},Ho=E=>{var Ue;const F=l.appendMediaSourceToTimeline(E,Ft.value);if(!F.ok){ft.value=F.message;return}const ee=F.value;ee.trackId&&(Ft.value=ee.trackId),l.handleClipSelect(ee.id);const ke=((Ue=on.value)==null?void 0:Ue.name)??"timeline";ft.value=`${hn(E)} added to ${ke}.`,Ze()},Ml=E=>{if(!l.replaceSelectedClipSource(E)){ft.value="Select a clip before replacing its source.";return}ft.value=`${hn(E)} replaced the selected clip.`,Ze()},$l=E=>{const F=hn(E);if(!l.removeMediaSource(E)){ft.value="Remove timeline clips before deleting this asset.";return}ft.value=`${F} removed.`,Ze()},$n=(E="video")=>{const F=l.addTimelineTrack(E);Ft.value=F.id,ft.value=`${F.name} added. New assets will be placed on that track.`,Ze()},va=E=>{const F=E.target;F&&(Ft.value=F.value||null)},vn=E=>{var ee;l.handleClipSelect(E);const F=(ee=l.selectedClip.value)==null?void 0:ee.trackId;F&&Da.value.some(ke=>ke.id===F)&&(Ft.value=F)},Zo=(E,F,ee)=>{const ke=l.moveClip(E,F,ee);if(!ke.ok){Qe.value=ke.message;return}Ze()},Go=E=>{const F=l.deleteClip(E);if(!F.ok){Qe.value=F.message;return}Qe.value="Clip deleted.",Ze()},gn=(E,F)=>{F(E)&&Ze()},po=(E,F)=>{const ee=l.renameTimelineTrack(E,F);if(!ee.ok){Qe.value=ee.message;return}Qe.value=`Track renamed to "${F}".`,Ze()},rn=E=>{const F=l.deleteTimelineTrack(E);if(!F.ok){Qe.value=F.message;return}Ft.value===E&&(Ft.value=null),Qe.value="Track deleted.",Ze()},la=(E,F)=>{const ee=l.reorderTimelineTrack(E,F);if(!ee.ok){Qe.value=ee.message;return}Qe.value=`Track moved ${F}.`,Ze()},Ta=E=>{dt.value=E},ln=()=>{dt.value=!dt.value},Ki=E=>{const F=E.target;if(!F)return;const ee=Number(F.value);Number.isFinite(ee)&&l.setZoomLevel(ee)},ia=e.ref(!1),bn=e.ref(0),za=e.ref(!1),Ut=e.ref(null),sn=e.ref(null),fo=e.ref("preparing");let Fn=null,ja=!1;const Xo={preparing:"Preparing export...",rendering:"Rendering frames...","encoding-video":"Encoding video...","encoding-audio":"Encoding audio...",muxing:"Muxing output...",storing:"Storing export...",complete:"Export complete"},ho=E=>typeof E=="string"&&E in Xo,Wa=(E,F)=>{fo.value=E,Ut.value=typeof F=="string"&&F.trim()!==""?F.trim():Xo[E]},Ea=(E,F,ee)=>{const ke=Number.isFinite(E)?Math.max(0,Math.min(100,E)):0;bn.value=ke,F&&Wa(F,ee)},Ko=E=>{if(ho(E.phase))return E.phase;switch(E.status){case"pending":return"preparing";case"processing":return"rendering";case"completed":return"complete";default:return fo.value}},Ji=E=>typeof E.progress_message=="string"&&E.progress_message.trim()!==""?E.progress_message.trim():void 0,Dn=(E,F,ee={allowClient:!0})=>{if(!Number.isFinite(F)||F<=0||E.timeline.length===0)return{route:"unsupported",exportDuration:F,message:"Export unavailable: the recipe has no renderable duration."};if(n.maxDuration>0&&F>n.maxDuration)return{route:"unsupported",exportDuration:F,message:`Export unavailable: duration exceeds the ${n.maxDuration}s limit.`};if(ee.allowClient&&n.clientExportThreshold>0&&F<=n.clientExportThreshold)return{route:"client",exportDuration:F};const Ue=!!n.serverRenderEndpoint,Oe=r.value.startsWith("temp-");return Ue&&!Oe?{route:"server-render",exportDuration:F}:{route:"recipe-download",exportDuration:F,message:Oe?"Local media — downloaded recipe.json. Client-side PIXI export is unavailable on this device.":"No server render endpoint configured — downloaded recipe.json."}},vo=()=>new Cl(n.serverRenderEndpoint??"/api/v1"),Ha=()=>{Fn!==null&&(clearInterval(Fn),Fn=null)},qi=E=>{Ha();const F=vo();Fn=setInterval(async()=>{if(ja){Ha();return}try{const ee=await F.getJob(E),ke=Number(ee.progress??0);if(Ea(ke,Ko(ee),Ji(ee)),i("server-render-progress",bn.value),ee.status==="completed"||ee.status==="failed"||ee.status==="cancelled")if(Ha(),ia.value=!1,sn.value=null,ee.status==="completed"){Ea(100,"complete"),za.value=!0,Ut.value=null;const Ue=typeof ee.output_media_id=="string"?ee.output_media_id:void 0,Oe={id:E};Ue!==void 0&&(Oe.output_media_id=Ue),i("server-render-completed",Oe)}else{const Ue=ee.status==="cancelled"||typeof ee.error_message=="string"&&/cancel/i.test(ee.error_message),Oe=Ue?"Export canceled.":typeof ee.error_message=="string"&&ee.error_message.trim()!==""?ee.error_message:"Export failed";Ut.value=Oe,Ue||i("server-render-failed",Oe)}}catch(ee){Ha(),ia.value=!1,sn.value=null;const ke=ee instanceof Error?ee.message:"Failed to check export progress";Ut.value=ke,i("server-render-failed",ke)}},2e3)},go=E=>{const F=new Blob([JSON.stringify(E,null,2)],{type:"application/json"}),ee=URL.createObjectURL(F),ke=document.createElement("a");ke.href=ee,ke.download=`video-recipe-${Date.now()}.json`,ke.click(),setTimeout(()=>URL.revokeObjectURL(ee),100)},bo=()=>{Ha(),ja=!1,A.resetClientExport(),sn.value=null,Ut.value=null,za.value=!1,bn.value=0,fo.value="preparing"},yn=async E=>{Ea(0,"preparing");const ee=await vo().createRenderJob({source_media_uuid:r.value,recipe:E}),ke=typeof ee.id=="string"?ee.id:null;if(!ke)throw new Error("Export failed: missing job id");sn.value=ke,i("export-started",ke),i("server-render-started",ke),Ea(1,"rendering"),qi(ke)},Jo=async(E,F)=>{if(!await A.canExportClientSide())return null;const ee=await A.renderRecipeWithPixi(E,F,ke=>{ja||Ea(ke,"rendering")});return ja?(Ut.value="Export canceled.",Ea(0),i("video-exported",null),null):(l.clearHasChanges(),i("recipe-generated",E),i("video-exported",ee),Ea(100,"complete"),za.value=!0,ee)},An=async E=>{bo(),ia.value=!0,Wa("preparing");try{const F=mt(Wt(pt(l.generateRecipe(),E)));pe(F,"before-export",!1),i("recipe-generated",F);const ee=jc(F,M.value),ke=Dn(F,ee);if(ke.route==="unsupported"){ia.value=!1,Ut.value=ke.message??"Export unavailable.",i("server-render-failed",Ut.value);return}if(ke.route==="client"){const Oe=await Jo(F,E);if(Oe!==null){const it=URL.createObjectURL(Oe.file),Nt=document.createElement("a");Nt.href=it,Nt.download=`edited-video-${Date.now()}.mp4`,Nt.click(),setTimeout(()=>URL.revokeObjectURL(it),100),ia.value=!1;return}}const Ue=ke.route==="client"?Dn(F,ee,{allowClient:!1}):ke;if(Ue.route==="unsupported"){ia.value=!1,Ut.value=Ue.message??"Export unavailable.",i("server-render-failed",Ut.value);return}if(Ue.route==="recipe-download"){go(F),ia.value=!1,Ea(100,"complete"),za.value=!0,Ut.value=Ue.message??"Downloaded recipe.json.";return}await yn(F)}catch(F){const ee=mt(l.generateRecipe());go(ee);const ke=F instanceof Error?F.message:"Export failed";ia.value=!1,Ea(0),sn.value=null,Ut.value=ke,i("server-render-failed",ke)}},yo=async()=>{ja=!0,k.value=!1,A.cancelClientExport();const E=sn.value;if(Ha(),ia.value=!1,Ea(0),Ut.value="Export canceled.",sn.value=null,E&&n.serverRenderEndpoint)try{await vo().cancelJob(E)}catch{}},Rn=()=>{l.togglePlayback()},wo=()=>{l.resetChanges()},wn=()=>{const E=_a();i("draft-saved",E)},Yi=()=>{An()},qo=()=>{i("close")};a({saveDraft:async()=>{const E=_a();return i("draft-saved",E),E},exportForUpload:async E=>{bo();const F=mt(E??l.generateRecipe()),ee=Wt(F),ke=Array.isArray(ee.filters)&&ee.filters.length>0,Ue=yt(ee);if(!(l.hasChanges.value||ke||Ue))return l.clearHasChanges(),i("video-exported",null),null;const it=jc(ee,M.value),Nt=Dn(ee,it);if(Nt.route==="unsupported"){const Kt=Nt.message??"Export unavailable.";throw Ut.value=Kt,new Error(`Video export failed: ${Kt}`)}if(Nt.route==="server-render")return ia.value=!0,await yn(ee),null;ia.value=!0;try{if(Nt.route==="client"){const pa=await Jo(ee);if(pa!==null)return pa}const Kt=Nt.route==="client"?Dn(ee,it,{allowClient:!1}):Nt;if(Kt.route==="server-render")return await yn(ee),null;if(Kt.route==="unsupported"){const pa=Kt.message??"Export unavailable.";throw Ut.value=pa,new Error(`Video export failed: ${pa}`)}return Ut.value=Kt.message??"Export unavailable for upload.",i("video-exported",null),null}catch(Kt){if(ja)return Ut.value="Export canceled.",Ea(0),i("video-exported",null),null;const pa=Kt instanceof Error?Kt.message:"Local WebGL export failed.";throw Ut.value=pa,new Error(`Video export failed: ${pa}`)}finally{ia.value=!1}}});const ko=e.ref(!1),Yo=E=>{var Oe,it;const F=[...l.timelineClips.value].sort((Nt,Kt)=>Nt.timelineStart-Kt.timelineStart);if(F.length===0)return;const ee=l.selectedClip.value;if(!ee){l.handleClipSelect(((Oe=F[0])==null?void 0:Oe.id)??null);return}const ke=F.findIndex(Nt=>Nt.id===ee.id);if(ke===-1){l.handleClipSelect(((it=F[0])==null?void 0:it.id)??null);return}const Ue=E==="next"?F[Math.min(ke+1,F.length-1)]:F[Math.max(ke-1,0)];Ue&&l.handleClipSelect(Ue.id)},Qo=()=>{l.seekTo(Math.min(l.totalDuration.value,l.playheadPosition.value+1))},Qi=()=>{l.seekTo(Math.max(0,l.playheadPosition.value-1))};return vB({playPause:Rn,frameForward:l.frameForward,frameBackward:l.frameBackward,secondForward:Qo,secondBackward:Qi,skipToStart:l.skipToStart,skipToEnd:l.skipToEnd,prevClip:()=>Yo("prev"),nextClip:()=>Yo("next"),splitAtPlayhead:l.splitAtPlayhead,deleteSelected:()=>{const E=l.deleteSelectedClip();E.ok?Qe.value="Clip deleted.":Qe.value=E.message},rippleDeleteSelected:()=>{l.rippleDeleteSelectedClip()?Qe.value="Clip removed and gap closed.":Qe.value="Nothing to ripple-delete."},undo:l.undo,redo:l.redo,save:wn,exportNow:()=>{if(l.timelineClips.value.length===0){Qe.value="Add media to export.";return}Yi()},showShortcutsOverlay:()=>{ko.value=!0}}),e.onMounted(()=>{document.documentElement.setAttribute("data-video-editor-version","v2"),q()}),e.onBeforeUnmount(()=>{document.documentElement.getAttribute("data-video-editor-version")==="v2"&&document.documentElement.removeAttribute("data-video-editor-version")}),e.onUnmounted(()=>{Ha(),ja=!0,A.cancelClientExport(),Je&&(clearTimeout(Je),Je=null),W.value&&(W.value.destroy(),W.value=null),U.value=null,j.value=null}),(E,F)=>(e.openBlock(),e.createElementBlock(e.Fragment,null,[e.createVNode(RN,{"data-testid":"video-editor-v2"},{toolbar:e.withCtx(()=>[e.createElementVNode("div",BB,[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["v2-toolbar-btn",{"is-active":e.unref(l).isPlaying.value}]),"data-testid":"v2-btn-play","aria-label":e.unref(l).isPlaying.value?"Pause":"Play",onClick:Rn},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(l).isPlaying.value?e.unref(ad):e.unref(nd),"aria-hidden":"true"},null,8,["icon"])],10,IB),e.createElementVNode("button",{type:"button",class:"v2-toolbar-btn","data-testid":"v2-btn-reset","aria-label":"Reset all changes",disabled:!e.unref(l).hasChanges.value,onClick:wo},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(io),"aria-hidden":"true"},null,8,["icon"])],8,MB)]),F[20]||(F[20]=e.createElementVNode("div",{class:"v2-toolbar-title","aria-live":"polite"},[e.createElementVNode("span",{class:"v2-toolbar-badge"},"V2"),e.createTextVNode(" Video Editor ")],-1)),e.createElementVNode("div",$B,[e.createElementVNode("label",FB,[F[18]||(F[18]=e.createElementVNode("span",{class:"sr-only"},"Fit mode",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":F[0]||(F[0]=ee=>T.value=ee),"aria-label":"Fit mode","data-testid":"v2-select-fit-mode"},[...F[17]||(F[17]=[e.createElementVNode("option",{value:"contain"},"Contain",-1),e.createElementVNode("option",{value:"cover"},"Cover",-1),e.createElementVNode("option",{value:"none"},"None",-1)])],512),[[e.vModelSelect,T.value]])]),e.createElementVNode("button",{type:"button",class:"v2-toolbar-btn","data-testid":"v2-btn-save","aria-label":"Save draft",disabled:!e.unref(l).hasChanges.value,onClick:wn},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(el),"aria-hidden":"true"},null,8,["icon"]),F[19]||(F[19]=e.createElementVNode("span",{class:"v2-toolbar-btn-label"},"Save",-1))],8,DB),e.createElementVNode("button",{type:"button",class:"v2-toolbar-btn","data-testid":"v2-btn-export","aria-label":e.unref(l).timelineClips.value.length===0?"Export disabled — add media first":"Export",title:e.unref(l).timelineClips.value.length===0?"Add media to export":void 0,disabled:ia.value||e.unref(l).timelineClips.value.length===0,onClick:Yi},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Fo),"aria-hidden":"true"},null,8,["icon"])],8,AB),e.createElementVNode("button",{type:"button",class:"v2-toolbar-btn","data-testid":"v2-btn-close","aria-label":"Close editor",onClick:qo},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Yn),"aria-hidden":"true"},null,8,["icon"])])])]),assets:e.withCtx(()=>[e.createElementVNode("div",RB,[e.createVNode(JN,{sources:Fa.value,"selected-source-id":co.value,"uploads-enabled":!!E.assetUploader,onAdd:Ho,onReplaceSelected:Ml,onRemove:$l,onImportFiles:Il},null,8,["sources","selected-source-id","uploads-enabled"]),ft.value?(e.openBlock(),e.createElementBlock("p",LB,e.toDisplayString(ft.value),1)):e.createCommentVNode("",!0)])]),canvas:e.withCtx(()=>[e.createElementVNode("div",PB,[e.withDirectives(e.createVNode(ps,{ref_key:"pixiPreviewRef",ref:b,class:"v2-preview-child","aria-hidden":!w.value,source:S.value,"fallback-duration":M.value,filters:B.value,playhead:_.value,"is-playing":e.unref(l).isPlaying.value,"fit-mode":T.value,active:w.value,onPlayPause:Rn,onFrameUpdate:O,onDurationChange:Z},null,8,["aria-hidden","source","fallback-duration","filters","playhead","is-playing","fit-mode","active"]),[[e.vShow,w.value]]),e.withDirectives(e.createVNode(Ts,{class:"v2-preview-child","aria-hidden":!g.value,"media-uuid":r.value,recipe:C.value,media:P.value,"enable-engine":g.value&&D.value,"fit-mode":T.value,onTimeUpdate:K,onPlayStateChange:de,onDurationChange:Z,onEngineReady:Lt},null,8,["aria-hidden","media-uuid","recipe","media","enable-engine","fit-mode"]),[[e.vShow,g.value]])])]),timeline:e.withCtx(({isMobile:ee})=>{var ke,Ue;return[e.createElementVNode("div",{class:e.normalizeClass(["v2-timeline",{"is-mobile":!!ee}])},[e.createElementVNode("div",UB,[e.createElementVNode("div",OB,[F[21]||(F[21]=e.createElementVNode("span",{class:"v2-timeline-title","data-testid":"v2-timeline-title"},"Timeline",-1)),e.createElementVNode("span",zB,e.toDisplayString(mo.value),1)]),e.createElementVNode("label",jB,[F[22]||(F[22]=e.createElementVNode("span",null,"Zoom",-1)),e.createElementVNode("input",{type:"range",min:"10",max:"600",value:e.unref(l).zoomLevel.value,"aria-label":"Timeline zoom","data-testid":"v2-timeline-zoom",onInput:Ki},null,40,WB),e.createElementVNode("span",HB,e.toDisplayString(Math.round(e.unref(l).zoomLevel.value))+" px/s",1)]),ee?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",ZB,[e.createElementVNode("button",{type:"button",class:"v2-toolbar-btn v2-toolbar-btn--ghost","data-testid":"v2-btn-add-track",onClick:F[1]||(F[1]=Oe=>$n("video"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(kr)},null,8,["icon"]),F[23]||(F[23]=e.createTextVNode(" Add Track ",-1))]),Da.value.length>0?(e.openBlock(),e.createElementBlock("label",GB,[F[24]||(F[24]=e.createElementVNode("span",null,"Place clips in",-1)),e.createElementVNode("select",{value:Ft.value??"","data-testid":"v2-select-target-track","aria-label":"Target track for added assets",onChange:va},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Da.value,Oe=>(e.openBlock(),e.createElementBlock("option",{key:Oe.id,value:Oe.id},e.toDisplayString(Oe.name),9,KB))),128))],40,XB)])):e.createCommentVNode("",!0)])),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["v2-toolbar-btn v2-toolbar-btn--ghost",{"is-active":dt.value}]),"data-testid":"v2-btn-snap-toggle","aria-pressed":dt.value?"true":"false",onClick:ln},e.toDisplayString(dt.value?"Snap On":"Snap Off"),11,JB)]),Qe.value?(e.openBlock(),e.createElementBlock("p",qB,e.toDisplayString(Qe.value),1)):e.createCommentVNode("",!0),e.unref(l).timelineClips.value.length===0?(e.openBlock(),e.createElementBlock("div",YB,[...F[25]||(F[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(Bs,{key:2,playhead:e.unref(l).playheadPosition.value,clips:e.unref(l).timelineClips.value,tracks:Pa.value,"selected-clip-id":((ke=e.unref(l).selectedClip.value)==null?void 0:ke.id)??((Ue=e.unref(l).timelineClips.value[0])==null?void 0:Ue.id)??null,duration:M.value,fps:e.unref(l).fps.value,"is-mobile":!!ee,"zoom-level":e.unref(l).zoomLevel.value,"snap-enabled":dt.value,sensitivity:.25,"onUpdate:playhead":F[2]||(F[2]=Oe=>e.unref(l).seekTo(Oe)),onTrim:F[3]||(F[3]=(Oe,it,Nt)=>e.unref(l).handleTrim(Oe,it,Nt)),onSplit:F[4]||(F[4]=Oe=>e.unref(l).handleSplit(Oe)),onClipSelect:vn,onClipDelete:Go,onClipMove:Zo,onSnapStateChange:Ta,onToggleLock:F[5]||(F[5]=Oe=>gn(Oe,e.unref(l).toggleTrackLock)),onToggleHidden:F[6]||(F[6]=Oe=>gn(Oe,e.unref(l).toggleTrackHidden)),onToggleMuted:F[7]||(F[7]=Oe=>gn(Oe,e.unref(l).toggleTrackMuted)),onToggleSolo:F[8]||(F[8]=Oe=>gn(Oe,e.unref(l).toggleTrackSolo)),onRenameTrack:po,onDeleteTrack:rn,onReorderTrack:la},null,8,["playhead","clips","tracks","selected-clip-id","duration","fps","is-mobile","zoom-level","snap-enabled"])),e.createVNode(Is,{"selected-clip":e.unref(l).selectedClip.value,"can-split":Ua.value,"can-delete":ha.value,"can-undo":e.unref(l).canUndo.value,"can-redo":e.unref(l).canRedo.value,"is-playing":e.unref(l).isPlaying.value,"zoom-level":e.unref(l).zoomLevel.value,"playback-speed":e.unref(l).playbackSpeed.value,"is-mobile":!!ee,"show-add-track":!!ee,onSplit:e.unref(l).splitAtPlayhead,onDelete:e.unref(l).deleteSelectedClip,onAddTrack:F[9]||(F[9]=Oe=>$n("video")),onDuplicate:e.unref(l).duplicateSelectedClip,onUndo:e.unref(l).undo,onRedo:e.unref(l).redo,onZoomIn:e.unref(l).zoomIn,onZoomOut:e.unref(l).zoomOut,onZoomChange:e.unref(l).setZoomLevel,onFitToWindow:e.unref(l).fitToWindow,onPlayPause:Rn,onFrameForward:e.unref(l).frameForward,onFrameBackward:e.unref(l).frameBackward,onSkipToStart:e.unref(l).skipToStart,onSkipToEnd:e.unref(l).skipToEnd,onSpeedChange:e.unref(l).setPlaybackSpeed},null,8,["selected-clip","can-split","can-delete","can-undo","can-redo","is-playing","zoom-level","playback-speed","is-mobile","show-add-track","onSplit","onDelete","onDuplicate","onUndo","onRedo","onZoomIn","onZoomOut","onZoomChange","onFitToWindow","onFrameForward","onFrameBackward","onSkipToStart","onSkipToEnd","onSpeedChange"])],2)]}),inspector:e.withCtx(()=>[Ae.value.length>0?(e.openBlock(),e.createBlock(bu,{key:0,class:"v2-draft-recovery",records:Ae.value,surface:"desktop","project-id":fe.value,"saved-at":De.value,onRestore:Te,onDismiss:He},null,8,["records","project-id","saved-at"])):e.createCommentVNode("",!0),e.createVNode(IT,{"active-tab":d.value,"onUpdate:activeTab":F[10]||(F[10]=ee=>d.value=ee),tabs:p.value},{filters:e.withCtx(()=>[e.createVNode(Ms,{filters:Ne.value,"active-filters":ce.value,"thumbnail-url":le.value,onApplyFilter:zt,onRemoveFilter:Ot,onUpdateParam:jt,onPreviewFilter:oa},null,8,["filters","active-filters","thumbnail-url"])]),adjustments:e.withCtx(()=>[e.unref(s).selectedFilter.value?(e.openBlock(),e.createBlock($s,{key:0,filter:e.unref(s).selectedFilter.value,"current-frame":e.unref(l).currentFrame.value,onUpdateParams:Q},null,8,["filter","current-frame"])):(e.openBlock(),e.createElementBlock("div",QB,[...F[26]||(F[26]=[e.createElementVNode("p",null,"Select a filter from the Filters tab to adjust its parameters.",-1)])])),e.createVNode(yu,{class:"v2-keyframe-panel",duration:st.value,target:"all","device-class":"desktop",onApplyPreset:Mt},null,8,["duration"])]),text:e.withCtx(()=>[e.createVNode(Ds,{overlays:Re.value,onAddOverlay:ge,onUpdateOverlay:me,onRemoveOverlay:se},null,8,["overlays"]),e.createVNode(gu,{class:"v2-caption-panel","caption-track":Ye.value,layout:"desktop",onImport:Fe,"onUpdate:captionTrack":It,onClear:At},null,8,["caption-track"])]),transitions:e.withCtx(()=>[e.createVNode(As,{"selected-clips":Vt.value,"applied-transitions":ut.value,onApplyTransition:Ve,onRemoveTransition:Pe,onPreviewTransition:et},null,8,["selected-clips","applied-transitions"])]),audio:e.withCtx(()=>[e.createVNode(Rs,{"audio-layers":lt.value,"master-volume":Ct.value,onAddTrack:gt,onUpdateTrack:Tt,onRemoveTrack:xt,onUpdateVolume:_t,onToggleMute:Xt,onUpdateMasterVolume:X},null,8,["audio-layers","master-volume"]),e.createVNode(vu,{class:"v2-audio-mixer",state:Bt.value,"device-class":"desktop",onUpdate:ne},null,8,["state"])]),export:e.withCtx(()=>[e.createVNode(Fs,{"can-export":In.value,"is-exporting":ia.value,"export-progress":bn.value,onExport:An,onCancelExport:yo,onSaveDraft:wn,onReset:wo},null,8,["can-export","is-exporting","export-progress"]),za.value?(e.openBlock(),e.createElementBlock("div",e4," Export complete ")):e.createCommentVNode("",!0),Ut.value&&!za.value?(e.openBlock(),e.createElementBlock("div",t4,e.toDisplayString(Ut.value),1)):e.createCommentVNode("",!0)]),_:1},8,["active-tab","tabs"])]),drawer:e.withCtx(()=>[e.createVNode(pB,{ref_key:"mobileDrawerRef",ref:u,"initial-snap":"half","aria-label":"Video editor controls"},{default:e.withCtx(()=>[Ae.value.length>0?(e.openBlock(),e.createBlock(bu,{key:0,class:"v2-draft-recovery",records:Ae.value,surface:"mobile","project-id":fe.value,"saved-at":De.value,onRestore:Te,onDismiss:He},null,8,["records","project-id","saved-at"])):e.createCommentVNode("",!0),e.createVNode(aB,{"selected-clip":uo.value,onOpenActions:F[11]||(F[11]=ee=>c.value="trim")},null,8,["selected-clip"]),e.createVNode(lB,{modelValue:c.value,"onUpdate:modelValue":F[12]||(F[12]=ee=>c.value=ee)},null,8,["modelValue"]),c.value==="look"?(e.openBlock(),e.createElementBlock("section",a4,[e.createElementVNode("div",n4,[e.createVNode(Ms,{filters:Ne.value,"active-filters":ce.value,"thumbnail-url":le.value,onApplyFilter:zt,onRemoveFilter:Ot,onUpdateParam:jt,onPreviewFilter:oa},null,8,["filters","active-filters","thumbnail-url"])]),e.createElementVNode("div",o4,[e.unref(s).selectedFilter.value?(e.openBlock(),e.createBlock($s,{key:0,filter:e.unref(s).selectedFilter.value,"current-frame":e.unref(l).currentFrame.value,onUpdateParams:Q},null,8,["filter","current-frame"])):(e.openBlock(),e.createElementBlock("div",i4,[...F[27]||(F[27]=[e.createElementVNode("p",null,"Select a filter from the Filters tab to adjust its parameters.",-1)])]))])])):c.value==="trim"?(e.openBlock(),e.createElementBlock("section",r4,[e.createVNode(Is,{"selected-clip":e.unref(l).selectedClip.value,"can-split":Ua.value,"can-delete":ha.value,"can-undo":e.unref(l).canUndo.value,"can-redo":e.unref(l).canRedo.value,"is-playing":e.unref(l).isPlaying.value,"zoom-level":e.unref(l).zoomLevel.value,"playback-speed":e.unref(l).playbackSpeed.value,"is-mobile":"","show-add-track":"",onSplit:e.unref(l).splitAtPlayhead,onDelete:e.unref(l).deleteSelectedClip,onAddTrack:F[13]||(F[13]=ee=>$n("video")),onDuplicate:e.unref(l).duplicateSelectedClip,onUndo:e.unref(l).undo,onRedo:e.unref(l).redo,onZoomIn:e.unref(l).zoomIn,onZoomOut:e.unref(l).zoomOut,onZoomChange:e.unref(l).setZoomLevel,onFitToWindow:e.unref(l).fitToWindow,onPlayPause:Rn,onFrameForward:e.unref(l).frameForward,onFrameBackward:e.unref(l).frameBackward,onSkipToStart:e.unref(l).skipToStart,onSkipToEnd:e.unref(l).skipToEnd,onSpeedChange:e.unref(l).setPlaybackSpeed},null,8,["selected-clip","can-split","can-delete","can-undo","can-redo","is-playing","zoom-level","playback-speed","onSplit","onDelete","onDuplicate","onUndo","onRedo","onZoomIn","onZoomOut","onZoomChange","onFitToWindow","onFrameForward","onFrameBackward","onSkipToStart","onSkipToEnd","onSpeedChange"])])):c.value==="text"?(e.openBlock(),e.createElementBlock("section",l4,[e.createVNode(Ds,{overlays:Re.value,onAddOverlay:ge,onUpdateOverlay:me,onRemoveOverlay:se},null,8,["overlays"]),e.createVNode(gu,{"caption-track":Ye.value,layout:"mobile",onImport:Fe,"onUpdate:captionTrack":It,onClear:At},null,8,["caption-track"])])):c.value==="audio"?(e.openBlock(),e.createElementBlock("section",s4,[e.createVNode(Rs,{"audio-layers":lt.value,"master-volume":Ct.value,onAddTrack:gt,onUpdateTrack:Tt,onRemoveTrack:xt,onUpdateVolume:_t,onToggleMute:Xt,onUpdateMasterVolume:X},null,8,["audio-layers","master-volume"]),e.createVNode(vu,{state:Bt.value,"device-class":"mobile",onUpdate:ne},null,8,["state"])])):c.value==="export"?(e.openBlock(),e.createElementBlock("section",d4,[e.createVNode(Fs,{"can-export":In.value,"is-exporting":ia.value,"export-progress":bn.value,"is-mobile":"",onExport:An,onCancelExport:yo,onSaveDraft:wn,onReset:wo},null,8,["can-export","is-exporting","export-progress"]),za.value?(e.openBlock(),e.createElementBlock("div",c4,"Export complete")):e.createCommentVNode("",!0),Ut.value&&!za.value?(e.openBlock(),e.createElementBlock("div",u4,e.toDisplayString(Ut.value),1)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("section",m4,[e.createElementVNode("div",p4,[e.createElementVNode("label",f4,[F[29]||(F[29]=e.createElementVNode("span",null,"Fit",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":F[14]||(F[14]=ee=>T.value=ee),"aria-label":"Mobile fit mode"},[...F[28]||(F[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,T.value]])]),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["v2-mobile-secondary-button",{"is-active":dt.value}]),"aria-pressed":dt.value?"true":"false","data-testid":"v2-mobile-btn-snap-toggle",onClick:ln},e.toDisplayString(dt.value?"Snap On":"Snap Off"),11,h4),e.createElementVNode("button",{type:"button",class:"v2-mobile-secondary-button","data-testid":"v2-mobile-btn-reset",disabled:!e.unref(l).hasChanges.value,onClick:wo}," Reset ",8,v4),e.createElementVNode("button",{type:"button",class:"v2-mobile-secondary-button","data-testid":"v2-mobile-btn-save",disabled:!e.unref(l).hasChanges.value,onClick:wn}," Save ",8,g4)]),v.value?(e.openBlock(),e.createElementBlock("details",b4,[F[30]||(F[30]=e.createElementVNode("summary",null,"Transitions",-1)),e.createVNode(As,{"selected-clips":Vt.value,"applied-transitions":ut.value,onApplyTransition:Ve,onRemoveTransition:Pe,onPreviewTransition:et},null,8,["selected-clips","applied-transitions"])])):e.createCommentVNode("",!0),e.createElementVNode("details",y4,[F[31]||(F[31]=e.createElementVNode("summary",null,"Keyframe presets",-1)),e.createVNode(yu,{duration:st.value,target:"all","device-class":"mobile",onApplyPreset:Mt},null,8,["duration"])])]))]),_:1},512)]),_:1}),ko.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"v2-shortcuts-overlay",role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts","data-testid":"v2-shortcuts-overlay",onClick:F[16]||(F[16]=e.withModifiers(ee=>ko.value=!1,["self"]))},[e.createElementVNode("div",w4,[e.createElementVNode("div",k4,[F[32]||(F[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:F[15]||(F[15]=ee=>ko.value=!1)},"×")]),F[33]||(F[33]=e.createStaticVNode('<dl class="v2-shortcuts-overlay__list" data-v-aa4426a6><div data-v-aa4426a6><dt data-v-aa4426a6>Space</dt><dd data-v-aa4426a6>Play / pause</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>← / →</dt><dd data-v-aa4426a6>Frame back / forward</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>Shift + ← / →</dt><dd data-v-aa4426a6>1 second back / forward</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>Home / End</dt><dd data-v-aa4426a6>Skip to start / end</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>[ / ]</dt><dd data-v-aa4426a6>Previous / next clip</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>S</dt><dd data-v-aa4426a6>Split at playhead</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>Delete</dt><dd data-v-aa4426a6>Delete selected clip</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>Shift + Delete</dt><dd data-v-aa4426a6>Ripple delete (closes the gap)</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>Cmd / Ctrl + Z</dt><dd data-v-aa4426a6>Undo</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>Cmd / Ctrl + Shift + Z</dt><dd data-v-aa4426a6>Redo</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>Cmd / Ctrl + S</dt><dd data-v-aa4426a6>Save draft</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>Cmd / Ctrl + E</dt><dd data-v-aa4426a6>Export</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>?</dt><dd data-v-aa4426a6>This overlay</dd></div></dl>',1))])])):e.createCommentVNode("",!0)],64))}}),E4=$e(_4,[["__scopeId","data-v-aa4426a6"]]),Ra=o=>o===null||typeof o!="object"||Array.isArray(o)?null:o,wt=o=>{if(typeof o=="number"&&Number.isFinite(o))return o;if(typeof o=="string"){const a=Number(o);return Number.isFinite(a)?a:null}return null},S4=(o,a)=>{if(a===null)return;const t=Ra(o.source)??{},n=wt(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=Ra(r[0]);if(d!==null){const c=wt(d.sourceIn)??0,u=wt(d.sourceOut)??wt(d.end)??wt(d.timelineEnd);if(c===0&&u!==null&&u>0&&u<=1){d.sourceOut=a;const p=wt(d.end);p!==null&&p>0&&p<=1&&(d.end=a);const f=wt(d.timelineEnd);f!==null&&f>0&&f<=1&&(d.timelineEnd=a)}}}const l=wt(o.trimEnd)??wt(o.trim_end);l!==null&&l>0&&l<=1&&(o.trimEnd=a);const s=Ra(o.trim);if(s!==null){const d=wt(s.end);d!==null&&d>0&&d<=1&&(s.end=a,o.trim=s)}},C4=(o,a)=>{if(!o)return!1;const t=Ra(o);if(t===null)return!1;const n=Ra(t.trim),i=Ra(t.source),l=wt(i==null?void 0:i.duration)??a,s=Array.isArray(o.filters)&&o.filters.length>0;let d=!1;if(Array.isArray(o.timeline)&&o.timeline.length===1){const f=o.timeline[0];f&&Array.isArray(f.filters)&&f.filters.length>0&&(d=!0)}let c=!1;const u=wt(t.trimStart)??wt(t.trim_start)??wt(n==null?void 0:n.start),m=wt(t.trimEnd)??wt(t.trim_end)??wt(n==null?void 0:n.end);if(u!==null&&u>0&&(c=!0),m!==null&&l!==void 0&&m<l&&(c=!0),!c&&Array.isArray(o.timeline)&&o.timeline.length===1){const f=o.timeline[0];if(f){const h=wt(f.sourceIn),v=wt(f.sourceOut);h!==null&&h>0&&(c=!0),v!==null&&l!==void 0&&v<l&&(c=!0)}}let p=!1;if(Array.isArray(o.timeline)&&o.timeline.length===1){const f=o.timeline[0];if(f){const h=wt(f.speed);p=h!==null&&h!==1}}return s||d||c||p},af=o=>{if(!o)return!1;const a=Ra(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 p,f;const t=JSON.parse(JSON.stringify(o)),n=Array.isArray(t.timeline)?t.timeline:[],i=n.length>0?Ra(n[0]):null,r=Array.isArray(i==null?void 0:i.filters)?i.filters:[],l=Array.isArray(t.filters)?t.filters:[];if(l.length>0?t.filters=l:t.filters=r,n.length===1&&i!==null){const h=wt(i.sourceIn),v=wt(i.sourceOut);h!==null&&t.trimStart===void 0&&(t.trimStart=h),v!==null&&t.trimEnd===void 0&&(t.trimEnd=v)}const s=Ra(t.trim);if(t.trimStart===void 0){const h=wt(s==null?void 0:s.start);h!==null&&(t.trimStart=h)}if(t.trimEnd===void 0){const h=wt(s==null?void 0:s.end);h!==null&&(t.trimEnd=h)}const d=Ra(t.source),c=wt(t.width)??wt(d==null?void 0:d.original_width)??wt((p=a.exportMeta)==null?void 0:p.width);c!==null&&(t.width=c);const u=wt(t.height)??wt(d==null?void 0:d.original_height)??wt((f=a.exportMeta)==null?void 0:f.height);u!==null&&(t.height=u);const m=Ra(t.output);return t.fps=wt(t.fps)??wt(m==null?void 0:m.fps)??30,S4(t,a.mediaDuration??null),t},N4={key:0},V4=["data-testid"],T4={class:"ve-mobile-header"},B4=["data-testid"],I4={class:"ve-mobile-title"},M4=["data-testid","disabled"],$4={key:1,class:"ve-mobile-spacer","aria-hidden":"true"},F4={class:"ve-body"},D4=["data-testid"],A4=["aria-label"],R4={class:"ve-header"},L4={class:"ve-title"},P4=["data-testid"],U4={class:"ve-body"},O4={class:"ve-footer"},z4=["data-testid"],j4=["data-testid","disabled"],W4=e.defineComponent({__name:"VideoEditorDialog",props:{open:{type:Boolean,default:!0},mediaUuid:{},initialRecipe:{},media:{},showThumbnailPicker:{type:Boolean,default:!1},title:{default:"Edit Video"},workflowMode:{default:"full"},featureFlags:{},clientExportThreshold:{default:20},maxDuration:{default:300},serverRenderEndpoint:{default:null},saveImmediate:{type:Boolean,default:!0},confirmText:{default:"Save"},savingText:{default:"Rendering..."},closeText:{default:"Cancel"},dataTestId:{default:"video-editor-dialog"},editorVersion:{}},emits:["update:open","close","recipe-generated","export-started","draft-saved","thumbnail-selected","video-exported","save-recipe","save-started","save-complete","save-error"],setup(o,{expose:a,emit:t}){const n=o,i=t,r=e.computed(()=>n.dataTestId),l=e.computed(()=>n.open),s=e.computed(()=>n.saveImmediate===!1),d=e.computed(()=>n.closeText),c=e.computed(()=>m.value?n.savingText:n.confirmText),u=e.ref(typeof window<"u"?window.innerWidth<768:!1),m=e.ref(!1),p=e.ref(!1),f=e.ref(null),h=`temp-${Date.now()}`,v=e.computed(()=>{var M;const z=(M=n.featureFlags)==null?void 0:M.export;return typeof z=="boolean"?z:n.workflowMode==="full"}),k=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),M=z.get("editor")??z.get("video-editor");if(M==="v1")return"v1";if(M==="v2")return"v2"}catch{}return"v2"}),y=e.computed(()=>k.value==="v2"?E4:Qp),w=e.computed(()=>typeof n.mediaUuid=="string"&&n.mediaUuid.trim()!==""?n.mediaUuid.trim():n.media&&n.media.uuid.trim()!==""?n.media.uuid.trim():h),g=e.computed(()=>{const 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}),b=()=>{u.value=window.innerWidth<768};e.onMounted(()=>{window.addEventListener("resize",b)}),e.onUnmounted(()=>{window.removeEventListener("resize",b)}),e.onErrorCaptured(()=>(p.value=!0,!1));const R=z=>{const M=Array.isArray(z.timeline)?z.timeline:[];if(M.length===0)return 0;let Z=0;for(const O of M){const K=Number(O.sourceIn),de=Number(O.sourceOut),Ne=Number(O.speed??1),ce=Number.isFinite(Ne)&&Ne>0?Ne:1;if(Number.isFinite(K)&&Number.isFinite(de)&&de>K){Z+=(de-K)/ce;continue}const le=Number(O.timelineStart),W=Number(O.timelineEnd);Number.isFinite(le)&&Number.isFinite(W)&&W>le&&(Z+=W-le)}return Z},V=(z,M,Z)=>{let O=null;const K=new Promise((de,Ne)=>{O=setTimeout(()=>Ne(new Error(`${Z} timed out after ${M}ms`)),M)});return Promise.race([z,K]).finally(()=>{O!==null&&clearTimeout(O)})},I=()=>{var K;const Z=(K=n.media)==null?void 0:K.duration;if(typeof Z!="number"||!Number.isFinite(Z)||Z<=0)return 12e3;const O=Math.round(Z*1e3);return Math.min(45e3,Math.max(12e3,O))},x=()=>{i("close"),i("update:open",!1)},T=()=>{m.value=!1,x()},$=z=>{i("recipe-generated",z)},S=z=>{i("export-started",z),i("save-started",z)},B=z=>{i("video-exported",z)},_=z=>{i("thumbnail-selected",z)},A=(z,M,Z)=>{i("save-recipe",z);const O={recipe:z,exportPayload:M};Z!==void 0&&(O.toastDescription=Z),i("save-complete",O),x()},P=z=>{m.value||(i("draft-saved",z),A(z,null))},D=async()=>{var z;if(!m.value){if(p.value||f.value===null){i("save-error",{code:"save-failed",message:"Unable to save video edits. Please try again."}),x();return}m.value=!0;try{const M=await V(f.value.saveDraft(),I(),"saveDraft");let Z=null,O=!1,K;const de=R(M),Ne=de>0?de:((z=n.media)==null?void 0:z.duration)??0;if(v.value&&Ne>0&&Ne<=n.clientExportThreshold&&typeof f.value.exportForUpload=="function"){O=!0;const le=Math.min(9e4,Math.max(15e3,n.clientExportThreshold*2e3));try{Z=await V(f.value.exportForUpload(M),le,"exportForUpload")}catch{Z=null}}if(af(M)&&Z===null){i("save-error",{code:"unsupported-client-export-required",message:"These edits require in-browser export. Shorten the clip or remove text overlays, transitions, or extra clips and try again."});return}O&&Z===null&&(K="Video edits saved. Final render will happen when you share."),A(M,Z,K)}catch{i("save-error",{code:"save-failed",message:"Unable to save video edits. Please try again."}),x()}finally{m.value=!1}}};return a({saveDraft:D}),(z,M)=>(e.openBlock(),e.createBlock(e.Teleport,{to:"body"},[l.value?(e.openBlock(),e.createElementBlock("div",N4,[u.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"ve-fullscreen","data-testid":r.value},[e.createElementVNode("header",T4,[e.createElementVNode("button",{class:"ve-mobile-action",type:"button","data-testid":`${r.value}-close-button`,onClick:T},e.toDisplayString(d.value),9,B4),e.createElementVNode("h2",I4,e.toDisplayString(z.title),1),s.value?(e.openBlock(),e.createElementBlock("button",{key:0,class:"ve-mobile-action ve-mobile-action--primary",type:"button","data-testid":`${r.value}-confirm-button`,disabled:m.value,onClick:D},e.toDisplayString(c.value),9,M4)):(e.openBlock(),e.createElementBlock("span",$4))]),e.createElementVNode("section",F4,[(e.openBlock(),e.createBlock(e.resolveDynamicComponent(y.value),e.mergeProps({ref_key:"videoEditorRef",ref:f,"media-uuid":w.value,"data-editor-version":k.value},g.value,{onClose:T,onDraftSaved:P,onExportStarted:S,onRecipeGenerated:$,onThumbnailSelected:_,onVideoExported:B}),null,16,["media-uuid","data-editor-version"]))])],8,V4)):(e.openBlock(),e.createElementBlock("div",{key:1,class:"ve-overlay","data-testid":r.value,onClick:e.withModifiers(T,["self"])},[e.createElementVNode("div",{class:"ve-dialog",role:"dialog","aria-label":z.title,"aria-modal":"true"},[e.createElementVNode("header",R4,[e.createElementVNode("h2",L4,e.toDisplayString(z.title),1),e.createElementVNode("button",{class:"ve-close",type:"button","data-testid":`${r.value}-close-button`,"aria-label":"Close",onClick:T}," ✕ ",8,P4)]),e.createElementVNode("section",U4,[(e.openBlock(),e.createBlock(e.resolveDynamicComponent(y.value),e.mergeProps({ref_key:"videoEditorRef",ref:f,"media-uuid":w.value,"data-editor-version":k.value},g.value,{onClose:T,onDraftSaved:P,onExportStarted:S,onRecipeGenerated:$,onThumbnailSelected:_,onVideoExported:B}),null,16,["media-uuid","data-editor-version"]))]),e.createElementVNode("footer",O4,[e.renderSlot(z.$slots,"footer",{close:T,isSaving:m.value,save:D},()=>[e.createElementVNode("button",{class:"ve-btn",type:"button","data-testid":`${r.value}-cancel-button`,onClick:T},e.toDisplayString(d.value),9,z4),s.value?(e.openBlock(),e.createElementBlock("button",{key:0,class:"ve-btn ve-btn--primary",type:"button","data-testid":`${r.value}-confirm-button`,disabled:m.value,onClick:D},e.toDisplayString(c.value),9,j4)):e.createCommentVNode("",!0)],!0)])],8,A4)],8,D4))])):e.createCommentVNode("",!0)]))}}),H4=$e(W4,[["__scopeId","data-v-3cc6e078"]]),Z4={class:"video-editor-modal"},G4={class:"video-preview-container"},X4=["src"],K4={class:"video-overlay-controls"},J4=["aria-label"],q4={class:"time-display"},Y4={class:"timeline-container"},Q4={class:"clip-name"},eI={class:"timeline-time-labels"},tI={class:"tool-tabs"},aI=["onClick"],nI={class:"tool-panel"},oI={key:0,class:"trim-panel"},iI={class:"trim-controls"},rI={key:1,class:"filters-panel"},lI={class:"filter-grid"},sI=["onClick"],dI={key:2,class:"text-panel"},cI={key:3,class:"transitions-panel"},uI={class:"transition-grid"},mI=["onClick"],pI={class:"action-buttons"},fI=e.defineComponent({__name:"VideoEditorSimple",props:{media:{}},emits:["save","cancel"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(),r=e.ref(""),l=e.ref(!1),s=e.ref(0),d=e.ref(0),c=e.ref("video-1"),u=e.ref(0),m=e.ref(0),p=e.ref(null),f=e.ref("trim"),h=e.ref(null),v=e.ref(""),k=[{id:"trim",label:"Trim",icon:Fr},{id:"filters",label:"Filters",icon:iv},{id:"text",label:"Text",icon:dm},{id:"transitions",label:"Transitions",icon:pv}],y=[{id:"none",name:"None"},{id:"grayscale",name:"Grayscale"},{id:"sepia",name:"Sepia"},{id:"blur",name:"Blur"},{id:"brightness",name:"Brightness"},{id:"contrast",name:"Contrast"}],w=[{id:"fade",name:"Fade"},{id:"slide",name:"Slide"},{id:"zoom",name:"Zoom"},{id:"wipe",name:"Wipe"}],g=e.ref();e.onMounted(()=>{var M,Z;(M=t.media)!=null&&M.url?r.value=t.media.url:(Z=t.media)!=null&&Z.file&&(r.value=URL.createObjectURL(t.media.file))}),e.onUnmounted(()=>{var M;(M=t.media)!=null&&M.file&&r.value&&URL.revokeObjectURL(r.value)});function b(){i.value&&(d.value=i.value.duration,m.value=d.value)}function R(){i.value&&(s.value=i.value.currentTime)}function V(){l.value=!1}function I(){i.value&&(l.value?(i.value.pause(),l.value=!1):(i.value.play(),l.value=!0))}function x(M){if(!M||isNaN(M))return"00:00";const Z=Math.floor(M/60),O=Math.floor(M%60);return`${Z.toString().padStart(2,"0")}:${O.toString().padStart(2,"0")}`}function T(M){if(!i.value||!g.value)return;const Z=g.value.getBoundingClientRect(),de=(M.clientX-Z.left)/Z.width*d.value;i.value.currentTime=Math.max(0,Math.min(de,d.value))}function $(){u.value=s.value}function S(){m.value=s.value}function B(){u.value=0,m.value=d.value}function _(M){p.value=M;const Z=K=>{if(!p.value||!g.value)return;const de=g.value.getBoundingClientRect(),le=(K.clientX-de.left)/de.width*d.value;p.value==="start"?u.value=Math.max(0,Math.min(le,m.value-1)):m.value=Math.max(u.value+1,Math.min(le,d.value))},O=()=>{p.value=null,document.removeEventListener("mousemove",Z),document.removeEventListener("mouseup",O)};document.addEventListener("mousemove",Z),document.addEventListener("mouseup",O)}function A(M){if(h.value=M,!i.value)return;const Z={none:"none",grayscale:"grayscale(100%)",sepia:"sepia(100%)",blur:"blur(5px)",brightness:"brightness(150%)",contrast:"contrast(150%)"};i.value.style.filter=Z[M]||"none"}function P(){}function D(M){}function z(){const M={timeline:[{id:c.value,url:r.value,startTime:0,endTime:d.value,sourceIn:u.value,sourceOut:m.value,track:0}],filters:h.value?[{type:h.value}]:[],textOverlays:v.value?[{content:v.value}]:[],duration:m.value-u.value};n("save",M)}return(M,Z)=>(e.openBlock(),e.createElementBlock("div",Z4,[e.createElementVNode("div",G4,[e.createElementVNode("video",{ref_key:"videoElement",ref:i,class:"video-preview",src:r.value,onLoadedmetadata:b,onTimeupdate:R,onEnded:V,controls:""},null,40,X4),e.createElementVNode("div",K4,[e.createElementVNode("button",{class:"play-pause-btn",onClick:I,"aria-label":l.value?"Pause":"Play"},[e.createVNode(e.unref(H.IonIcon),{icon:l.value?e.unref(gv):e.unref(kv)},null,8,["icon"])],8,J4),e.createElementVNode("div",q4,e.toDisplayString(x(s.value))+" / "+e.toDisplayString(x(d.value)),1)])]),e.createElementVNode("div",Y4,[e.createElementVNode("div",{class:"timeline-track",onClick:T,ref_key:"timelineTrack",ref:g},[e.createElementVNode("div",{class:"timeline-clip",style:e.normalizeStyle({left:`${u.value/d.value*100}%`,right:`${100-m.value/d.value*100}%`})},[e.createElementVNode("span",Q4,e.toDisplayString(c.value),1)],4),e.createElementVNode("div",{class:"timeline-playhead",style:e.normalizeStyle({left:`${s.value/d.value*100}%`})},null,4),f.value==="trim"?(e.openBlock(),e.createElementBlock("div",{key:0,class:"trim-handle trim-start",style:e.normalizeStyle({left:`${u.value/d.value*100}%`}),onMousedown:Z[0]||(Z[0]=O=>_("start"))},null,36)):e.createCommentVNode("",!0),f.value==="trim"?(e.openBlock(),e.createElementBlock("div",{key:1,class:"trim-handle trim-end",style:e.normalizeStyle({left:`${m.value/d.value*100}%`}),onMousedown:Z[1]||(Z[1]=O=>_("end"))},null,36)):e.createCommentVNode("",!0)],512),e.createElementVNode("div",eI,[e.createElementVNode("span",null,e.toDisplayString(x(0)),1),e.createElementVNode("span",null,e.toDisplayString(x(d.value)),1)])]),e.createElementVNode("div",tI,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(k,O=>e.createElementVNode("button",{key:O.id,class:e.normalizeClass(["tool-tab",{active:f.value===O.id}]),onClick:K=>f.value=O.id},[e.createVNode(e.unref(H.IonIcon),{icon:O.icon},null,8,["icon"]),e.createTextVNode(" "+e.toDisplayString(O.label),1)],10,aI)),64))]),e.createElementVNode("div",nI,[f.value==="trim"?(e.openBlock(),e.createElementBlock("div",oI,[Z[7]||(Z[7]=e.createElementVNode("h3",null,"Trim Video",-1)),Z[8]||(Z[8]=e.createElementVNode("p",null,"Click and drag on the timeline to set trim points",-1)),e.createElementVNode("div",iI,[e.createElementVNode("button",{class:"btn-trim",onClick:$},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(mc)},null,8,["icon"]),Z[4]||(Z[4]=e.createTextVNode(" Set Start ",-1))]),e.createElementVNode("button",{class:"btn-trim",onClick:S},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(mc)},null,8,["icon"]),Z[5]||(Z[5]=e.createTextVNode(" Set End ",-1))]),e.createElementVNode("button",{class:"btn-trim",onClick:B},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Yn)},null,8,["icon"]),Z[6]||(Z[6]=e.createTextVNode(" Clear ",-1))])])])):f.value==="filters"?(e.openBlock(),e.createElementBlock("div",rI,[Z[9]||(Z[9]=e.createElementVNode("h3",null,"Filters",-1)),e.createElementVNode("div",lI,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(y,O=>e.createElementVNode("button",{key:O.id,class:e.normalizeClass(["filter-option",{active:h.value===O.id}]),onClick:K=>A(O.id)},e.toDisplayString(O.name),11,sI)),64))])])):f.value==="text"?(e.openBlock(),e.createElementBlock("div",dI,[Z[10]||(Z[10]=e.createElementVNode("h3",null,"Text Overlay",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":Z[2]||(Z[2]=O=>v.value=O),type:"text",placeholder:"Enter text...",class:"text-input"},null,512),[[e.vModelText,v.value]]),e.createElementVNode("button",{class:"btn-add-text",onClick:P},"Add Text")])):f.value==="transitions"?(e.openBlock(),e.createElementBlock("div",cI,[Z[11]||(Z[11]=e.createElementVNode("h3",null,"Transitions",-1)),e.createElementVNode("div",uI,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(w,O=>e.createElementVNode("button",{key:O.id,class:"transition-option",onClick:K=>(O.id,void 0)},e.toDisplayString(O.name),9,mI)),64))])])):e.createCommentVNode("",!0)]),e.createElementVNode("div",pI,[e.createElementVNode("button",{class:"btn-cancel",onClick:Z[3]||(Z[3]=O=>M.$emit("cancel"))},"CANCEL"),e.createElementVNode("button",{class:"btn-save",onClick:z},"SAVE")])]))}}),hI=$e(fI,[["__scopeId","data-v-b933f33b"]]),vI={class:"time-label"},gI=e.defineComponent({__name:"TimeRuler",props:{duration:{},zoom:{}},setup(o){const a=o,t=e.computed(()=>({width:`${a.duration*a.zoom*100}px`})),n=e.computed(()=>{const l=[],s=i(a.duration,a.zoom);for(let d=0;d<=a.duration;d+=s){const c=`${d/a.duration*100}%`,u=r(d),m=d%(s*5)===0;l.push({time:d,position:c,label:u,major:m})}return l});function i(l,s){const d=l/(10*s);return d<=1?1:d<=5?5:d<=10?10:d<=30?30:d<=60?60:Math.ceil(d/60)*60}function r(l){const s=Math.floor(l/60),d=Math.floor(l%60);return s===0?`${d}s`:d===0?`${s}m`:`${s}:${d.toString().padStart(2,"0")}`}return(l,s)=>(e.openBlock(),e.createElementBlock("div",{class:"time-ruler",style:e.normalizeStyle(t.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.value,d=>(e.openBlock(),e.createElementBlock("div",{key:d.time,class:"time-mark",style:e.normalizeStyle({left:d.position})},[e.createElementVNode("span",vI,e.toDisplayString(d.label),1),e.createElementVNode("div",{class:e.normalizeClass(["time-tick",{major:d.major}])},null,2)],4))),128))],4))}}),bI=$e(gI,[["__scopeId","data-v-0ef9c910"]]),yI=["data-track-index"],wI={class:"track-header"},kI={class:"track-label"},_I={class:"track-controls"},EI=["data-testid","aria-label"],SI=["data-testid","onMousedown","onClick"],CI={class:"clip-content"},xI={class:"clip-name"},NI={key:0,class:"clip-thumbnail"},VI=["src","alt"],TI=["onMousedown","aria-label"],BI=["onMousedown","aria-label"],II=e.defineComponent({__name:"VideoTrack",props:{clips:{},trackIndex:{},zoom:{},duration:{}},emits:["clip-move","clip-trim","clip-select"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(null),r=e.ref(!1),l=e.ref(!1),s=e.ref(null),d=e.computed(()=>({width:`${t.duration*t.zoom*100}px`}));function c(k){const y=k.timelineEnd-k.timelineStart,w=k.timelineStart/t.duration*100,g=y/t.duration*100;return{left:`${w}%`,width:`${g}%`,backgroundColor:u(k)}}function u(k){const y=["#4A90E2","#7ED321","#F5A623","#BD10E0","#9013FE","#50E3C2","#B8E986","#F8E71C"],w=parseInt(k.id.replace(/\D/g,""))%y.length;return y[w]}function m(k){return k.label?k.label:k.url?(k.url.split("/").pop()||"Clip").split(".")[0]:`Clip ${k.id.slice(-4)}`}function p(k){i.value=k.id,n("clip-select",k.id)}function f(){r.value=!r.value}function h(k,y){if(s.value)return;l.value=!0;const w=y.clientX,g=k.timelineStart,b=V=>{if(!l.value)return;const I=V.clientX-w,x=parseFloat(d.value.width),T=I/(t.zoom*100)*(t.duration/x),$=Math.max(0,g+T);n("clip-move",k.id,$)},R=()=>{l.value=!1,document.removeEventListener("mousemove",b),document.removeEventListener("mouseup",R)};document.addEventListener("mousemove",b),document.addEventListener("mouseup",R)}function v(k,y,w){s.value=y;const g=w.clientX,b=k.sourceIn,R=k.sourceOut,V=x=>{if(!s.value)return;const T=x.clientX-g,$=parseFloat(d.value.width),S=T/(t.zoom*100)*(t.duration/$);if(s.value==="start"){const B=Math.max(0,b+S);n("clip-trim",k.id,B,R)}else{const B=Math.max(b+1,R+S);n("clip-trim",k.id,b,B)}},I=()=>{s.value=null,document.removeEventListener("mousemove",V),document.removeEventListener("mouseup",I)};document.addEventListener("mousemove",V),document.addEventListener("mouseup",I)}return(k,y)=>(e.openBlock(),e.createElementBlock("div",{class:"video-track","data-track-index":k.trackIndex},[e.createElementVNode("div",wI,[e.createElementVNode("span",kI,"Track "+e.toDisplayString(k.trackIndex+1),1),e.createElementVNode("div",_I,[k.clips.length>0?(e.openBlock(),e.createElementBlock("button",{key:0,class:"track-btn","data-testid":`btn-mute-track-${k.trackIndex}`,"aria-label":`${r.value?"Unmute":"Mute"} track ${k.trackIndex+1}`,onClick:f},[e.createVNode(e.unref(H.IonIcon),{icon:r.value?e.unref(Dv):e.unref($v)},null,8,["icon"])],8,EI)):e.createCommentVNode("",!0)])]),e.createElementVNode("div",{class:"track-timeline",style:e.normalizeStyle(d.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(k.clips,w=>(e.openBlock(),e.createElementBlock("div",{key:w.id,class:e.normalizeClass(["timeline-clip",{selected:w.id===i.value}]),style:e.normalizeStyle(c(w)),"data-testid":`clip-${w.id}`,onMousedown:g=>h(w,g),onClick:g=>p(w)},[e.createElementVNode("div",CI,[e.createElementVNode("span",xI,e.toDisplayString(m(w)),1),w.thumbnail?(e.openBlock(),e.createElementBlock("div",NI,[e.createElementVNode("img",{src:w.thumbnail,alt:m(w)},null,8,VI)])):e.createCommentVNode("",!0)]),e.createElementVNode("div",{class:"trim-handle trim-start",onMousedown:e.withModifiers(g=>v(w,"start",g),["stop"]),"aria-label":`Trim start of ${m(w)}`},null,40,TI),e.createElementVNode("div",{class:"trim-handle trim-end",onMousedown:e.withModifiers(g=>v(w,"end",g),["stop"]),"aria-label":`Trim end of ${m(w)}`},null,40,BI)],46,SI))),128))],4)],8,yI))}}),MI=$e(II,[["__scopeId","data-v-48e480d2"]]),$I={class:"video-timeline"},FI={class:"timeline-tracks"},DI=["aria-label","aria-valuenow","aria-valuemax"],AI={class:"timeline-controls"},RI={class:"zoom-level"},LI=e.defineComponent({__name:"VideoTimeline",props:{clips:{},duration:{},currentTime:{}},emits:["update:clips","seek","clip-move","clip-trim"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(1),r=e.ref(null),l=e.ref(!1),s=e.ref(),d=e.computed(()=>{const g=Math.max(0,...t.clips.map(b=>b.track||0));return Array(g+1).fill(null)}),c=e.computed(()=>`${t.currentTime/t.duration*100}%`);function u(g){return t.clips.filter(b=>(b.track||0)===g)}function m(g){const b=Math.floor(g/60),R=Math.floor(g%60);return`${b}:${R.toString().padStart(2,"0")}`}function p(g,b){n("clip-move",g,b)}function f(g,b,R){n("clip-trim",g,b,R)}function h(g){r.value=g}function v(){i.value=Math.min(i.value*1.2,5)}function k(){i.value=Math.max(i.value/1.2,.5)}function y(){l.value=!0;const g=R=>{if(!l.value||!s.value)return;const V=s.value.getBoundingClientRect(),T=Math.max(0,Math.min(R.clientX-V.left,V.width))/V.width*t.duration;n("seek",T)},b=()=>{l.value=!1,document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",b)};document.addEventListener("mousemove",g),document.addEventListener("mouseup",b)}function w(g){let b=t.currentTime;switch(g.key){case"ArrowLeft":b=Math.max(0,t.currentTime-1);break;case"ArrowRight":b=Math.min(t.duration,t.currentTime+1);break;case"Home":b=0;break;case"End":b=t.duration;break;default:return}g.preventDefault(),n("seek",b)}return e.onMounted(()=>{s.value=document.querySelector(".video-timeline")}),e.onUnmounted(()=>{}),(g,b)=>(e.openBlock(),e.createElementBlock("div",$I,[e.createVNode(bI,{duration:g.duration,zoom:i.value},null,8,["duration","zoom"]),e.createElementVNode("div",FI,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(d.value,(R,V)=>(e.openBlock(),e.createBlock(MI,{key:`track-${V}`,"data-testid":`track-${V}`,clips:u(V),"track-index":V,zoom:i.value,duration:g.duration,onClipMove:p,onClipTrim:f,onClipSelect:h},null,8,["data-testid","clips","track-index","zoom","duration"]))),128))]),e.createElementVNode("div",{class:"timeline-playhead",style:e.normalizeStyle({left:c.value}),onMousedown:y,"data-testid":"playhead","aria-label":`Playhead at ${m(g.currentTime)}`,role:"slider","aria-valuenow":g.currentTime,"aria-valuemax":g.duration,tabindex:"0",onKeydown:w},null,44,DI),e.createElementVNode("div",AI,[e.createElementVNode("button",{"data-testid":"btn-zoom-in","aria-label":"Zoom in",onClick:v},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(ed)},null,8,["icon"])]),e.createElementVNode("span",RI,e.toDisplayString(Math.round(i.value*100))+"%",1),e.createElementVNode("button",{"data-testid":"btn-zoom-out","aria-label":"Zoom out",onClick:k},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Nv)},null,8,["icon"])])])]))}}),PI=$e(LI,[["__scopeId","data-v-001df415"]]),UI={class:"video-filters-panel"},OI={class:"filter-controls"},zI=["for"],jI={class:"filter-slider-group"},WI=["id","onUpdate:modelValue","min","max","step","data-testid","aria-label","aria-valuenow","aria-valuemin","aria-valuemax","onInput"],HI={class:"filter-value"},ZI={class:"filter-actions"},GI={key:0,class:"filter-presets"},XI={class:"preset-list"},KI=["data-testid","aria-label","onClick"],JI=e.defineComponent({__name:"VideoFiltersPanel",emits:["filter-change"],setup(o,{emit:a}){const t=a,n=[{type:"brightness",label:"Brightness",min:0,max:200,step:1,default:100},{type:"contrast",label:"Contrast",min:0,max:200,step:1,default:100},{type:"saturation",label:"Saturation",min:0,max:200,step:1,default:100},{type:"hue",label:"Hue",min:-180,max:180,step:1,default:0},{type:"blur",label:"Blur",min:0,max:10,step:.5,default:0},{type:"sharpen",label:"Sharpen",min:0,max:10,step:.5,default:0},{type:"sepia",label:"Sepia",min:0,max:100,step:1,default:0},{type:"grayscale",label:"Grayscale",min:0,max:100,step:1,default:0}],i=e.reactive(n.reduce((p,f)=>(p[f.type]=f.default,p),{})),r=e.ref([{id:"vintage",name:"Vintage",values:{brightness:110,contrast:120,saturation:80,sepia:30}},{id:"noir",name:"Film Noir",values:{brightness:90,contrast:130,grayscale:100}},{id:"vibrant",name:"Vibrant",values:{brightness:110,contrast:110,saturation:140}},{id:"dreamy",name:"Dreamy",values:{brightness:120,blur:2,saturation:90}}]);function l(p,f){switch(p){case"brightness":case"contrast":case"saturation":case"sepia":case"grayscale":return`${f}%`;case"hue":return`${f}°`;case"blur":case"sharpen":return f.toFixed(1);default:return f.toString()}}function s(p){return["brightness","contrast","saturation","hue","blur","sharpen","sepia","grayscale"].includes(p)}function d(p){if(!s(p))return;const f={id:`filter-${p}`,filterId:p,params:{value:i[p]},intensity:1};t("filter-change",f)}function c(){n.forEach(p=>{i[p.type]=p.default,d(p.type)})}function u(){const p=prompt("Enter preset name:");if(!p)return;const f={id:`custom-${Date.now()}`,name:p,values:{...i}};r.value.push(f)}function m(p){Object.entries(p.values).forEach(([f,h])=>{i[f]=h,d(f)})}return(p,f)=>(e.openBlock(),e.createElementBlock("div",UI,[f[3]||(f[3]=e.createElementVNode("h3",null,"Video Filters",-1)),e.createElementVNode("div",OI,[(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,zI),e.createElementVNode("div",jI,[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,WI),[[e.vModelText,i[h.type],void 0,{number:!0}]]),e.createElementVNode("span",HI,e.toDisplayString(l(h.type,i[h.type])),1)])])),64))]),e.createElementVNode("div",ZI,[e.createElementVNode("button",{class:"reset-filters-btn","data-testid":"btn-reset-filters","aria-label":"Reset all filters to default",onClick:c},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(io)},null,8,["icon"]),f[0]||(f[0]=e.createTextVNode(" Reset All Filters ",-1))]),e.createElementVNode("button",{class:"save-preset-btn","data-testid":"btn-save-preset","aria-label":"Save current filter settings as preset",onClick:u},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(el)},null,8,["icon"]),f[1]||(f[1]=e.createTextVNode(" Save as Preset ",-1))])]),r.value.length>0?(e.openBlock(),e.createElementBlock("div",GI,[f[2]||(f[2]=e.createElementVNode("h4",null,"Presets",-1)),e.createElementVNode("div",XI,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.value,h=>(e.openBlock(),e.createElementBlock("button",{key:h.id,class:"preset-btn","data-testid":`preset-${h.id}`,"aria-label":`Apply ${h.name} preset`,onClick:v=>m(h)},e.toDisplayString(h.name),9,KI))),128))])])):e.createCommentVNode("",!0)]))}}),qI=$e(JI,[["__scopeId","data-v-5ad2ac63"]]),YI={class:"video-text-panel"},QI={class:"text-input-group"},eM={class:"text-options"},tM={class:"option-row"},aM={class:"option-row"},nM={class:"option-row"},oM={class:"option-row"},iM={class:"checkbox-label"},rM={class:"option-row"},lM={class:"text-overlay-list"},sM={key:0,class:"empty-state"},dM=["data-testid"],cM={class:"overlay-preview"},uM={class:"overlay-controls"},mM=["data-testid","aria-label","onClick"],pM=["data-testid","aria-label","onClick"],fM=["data-testid","aria-label","onClick"],hM=e.defineComponent({__name:"VideoTextPanel",emits:["text-add","text-remove","text-update"],setup(o,{emit:a}){const t=a,n=e.ref([]),i=e.reactive({text:"",fontFamily:"Arial",fontSize:32,color:"#FFFFFF",backgroundColor:"#000000",hasBackground:!0,animation:"fade-in"});function r(){if(!i.text.trim())return;const c={id:`text-${Date.now()}`,text:i.text,x:50,y:50,fontSize:i.fontSize,fontFamily:i.fontFamily,color:i.color,startTime:0,opacity:1};i.hasBackground&&(c.backgroundColor=i.backgroundColor),i.animation!=="none"&&(c.animation=i.animation),n.value.push(c),t("text-add",c),i.text=""}function l(c){const u=n.value.findIndex(m=>m.id===c);u!==-1&&(n.value.splice(u,1),t("text-remove",c))}function s(c){i.text=c.text,i.fontFamily=c.fontFamily||"Arial",i.fontSize=c.fontSize,i.color=c.color,i.backgroundColor=c.backgroundColor||"#000000",i.hasBackground=!!c.backgroundColor,i.animation=c.animation||"none",l(c.id)}function d(c){const u={...c,id:`text-${Date.now()}`,x:c.x+10,y:c.y+10};n.value.push(u),t("text-add",u)}return(c,u)=>(e.openBlock(),e.createElementBlock("div",YI,[u[17]||(u[17]=e.createElementVNode("h3",null,"Text Overlays",-1)),e.createElementVNode("div",QI,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":u[0]||(u[0]=m=>i.text=m),type:"text",placeholder:"Enter text...",class:"text-input","data-testid":"input-text","aria-label":"Text overlay content",onKeyup:e.withKeys(r,["enter"])},null,544),[[e.vModelText,i.text]]),e.createElementVNode("button",{class:"add-text-btn","data-testid":"btn-add-text","aria-label":"Add text overlay",onClick:r},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(ed)},null,8,["icon"]),u[7]||(u[7]=e.createTextVNode(" Add ",-1))])]),e.createElementVNode("div",eM,[e.createElementVNode("div",tM,[u[9]||(u[9]=e.createElementVNode("label",{for:"font-family"},"Font:",-1)),e.withDirectives(e.createElementVNode("select",{id:"font-family","onUpdate:modelValue":u[1]||(u[1]=m=>i.fontFamily=m),"data-testid":"select-font"},[...u[8]||(u[8]=[e.createStaticVNode('<option value="Arial" data-v-4d240e1e>Arial</option><option value="Helvetica" data-v-4d240e1e>Helvetica</option><option value="Times New Roman" data-v-4d240e1e>Times New Roman</option><option value="Georgia" data-v-4d240e1e>Georgia</option><option value="Courier New" data-v-4d240e1e>Courier New</option><option value="Impact" data-v-4d240e1e>Impact</option><option value="Comic Sans MS" data-v-4d240e1e>Comic Sans MS</option>',7)])],512),[[e.vModelSelect,i.fontFamily]])]),e.createElementVNode("div",aM,[u[10]||(u[10]=e.createElementVNode("label",{for:"font-size"},"Size:",-1)),e.withDirectives(e.createElementVNode("input",{id:"font-size","onUpdate:modelValue":u[2]||(u[2]=m=>i.fontSize=m),type:"number",min:"10",max:"200","data-testid":"input-font-size"},null,512),[[e.vModelText,i.fontSize,void 0,{number:!0}]])]),e.createElementVNode("div",nM,[u[11]||(u[11]=e.createElementVNode("label",{for:"text-color"},"Color:",-1)),e.withDirectives(e.createElementVNode("input",{id:"text-color","onUpdate:modelValue":u[3]||(u[3]=m=>i.color=m),type:"color","data-testid":"input-text-color"},null,512),[[e.vModelText,i.color]])]),e.createElementVNode("div",oM,[u[13]||(u[13]=e.createElementVNode("label",{for:"bg-color"},"Background:",-1)),e.withDirectives(e.createElementVNode("input",{id:"bg-color","onUpdate:modelValue":u[4]||(u[4]=m=>i.backgroundColor=m),type:"color","data-testid":"input-bg-color"},null,512),[[e.vModelText,i.backgroundColor]]),e.createElementVNode("label",iM,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":u[5]||(u[5]=m=>i.hasBackground=m),type:"checkbox","data-testid":"checkbox-bg"},null,512),[[e.vModelCheckbox,i.hasBackground]]),u[12]||(u[12]=e.createTextVNode(" Enable ",-1))])]),e.createElementVNode("div",rM,[u[15]||(u[15]=e.createElementVNode("label",{for:"text-animation"},"Animation:",-1)),e.withDirectives(e.createElementVNode("select",{id:"text-animation","onUpdate:modelValue":u[6]||(u[6]=m=>i.animation=m),"data-testid":"select-animation"},[...u[14]||(u[14]=[e.createStaticVNode('<option value="none" data-v-4d240e1e>None</option><option value="fade-in" data-v-4d240e1e>Fade In</option><option value="slide-left" data-v-4d240e1e>Slide from Left</option><option value="slide-right" data-v-4d240e1e>Slide from Right</option><option value="slide-up" data-v-4d240e1e>Slide from Bottom</option><option value="slide-down" data-v-4d240e1e>Slide from Top</option><option value="typewriter" data-v-4d240e1e>Typewriter</option><option value="bounce" data-v-4d240e1e>Bounce</option>',8)])],512),[[e.vModelSelect,i.animation]])])]),e.createElementVNode("div",lM,[u[16]||(u[16]=e.createElementVNode("h4",null,"Active Overlays",-1)),n.value.length===0?(e.openBlock(),e.createElementBlock("div",sM," No text overlays added yet ")):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.value,(m,p)=>(e.openBlock(),e.createElementBlock("div",{key:m.id,class:"text-overlay-item","data-testid":`overlay-${p}`},[e.createElementVNode("div",cM,[e.createElementVNode("span",{style:e.normalizeStyle({fontFamily:m.fontFamily,fontSize:`${Math.min(m.fontSize/4,16)}px`,color:m.color})},e.toDisplayString(m.text),5)]),e.createElementVNode("div",uM,[e.createElementVNode("button",{class:"edit-btn","data-testid":`btn-edit-${p}`,"aria-label":`Edit overlay: ${m.text}`,onClick:f=>s(m)},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(lv)},null,8,["icon"])],8,mM),e.createElementVNode("button",{class:"duplicate-btn","data-testid":`btn-duplicate-${p}`,"aria-label":`Duplicate overlay: ${m.text}`,onClick:f=>d(m)},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(ms)},null,8,["icon"])],8,pM),e.createElementVNode("button",{class:"remove-btn","data-testid":`btn-remove-${p}`,"aria-label":`Remove overlay: ${m.text}`,onClick:f=>l(m.id)},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Dr)},null,8,["icon"])],8,fM)])],8,dM))),128))])]))}}),vM=$e(hM,[["__scopeId","data-v-4d240e1e"]]),gM={class:"video-tools-panel"},bM={class:"tool-tabs"},yM=["data-testid","aria-label","aria-selected","onClick"],wM={class:"tool-content"},kM={key:0,class:"trim-panel",role:"tabpanel","aria-label":"Trim controls"},_M={class:"trim-actions"},EM={key:3,class:"transitions-panel",role:"tabpanel","aria-label":"Transition controls"},SM={class:"transition-types"},CM=["data-testid","aria-label","onClick"],xM={class:"transition-preview"},NM=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:Fr},{id:"filters",name:"Filters",icon:Cn},{id:"text",name:"Text",icon:dm},{id:"transitions",name:"Transitions",icon:hc}],t=[{id:"fade",name:"Fade",icon:Wl},{id:"slide-left",name:"Slide Left",icon:ev},{id:"slide-right",name:"Slide Right",icon:tv},{id:"dissolve",name:"Dissolve",icon:Wl},{id:"wipe",name:"Wipe",icon:hc},{id:"zoom",name:"Zoom",icon:Wl}];return(n,i)=>(e.openBlock(),e.createElementBlock("div",gM,[e.createElementVNode("div",bM,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(a,r=>e.createElementVNode("button",{key:r.id,class:e.normalizeClass(["tool-tab",{active:n.activeTool===r.id}]),"data-testid":`tab-${r.id}`,"aria-label":`${r.name} tool`,"aria-selected":n.activeTool===r.id,role:"tab",onClick:l=>n.$emit("tool-change",r.id)},[e.createVNode(e.unref(H.IonIcon),{icon:r.icon},null,8,["icon"]),e.createTextVNode(" "+e.toDisplayString(r.name),1)],10,yM)),64))]),e.createElementVNode("div",wM,[n.activeTool==="trim"?(e.openBlock(),e.createElementBlock("div",kM,[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",_M,[e.createElementVNode("button",{class:"action-btn","data-testid":"btn-set-start","aria-label":"Set trim start at current position",onClick:i[0]||(i[0]=r=>n.$emit("trim-set-start"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(pc)},null,8,["icon"]),i[5]||(i[5]=e.createTextVNode(" Set Start ",-1))]),e.createElementVNode("button",{class:"action-btn","data-testid":"btn-set-end","aria-label":"Set trim end at current position",onClick:i[1]||(i[1]=r=>n.$emit("trim-set-end"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(pc)},null,8,["icon"]),i[6]||(i[6]=e.createTextVNode(" Set End ",-1))]),e.createElementVNode("button",{class:"action-btn","data-testid":"btn-clear-trim","aria-label":"Clear trim points",onClick:i[2]||(i[2]=r=>n.$emit("trim-clear"))},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Yn)},null,8,["icon"]),i[7]||(i[7]=e.createTextVNode(" Clear ",-1))])])])):e.createCommentVNode("",!0),n.activeTool==="filters"?(e.openBlock(),e.createBlock(qI,{key:1,onFilterChange:i[3]||(i[3]=r=>n.$emit("filter-change",r))})):e.createCommentVNode("",!0),n.activeTool==="text"?(e.openBlock(),e.createBlock(vM,{key:2,onTextAdd:i[4]||(i[4]=r=>n.$emit("text-add",r))})):e.createCommentVNode("",!0),n.activeTool==="transitions"?(e.openBlock(),e.createElementBlock("div",EM,[i[10]||(i[10]=e.createElementVNode("h3",null,"Transitions",-1)),e.createElementVNode("div",SM,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(t,r=>e.createElementVNode("button",{key:r.id,class:"transition-btn","data-testid":`transition-${r.id}`,"aria-label":`Add ${r.name} transition`,onClick:l=>n.$emit("transition-add",r.id)},[e.createElementVNode("div",xM,[e.createVNode(e.unref(H.IonIcon),{icon:r.icon},null,8,["icon"])]),e.createElementVNode("span",null,e.toDisplayString(r.name),1)],8,CM)),64))])])):e.createCommentVNode("",!0)])]))}}),VM=$e(NM,[["__scopeId","data-v-fc135306"]]),TM={class:"video-export-panel"},BM={class:"export-presets"},IM=["value"],MM={key:0,class:"preset-details"},$M={class:"detail-row"},FM={class:"detail-row"},DM={class:"detail-row"},AM={class:"advanced-options"},RM={class:"options-content"},LM={class:"option-group"},PM={class:"option-group"},UM={class:"option-group"},OM=["disabled"],zM={key:1,class:"export-progress"},jM={class:"progress-message"},WM={class:"progress-bar"},HM=["aria-valuenow"],ZM={class:"progress-percentage"},GM=e.defineComponent({__name:"VideoExportPanel",props:{presets:{},isExporting:{type:Boolean},exportProgress:{}},emits:["export"],setup(o,{emit:a}){const t=o,n=a,i=e.ref("instagram-reel"),r=e.reactive({quality:"medium",bitrate:5,includeAudio:!0}),l=e.computed(()=>t.presets.find(c=>c.id===i.value)),s=e.computed(()=>t.exportProgress<10?"Initializing export...":t.exportProgress<30?"Processing video tracks...":t.exportProgress<50?"Applying filters and effects...":t.exportProgress<70?"Rendering frames...":t.exportProgress<90?"Encoding video...":t.exportProgress<100?"Finalizing export...":"Export complete!");function d(){l.value&&n("export",{...l.value,options:{...r}})}return(c,u)=>(e.openBlock(),e.createElementBlock("div",TM,[u[14]||(u[14]=e.createElementVNode("h3",null,"Export Video",-1)),e.createElementVNode("div",BM,[u[4]||(u[4]=e.createElementVNode("label",{for:"preset-select"},"Export Preset:",-1)),e.withDirectives(e.createElementVNode("select",{id:"preset-select","onUpdate:modelValue":u[0]||(u[0]=m=>i.value=m),"data-testid":"preset-select","aria-label":"Select export preset"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.presets,m=>(e.openBlock(),e.createElementBlock("option",{key:m.id,value:m.id},e.toDisplayString(m.name),9,IM))),128))],512),[[e.vModelSelect,i.value]])]),l.value?(e.openBlock(),e.createElementBlock("div",MM,[e.createElementVNode("div",$M,[u[5]||(u[5]=e.createElementVNode("span",null,"Resolution:",-1)),e.createElementVNode("span",null,e.toDisplayString(l.value.width)+"x"+e.toDisplayString(l.value.height),1)]),e.createElementVNode("div",FM,[u[6]||(u[6]=e.createElementVNode("span",null,"Frame Rate:",-1)),e.createElementVNode("span",null,e.toDisplayString(l.value.fps)+" fps",1)]),e.createElementVNode("div",DM,[u[7]||(u[7]=e.createElementVNode("span",null,"Format:",-1)),e.createElementVNode("span",null,e.toDisplayString(l.value.format.toUpperCase()),1)])])):e.createCommentVNode("",!0),e.createElementVNode("details",AM,[u[12]||(u[12]=e.createElementVNode("summary",null,"Advanced Options",-1)),e.createElementVNode("div",RM,[e.createElementVNode("div",LM,[u[9]||(u[9]=e.createElementVNode("label",{for:"quality-select"},"Quality:",-1)),e.withDirectives(e.createElementVNode("select",{id:"quality-select","onUpdate:modelValue":u[1]||(u[1]=m=>r.quality=m),"data-testid":"quality-select"},[...u[8]||(u[8]=[e.createElementVNode("option",{value:"low"},"Low (smaller file)",-1),e.createElementVNode("option",{value:"medium"},"Medium (balanced)",-1),e.createElementVNode("option",{value:"high"},"High (best quality)",-1)])],512),[[e.vModelSelect,r.quality]])]),e.createElementVNode("div",PM,[u[10]||(u[10]=e.createElementVNode("label",{for:"bitrate-input"},"Bitrate (Mbps):",-1)),e.withDirectives(e.createElementVNode("input",{id:"bitrate-input","onUpdate:modelValue":u[2]||(u[2]=m=>r.bitrate=m),type:"number",min:"1",max:"50","data-testid":"bitrate-input"},null,512),[[e.vModelText,r.bitrate,void 0,{number:!0}]])]),e.createElementVNode("div",UM,[e.createElementVNode("label",null,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":u[3]||(u[3]=m=>r.includeAudio=m),type:"checkbox","data-testid":"include-audio"},null,512),[[e.vModelCheckbox,r.includeAudio]]),u[11]||(u[11]=e.createTextVNode(" Include Audio ",-1))])])])]),e.createElementVNode("button",{class:"btn-export",disabled:c.isExporting||!l.value,"data-testid":"btn-start-export","aria-label":"Start video export",onClick:d},[c.isExporting?(e.openBlock(),e.createBlock(e.unref(H.IonSpinner),{key:0,name:"crescent"})):(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Fo)},null,8,["icon"]),u[13]||(u[13]=e.createTextVNode(" Export Video ",-1))],64))],8,OM),c.isExporting?(e.openBlock(),e.createElementBlock("div",zM,[e.createElementVNode("div",jM,e.toDisplayString(s.value),1),e.createElementVNode("div",WM,[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,HM)]),e.createElementVNode("div",ZM,e.toDisplayString(c.exportProgress)+"% ",1)])):e.createCommentVNode("",!0)]))}}),XM=$e(GM,[["__scopeId","data-v-5caf8fe6"]]),KM=["data-testid"],JM={class:"progress-header"},qM={class:"file-info"},YM={class:"file-details"},QM={class:"file-name"},e3={class:"file-meta"},t3={class:"file-size"},a3={key:0,class:"separator"},n3={key:1,class:"upload-speed"},o3={key:2,class:"separator"},i3={key:3,class:"time-remaining"},r3={class:"progress-actions"},l3={key:0,class:"status-icon completed","data-testid":"video-upload-status-completed"},s3={key:1,class:"status-icon error","data-testid":"video-upload-status-error"},d3={key:2,class:"status-icon processing","data-testid":"video-upload-status-processing",role:"status","aria-label":"Processing video"},c3=["aria-valuenow","aria-label"],u3={class:"progress-bar"},m3={class:"progress-percent"},p3={key:1,class:"error-message","data-testid":"video-upload-error"},f3={key:2,class:"thumbnail-preview","data-testid":"video-upload-thumbnail"},h3=["src","alt"],v3={key:0,class:"video-duration"},g3=e.defineComponent({__name:"VideoUploadProgress",props:{upload:{}},emits:["cancel","retry","remove"],setup(o){const a=o,t=e.computed(()=>({"is-uploading":a.upload.status==="uploading","is-processing":a.upload.status==="processing","is-completed":a.upload.status==="completed","is-error":a.upload.status==="error","is-pending":a.upload.status==="pending"})),n=e.computed(()=>cm),i=e.computed(()=>["uploading","processing"].includes(a.upload.status)),r=e.computed(()=>(a.upload.status==="processing",a.upload.progress||0)),l=e.computed(()=>{if(!a.upload.timeRemaining||a.upload.status!=="uploading")return null;const p=a.upload.timeRemaining;if(p<60)return`${Math.round(p)}s`;const f=Math.floor(p/60);return f<60?`${f}m ${Math.round(p%60)}s`:`${Math.floor(f/60)}h ${f%60}m`}),s=e.computed(()=>{var p;return a.upload.status==="completed"&&((p=a.upload.media)!=null&&p.thumbnail_url)?a.upload.media.thumbnail_url:null}),d=e.computed(()=>{var p;return(p=a.upload.media)==null?void 0:p.duration});function c(p){if(p===0)return"0 B";const f=["B","KB","MB","GB","TB"],h=1024,v=Math.floor(Math.log(p)/Math.log(h));return`${(p/Math.pow(h,v)).toFixed(1)} ${f[v]}`}function u(p){if(p===0)return"0 B/s";const f=["B/s","KB/s","MB/s","GB/s"],h=1024,v=Math.floor(Math.log(p)/Math.log(h));return`${(p/Math.pow(h,v)).toFixed(1)} ${f[v]}`}function m(p){const f=Math.floor(p/3600),h=Math.floor(p%3600/60),v=Math.floor(p%60);return f>0?`${f}:${h.toString().padStart(2,"0")}:${v.toString().padStart(2,"0")}`:`${h}:${v.toString().padStart(2,"0")}`}return(p,f)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["upload-progress-item",t.value]),"data-testid":`video-upload-progress-${p.upload.id}`},[e.createElementVNode("div",JM,[e.createElementVNode("div",qM,[e.createVNode(e.unref(H.IonIcon),{icon:n.value,class:"file-icon","aria-hidden":"true"},null,8,["icon"]),e.createElementVNode("div",YM,[e.createElementVNode("h4",QM,e.toDisplayString(p.upload.filename),1),e.createElementVNode("p",e3,[e.createElementVNode("span",t3,e.toDisplayString(c(p.upload.bytesTotal||0)),1),p.upload.status==="uploading"?(e.openBlock(),e.createElementBlock("span",a3,"•")):e.createCommentVNode("",!0),p.upload.status==="uploading"?(e.openBlock(),e.createElementBlock("span",n3,e.toDisplayString(u(p.upload.uploadSpeed||0)),1)):e.createCommentVNode("",!0),l.value?(e.openBlock(),e.createElementBlock("span",o3,"•")):e.createCommentVNode("",!0),l.value?(e.openBlock(),e.createElementBlock("span",i3,e.toDisplayString(l.value)+" remaining ",1)):e.createCommentVNode("",!0)])])]),e.createElementVNode("div",r3,[p.upload.status==="completed"?(e.openBlock(),e.createElementBlock("div",l3,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(im)},null,8,["icon"])])):p.upload.status==="error"?(e.openBlock(),e.createElementBlock("div",s3,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Qh),"aria-hidden":"true"},null,8,["icon"])])):p.upload.status==="processing"?(e.openBlock(),e.createElementBlock("div",d3,[e.createVNode(e.unref(H.IonSpinner),{name:"crescent"})])):e.createCommentVNode("",!0),p.upload.status==="uploading"?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:3,fill:"clear",size:"small",onClick:f[0]||(f[0]=h=>p.$emit("cancel")),"data-testid":"btn-cancel-video-upload","aria-label":"Cancel upload"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Yn),slot:"icon-only"},null,8,["icon"])]),_:1})):p.upload.status==="error"?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:4,fill:"clear",size:"small",onClick:f[1]||(f[1]=h=>p.$emit("retry")),"data-testid":"btn-retry-video-upload","aria-label":"Retry upload"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(io),slot:"icon-only"},null,8,["icon"])]),_:1})):p.upload.status==="completed"?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:5,fill:"clear",size:"small",onClick:f[2]||(f[2]=h=>p.$emit("remove")),"data-testid":"btn-remove-video-upload","aria-label":"Remove from list"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Yn),slot:"icon-only"},null,8,["icon"])]),_:1})):e.createCommentVNode("",!0)])]),i.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"progress-bar-container","data-testid":"video-upload-progress-bar",role:"progressbar","aria-valuenow":Math.round(r.value),"aria-valuemin":"0","aria-valuemax":"100","aria-label":p.upload.status==="processing"?"Processing progress":"Upload progress"},[e.createElementVNode("div",u3,[e.createElementVNode("div",{class:e.normalizeClass(["progress-fill",{indeterminate:p.upload.status==="processing"}]),style:e.normalizeStyle({width:r.value+"%"})},null,6)]),e.createElementVNode("span",m3,e.toDisplayString(Math.round(r.value))+"%",1)],8,c3)):e.createCommentVNode("",!0),p.upload.error?(e.openBlock(),e.createElementBlock("div",p3,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Av)},null,8,["icon"]),e.createElementVNode("span",null,e.toDisplayString(p.upload.error),1)])):e.createCommentVNode("",!0),s.value?(e.openBlock(),e.createElementBlock("div",f3,[e.createElementVNode("img",{src:s.value,alt:p.upload.filename},null,8,h3),d.value?(e.openBlock(),e.createElementBlock("div",v3,e.toDisplayString(m(d.value)),1)):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)],10,KM))}}),b3=$e(g3,[["__scopeId","data-v-9eacbf91"]]),os=4,y3=500,w3=new Set([408,425,429,500,502,503,504,520,521,522,523,524,525]);function xl(o){return typeof o=="object"&&o!==null}function ku(o){return xl(o)?typeof o.upload_url=="string"&&typeof o.upload_id=="string"&&typeof o.media_uuid=="string"&&typeof o.expires_at=="string":!1}function k3(o){if(ku(o))return o;if(xl(o)&&ku(o.data))return o.data;throw new Error("Invalid upload response from backend")}function _u(o){return xl(o)?typeof o.uuid=="string"&&typeof o.processing_status=="string":!1}function _3(o){if(_u(o))return o;if(xl(o)&&_u(o.data))return o.data;throw new Error("Invalid media response from backend")}function fr(o){return o?{...o}:{}}function Eu(o,a="PUT"){return typeof o.method=="string"&&o.method.trim()!==""?o.method.trim().toUpperCase():a}function E3(o){return o.resumable===!0?!0:/tusupload/i.test(o.upload_url)}function S3(o){if(typeof btoa=="function")try{return btoa(unescape(encodeURIComponent(o)))}catch{return btoa(o)}throw new Error("Base64 encoder is unavailable for TUS metadata")}function C3(o,a){return[["filename",o.filename],["filetype",o.file.type||"application/octet-stream"],["uploadid",a.upload_id],["mediauuid",a.media_uuid]].map(([n,i])=>`${n} ${S3(i)}`).join(",")}function hr(o,a){const t=Math.max(o.bytesTotal,1);o.bytesUploaded=a,o.progress=Math.min(100,a/t*100);const n=Math.max((Date.now()-o.startedAt.getTime())/1e3,.001);o.uploadSpeed=a/n;const i=Math.max(t-a,0);o.timeRemaining=i/Math.max(o.uploadSpeed,1)}function x3(o,a){return o instanceof Error?o:new Error(a)}function N3(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 Su(o){const a=Math.max(0,o-1),t=y3*Math.pow(2,a);return Math.min(5e3,t)}function Cu(o){return new Promise(a=>{window.setTimeout(a,o)})}async function xu(o,a){for(let t=1;t<=os;t+=1)try{const n=await a();if(n.ok||!w3.has(n.status)||t>=os)return n;await Cu(Su(t))}catch(n){if(!N3(n)||t>=os)throw n;await Cu(Su(t))}throw new Error(`${o} failed after retry attempts`)}function V3(o={}){const a=e.ref(new Map),t=e.ref(new Set),n=e.ref(null),i=new Map,r=new Map,l=e.computed(()=>t.value.size>0),s=e.computed(()=>Array.from(a.value.values())),d=e.computed(()=>{const S=Array.from(a.value.values());return S.length===0?0:S.reduce((_,A)=>_+A.progress,0)/S.length});function c(S){n.value=S}function u(){}async function m(S){var _;const B=S.filter(A=>p(A));if(B.length!==0&&((_=o.onFilesSelected)==null||_.call(o,B),o.autoUpload!==!1))for(const A of B)await f(A)}function p(S){return!(o.maxFileSize&&S.size>o.maxFileSize||o.allowedFormats&&o.allowedFormats.length>0&&!o.allowedFormats.includes(S.type))}async function f(S){var A,P,D;const B=$(S);if(a.value.has(B)){const z=a.value.get(B);if((z==null?void 0:z.status)==="uploading")return}const _={id:B,file:S,filename:S.name,progress:0,status:"pending",startedAt:new Date,bytesTotal:S.size,bytesUploaded:0};a.value.set(_.id,_),t.value.add(_.id);try{_.status="uploading",(A=o.onUploadStart)==null||A.call(o,_);const z=await h(S);o.resumable===!0||z.resumable===!0?await k(_,z):await v(_,z),_.status="processing",_.progress=100;const Z=await R(z.media_uuid);_.status="completed",_.media=Z,(P=o.onUploadComplete)==null||P.call(o,Z)}catch(z){if(_.status!=="cancelled"){const M=x3(z,"Upload failed");_.status="error",_.error=M.message,(D=o.onUploadError)==null||D.call(o,M,_)}}finally{t.value.delete(_.id),i.delete(_.id),r.delete(_.id)}}async function h(S){if(!n.value)throw new Error("API client not configured");const B={collection:o.collection||"videos",filename:S.name,size:S.size,mime_type:S.type,...o.ownerUuid!==void 0?{ownerUuid:o.ownerUuid}:{},...o.ownerType!==void 0?{ownerType:o.ownerType}:{}},_=await n.value.post("/api/v1/video/upload",B);return k3(_)}async function v(S,B){const _=new XMLHttpRequest,A=Eu(B),P=fr(B.headers);return new Promise((D,z)=>{_.upload.addEventListener("progress",M=>{var Z;M.lengthComputable&&(hr(S,M.loaded),(Z=o.onUploadProgress)==null||Z.call(o,S))}),_.addEventListener("load",()=>{i.delete(S.id),_.status>=200&&_.status<300?D():z(new Error(`Upload failed with status ${_.status}`))}),_.addEventListener("error",()=>{i.delete(S.id),z(new Error("Upload failed"))}),_.addEventListener("abort",()=>{i.delete(S.id),z(new Error("Upload cancelled"))}),_.open(A,B.upload_url),Object.entries(P).forEach(([M,Z])=>{_.setRequestHeader(M,Z)}),!Object.keys(P).some(M=>M.toLowerCase()==="content-type")&&S.file.type&&_.setRequestHeader("Content-Type",S.file.type),i.set(S.id,_),_.send(S.file)})}async function k(S,B){var z;if(E3(B)){await y(S,B);return}const _=o.chunkSize||5*1024*1024,A=w(S.file,_),P=new AbortController;r.set(S.id,P);const D=await b(B.upload_id);D&&(A.forEach(M=>{M.end<=D.bytesUploaded&&(M.uploaded=!0)}),hr(S,D.bytesUploaded));for(const M of A)M.uploaded||(await g(S,B,M,P),hr(S,M.end),(z=o.onUploadProgress)==null||z.call(o,S))}async function y(S,B){var O;const _=new AbortController;r.set(S.id,_);const A={...fr(B.headers),"Tus-Resumable":"1.0.0","Upload-Length":String(S.file.size),"Upload-Metadata":C3(S,B)},P=await xu("Resumable upload initialization",()=>fetch(B.upload_url,{method:"POST",headers:A,signal:_.signal}));if(!P.ok)throw new Error(`Failed to initialize resumable upload: ${P.status}`);const D=P.headers.get("Location");if(!D)throw new Error("Resumable upload endpoint did not return upload location");const z=new URL(D,B.upload_url).toString(),M=o.chunkSize||5*1024*1024;let Z=0;for(;Z<S.file.size;){const K=Math.min(Z+M,S.file.size),de=S.file.slice(Z,K),Ne={...fr(B.headers),"Tus-Resumable":"1.0.0","Upload-Offset":String(Z),"Content-Type":"application/offset+octet-stream"},ce=await xu("Resumable chunk upload",()=>fetch(z,{method:"PATCH",headers:Ne,body:de,signal:_.signal}));if(ce.status===409){const W=Number(ce.headers.get("Upload-Offset")??"-1");if(Number.isFinite(W)&&W>=0){Z=W;continue}}if(!ce.ok)throw new Error(`Resumable chunk upload failed: ${ce.status}`);const le=Number(ce.headers.get("Upload-Offset")??String(K));Z=Number.isFinite(le)&&le>Z?le:K,hr(S,Z),(O=o.onUploadProgress)==null||O.call(o,S)}}function w(S,B){const _=[];let A=0,P=0;for(;A<S.size;){const D=Math.min(A+B,S.size);_.push({start:A,end:D,blob:S.slice(A,D),index:P,uploaded:!1}),A=D,P++}return _}async function g(S,B,_,A){const P={...fr(B.headers),"Content-Range":`bytes ${_.start}-${_.end-1}/${S.file.size}`,"Content-Type":S.file.type||"application/octet-stream"},D=await fetch(B.upload_url,{method:Eu(B),headers:P,body:_.blob,signal:A.signal});if(!D.ok)throw new Error(`Chunk upload failed: ${D.status}`);_.uploaded=!0}async function b(S){return null}async function R(S){if(!n.value)throw new Error("API client not configured");const B=60;let _=0;for(;_<B;){const A=await n.value.get(`/api/v1/video/${S}`),P=_3(A),D=String(P.processing_status);if(D==="ready")return P;if(D==="failed"||D==="error")throw new Error("Video processing failed");await new Promise(z=>{window.setTimeout(z,5e3)}),_++}throw new Error("Video processing timeout")}function V(S){const B=a.value.get(S);if(!B)return;const _=i.get(S);_&&(_.abort(),i.delete(S));const A=r.get(S);A&&(A.abort(),r.delete(S)),B.status="cancelled",B.error="Upload cancelled",t.value.delete(S)}async function I(S){const B=a.value.get(S);B&&(B.status="pending",B.error="",B.progress=0,B.bytesUploaded=0,await f(B.file))}function x(S){a.value.delete(S),t.value.delete(S),i.delete(S),r.delete(S)}function T(){Array.from(a.value.entries()).forEach(([S,B])=>{B.status==="completed"&&a.value.delete(S)})}function $(S){return`${S.name}-${S.size}-${Date.now()}`}return{uploads:s,isUploading:l,totalProgress:d,openFilePicker:u,handleFileSelect:m,validateFile:p,startUpload:f,cancelUpload:V,retryUpload:I,removeUpload:x,clearCompleted:T,setApiClient:c}}const T3=["accept","multiple"],B3={key:0,class:"upload-trigger","data-testid":"video-uploader-trigger"},I3=["onKeydown"],M3={key:1,class:"upload-list","data-testid":"video-upload-list"},$3={class:"drag-content"},F3=e.defineComponent({__name:"VideoUploader",props:{collection:{default:"videos"},multiple:{type:Boolean,default:!1},maxFileSize:{default:5*1024*1024*1024},maxDuration:{},allowedFormats:{default:()=>["video/mp4","video/webm","video/quicktime","video/x-msvideo"]},autoUpload:{type:Boolean,default:!0},resumable:{type:Boolean,default:!0},label:{default:"Upload Video"},description:{default:"Click to select or drag and drop"},ownerUuid:{},ownerType:{},apiClient:{}},emits:["upload-start","upload-progress","upload-complete","upload-error","files-selected"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(),r=e.ref(!1),{uploads:l,isUploading:s,handleFileSelect:d,cancelUpload:c,retryUpload:u,removeUpload:m,setApiClient:p}=V3({collection:t.collection,...t.ownerUuid!==void 0?{ownerUuid:t.ownerUuid}:{},...t.ownerType!==void 0?{ownerType:t.ownerType}:{},maxFileSize:t.maxFileSize,...t.maxDuration!==void 0?{maxDuration:t.maxDuration}:{},allowedFormats:t.allowedFormats,autoUpload:t.autoUpload,resumable:t.resumable,onUploadStart:b=>n("upload-start",b),onUploadProgress:b=>n("upload-progress",b),onUploadComplete:b=>n("upload-complete",b),onUploadError:(b,R)=>n("upload-error",b,R),onFilesSelected:b=>n("files-selected",b)});t.apiClient&&p(t.apiClient);const f=e.computed(()=>t.allowedFormats.join(",")),h=e.computed(()=>t.multiple||l.value.length===0);function v(){i.value&&i.value.click()}function k(b){const R=b.target,V=Array.from(R.files||[]);V.length>0&&(d(V),R.value="")}function y(b){var I;b.preventDefault(),r.value=!1;const V=Array.from(((I=b.dataTransfer)==null?void 0:I.files)||[]).filter(x=>x.type.startsWith("video/"));V.length>0&&d(V)}function w(b){var R;b.preventDefault(),(R=b.dataTransfer)!=null&&R.types.includes("Files")&&(r.value=!0)}function g(b){b.target.closest(".video-uploader")||(r.value=!1)}return e.onMounted(()=>{document.addEventListener("dragover",w),document.addEventListener("dragleave",g),document.addEventListener("drop",b=>b.preventDefault())}),e.onUnmounted(()=>{document.removeEventListener("dragover",w),document.removeEventListener("dragleave",g),document.removeEventListener("drop",b=>b.preventDefault())}),(b,R)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-uploader",{"is-uploading":e.unref(s)}]),"data-testid":"video-uploader"},[e.createElementVNode("input",{ref_key:"fileInputEl",ref:i,type:"file",accept:f.value,multiple:b.multiple,onChange:k,"data-testid":"video-uploader-input","aria-label":"Select video files to upload",hidden:""},null,40,T3),!e.unref(s)||h.value?(e.openBlock(),e.createElementBlock("div",B3,[e.renderSlot(b.$slots,"trigger",{open:v},()=>[e.createElementVNode("div",{class:"default-upload-area","data-testid":"video-uploader-area",role:"button",tabindex:"0","aria-label":"Click to select video for upload",onClick:v,onKeydown:[e.withKeys(v,["enter"]),e.withKeys(e.withModifiers(v,["prevent"]),["space"])]},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(cm),class:"upload-icon","aria-hidden":"true"},null,8,["icon"]),e.createElementVNode("h3",null,e.toDisplayString(b.label),1),e.createElementVNode("p",null,e.toDisplayString(b.description),1),e.createVNode(e.unref(H.IonButton),{size:"small","data-testid":"btn-select-video","aria-label":"Select video file"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(ed),slot:"start","aria-hidden":"true"},null,8,["icon"]),R[2]||(R[2]=e.createTextVNode(" Select Video ",-1))]),_:1})],40,I3)],!0)])):e.createCommentVNode("",!0),e.unref(l).length>0?(e.openBlock(),e.createElementBlock("div",M3,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(l),V=>(e.openBlock(),e.createBlock(b3,{key:V.id,upload:V,onCancel:I=>e.unref(c)(V.id),onRetry:I=>e.unref(u)(V.id),onRemove:I=>e.unref(m)(V.id)},null,8,["upload","onCancel","onRetry","onRemove"]))),128))])):e.createCommentVNode("",!0),r.value?(e.openBlock(),e.createElementBlock("div",{key:2,class:"drag-overlay","data-testid":"video-uploader-drag-overlay",onDrop:y,onDragover:R[0]||(R[0]=e.withModifiers(()=>{},["prevent"])),onDragleave:R[1]||(R[1]=V=>r.value=!1)},[e.createElementVNode("div",$3,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Fo),"aria-hidden":"true"},null,8,["icon"]),R[3]||(R[3]=e.createElementVNode("p",null,"Drop video files here",-1))])],32)):e.createCommentVNode("",!0)],2))}}),D3=$e(F3,[["__scopeId","data-v-ea7587f7"]]),A3=["aria-valuenow","aria-valuemax","aria-label"],R3={class:"progress-bar"},L3={class:"time-display","data-testid":"video-time-display"},P3={class:"current-time"},U3={class:"duration"},O3={class:"control-buttons"},z3={class:"controls-left"},j3=["aria-label"],W3={class:"controls-center"},H3={key:0,class:"volume-controls"},Z3=["aria-label"],G3=["value"],X3={class:"controls-right"},K3={key:0,class:"quality-selector"},J3=["aria-expanded"],q3={class:"quality-label"},Y3={key:0,class:"quality-menu","data-testid":"video-quality-menu",role:"menu"},Q3=["data-testid","aria-label","onClick"],e$=["aria-label"],t$=e.defineComponent({__name:"VideoControls",props:{playing:{type:Boolean},currentTime:{},duration:{},buffered:{},volume:{default:100},muted:{type:Boolean,default:!1},fullscreen:{type:Boolean,default:!1},isLive:{type:Boolean,default:!1},qualityLevels:{default:()=>[]},currentQuality:{default:"Auto"}},emits:["play-pause","play","pause","seek","skip-forward","skip-backward","toggleMute","setVolume","toggleFullscreen","togglePiP","selectQuality"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!0),r=e.ref(!1),l=e.ref(),s=H.isPlatform("mobile"),d="pictureInPictureEnabled"in document,c=e.computed(()=>({width:`${t.currentTime/t.duration*100}%`})),u=e.computed(()=>({left:`${t.currentTime/t.duration*100}%`})),m=e.computed(()=>{if(!t.buffered||t.buffered.length===0)return{width:"0%"};for(let b=0;b<t.buffered.length;b++){const R=t.buffered.start(b),V=t.buffered.end(b);if(t.currentTime>=R&&t.currentTime<=V)return{width:`${V/t.duration*100}%`}}return t.buffered.length>0?{width:`${t.buffered.end(0)/t.duration*100}%`}:{width:"0%"}}),p=e.computed(()=>t.muted||t.volume===0?Fv:t.volume<33?Iv:t.volume<66?Mv:Bv);let f=null;function h(){i.value=!0,v()}function v(){f&&clearTimeout(f),t.playing&&!s&&(f=setTimeout(()=>{i.value=!1},3e3))}function k(b){if(!l.value||t.isLive)return;const R=l.value.getBoundingClientRect(),I=(b.clientX-R.left)/R.width*t.duration;n("seek",Math.max(0,Math.min(I,t.duration)))}function y(b){const R=b.target;n("setVolume",parseInt(R.value))}function w(b){n("selectQuality",b),r.value=!1}function g(b){if(!isFinite(b))return"0:00";const R=Math.floor(b/3600),V=Math.floor(b%3600/60),I=Math.floor(b%60);return R>0?`${R}:${V.toString().padStart(2,"0")}:${I.toString().padStart(2,"0")}`:`${V}:${I.toString().padStart(2,"0")}`}return e.onMounted(()=>{document.addEventListener("mousemove",h),v()}),e.onUnmounted(()=>{document.removeEventListener("mousemove",h),f&&clearTimeout(f)}),(b,R)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-controls",{"controls-visible":i.value}]),"data-testid":"video-controls"},[e.createElementVNode("div",{class:"progress-container","data-testid":"video-progress-bar",role:"slider","aria-valuenow":Math.round(b.currentTime),"aria-valuemin":"0","aria-valuemax":Math.round(b.duration),"aria-label":b.isLive?"Live stream":"Video progress",tabindex:"0",onClick:k},[e.createElementVNode("div",R3,[e.createElementVNode("div",{class:"progress-buffered",style:e.normalizeStyle(m.value)},null,4),e.createElementVNode("div",{class:"progress-played",style:e.normalizeStyle(c.value)},null,4),e.createElementVNode("div",{class:"progress-thumb",style:e.normalizeStyle(u.value)},null,4)]),e.createElementVNode("div",L3,[e.createElementVNode("span",P3,e.toDisplayString(g(b.currentTime)),1),R[7]||(R[7]=e.createElementVNode("span",{class:"separator"},"/",-1)),e.createElementVNode("span",U3,e.toDisplayString(b.isLive?"LIVE":g(b.duration)),1)])],8,A3),e.createElementVNode("div",O3,[e.createElementVNode("div",z3,[e.createElementVNode("button",{class:"control-btn play-pause","data-testid":"btn-video-play-pause",onClick:R[0]||(R[0]=V=>b.$emit("play-pause")),"aria-label":b.playing?"Pause":"Play"},[e.createVNode(e.unref(H.IonIcon),{icon:b.playing?e.unref(vv):e.unref(bv),"aria-hidden":"true"},null,8,["icon"])],8,j3),b.isLive?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("button",{key:0,class:"control-btn skip-backward","data-testid":"btn-video-skip-backward",onClick:R[1]||(R[1]=V=>b.$emit("skip-backward")),"aria-label":"Skip backward 10 seconds"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(yv),"aria-hidden":"true"},null,8,["icon"]),R[8]||(R[8]=e.createElementVNode("span",{class:"skip-label"},"10",-1))])),b.isLive?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("button",{key:1,class:"control-btn skip-forward","data-testid":"btn-video-skip-forward",onClick:R[2]||(R[2]=V=>b.$emit("skip-forward")),"aria-label":"Skip forward 10 seconds"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(_v),"aria-hidden":"true"},null,8,["icon"]),R[9]||(R[9]=e.createElementVNode("span",{class:"skip-label"},"10",-1))]))]),e.createElementVNode("div",W3,[e.unref(s)?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",H3,[e.createElementVNode("button",{class:"control-btn mute-btn","data-testid":"btn-video-mute",onClick:R[3]||(R[3]=V=>b.$emit("toggleMute")),"aria-label":b.muted?"Unmute":"Mute"},[e.createVNode(e.unref(H.IonIcon),{icon:p.value,"aria-hidden":"true"},null,8,["icon"])],8,Z3),e.createElementVNode("input",{type:"range",class:"volume-slider","data-testid":"slider-video-volume",min:"0",max:"100",value:b.muted?0:b.volume,onInput:y,"aria-label":"Volume"},null,40,G3)]))]),e.createElementVNode("div",X3,[b.qualityLevels.length>1?(e.openBlock(),e.createElementBlock("div",K3,[e.createElementVNode("button",{class:"control-btn quality-btn","data-testid":"btn-video-quality",onClick:R[4]||(R[4]=V=>r.value=!r.value),"aria-label":"Quality settings","aria-expanded":r.value},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Vv),"aria-hidden":"true"},null,8,["icon"]),e.createElementVNode("span",q3,e.toDisplayString(b.currentQuality),1)],8,J3),r.value?(e.openBlock(),e.createElementBlock("div",Y3,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(b.qualityLevels,V=>(e.openBlock(),e.createElementBlock("button",{key:V.label,class:e.normalizeClass(["quality-option",{active:V.label===b.currentQuality}]),"data-testid":`btn-video-quality-${V.label}`,"aria-label":`Set quality to ${V.label}`,role:"menuitem",onClick:I=>w(V)},e.toDisplayString(V.label),11,Q3))),128))])):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0),!e.unref(s)&&d?(e.openBlock(),e.createElementBlock("button",{key:1,class:"control-btn pip-btn","data-testid":"btn-video-pip",onClick:R[5]||(R[5]=V=>b.$emit("togglePiP")),"aria-label":"Picture in Picture"},[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(Tv),"aria-hidden":"true"},null,8,["icon"])])):e.createCommentVNode("",!0),e.createElementVNode("button",{class:"control-btn fullscreen-btn","data-testid":"btn-video-fullscreen",onClick:R[6]||(R[6]=V=>b.$emit("toggleFullscreen")),"aria-label":b.fullscreen?"Exit fullscreen":"Enter fullscreen"},[e.createVNode(e.unref(H.IonIcon),{icon:b.fullscreen?e.unref(rv):e.unref(dv),"aria-hidden":"true"},null,8,["icon"])],8,e$)])])],2))}}),a$=$e(t$,[["__scopeId","data-v-2ae77c13"]]);function n$(o={}){var de,Ne,ce;const a=e.ref(),t=e.ref(),n=e.ref(!1),i=e.ref(0),r=e.ref(0),l=e.ref(100),s=e.ref(o.muted||!1),d=e.ref(!1),c=e.ref(),u=e.ref(1),m=e.ref(!1),p=e.ref(null),f=e.ref("idle"),h=e.ref(o.playbackUrl||((de=o.media)==null?void 0:de.playback_url)||((Ne=o.media)==null?void 0:Ne.url)||""),v=e.ref(null),k=e.ref(o.isLive||!1),y=e.ref(null),w=e.ref(null);function g(le){w.value=le}if((ce=o.media)!=null&&ce.token_expires_at){const le=new Date(o.media.token_expires_at);v.value=Number.isNaN(le.getTime())?null:le}async function b(){var W;const le=k.value?t.value:a.value;if(le)try{await le.play(),n.value=!0,f.value=k.value?"live":"playing",(W=o.onPlay)==null||W.call(o)}catch{p.value="Failed to play video",f.value="error"}}function R(){var W;const le=k.value?t.value:a.value;le&&(le.pause(),n.value=!1,f.value="paused",(W=o.onPause)==null||W.call(o))}function V(){n.value?R():b()}function I(le){const W=k.value?t.value:a.value;if(!W||k.value)return;const C=Number.isFinite(W.duration)?W.duration:le;W.currentTime=Math.max(0,Math.min(le,C)),i.value=W.currentTime}function x(le=10){const W=a.value;!W||k.value||I(W.currentTime+le)}function T(le=10){const W=a.value;!W||k.value||I(W.currentTime-le)}function $(){const le=k.value?t.value:a.value;le&&(le.muted=!le.muted,s.value=le.muted)}function S(le){const W=k.value?t.value:a.value;if(!W)return;const C=Math.max(0,Math.min(100,le));W.volume=C/100,l.value=C,C>0&&W.muted&&(W.muted=!1,s.value=!1)}function B(le){const W=a.value;!W||k.value||(W.playbackRate=le,u.value=le)}async function _(){const le=document.querySelector(".video-player-container");if(le)try{document.fullscreenElement?(await document.exitFullscreen(),d.value=!1):(await le.requestFullscreen(),d.value=!0)}catch{}}async function A(){const le=k.value?t.value:a.value;if(le)try{document.pictureInPictureElement?await document.exitPictureInPicture():document.pictureInPictureEnabled&&await le.requestPictureInPicture()}catch{}}async function P(){var W;p.value=null,f.value="loading",(W=o.media)!=null&&W.provider&&o.media.provider!=="local"&&await D();const le=k.value?t.value:a.value;le&&(le.load(),await b())}async function D(){if(!(!w.value||!o.media))try{m.value=!0;const le=await w.value.get(`/api/v1/video/${o.media.uuid}/playback`);h.value=le.playback_url,v.value=new Date(le.token_expires_at);const W=k.value?t.value:a.value;if(W&&W.src!==h.value){const C=!W.paused,U=W.currentTime;W.src=h.value,k.value||(W.currentTime=U),C&&await b()}}catch{p.value="Failed to refresh playback token",f.value="error"}finally{m.value=!1}}async function z(le){if(t.value){if(t.value.canPlayType("application/vnd.apple.mpegurl")){t.value.src=le;return}try{t.value.src=le}catch{p.value="Live streaming not supported in this browser",f.value="error"}}}function M(){y.value&&(y.value.destroy(),y.value=null)}function Z(){var W;const le=k.value?t.value:a.value;le&&(i.value=le.currentTime,r.value=le.duration,(W=o.onTimeUpdate)==null||W.call(o,le.currentTime))}const O=e.computed(()=>{if(!c.value||c.value.length===0||!r.value)return 0;for(let le=0;le<c.value.length;le++){const W=c.value.start(le),C=c.value.end(le);if(i.value>=W&&i.value<=C)return C/r.value*100}return 0});function K(){if(!v.value)return!1;const le=new Date;return v.value.getTime()-le.getTime()<5*60*1e3}return e.watch([a,t],([le,W])=>{const C=k.value?W:le;C&&(C.addEventListener("timeupdate",Z),C.addEventListener("loadedmetadata",()=>{r.value=C.duration,f.value="ready"}),C.addEventListener("progress",()=>{c.value=C.buffered}),C.addEventListener("ended",()=>{var U;n.value=!1,f.value="ended",(U=o.onEnded)==null||U.call(o)}),C.addEventListener("error",U=>{var j;f.value="error",(j=o.onError)==null||j.call(o,"Video playback error")}),C.volume=l.value/100,C.muted=s.value)}),e.onUnmounted(()=>{M();const le=k.value?t.value:a.value;le&&le.removeEventListener("timeupdate",Z)}),{videoEl:a,liveVideoEl:t,playing:n,currentTime:i,duration:r,volume:l,muted:s,isFullscreen:d,bufferedRanges:c,bufferedPercent:O,playbackRate:u,isLoading:m,error:p,status:f,currentPlaybackUrl:h,tokenExpiresAt:v,play:b,pause:R,togglePlayPause:V,seek:I,skipForward:x,skipBackward:T,toggleMute:$,setVolume:S,setPlaybackRate:B,toggleFullscreen:_,togglePiP:A,retry:P,refreshToken:D,setupLiveStream:z,setApiClient:g,shouldRefreshToken:K}}const o$=["src","poster","controls","autoplay","muted","loop","preload"],i$={key:1,ref:"livePlayerEl",class:"live-player"},r$=["controls","muted"],l$={key:0,class:"live-indicator","data-testid":"video-live-indicator","aria-label":"Live stream"},s$={key:2,class:"video-loading","data-testid":"video-loading",role:"status","aria-label":"Loading video"},d$={key:3,class:"video-error","data-testid":"video-error",role:"alert"},c$={key:5,class:"gesture-zones","data-testid":"video-gesture-zones"},u$=e.defineComponent({__name:"VideoPlayer",props:{media:{},playbackUrl:{},apiClient:{},isLive:{type:Boolean,default:!1},controls:{type:Boolean,default:!0},autoplay:{type:Boolean,default:!1},muted:{type:Boolean,default:!1},loop:{type:Boolean,default:!1},poster:{},preload:{default:"metadata"},showCustomControls:{type:Boolean,default:!1},enableGestures:{type:Boolean,default:!0},className:{},crossorigin:{}},emits:["play","pause","ended","error","timeupdate","loadedmetadata","progress"],setup(o,{emit:a}){const t=o,n=a,{videoEl:i,liveVideoEl:r,playing:l,currentTime:s,duration:d,volume:c,muted:u,isFullscreen:m,bufferedRanges:p,isLoading:f,error:h,status:v,currentPlaybackUrl:k,tokenExpiresAt:y,play:w,pause:g,seek:b,toggleMute:R,setVolume:V,toggleFullscreen:I,togglePlayPause:x,skipForward:T,skipBackward:$,retry:S,refreshToken:B,setApiClient:_,shouldRefreshToken:A,setupLiveStream:P}=n$({...t.media!==void 0?{media:t.media}:{},...t.playbackUrl!==void 0?{playbackUrl:t.playbackUrl}:{},isLive:t.isLive??!1,autoplay:t.autoplay??!1,muted:t.muted??!1});async function D(){await B()}const z=e.computed(()=>{const j=["video-player-container"];return t.className&&j.push(t.className),m.value&&j.push("fullscreen"),t.isLive&&j.push("is-live"),l.value&&j.push("is-playing"),f.value&&j.push("is-loading"),j}),M=e.computed(()=>{var j,re;if(t.poster)return t.poster;if((j=t.media)!=null&&j.poster_url)return t.media.poster_url;if((re=t.media)!=null&&re.thumbnail_url)return t.media.thumbnail_url});function Z(j){const re=j.target;n("loadedmetadata",{duration:re.duration,width:re.videoWidth,height:re.videoHeight})}function O(j){const re=j.target;s.value=re.currentTime,n("timeupdate",re.currentTime)}function K(){l.value=!0,n("play")}function de(){l.value=!1,n("pause")}function Ne(){l.value=!1,n("ended")}function ce(j){const re=j.target;let ue="Failed to load video";if(re.error)switch(re.error.code){case re.error.MEDIA_ERR_ABORTED:ue="Video playback aborted";break;case re.error.MEDIA_ERR_NETWORK:ue="Network error while loading video";break;case re.error.MEDIA_ERR_DECODE:ue="Video decoding error";break;case re.error.MEDIA_ERR_SRC_NOT_SUPPORTED:ue="Video format not supported";break}h.value=ue,n("error",ue)}function le(j){const re=j.target;p.value=re.buffered,n("progress",re.buffered)}function W(){f.value=!0}function C(){f.value=!1}e.watch(()=>t.apiClient,j=>{j&&_(j)},{immediate:!0}),e.watch(()=>t.playbackUrl,j=>{typeof j=="string"&&j.length>0&&(k.value=j)},{immediate:!0}),e.watch(()=>{var j;return(j=t.media)==null?void 0:j.token_expires_at},j=>{if(!j){y.value=null;return}const re=new Date(j);y.value=Number.isNaN(re.getTime())?null:re},{immediate:!0}),e.watch(()=>{var j;return(j=t.media)==null?void 0:j.playback_url},async(j,re)=>{if(t.playbackUrl||!j||j===re)return;const ue=i.value;if(!ue||t.isLive){k.value=j;return}const Xe=!ue.paused,be=ue.currentTime;k.value=j,await e.nextTick();try{ue.currentTime=be}catch{}Xe&&await w()},{immediate:!0});let U=null;return e.watch(()=>t.isLive,async j=>{var ue;if(!j)return;const re=t.playbackUrl||((ue=t.media)==null?void 0:ue.playback_url)||"";re&&await P(re)},{immediate:!0}),e.onMounted(()=>{var j;(j=t.media)!=null&&j.provider&&t.media.provider!=="local"&&(U=setInterval(()=>{A()&&D()},3e4)),H.isPlatform("mobile")&&t.showCustomControls}),e.onUnmounted(()=>{U&&clearInterval(U)}),(j,re)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-player-container",z.value]),"data-testid":"video-player"},[j.isLive?(e.openBlock(),e.createElementBlock("div",i$,[e.createElementVNode("video",{ref_key:"liveVideoEl",ref:r,controls:j.controls&&!j.showCustomControls,autoplay:!0,muted:e.unref(u),onPlay:K,onPause:de,onError:ce,playsinline:"",class:"video-element","data-testid":"video-element"},null,40,r$),e.unref(v)==="live"?(e.openBlock(),e.createElementBlock("div",l$,[...re[3]||(re[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(k),poster:M.value,controls:j.controls&&!j.showCustomControls,autoplay:j.autoplay,muted:e.unref(u),loop:j.loop,preload:j.preload,onLoadedmetadata:Z,onTimeupdate:O,onPlay:K,onPause:de,onEnded:Ne,onError:ce,onProgress:le,onWaiting:W,onCanplay:C,playsinline:"",class:"video-element","data-testid":"video-element"},null,40,o$)),e.unref(f)?(e.openBlock(),e.createElementBlock("div",s$,[e.createVNode(e.unref(H.IonSpinner),{name:"crescent"})])):e.createCommentVNode("",!0),e.unref(h)?(e.openBlock(),e.createElementBlock("div",d$,[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(td),"aria-hidden":"true"},null,8,["icon"]),e.createElementVNode("p",null,e.toDisplayString(e.unref(h)),1),e.createVNode(e.unref(H.IonButton),{size:"small",onClick:e.unref(S),"data-testid":"btn-video-retry","aria-label":"Retry loading video"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{icon:e.unref(io),slot:"start","aria-hidden":"true"},null,8,["icon"]),re[4]||(re[4]=e.createTextVNode(" Retry ",-1))]),_:1},8,["onClick"])])):e.createCommentVNode("",!0),j.showCustomControls&&!e.unref(h)?(e.openBlock(),e.createBlock(a$,{key:4,playing:e.unref(l),currentTime:e.unref(s),duration:e.unref(d),buffered:e.unref(p),volume:e.unref(c),muted:e.unref(u),fullscreen:e.unref(m),isLive:j.isLive,onPlay:e.unref(w),onPause:e.unref(g),onSeek:e.unref(b),onToggleMute:e.unref(R),onSetVolume:e.unref(V),onToggleFullscreen:e.unref(I),class:"custom-controls"},null,8,["playing","currentTime","duration","buffered","volume","muted","fullscreen","isLive","onPlay","onPause","onSeek","onToggleMute","onSetVolume","onToggleFullscreen"])):e.createCommentVNode("",!0),j.enableGestures&&!e.unref(h)?(e.openBlock(),e.createElementBlock("div",c$,[e.createElementVNode("div",{class:"gesture-left","data-testid":"video-gesture-skip-back","aria-label":"Double tap to skip backward",onDblclick:re[0]||(re[0]=(...ue)=>e.unref($)&&e.unref($)(...ue))},null,32),e.createElementVNode("div",{class:"gesture-center","data-testid":"video-gesture-play-pause","aria-label":"Tap to play or pause",onClick:re[1]||(re[1]=(...ue)=>e.unref(x)&&e.unref(x)(...ue))}),e.createElementVNode("div",{class:"gesture-right","data-testid":"video-gesture-skip-forward","aria-label":"Double tap to skip forward",onDblclick:re[2]||(re[2]=(...ue)=>e.unref(T)&&e.unref(T)(...ue))},null,32)])):e.createCommentVNode("",!0)],2))}}),nf=$e(u$,[["__scopeId","data-v-b8db4951"]]),m$=Qr.defineStore("video",()=>{const o=e.ref(new Map),a=e.ref(new Map),t=e.ref(new Map),n=e.ref(null),i=e.ref(!1),r=e.computed(()=>Array.from(o.value.values())),l=e.computed(()=>Array.from(a.value.values())),s=e.computed(()=>l.value.filter(P=>P.status==="live")),d=e.computed(()=>r.value.filter(P=>P.processing_status==="processing"));function c(P){o.value.set(P.uuid,P)}function u(P,D){const z=o.value.get(P);z&&o.value.set(P,{...z,...D})}function m(P){o.value.delete(P)}function p(P){return o.value.get(P)}function f(P){a.value.set(P.id,P)}function h(P,D){const z=a.value.get(P);z&&a.value.set(P,{...z,...D})}function v(P,D){const z=a.value.get(P);z&&a.value.set(P,{...z,status:D.status,viewer_count:D.viewer_count,peak_viewers:D.peak_viewers})}function k(P){a.value.delete(P)}function y(P){return a.value.get(P)}function w(P){return l.value.find(D=>D.media_uuid===P)}function g(P){t.value.set(P.id,P)}function b(P,D){const z=t.value.get(P);z&&t.value.set(P,{...z,...D})}function R(P){t.value.delete(P)}function V(P){return t.value.get(P)}function I(P){return Array.from(t.value.values()).filter(D=>D.media_uuid===P)}function x(P){n.value=P}function T(P){n.value&&(n.value={...n.value,...P})}function $(){n.value=null}function S(P){i.value=P}function B(){o.value.clear(),a.value.clear(),t.value.clear(),n.value=null,i.value=!1}function _(P){o.value.clear(),P.forEach(D=>{o.value.set(D.uuid,D)})}function A(P){a.value.clear(),P.forEach(D=>{a.value.set(D.id,D)})}return{videos:o,liveStreams:a,exportJobs:t,currentEditorState:n,isProcessing:i,allVideos:r,allLiveStreams:l,activeLiveStreams:s,processingVideos:d,setVideo:c,updateVideo:u,removeVideo:m,getVideo:p,setLiveStream:f,updateLiveStream:h,updateLiveStreamStats:v,removeLiveStream:k,getLiveStream:y,getLiveStreamByMedia:w,addExportJob:g,updateExportJob:b,removeExportJob:R,getExportJob:V,getExportJobsByMedia:I,setEditorState:x,updateEditorState:T,clearEditorState:$,setProcessing:S,clearAll:B,loadVideos:_,loadLiveStreams:A}});let Hn=null;function p$(o){Hn=o}const vr={post:async(o,a)=>{if(!Hn)throw new Error("HTTP client not configured");return await Hn(`/api/v1/video${o}`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json"}})},get:async o=>{if(!Hn)throw new Error("HTTP client not configured");return await Hn(`/api/v1/video${o}`)},delete:async o=>{if(!Hn)throw new Error("HTTP client not configured");return await Hn(`/api/v1/video${o}`,{method:"DELETE"})}};function gr(o,a=null){const t=typeof o.id=="string"&&o.id!==""?o.id:typeof o.stream_id=="string"&&o.stream_id!==""?o.stream_id:a==null?void 0:a.id;if(!t)throw new Error("Invalid live stream response: missing stream id");const n={id:t,media_uuid:o.media_uuid??(a==null?void 0:a.media_uuid)??"",stream_key:o.stream_key??(a==null?void 0:a.stream_key)??"",rtmp_url:o.rtmp_url??(a==null?void 0:a.rtmp_url)??"",status:o.status??(a==null?void 0:a.status)??"idle",viewer_count:o.viewer_count??(a==null?void 0:a.viewer_count)??0,peak_viewers:o.peak_viewers??(a==null?void 0:a.peak_viewers)??0,auto_record:o.auto_record??(a==null?void 0:a.auto_record)??!0,low_latency:o.low_latency??(a==null?void 0:a.low_latency)??!1},i=o.playback_url??(a==null?void 0:a.playback_url);i!==void 0&&(n.playback_url=i);const r=o.started_at??(a==null?void 0:a.started_at);r!==void 0&&(n.started_at=r);const l=o.ended_at??(a==null?void 0:a.ended_at);return l!==void 0&&(n.ended_at=l),(a==null?void 0:a.metadata)!==void 0&&(n.metadata=a.metadata),(a==null?void 0:a.vod_media_uuid)!==void 0&&(n.vod_media_uuid=a.vod_media_uuid),n}function is(o,a){return o instanceof Error&&o.message?o.message:a}function f$(o){const a=m$(),t=e.ref(null),n=e.ref(!1),i=e.ref(!0),r=e.ref(""),l=e.ref(!1),s=e.ref(!1),d=e.ref(null),c=e.ref(null),u=e.ref(0),m=e.ref(0);let p;const f=e.computed(()=>c.value?Math.floor((new Date().getTime()-c.value.getTime())/1e3):0),h=e.computed(()=>{var $;if(!(($=t.value)!=null&&$.playback_url))return null;const T=new URL(t.value.playback_url);return T.searchParams.set("live","true"),n.value&&T.searchParams.set("latency","low"),T.toString()}),v=e.computed(()=>{var T;return((T=t.value)==null?void 0:T.status)==="live"}),k=e.computed(()=>{var T;return((T=t.value)==null?void 0:T.status)==="idle"}),y=e.computed(()=>{var T;return((T=t.value)==null?void 0:T.status)==="ended"});async function w(T={}){l.value=!0,d.value=null;try{const $=await vr.post("/live",{title:r.value||T.title||"Live Stream",low_latency:T.low_latency??n.value,auto_record:T.auto_record??i.value,...T}),S=gr($);return t.value=S,a.setLiveStream(S),V(),S}catch($){throw d.value=is($,"Failed to create stream"),$ instanceof Error?$:new Error(d.value)}finally{l.value=!1}}async function g(){if(!t.value)throw new Error("No active stream");s.value=!0,d.value=null;try{const T=await vr.post(`/live/${t.value.id}/end`),$=gr(T,t.value);return t.value=$,a.setLiveStream($),I(),$}catch(T){throw d.value=is(T,"Failed to end stream"),T instanceof Error?T:new Error(d.value)}finally{s.value=!1}}async function b(){if(t.value)try{const T=await vr.get(`/live/${t.value.id}`),$=gr(T,t.value);u.value=$.viewer_count,m.value=$.peak_viewers,t.value=$;const S={status:$.status,viewer_count:$.viewer_count,peak_viewers:$.peak_viewers};$.started_at&&(S.started_at=$.started_at),$.ended_at&&(S.ended_at=$.ended_at),a.updateLiveStreamStats($.id,S),$.status==="live"&&!c.value&&$.started_at&&(c.value=new Date($.started_at)),$.status==="ended"&&I()}catch{}}async function R(T){try{const $=await vr.get(`/live/${T}`),S=gr($,t.value);return{rtmp_url:S.rtmp_url,stream_key:S.stream_key,playback_url:S.playback_url||""}}catch($){throw d.value=is($,"Failed to get stream credentials"),$ instanceof Error?$:new Error(d.value)}}function V(T=5e3){I(),p=window.setInterval(()=>{b()},T)}function I(){p!==void 0&&(clearInterval(p),p=void 0)}async function x(){if(!o)return;const T=a.getLiveStreamByMedia(o);T&&(t.value=T,u.value=T.viewer_count,m.value=T.peak_viewers,T.status==="live"&&(V(),T.started_at&&(c.value=new Date(T.started_at))))}return o&&x(),e.onUnmounted(()=>{I()}),{stream:t,lowLatency:n,autoRecord:i,streamTitle:r,isCreating:l,isEnding:s,error:d,streamDuration:f,viewerCount:u,peakViewers:m,playbackUrl:h,isLive:v,isIdle:k,hasEnded:y,createStream:w,endStream:g,refreshStreamStatus:b,getStreamCredentials:R,startStatusPolling:V,stopStatusPolling:I}}const h$={class:"stream-status"},v$={class:"flex items-center justify-between"},g$={class:"flex items-center gap-3"},b$={key:0,class:"flex items-center"},y$={key:2,class:"text-sm text-gray-600"},w$={key:0,class:"flex items-center gap-2"},k$={class:"text-sm font-medium text-gray-700"},_$={key:0,class:"text-xs text-gray-500"},E$=e.defineComponent({__name:"StreamStatus",props:{status:{},viewers:{},peakViewers:{},duration:{}},setup(o){const a=o,t=e.computed(()=>({idle:"Ready to Stream",live:"Live",ended:"Stream Ended",error:"Error"})[a.status]||a.status),n=e.computed(()=>{const r="px-3 py-1 rounded-full text-xs font-semibold uppercase",l={idle:"bg-gray-100 text-gray-700",live:"bg-red-100 text-red-700",ended:"bg-blue-100 text-blue-700",error:"bg-yellow-100 text-yellow-700"};return`${r} ${l[a.status]||l.idle}`}),i=e.computed(()=>{if(!a.duration)return null;const r=Math.floor(a.duration/3600),l=Math.floor(a.duration%3600/60),s=a.duration%60;return r>0?`${r}:${l.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`:`${l}:${s.toString().padStart(2,"0")}`});return(r,l)=>(e.openBlock(),e.createElementBlock("div",h$,[e.createElementVNode("div",v$,[e.createElementVNode("div",g$,[r.status==="live"?(e.openBlock(),e.createElementBlock("div",b$,[...l[0]||(l[0]=[e.createElementVNode("span",{class:"relative flex h-3 w-3"},[e.createElementVNode("span",{class:"animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"}),e.createElementVNode("span",{class:"relative inline-flex rounded-full h-3 w-3 bg-red-500"})],-1),e.createElementVNode("span",{class:"ml-2 text-sm font-semibold text-red-600 uppercase"},"Live",-1)])])):(e.openBlock(),e.createElementBlock("div",{key:1,class:e.normalizeClass(n.value)},e.toDisplayString(t.value),3)),i.value?(e.openBlock(),e.createElementBlock("div",y$,e.toDisplayString(i.value),1)):e.createCommentVNode("",!0)]),r.viewers!==void 0?(e.openBlock(),e.createElementBlock("div",w$,[l[1]||(l[1]=e.createElementVNode("svg",{class:"w-4 h-4 text-gray-500",fill:"currentColor",viewBox:"0 0 20 20"},[e.createElementVNode("path",{d:"M10 12a2 2 0 100-4 2 2 0 000 4z"}),e.createElementVNode("path",{"fill-rule":"evenodd",d:"M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z","clip-rule":"evenodd"})],-1)),e.createElementVNode("span",k$,e.toDisplayString(r.viewers)+" "+e.toDisplayString(r.viewers===1?"viewer":"viewers"),1),r.peakViewers>r.viewers?(e.openBlock(),e.createElementBlock("span",_$," (Peak: "+e.toDisplayString(r.peakViewers)+") ",1)):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)])]))}}),S$=$e(E$,[["__scopeId","data-v-1d09c19f"]]),C$={class:"stream-credentials"},x$={class:"space-y-3"},N$={class:"credential-field"},V$={class:"flex gap-2"},T$=["value"],B$={class:"credential-field"},I$={class:"flex gap-2"},M$=["value","type"],$$=["aria-label"],F$={key:0,class:"w-4 h-4 text-gray-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},D$={key:1,class:"w-4 h-4 text-gray-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},A$={key:0,class:"mt-2 text-sm text-green-600"},R$=e.defineComponent({__name:"StreamCredentials",props:{rtmpUrl:{},streamKey:{}},emits:["copy"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!1),r=e.ref(""),l=e.computed(()=>{if(i.value)return t.streamKey;if(t.streamKey.length>8){const c=t.streamKey.slice(0,4),u=t.streamKey.slice(-4);return`${c}${"•".repeat(16)}${u}`}return"•".repeat(t.streamKey.length)});function s(){i.value=!i.value}async function d(c,u){try{await navigator.clipboard.writeText(c),r.value=u,n("copy",c,u),setTimeout(()=>{r.value=""},2e3)}catch{}}return(c,u)=>(e.openBlock(),e.createElementBlock("div",C$,[u[8]||(u[8]=e.createElementVNode("h4",{class:"text-sm font-medium text-gray-700 mb-3"},"Stream Settings",-1)),e.createElementVNode("div",x$,[e.createElementVNode("div",N$,[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",V$,[e.createElementVNode("input",{value:c.rtmpUrl,readonly:"",type:"text",class:"flex-1 px-3 py-2 bg-gray-50 border border-gray-200 rounded-md text-sm font-mono text-gray-700","aria-label":"RTMP server URL"},null,8,T$),e.createElementVNode("button",{onClick:u[0]||(u[0]=m=>d(c.rtmpUrl,"RTMP URL")),class:"px-3 py-2 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors","aria-label":"Copy RTMP URL"},[...u[2]||(u[2]=[e.createElementVNode("svg",{class:"w-4 h-4 text-gray-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})],-1)])])])]),e.createElementVNode("div",B$,[u[7]||(u[7]=e.createElementVNode("label",{class:"block text-xs font-medium text-gray-500 mb-1"},"Stream Key",-1)),e.createElementVNode("div",I$,[e.createElementVNode("input",{value:l.value,readonly:"",type:i.value?"text":"password",class:"flex-1 px-3 py-2 bg-gray-50 border border-gray-200 rounded-md text-sm font-mono text-gray-700","aria-label":"Stream key"},null,8,M$),e.createElementVNode("button",{onClick:s,class:"px-3 py-2 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors","aria-label":i.value?"Hide stream key":"Show stream key"},[i.value?(e.openBlock(),e.createElementBlock("svg",D$,[...u[5]||(u[5]=[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"},null,-1)])])):(e.openBlock(),e.createElementBlock("svg",F$,[...u[4]||(u[4]=[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"},null,-1),e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"},null,-1)])]))],8,$$),e.createElementVNode("button",{onClick:u[1]||(u[1]=m=>d(c.streamKey,"Stream Key")),class:"px-3 py-2 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors","aria-label":"Copy stream key"},[...u[6]||(u[6]=[e.createElementVNode("svg",{class:"w-4 h-4 text-gray-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})],-1)])])])])]),u[9]||(u[9]=e.createElementVNode("details",{class:"mt-4"},[e.createElementVNode("summary",{class:"cursor-pointer text-sm text-blue-600 hover:text-blue-700"}," How to connect with OBS Studio "),e.createElementVNode("div",{class:"mt-2 p-3 bg-blue-50 rounded-md text-sm text-gray-700"},[e.createElementVNode("ol",{class:"list-decimal list-inside space-y-1"},[e.createElementVNode("li",null,"Open OBS Studio"),e.createElementVNode("li",null,"Go to Settings → Stream"),e.createElementVNode("li",null,'Set Service to "Custom"'),e.createElementVNode("li",null,'Paste the RTMP URL in "Server"'),e.createElementVNode("li",null,'Paste the Stream Key in "Stream Key"'),e.createElementVNode("li",null,'Click OK and then "Start Streaming"')])])],-1)),e.createVNode(e.Transition,{name:"fade"},{default:e.withCtx(()=>[r.value?(e.openBlock(),e.createElementBlock("div",A$,e.toDisplayString(r.value)+" copied to clipboard! ",1)):e.createCommentVNode("",!0)]),_:1})]))}}),L$=$e(R$,[["__scopeId","data-v-306d92f6"]]),P$={class:"live-stream-manager","data-testid":"live-stream-manager"},U$={key:0,class:"stream-setup"},O$={class:"space-y-4"},z$={class:"flex items-center justify-between p-4 bg-gray-50 rounded-lg"},j$={class:"flex items-center justify-between p-4 bg-gray-50 rounded-lg"},W$=["disabled"],H$={key:0},Z$={key:1,class:"flex items-center justify-center"},G$={key:1,class:"stream-active space-y-6"},X$={key:1,class:"video-preview"},K$={key:2,class:"analytics-panel"},J$={class:"grid grid-cols-2 gap-4"},q$={class:"bg-gray-50 p-3 rounded"},Y$={class:"text-2xl font-bold text-gray-900"},Q$={class:"bg-gray-50 p-3 rounded"},e5={class:"text-2xl font-bold text-gray-900"},t5={class:"stream-controls flex gap-3"},a5=["disabled"],n5={key:0},o5={key:1},i5={key:2,class:"mt-4 p-4 bg-red-50 border border-red-200 rounded-lg"},r5={class:"text-red-600 text-sm"},l5=e.defineComponent({__name:"LiveStreamManager",props:{mediaUuid:{},onStreamCreated:{type:Function},onStreamEnded:{type:Function},httpClient:{type:Function}},emits:["stream-created","stream-ended","error"],setup(o,{emit:a}){const t=o,n=a;t.httpClient&&p$(t.httpClient);const{stream:i,lowLatency:r,autoRecord:l,streamTitle:s,isCreating:d,isEnding:c,error:u,createStream:m,endStream:p,streamDuration:f,playbackUrl:h,refreshStreamStatus:v}=f$(t.mediaUuid),k=e.ref(!1);async function y(){var V;try{const I=await m({title:s.value,low_latency:r.value,auto_record:l.value});n("stream-created",I),(V=t.onStreamCreated)==null||V.call(t,I)}catch(I){n("error",I)}}async function w(){var V;try{const I=await p();n("stream-ended",I),(V=t.onStreamEnded)==null||V.call(t,I)}catch(I){n("error",I)}}function g(){i.value=null,s.value="",k.value=!1,u.value=null}async function b(V,I){try{await navigator.clipboard.writeText(V)}catch{}}let R;return e.onMounted(()=>{var V;((V=i.value)==null?void 0:V.status)==="live"&&(R=window.setInterval(()=>{v()},5e3))}),e.onUnmounted(()=>{R&&clearInterval(R)}),(V,I)=>(e.openBlock(),e.createElementBlock("div",P$,[e.unref(i)?(e.openBlock(),e.createElementBlock("div",G$,[e.createVNode(S$,{status:e.unref(i).status,viewers:e.unref(i).viewer_count,duration:e.unref(f),"peak-viewers":e.unref(i).peak_viewers},null,8,["status","viewers","duration","peak-viewers"]),e.unref(i).status==="idle"?(e.openBlock(),e.createBlock(L$,{key:0,"rtmp-url":e.unref(i).rtmp_url,"stream-key":e.unref(i).stream_key,onCopy:b},null,8,["rtmp-url","stream-key"])):e.createCommentVNode("",!0),e.unref(h)?(e.openBlock(),e.createElementBlock("div",X$,[I[9]||(I[9]=e.createElementVNode("h4",{class:"text-sm font-medium text-gray-700 mb-2"},"Live Preview",-1)),e.createVNode(nf,{"playback-url":e.unref(h),"is-live":!0,muted:!0,controls:!1,class:"w-full rounded-lg overflow-hidden"},null,8,["playback-url"])])):e.createCommentVNode("",!0),e.unref(i).status==="live"?(e.openBlock(),e.createElementBlock("div",K$,[I[12]||(I[12]=e.createElementVNode("h4",{class:"text-sm font-medium text-gray-700 mb-3"},"Live Analytics",-1)),e.createElementVNode("div",J$,[e.createElementVNode("div",q$,[e.createElementVNode("div",Y$,e.toDisplayString(e.unref(i).viewer_count),1),I[10]||(I[10]=e.createElementVNode("div",{class:"text-xs text-gray-500"},"Current Viewers",-1))]),e.createElementVNode("div",Q$,[e.createElementVNode("div",e5,e.toDisplayString(e.unref(i).peak_viewers),1),I[11]||(I[11]=e.createElementVNode("div",{class:"text-xs text-gray-500"},"Peak Viewers",-1))])])])):e.createCommentVNode("",!0),e.createElementVNode("div",t5,[e.unref(i).status==="idle"?(e.openBlock(),e.createElementBlock("button",{key:0,onClick:I[3]||(I[3]=x=>k.value=!k.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(k.value?"Hide":"Show")+" Credentials ",1)):e.createCommentVNode("",!0),e.unref(i).status==="live"?(e.openBlock(),e.createElementBlock("button",{key:1,onClick:w,disabled:e.unref(c),class:"flex-1 py-2 px-4 bg-red-600 text-white font-medium rounded-lg hover:bg-red-700 disabled:opacity-50 transition-colors","aria-label":"End live stream"},[e.unref(c)?(e.openBlock(),e.createElementBlock("span",o5,"Ending...")):(e.openBlock(),e.createElementBlock("span",n5,"End Stream"))],8,a5)):e.createCommentVNode("",!0),e.unref(i).status==="ended"?(e.openBlock(),e.createElementBlock("button",{key:2,onClick:g,class:"flex-1 py-2 px-4 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition-colors"}," Start New Stream ")):e.createCommentVNode("",!0)])])):(e.openBlock(),e.createElementBlock("div",U$,[I[8]||(I[8]=e.createElementVNode("h3",{class:"text-lg font-semibold mb-4"},"Start Live Stream",-1)),e.createElementVNode("div",O$,[e.createElementVNode("div",z$,[I[4]||(I[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":I[0]||(I[0]=x=>e.isRef(r)?r.value=x:null),type:"checkbox",class:"h-5 w-5 text-blue-600 rounded focus:ring-blue-500","aria-label":"Enable low latency mode"},null,512),[[e.vModelCheckbox,e.unref(r)]])]),e.createElementVNode("div",j$,[I[5]||(I[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":I[1]||(I[1]=x=>e.isRef(l)?l.value=x:null),type:"checkbox",class:"h-5 w-5 text-blue-600 rounded focus:ring-blue-500","aria-label":"Enable auto-recording"},null,512),[[e.vModelCheckbox,e.unref(l)]])]),e.createElementVNode("div",null,[I[6]||(I[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":I[2]||(I[2]=x=>e.isRef(s)?s.value=x:null),type:"text",class:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"My Live Stream"},null,512),[[e.vModelText,e.unref(s)]])]),e.createElementVNode("button",{onClick:y,disabled:e.unref(d),class:"w-full py-3 px-4 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors","data-testid":"create-stream-button","aria-label":"Create live stream"},[e.unref(d)?(e.openBlock(),e.createElementBlock("span",Z$,[...I[7]||(I[7]=[e.createElementVNode("svg",{class:"animate-spin h-5 w-5 mr-2",viewBox:"0 0 24 24"},[e.createElementVNode("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4",fill:"none"}),e.createElementVNode("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})],-1),e.createTextVNode(" Creating... ",-1)])])):(e.openBlock(),e.createElementBlock("span",H$,"Create Stream"))],8,W$)])])),e.unref(u)?(e.openBlock(),e.createElementBlock("div",i5,[e.createElementVNode("p",r5,e.toDisplayString(e.unref(u)),1)])):e.createCommentVNode("",!0)]))}}),s5=$e(l5,[["__scopeId","data-v-26291f6f"]]),d5={class:"album-tree-node"},c5=["data-album-id","draggable","aria-selected","aria-expanded"],u5={key:1,class:"album-node__chevron-placeholder"},m5={key:2,"data-testid":"media-count",class:"album-node__count"},p5={key:0,class:"album-tree-node__children",role:"group"},f5=16,h5=e.defineComponent({__name:"AlbumTreeNode",props:{album:{},depth:{},selectedId:{},expandedIds:{},focusedId:{},draggable:{type:Boolean},showMediaCount:{type:Boolean},compact:{type:Boolean},dragState:{}},emits:["select","toggle-expand","drag-start","drag-over","drag-leave","drop"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>t.expandedIds.has(t.album.id)),r=e.computed(()=>t.selectedId===t.album.id),l=e.computed(()=>t.focusedId===t.album.id),s=e.computed(()=>t.album.children_count>0),d=e.computed(()=>`${t.depth*f5}px`),c=e.computed(()=>{var g;return((g=t.dragState)==null?void 0:g.draggedAlbumId)===t.album.id}),u=e.computed(()=>{var g;return((g=t.dragState)==null?void 0:g.dropTargetId)===t.album.id}),m=e.computed(()=>{var g;return(g=t.dragState)!=null&&g.draggedAlbumId?t.dragState.draggedAlbumId===t.album.id:!1}),p=e.computed(()=>{const g=["album-node"];return r.value&&g.push("album-node--selected"),l.value&&g.push("album-node--focused"),t.compact&&g.push("album-node--compact"),c.value&&g.push("album-node--dragging"),u.value&&g.push("album-node--drop-target"),m.value&&g.push("album-node--invalid-drop"),g});function f(){n("select",t.album)}function h(g){g.stopPropagation(),n("toggle-expand",t.album.id)}function v(g){t.draggable&&(g.dataTransfer&&(g.dataTransfer.setData("text/plain",t.album.id),g.dataTransfer.effectAllowed="move"),n("drag-start",t.album.id))}function k(g){t.draggable&&(g.preventDefault(),g.dataTransfer&&(g.dataTransfer.dropEffect="move"),n("drag-over",t.album.id))}function y(){n("drag-leave",t.album.id)}function w(g){t.draggable&&(g.preventDefault(),n("drop",t.album.id))}return(g,b)=>{var V;const R=e.resolveComponent("AlbumTreeNode",!0);return e.openBlock(),e.createElementBlock("div",d5,[e.createElementVNode("div",{"data-testid":"album-node","data-album-id":g.album.id,class:e.normalizeClass(p.value),style:e.normalizeStyle({paddingLeft:d.value}),draggable:g.draggable,role:"treeitem","aria-selected":r.value,"aria-expanded":s.value?i.value:void 0,onDragstart:v,onDragover:k,onDragleave:y,onDrop:w},[s.value?(e.openBlock(),e.createElementBlock("button",{key:0,"data-testid":"expand-chevron",class:"album-node__chevron",type:"button","aria-label":"Toggle expand",onClick:h},[e.createVNode(e.unref(H.IonIcon),{icon:i.value?e.unref(nv):e.unref(ov)},null,8,["icon"])])):(e.openBlock(),e.createElementBlock("span",u5)),e.createVNode(e.unref(H.IonIcon),{icon:e.unref(mv),class:"album-node__icon"},null,8,["icon"]),e.createElementVNode("span",{"data-testid":"album-name",class:"album-node__name",onClick:f},e.toDisplayString(g.album.name),1),g.showMediaCount?(e.openBlock(),e.createElementBlock("span",m5,e.toDisplayString(g.album.media_count),1)):e.createCommentVNode("",!0)],46,c5),i.value&&((V=g.album.children)!=null&&V.length)?(e.openBlock(),e.createElementBlock("div",p5,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(g.album.children,I=>(e.openBlock(),e.createBlock(R,{key:I.id,album:I,depth:g.depth+1,"selected-id":g.selectedId,"expanded-ids":g.expandedIds,"focused-id":g.focusedId,draggable:g.draggable,"show-media-count":g.showMediaCount,compact:g.compact,onSelect:b[0]||(b[0]=x=>n("select",x)),onToggleExpand:b[1]||(b[1]=x=>n("toggle-expand",x))},null,8,["album","depth","selected-id","expanded-ids","focused-id","draggable","show-media-count","compact"]))),128))])):e.createCommentVNode("",!0)])}}}),v5=$e(h5,[["__scopeId","data-v-76be65a6"]]);let ao={apiBaseUrl:"/api/v1"};function of(o){ao={...ao,...o}}function g5(){return{...ao}}function b5(o){ao={...o}}function Nu(o,a){const t=(o??a).trim().replace(/\/+$/,"");return t===""?a:/^https?:\/\//i.test(t)||t.startsWith("/")?t:`/${t}`}function y5(){const o=Nu(ao.apiBaseUrl,"/api/v1");return Nu(ao.albumBaseUrl,`${o}/albums`)}function dn(o){return encodeURIComponent(o)}function w5(o,a){const t=new URLSearchParams;for(const[i,r]of Object.entries(a))r!==void 0&&t.set(i,r===null?"null":String(r));const n=t.toString();return n===""?o:`${o}?${n}`}function Ja(o="",a={}){return w5(`${y5()}${o}`,a)}async function k5(o,a={}){const t=a.method??"GET",n={Accept:"application/json",...a.headers},i={method:t,credentials:a.credentials??"include",headers:n};a.body!==void 0&&(n["Content-Type"]=n["Content-Type"]??"application/json",i.body=JSON.stringify(a.body));const r=await fetch(o,i);if(!r.ok)throw new Error(`Album request failed with status ${r.status}.`);return r.status===204?{}:await r.json()}const _5=3,E5=6e4,Io={count:0,haltUntil:0};function S5(){Io.count=0,Io.haltUntil=0}function C5(){Io.count+=1,Io.count>=_5&&(Io.haltUntil=Date.now()+E5)}function x5(){return Date.now()<Io.haltUntil}async function qa(o,a){if(x5())throw new Error("Album requests are temporarily halted after consecutive failures.");const t=ao.httpClient??k5;try{const n=await t(o,a);return S5(),n}catch(n){throw C5(),n}}function ri(o){if(typeof o!="object"||o===null)throw new Error("Album response was invalid");const a=o;if(typeof a.data!="object"||a.data===null)throw new Error("Album response was invalid");const t=a.data;return typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?t.data:a.data}function N5(o){if(typeof o!="object"||o===null)return[];const a=o;if(Array.isArray(a.data))return a.data;if(typeof a.data=="object"&&a.data!==null){const t=a.data;if(Array.isArray(t.data))return t.data}return[]}const Nl=Qr.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 x=new Map;return o.value.forEach(T=>x.set(T.id,T)),x}),l=e.computed(()=>o.value.filter(x=>x.parent_id===null));function s(x){const T=o.value.findIndex($=>$.id===x.id);T>=0?o.value[T]=x:o.value.push(x)}function d(x,T){Array.isArray(T.media)&&a.value.set(x,T.media)}async function c(x){t.value=!0,n.value=null;try{const T=(x==null?void 0:x.parent_id)??null,$=await qa(Ja("",{parent_id:T})),S=N5($);for(const B of S)s(B);T!==null&&i.value.add(T)}catch(T){n.value=T instanceof Error?T.message:"Unknown error"}finally{t.value=!1}}async function u(x){t.value=!0,n.value=null;try{const T=await qa(Ja(`/${dn(x)}`)),$=ri(T);return s($),$}catch(T){throw n.value=T instanceof Error?T.message:"Unknown error",T}finally{t.value=!1}}async function m(x){t.value=!0,n.value=null;try{const T=await qa(Ja(`/${dn(x)}`,{include_media:!0})),$=ri(T);s($);const S=Array.isArray($.media)?$.media:[];return a.value.set(x,S),S}catch(T){throw n.value=T instanceof Error?T.message:"Unknown error",T}finally{t.value=!1}}async function p(x,T,$){t.value=!0,n.value=null;try{const S={media_uuids:T};$!==void 0&&(S.order_column=$);const B=await qa(Ja(`/${dn(x)}/media`),{method:"POST",body:S}),_=ri(B);return s(_),d(x,_),_}catch(S){throw n.value=S instanceof Error?S.message:"Unknown error",S}finally{t.value=!1}}async function f(x,T){t.value=!0,n.value=null;try{await qa(Ja(`/${dn(x)}/media/${dn(T)}`),{method:"DELETE"});const $=a.value.get(x)||[];a.value.set(x,$.filter(S=>S.uuid!==T))}catch($){throw n.value=$ instanceof Error?$.message:"Unknown error",$}finally{t.value=!1}}async function h(x,T){t.value=!0,n.value=null;try{const $=await qa(Ja(`/${dn(x)}/media/reorder`),{method:"POST",body:{ordered_media_uuids:T}});if($.data!==void 0){s($.data),d(x,$.data);return}const S=a.value.get(x)||[],B=T.map(_=>S.find(A=>A.uuid===_)).filter(_=>_!==void 0);a.value.set(x,B)}catch($){throw n.value=$ instanceof Error?$.message:"Unknown error",$}finally{t.value=!1}}async function v(x){t.value=!0,n.value=null;try{const T=await qa(Ja(),{method:"POST",body:x}),$=ri(T);return s($),$}catch(T){throw n.value=T instanceof Error?T.message:"Unknown error",T}finally{t.value=!1}}async function k(x,T){t.value=!0,n.value=null;try{const $=await qa(Ja(`/${dn(x)}`),{method:"PATCH",body:T}),S=ri($);return s(S),S}catch($){throw n.value=$ instanceof Error?$.message:"Unknown error",$}finally{t.value=!1}}async function y(x){t.value=!0,n.value=null;try{await qa(Ja(`/${dn(x)}`),{method:"DELETE"});const T=o.value.findIndex($=>$.id===x);T>=0&&o.value.splice(T,1),a.value.delete(x)}catch(T){throw n.value=T instanceof Error?T.message:"Unknown error",T}finally{t.value=!1}}function w(x){return o.value.filter(T=>T.parent_id===x)}function g(x){return i.value.has(x)}function b(x){return a.value.get(x)||[]}async function R(x,T){const $=o.value.findIndex(B=>B.id===x);if($<0)return;const S=o.value[$];o.value[$]={...S,parent_id:T};try{const B=await qa(Ja(`/${dn(x)}/move`),{method:"POST",body:{parent_id:T}});B.data!==void 0&&s(B.data)}catch(B){throw o.value[$]=S,n.value=B instanceof Error?B.message:"Unknown error",B instanceof Error?B:new Error("Failed to move album")}}function V(x){o.value=x}function I(){o.value=[],a.value.clear(),t.value=!1,n.value=null,i.value.clear()}return{albums:o,albumMedia:a,loading:t,error:n,childrenLoadedById:i,albumsById:r,rootAlbums:l,fetchAlbums:c,fetchAlbum:u,fetchAlbumMedia:m,attachMedia:p,detachMedia:f,reorderAlbumMedia:h,createAlbum:v,updateAlbum:k,deleteAlbum:y,getChildrenOf:w,childrenLoaded:g,getAlbumMedia:b,moveAlbum:R,setAlbums:V,reset:I}});function Vl(){const o=Nl(),{albums:a,albumsById:t,rootAlbums:n,loading:i,error:r}=Qr.storeToRefs(o);async function l(w){await o.fetchAlbums(w)}async function s(w){return await o.fetchAlbum(w)}async function d(w){return await o.fetchAlbumMedia(w)}async function c(w,g,b){return await o.attachMedia(w,g,b)}async function u(w,g){await o.detachMedia(w,g)}async function m(w,g){await o.reorderAlbumMedia(w,g)}async function p(w){return await o.createAlbum(w)}async function f(w,g){return await o.updateAlbum(w,g)}async function h(w){await o.deleteAlbum(w)}function v(w){return o.getChildrenOf(w)}function k(w){return o.childrenLoaded(w)}async function y(w,g){await o.moveAlbum(w,g)}return{albums:a,albumsById:t,rootAlbums:n,loading:i,error:r,fetchAlbums:l,fetchAlbum:s,fetchAlbumMedia:d,attachMedia:c,detachMedia:u,reorderAlbumMedia:m,createAlbum:p,updateAlbum:f,deleteAlbum:h,getChildrenOf:v,childrenLoaded:k,moveAlbum:y}}function rf(o){const{childrenByParentId:a,onMove:t}=o,n=e.ref({isDragging:!1,draggedAlbumId:null,dropTargetId:null,dropPosition:null});function i(m,p){if(m===p)return!0;const f=new Set,h=[m];for(;h.length>0;){const v=h.shift();if(!v||f.has(v))continue;f.add(v);const k=a.get(v)||[];for(const y of k){if(y===p)return!0;h.push(y)}}return!1}function r(m,p){return m===p?!1:p===null?!0:!i(m,p)}function l(m){n.value={isDragging:!0,draggedAlbumId:m,dropTargetId:null,dropPosition:null}}function s(){n.value={isDragging:!1,draggedAlbumId:null,dropTargetId:null,dropPosition:null}}function d(m){n.value.dropTargetId=m}function c(){n.value.dropTargetId=null,n.value.dropPosition=null}async function u(){const{draggedAlbumId:m,dropTargetId:p}=n.value;if(!m){s();return}if(!r(m,p)){s();return}try{await t(m,p)}finally{s()}}return{dragState:n,isDescendant:i,canDropOn:r,startDrag:l,endDrag:s,setDropTarget:d,clearDropTarget:c,executeDrop:u}}const V5={key:0,"data-testid":"loading-spinner",class:"album-tree__loading"},T5={key:1,"data-testid":"error-state",class:"album-tree__error"},B5={key:2,"data-testid":"empty-state",class:"album-tree__empty"},I5={key:3,class:"album-tree__content",role:"group"},M5=e.defineComponent({__name:"AlbumTree",props:{modelValue:{default:null},expandedIds:{default:()=>[]},draggable:{type:Boolean,default:!0},showMediaCount:{type:Boolean,default:!0},compact:{type:Boolean,default:!1},mode:{default:"standalone"}},emits:["update:modelValue","album-selected","album-moved","album-expanded","album-collapsed"],setup(o,{expose:a,emit:t}){const n=o,i=t,r=e.computed(()=>n.draggable===!0),l=e.computed(()=>n.showMediaCount===!0),s=e.computed(()=>n.compact===!0),d=e.computed(()=>({"album-tree--rail":n.mode==="rail"})),{albums:c,rootAlbums:u,loading:m,error:p,fetchAlbums:f,getChildrenOf:h,childrenLoaded:v,moveAlbum:k}=Vl(),y=e.shallowRef(new Set(n.expandedIds)),w=e.ref(n.modelValue??null),g=e.ref(null),b=new Map,R=new Map;function V(C){b.clear(),R.clear();for(const U of C){b.set(U.id,U);const j=U.parent_id??null,re=R.get(j)??[];re.push(U.id),R.set(j,re)}}e.watch(c,C=>{V(C)},{immediate:!0});const{dragState:I,canDropOn:x,startDrag:T,endDrag:$,setDropTarget:S,clearDropTarget:B,executeDrop:_}=rf({childrenByParentId:R,onMove:async(C,U)=>{await k(C,U),i("album-moved",{albumId:C,newParentId:U})}});e.watch(()=>n.modelValue,C=>{w.value=C??null}),e.watch(()=>n.expandedIds,C=>{y.value=new Set(C)}),e.onMounted(async()=>{await f({parent_id:null})});const A=e.computed(()=>u.value.map(C=>P(C)));function P(C){if(!y.value.has(C.id))return C;const U=h(C.id);return{...C,children:U.map(j=>P(j))}}const D=e.computed(()=>{const C=[];function U(j){var re;for(const ue of j)C.push(ue),y.value.has(ue.id)&&((re=ue.children)!=null&&re.length)&&U(ue.children)}return U(A.value),C});function z(C){var re;if(!D.value.length)return;const U=g.value?D.value.findIndex(ue=>ue.id===g.value):-1,j=U>=0?D.value[U]:null;switch(C.key){case"ArrowDown":C.preventDefault(),U<D.value.length-1?g.value=D.value[U+1].id:U===-1&&D.value.length>0&&(g.value=D.value[0].id);break;case"ArrowUp":C.preventDefault(),U>0&&(g.value=D.value[U-1].id);break;case"ArrowRight":C.preventDefault(),j&&(j.children_count>0&&!y.value.has(j.id)?M(j.id):y.value.has(j.id)&&((re=j.children)!=null&&re.length)&&(g.value=j.children[0].id));break;case"ArrowLeft":C.preventDefault(),j&&(y.value.has(j.id)&&j.children_count>0?M(j.id):j.parent_id&&(g.value=j.parent_id));break;case"Enter":case" ":C.preventDefault(),j&&Z(j);break;case"Home":C.preventDefault(),D.value.length>0&&(g.value=D.value[0].id);break;case"End":C.preventDefault(),D.value.length>0&&(g.value=D.value[D.value.length-1].id);break}}async function M(C){y.value.has(C)?(y.value.delete(C),i("album-collapsed",C)):(v(C)||await f({parent_id:C}),y.value.add(C),i("album-expanded",C))}function Z(C){w.value=C.id,i("update:modelValue",C.id),i("album-selected",C)}function O(C){n.draggable&&T(C)}function K(C){var j;if(!n.draggable)return;const U=(j=I.value)==null?void 0:j.draggedAlbumId;U&&(S(C),x(U,C))}function de(){n.draggable&&B()}async function Ne(C){n.draggable&&(S(C),await _())}function ce(C){n.draggable&&(C.preventDefault(),S(null))}async function le(C){n.draggable&&(C.preventDefault(),S(null),await _())}function W(){$()}return a({focusedId:g}),(C,U)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["album-tree",d.value]),"data-testid":"album-tree",tabindex:"0",role:"tree","aria-label":"Album tree",onKeydown:z,onDragover:ce,onDrop:le,onDragend:W},[e.unref(m)?(e.openBlock(),e.createElementBlock("div",V5,[e.createVNode(e.unref(H.IonSpinner),{name:"crescent"})])):e.unref(p)?(e.openBlock(),e.createElementBlock("div",T5,[e.createElementVNode("p",null,e.toDisplayString(e.unref(p)),1)])):e.unref(u).length?(e.openBlock(),e.createElementBlock("div",I5,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(A.value,j=>(e.openBlock(),e.createBlock(v5,{key:j.id,album:j,depth:0,"selected-id":w.value,"expanded-ids":y.value,"focused-id":g.value,draggable:r.value,"drag-state":r.value?e.unref(I):null,"show-media-count":l.value,compact:s.value,onSelect:Z,onToggleExpand:M,onDragStart:O,onDragOver:K,onDragLeave:de,onDrop:Ne},null,8,["album","selected-id","expanded-ids","focused-id","draggable","drag-state","show-media-count","compact"]))),128))])):(e.openBlock(),e.createElementBlock("div",B5,[U[0]||(U[0]=e.createElementVNode("p",null,"No albums yet",-1)),e.renderSlot(C.$slots,"empty-action",{},void 0,!0)]))],34))}}),Tl=$e(M5,[["__scopeId","data-v-ee405f62"]]),$5=300,F5=e.defineComponent({__name:"AlbumBrowser",props:{isOpen:{type:Boolean},selectedAlbumId:{default:null},title:{default:"Select Album"},confirmText:{default:"Select"}},emits:["close","confirm"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(t.selectedAlbumId??null),r=e.ref(null),l=e.ref(0),s=e.ref(null);e.watch(()=>t.selectedAlbumId,f=>{i.value=f??null});const d=e.computed(()=>r.value!==null);function c(f){const h=Date.now();if(s.value===f.id&&h-l.value<$5){n("confirm",f);return}l.value=h,s.value=f.id,i.value=f.id,r.value=f}function u(){r.value&&n("confirm",r.value)}function m(){n("close")}function p(){n("close")}return(f,h)=>(e.openBlock(),e.createBlock(e.unref(H.IonModal),{"is-open":f.isOpen,class:"album-browser-modal",onDidDismiss:p},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonHeader),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonToolbar),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonTitle),null,{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(f.title),1)]),_:1}),e.createVNode(e.unref(H.IonButtons),{slot:"end"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButton),{"data-testid":"cancel-button",onClick:m},{default:e.withCtx(()=>[...h[1]||(h[1]=[e.createTextVNode(" Cancel ",-1)])]),_:1})]),_:1})]),_:1})]),_:1}),e.createVNode(e.unref(H.IonContent),{class:"album-browser-content"},{default:e.withCtx(()=>[e.createVNode(Tl,{modelValue:i.value,"onUpdate:modelValue":h[0]||(h[0]=v=>i.value=v),draggable:!1,"show-media-count":!0,compact:!1,onAlbumSelected:c},null,8,["modelValue"])]),_:1}),e.createVNode(e.unref(H.IonFooter),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonToolbar),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButtons),{slot:"end"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButton),{fill:"clear",onClick:m},{default:e.withCtx(()=>[...h[2]||(h[2]=[e.createTextVNode(" Cancel ",-1)])]),_:1}),e.createVNode(e.unref(H.IonButton),{"data-testid":"confirm-button",fill:"solid",color:"primary",disabled:!d.value,onClick:u},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(f.confirmText),1)]),_:1},8,["disabled"])]),_:1})]),_:1})]),_:1})]),_:1},8,["is-open"]))}}),lf=$e(F5,[["__scopeId","data-v-21676ec1"]]),D5={class:"ion-padding-start text-sm"},A5={class:"ion-padding-start text-sm"},R5={key:1},L5={key:1,class:"album-manager-inline rounded-lg border border-gray-200 bg-white p-4"},P5={class:"flex items-center justify-between gap-3 pb-3"},U5={class:"text-base font-semibold text-gray-900"},O5={class:"ion-padding-start text-sm"},z5={class:"ion-padding-start text-sm"},j5={class:"flex justify-between pt-2"},W5={key:1},li=255,si=1e3,H5=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=Nl(),r=e.computed(()=>t.albumId!==null&&t.albumId!==void 0),l=e.computed(()=>r.value?"Edit Album":"Create Album"),s=e.computed(()=>r.value?"Save":"Create"),d=e.ref({name:"",description:"",parent_id:t.parentId}),c=e.ref({name:!1,description:!1}),u=e.ref(null),m=e.ref(!1),p=e.ref(null),f=e.ref(!1),h=e.ref(!1),v=e.computed(()=>c.value.name?d.value.name.trim()?d.value.name.length>li?`Name must be ${li} characters or less`:null:"Name is required":null),k=e.computed(()=>c.value.description&&d.value.description.length>si?`Description must be ${si} characters or less`:null),y=e.computed(()=>{const D=d.value.name.trim().length>0,z=d.value.name.length<=li,M=d.value.description.length<=si;return D&&z&&M&&!f.value}),w=e.computed(()=>{var D;return((D=u.value)==null?void 0:D.name)??"None (Root)"}),g=e.computed(()=>p.value?p.value.children_count===0&&p.value.media_count===0:!1),b=e.computed(()=>p.value?p.value.children_count>0?"Cannot delete album with child albums. Move or delete children first.":p.value.media_count>0?"Cannot delete album with media. Remove media first.":`Are you sure you want to delete "${p.value.name}"? This action cannot be undone.`:"");e.onMounted(async()=>{t.albumId&&await R()});async function R(){if(t.albumId)try{const D=await i.fetchAlbum(t.albumId);p.value=D,d.value={name:D.name,description:D.description??"",parent_id:D.parent_id},D.parent_id&&(u.value={id:D.parent_id,name:"Parent Album"})}catch(D){n("error",D)}}function V(){c.value.name=!0}function I(){c.value.description=!0}function x(){m.value=!0}function T(D){u.value={id:D.id,name:D.name},d.value.parent_id=D.id,m.value=!1}function $(){m.value=!1}function S(){n("close")}function B(){n("close")}async function _(){if(c.value.name=!0,c.value.description=!0,!(!y.value||f.value)){f.value=!0;try{const D={name:d.value.name.trim(),description:d.value.description.trim(),parent_id:d.value.parent_id};if(r.value&&t.albumId){const z=await i.updateAlbum(t.albumId,D);n("updated",z)}else{const z=await i.createAlbum(D);n("created",z)}n("close")}catch(D){n("error",D)}finally{f.value=!1}}}function A(){g.value&&(h.value=!0)}async function P(D){var M;if((((M=D.detail)==null?void 0:M.role)??"")!=="confirm"){h.value=!1;return}if(t.albumId){f.value=!0;try{await i.deleteAlbum(t.albumId),n("deleted",t.albumId),n("close")}catch(Z){n("error",Z)}finally{f.value=!1,h.value=!1}}}return(D,z)=>(e.openBlock(),e.createElementBlock(e.Fragment,null,[D.mode==="modal"?(e.openBlock(),e.createBlock(e.unref(H.IonModal),{key:0,"is-open":D.isOpen,class:"album-manager-modal",onDidDismiss:B},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonHeader),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonToolbar),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonTitle),null,{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(l.value),1)]),_:1}),e.createVNode(e.unref(H.IonButtons),{slot:"end"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButton),{"data-testid":"cancel-btn",fill:"clear",onClick:S},{default:e.withCtx(()=>[...z[4]||(z[4]=[e.createTextVNode(" Cancel ",-1)])]),_:1})]),_:1})]),_:1})]),_:1}),e.createVNode(e.unref(H.IonContent),{class:"album-manager-content"},{default:e.withCtx(()=>[e.createElementVNode("form",{"data-testid":"album-form",class:"p-4 space-y-3",onSubmit:e.withModifiers(_,["prevent"])},[e.createVNode(e.unref(H.IonItem),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),{position:"stacked"},{default:e.withCtx(()=>[...z[5]||(z[5]=[e.createTextVNode("Name *",-1)])]),_:1}),e.createVNode(e.unref(H.IonInput),{modelValue:d.value.name,"onUpdate:modelValue":z[0]||(z[0]=M=>d.value.name=M),"data-testid":"name-input",maxlength:li,onIonBlur:V},null,8,["modelValue"])]),_:1}),v.value?(e.openBlock(),e.createBlock(e.unref(H.IonText),{key:0,color:"danger","data-testid":"name-error"},{default:e.withCtx(()=>[e.createElementVNode("p",D5,e.toDisplayString(v.value),1)]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(H.IonItem),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),{position:"stacked"},{default:e.withCtx(()=>[...z[6]||(z[6]=[e.createTextVNode("Description",-1)])]),_:1}),e.createVNode(e.unref(H.IonTextarea),{modelValue:d.value.description,"onUpdate:modelValue":z[1]||(z[1]=M=>d.value.description=M),"data-testid":"description-input",maxlength:si,onIonBlur:I},null,8,["modelValue"])]),_:1}),k.value?(e.openBlock(),e.createBlock(e.unref(H.IonText),{key:1,color:"danger","data-testid":"description-error"},{default:e.withCtx(()=>[e.createElementVNode("p",A5,e.toDisplayString(k.value),1)]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(H.IonItem),{button:"","data-testid":"parent-selector",onClick:x},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...z[7]||(z[7]=[e.createTextVNode("Parent Album",-1)])]),_:1}),e.createVNode(e.unref(H.IonNote),{slot:"end","data-testid":"parent-name"},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(w.value),1)]),_:1})]),_:1})],32)]),_:1}),e.createVNode(e.unref(H.IonFooter),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonToolbar),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButtons),{slot:"start"},{default:e.withCtx(()=>[r.value?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:0,"data-testid":"delete-btn",color:"danger",disabled:!g.value,title:g.value?void 0:b.value,onClick:A},{default:e.withCtx(()=>[...z[8]||(z[8]=[e.createTextVNode(" Delete ",-1)])]),_:1},8,["disabled","title"])):e.createCommentVNode("",!0)]),_:1}),e.createVNode(e.unref(H.IonButtons),{slot:"end"},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonButton),{"data-testid":"submit-btn",type:"submit",color:"primary",disabled:!y.value,onClick:_},{default:e.withCtx(()=>[f.value?(e.openBlock(),e.createBlock(e.unref(H.IonSpinner),{key:0,"data-testid":"loading-spinner",name:"crescent"})):(e.openBlock(),e.createElementBlock("span",R5,e.toDisplayString(s.value),1))]),_:1},8,["disabled"])]),_:1})]),_:1})]),_:1})]),_:1},8,["is-open"])):(e.openBlock(),e.createElementBlock("div",L5,[e.createElementVNode("div",P5,[e.createElementVNode("h2",U5,e.toDisplayString(l.value),1),e.createVNode(e.unref(H.IonButton),{"data-testid":"cancel-btn",fill:"clear",onClick:S},{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(_,["prevent"])},[e.createVNode(e.unref(H.IonItem),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),{position:"stacked"},{default:e.withCtx(()=>[...z[10]||(z[10]=[e.createTextVNode("Name *",-1)])]),_:1}),e.createVNode(e.unref(H.IonInput),{modelValue:d.value.name,"onUpdate:modelValue":z[2]||(z[2]=M=>d.value.name=M),"data-testid":"name-input",maxlength:li,onIonBlur:V},null,8,["modelValue"])]),_:1}),v.value?(e.openBlock(),e.createBlock(e.unref(H.IonText),{key:0,color:"danger","data-testid":"name-error"},{default:e.withCtx(()=>[e.createElementVNode("p",O5,e.toDisplayString(v.value),1)]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(H.IonItem),null,{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),{position:"stacked"},{default:e.withCtx(()=>[...z[11]||(z[11]=[e.createTextVNode("Description",-1)])]),_:1}),e.createVNode(e.unref(H.IonTextarea),{modelValue:d.value.description,"onUpdate:modelValue":z[3]||(z[3]=M=>d.value.description=M),"data-testid":"description-input",maxlength:si,onIonBlur:I},null,8,["modelValue"])]),_:1}),k.value?(e.openBlock(),e.createBlock(e.unref(H.IonText),{key:1,color:"danger","data-testid":"description-error"},{default:e.withCtx(()=>[e.createElementVNode("p",z5,e.toDisplayString(k.value),1)]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(H.IonItem),{button:"","data-testid":"parent-selector",onClick:x},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonLabel),null,{default:e.withCtx(()=>[...z[12]||(z[12]=[e.createTextVNode("Parent Album",-1)])]),_:1}),e.createVNode(e.unref(H.IonNote),{slot:"end","data-testid":"parent-name"},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(w.value),1)]),_:1})]),_:1}),e.createElementVNode("div",j5,[e.createElementVNode("div",null,[r.value?(e.openBlock(),e.createBlock(e.unref(H.IonButton),{key:0,"data-testid":"delete-btn",color:"danger",fill:"outline",disabled:!g.value,title:g.value?void 0:b.value,onClick:A},{default:e.withCtx(()=>[...z[13]||(z[13]=[e.createTextVNode(" Delete ",-1)])]),_:1},8,["disabled","title"])):e.createCommentVNode("",!0)]),e.createVNode(e.unref(H.IonButton),{"data-testid":"submit-btn",type:"submit",color:"primary",disabled:!y.value,onClick:_},{default:e.withCtx(()=>[f.value?(e.openBlock(),e.createBlock(e.unref(H.IonSpinner),{key:0,"data-testid":"loading-spinner",name:"crescent"})):(e.openBlock(),e.createElementBlock("span",W5,e.toDisplayString(s.value),1))]),_:1},8,["disabled"])])],32)])),e.createVNode(lf,{"is-open":m.value,"selected-album-id":d.value.parent_id,title:"Select Parent Album",onClose:$,onConfirm:T},null,8,["is-open","selected-album-id"]),e.createVNode(e.unref(H.IonAlert),{"is-open":h.value,header:"Delete Album?",message:b.value,buttons:[{text:"Cancel",role:"cancel"},{text:"Delete",role:"confirm",cssClass:"alert-button-danger"}],onDidDismiss:P},null,8,["is-open","message"])],64))}}),Z5=$e(H5,[["__scopeId","data-v-22083f3a"]]),G5={class:"album-media-grid"},X5={class:"aspect-square"},K5={key:1,"data-testid":"empty-state",class:"flex flex-col items-center justify-center py-12 gap-4"},J5={class:"text-gray-500"},q5=["data-media-id","draggable","onDragstart","onDragover","onDrop","onMouseenter"],Y5={key:0,"data-testid":"drop-indicator",class:"absolute inset-0 border-2 border-primary rounded-lg pointer-events-none z-30"},Q5={key:1,class:"absolute top-2 right-2 z-20 opacity-0 group-hover:opacity-100 transition-opacity cursor-grab"},eF={class:"aspect-square relative"},tF=["src","alt"],aF={key:0,class:"absolute inset-0 bg-black/50 flex items-center justify-center gap-2 transition-opacity"},nF=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=Nl(),r=e.ref([]),l=e.ref(!1),s=e.ref(null),d=e.ref(null),c=e.ref(null),u=e.computed(()=>t.isLoading||l.value),m=e.computed(()=>!u.value&&r.value.length===0),p=e.computed(()=>{const B=t.columns;return["grid","gap-4",`grid-cols-${B.mobile??2}`,`sm:grid-cols-${B.sm??3}`,`md:grid-cols-${B.md??4}`,`lg:grid-cols-${B.lg??5}`,`xl:grid-cols-${B.xl??6}`]}),f=e.computed(()=>(t.columns.md??4)*2);e.onMounted(async()=>{await h()}),e.watch(()=>t.albumId,async()=>{await h()});async function h(){l.value=!0;try{const B=await i.fetchAlbumMedia(t.albumId);r.value=B}catch{r.value=[]}finally{l.value=!1}}function v(B){return t.selectedItems.includes(B)}function k(B){n("toggle-select",B);const _=v(B.uuid)?t.selectedItems.filter(A=>A!==B.uuid):[...t.selectedItems,B.uuid];n("selection-change",_)}function y(B){if(B.conversions&&typeof B.conversions=="object"){const _=B.conversions.thumb;if(typeof _=="string")return _}return B.original_url}function w(B){s.value=B}function g(){s.value=null}function b(B){n("preview",B)}function R(B){n("edit",B)}function V(B){n("detach",B.uuid)}function I(){n("add")}function x(B,_){t.reorderable&&(d.value=_,B.dataTransfer&&(B.dataTransfer.effectAllowed="move",B.dataTransfer.setData("text/plain",String(_))))}function T(B,_){!t.reorderable||d.value===null||(B.preventDefault(),c.value=_)}function $(B,_){if(!t.reorderable||d.value===null)return;B.preventDefault();const A=d.value;if(A!==_){const P=[...r.value],[D]=P.splice(A,1);P.splice(_,0,D),r.value=P;const z=P.map(M=>M.uuid);n("reorder",z),i.reorderAlbumMedia(t.albumId,z).catch(()=>{h()})}d.value=null,c.value=null}function S(){d.value=null,c.value=null}return(B,_)=>(e.openBlock(),e.createElementBlock("div",G5,[u.value?(e.openBlock(),e.createElementBlock("div",{key:0,"data-testid":"loading-grid",class:e.normalizeClass(p.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(f.value,A=>(e.openBlock(),e.createBlock(e.unref(H.IonCard),{key:A,class:"m-0"},{default:e.withCtx(()=>[e.createElementVNode("div",X5,[e.createVNode(e.unref(H.IonSkeletonText),{animated:"",class:"w-full h-full skeleton"})])]),_:1}))),128))],2)):m.value?(e.openBlock(),e.createElementBlock("div",K5,[e.createVNode(e.unref(H.IonIcon),{name:"images-outline",class:"text-6xl text-gray-400"}),e.createElementVNode("p",J5,e.toDisplayString(B.emptyText),1),e.createVNode(e.unref(H.IonButton),{"data-testid":"add-media-btn",onClick:I},{default:e.withCtx(()=>[..._[0]||(_[0]=[e.createTextVNode(" Add Media ",-1)])]),_:1})])):(e.openBlock(),e.createElementBlock("div",{key:2,"data-testid":"media-grid",class:e.normalizeClass(p.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.value,(A,P)=>(e.openBlock(),e.createElementBlock("div",{key:A.uuid,"data-media-id":A.uuid,class:e.normalizeClass(["media-item relative group",{"opacity-50":d.value===P,"ring-2 ring-primary":c.value===P&&d.value!==P}]),draggable:B.reorderable,onDragstart:D=>x(D,P),onDragover:D=>T(D,P),onDrop:D=>$(D,P),onDragend:S,onMouseenter:D=>w(A.uuid),onMouseleave:g},[c.value===P&&d.value!==P&&B.reorderable?(e.openBlock(),e.createElementBlock("div",Y5)):e.createCommentVNode("",!0),B.reorderable?(e.openBlock(),e.createElementBlock("div",Q5,[e.createVNode(e.unref(H.IonIcon),{name:"reorder-three-outline",class:"text-white drop-shadow-md"})])):e.createCommentVNode("",!0),B.selectionMode?(e.openBlock(),e.createBlock(e.unref(H.IonCheckbox),{key:2,"data-testid":"media-checkbox",checked:v(A.uuid),class:"absolute top-2 left-2 z-20",onIonChange:D=>k(A)},null,8,["checked","onIonChange"])):e.createCommentVNode("",!0),e.createVNode(e.unref(H.IonCard),{class:"m-0 overflow-hidden"},{default:e.withCtx(()=>[e.createElementVNode("div",eF,[e.createElementVNode("img",{src:y(A),alt:A.file_name,class:"w-full h-full object-cover"},null,8,tF),B.showActions&&s.value===A.uuid?(e.openBlock(),e.createElementBlock("div",aF,[e.createVNode(e.unref(H.IonButton),{"data-testid":"action-preview",fill:"clear",size:"small",color:"light",onClick:D=>b(A)},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{slot:"icon-only",name:"eye-outline"})]),_:1},8,["onClick"]),e.createVNode(e.unref(H.IonButton),{"data-testid":"action-edit",fill:"clear",size:"small",color:"light",onClick:D=>R(A)},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{slot:"icon-only",name:"create-outline"})]),_:1},8,["onClick"]),e.createVNode(e.unref(H.IonButton),{"data-testid":"action-detach",fill:"clear",size:"small",color:"danger",onClick:D=>V(A)},{default:e.withCtx(()=>[e.createVNode(e.unref(H.IonIcon),{slot:"icon-only",name:"close-circle-outline"})]),_:1},8,["onClick"])])):e.createCommentVNode("",!0)])]),_:2},1024)],42,q5))),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:I},[e.createVNode(e.unref(H.IonIcon),{name:"add-circle-outline",class:"text-4xl text-gray-400"}),_[1]||(_[1]=e.createElementVNode("span",{class:"text-sm text-gray-500"},"Add Media",-1))])],2))]))}}),oF=$e(nF,[["__scopeId","data-v-d84b796a"]]),iF={key:0,class:"media-album-inline-create","data-testid":"media-album-inline-create"},rF={class:"media-album-inline-create__field"},lF={class:"media-album-inline-create__field"},sF=["value"],dF={key:1,class:"media-album-inline-create__autocomplete"},cF={class:"media-album-inline-create__autocomplete-input-wrap"},uF={key:0,class:"media-album-inline-create__autocomplete-list"},mF=["onMousedown"],pF={key:1,class:"media-album-inline-create__autocomplete-empty"},fF={class:"media-album-inline-create__actions"},hF=e.defineComponent({__name:"MediaAlbumInlineCreate",props:{open:{type:Boolean,default:!1},nameLabel:{default:"Album name"},albums:{default:()=>[]}},emits:["cancel","create"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(""),r=e.ref(""),l=e.ref(""),s=e.ref(!1),d=e.computed(()=>t.albums.length>5),c=e.computed(()=>{if(l.value.trim()==="")return t.albums;const k=l.value.toLowerCase();return t.albums.filter(y=>y.name.toLowerCase().includes(k))}),u=e.computed(()=>{if(r.value==="")return"";const k=t.albums.find(y=>y.id===r.value);return(k==null?void 0:k.name)??""}),m=k=>{r.value=k.id,l.value=k.name,s.value=!1},p=()=>{r.value="",l.value="",s.value=!1},f=()=>{s.value=!0,r.value!==""&&(l.value=u.value)},h=()=>{setTimeout(()=>{s.value=!1,r.value!==""?l.value=u.value:l.value=""},150)},v=()=>{i.value.trim()!==""&&(n("create",i.value.trim(),r.value!==""?r.value:void 0),i.value="",r.value="",l.value="")};return(k,y)=>k.open?(e.openBlock(),e.createElementBlock("section",iF,[y[7]||(y[7]=e.createElementVNode("h4",{class:"media-album-inline-create__heading"}," New album ",-1)),e.createElementVNode("label",rF,[e.createElementVNode("span",null,e.toDisplayString(k.nameLabel),1),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":y[0]||(y[0]=w=>i.value=w),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",lF,[y[6]||(y[6]=e.createElementVNode("span",null,"Parent album (optional)",-1)),d.value?(e.openBlock(),e.createElementBlock("div",dF,[e.createElementVNode("div",cF,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":y[2]||(y[2]=w=>l.value=w),type:"text",class:"media-album-inline-create__input",placeholder:"Search albums...","data-testid":"input-media-album-parent-search",onFocus:f,onBlur:h},null,544),[[e.vModelText,l.value]]),r.value!==""?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-album-inline-create__autocomplete-clear","aria-label":"Clear parent album",onMousedown:e.withModifiers(p,["prevent"])},[...y[5]||(y[5]=[e.createElementVNode("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2.5","stroke-linecap":"round"},[e.createElementVNode("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.createElementVNode("line",{x1:"6",y1:"6",x2:"18",y2:"18"})],-1)])],32)):e.createCommentVNode("",!0)]),s.value?(e.openBlock(),e.createElementBlock("ul",uF,[r.value!==""?(e.openBlock(),e.createElementBlock("li",{key:0,class:"media-album-inline-create__autocomplete-option media-album-inline-create__autocomplete-option--none",onMousedown:e.withModifiers(p,["prevent"])}," None ",32)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.value,w=>(e.openBlock(),e.createElementBlock("li",{key:w.id,class:e.normalizeClass(["media-album-inline-create__autocomplete-option",{"is-selected":w.id===r.value}]),onMousedown:e.withModifiers(g=>m(w),["prevent"])},e.toDisplayString(w.name),43,mF))),128)),c.value.length===0?(e.openBlock(),e.createElementBlock("li",pF," No albums match ")):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)])):e.withDirectives((e.openBlock(),e.createElementBlock("select",{key:0,"onUpdate:modelValue":y[1]||(y[1]=w=>r.value=w),class:"media-album-inline-create__input","data-testid":"select-media-album-parent"},[y[4]||(y[4]=e.createElementVNode("option",{value:""}," None ",-1)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(k.albums,w=>(e.openBlock(),e.createElementBlock("option",{key:w.id,value:w.id},e.toDisplayString(w.name),9,sF))),128))],512)),[[e.vModelSelect,r.value]])]),e.createElementVNode("div",fF,[e.createElementVNode("button",{type:"button",class:"media-album-inline-create__button","data-testid":"btn-media-album-cancel",onClick:y[3]||(y[3]=w=>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)}}),Id=$e(hF,[["__scopeId","data-v-a85162fe"]]),vF={class:"media-album-unavailable-state","data-testid":"media-album-unavailable-state"},gF=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",vF,[e.createElementVNode("h3",null,e.toDisplayString(n.title),1),e.createElementVNode("p",null,e.toDisplayString(n.body),1),e.createElementVNode("button",{type:"button",class:"media-album-unavailable-state__button",onClick:i[0]||(i[0]=r=>t("goToLibrary"))},e.toDisplayString(n.actionLabel),1)]))}}),sf=$e(gF,[["__scopeId","data-v-04620e64"]]);/*!
350
- * tabbable 6.2.0
351
- * @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE
352
- */var df=["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])"],Xr=df.join(","),cf=typeof Element>"u",no=cf?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,Kr=!cf&&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},Jr=function o(a,t){var n;t===void 0&&(t=!0);var i=a==null||(n=a.getAttribute)===null||n===void 0?void 0:n.call(a,"inert"),r=i===""||i==="true",l=r||t&&a&&o(a.parentNode);return l},bF=function(a){var t,n=a==null||(t=a.getAttribute)===null||t===void 0?void 0:t.call(a,"contenteditable");return n===""||n==="true"},uf=function(a,t,n){if(Jr(a))return[];var i=Array.prototype.slice.apply(a.querySelectorAll(Xr));return t&&no.call(a,Xr)&&i.unshift(a),i=i.filter(n),i},mf=function o(a,t,n){for(var i=[],r=Array.from(a);r.length;){var l=r.shift();if(!Jr(l,!1))if(l.tagName==="SLOT"){var s=l.assignedElements(),d=s.length?s:l.children,c=o(d,!0,n);n.flatten?i.push.apply(i,c):i.push({scopeParent:l,candidates:c})}else{var u=no.call(l,Xr);u&&n.filter(l)&&(t||!a.includes(l))&&i.push(l);var m=l.shadowRoot||typeof n.getShadowRoot=="function"&&n.getShadowRoot(l),p=!Jr(m,!1)&&(!n.shadowRootFilter||n.shadowRootFilter(l));if(m&&p){var f=o(m===!0?l.children:m.children,!0,n);n.flatten?i.push.apply(i,f):i.push({scopeParent:l,candidates:f})}else r.unshift.apply(r,l.children)}}return i},pf=function(a){return!isNaN(parseInt(a.getAttribute("tabindex"),10))},Gn=function(a){if(!a)throw new Error("No node provided");return a.tabIndex<0&&(/^(AUDIO|VIDEO|DETAILS)$/.test(a.tagName)||bF(a))&&!pf(a)?0:a.tabIndex},yF=function(a,t){var n=Gn(a);return n<0&&t&&!pf(a)?0:n},wF=function(a,t){return a.tabIndex===t.tabIndex?a.documentOrder-t.documentOrder:a.tabIndex-t.tabIndex},ff=function(a){return a.tagName==="INPUT"},kF=function(a){return ff(a)&&a.type==="hidden"},_F=function(a){var t=a.tagName==="DETAILS"&&Array.prototype.slice.apply(a.children).some(function(n){return n.tagName==="SUMMARY"});return t},EF=function(a,t){for(var n=0;n<a.length;n++)if(a[n].checked&&a[n].form===t)return a[n]},SF=function(a){if(!a.name)return!0;var t=a.form||Kr(a),n=function(s){return t.querySelectorAll('input[type="radio"][name="'+s+'"]')},i;if(typeof window<"u"&&typeof window.CSS<"u"&&typeof window.CSS.escape=="function")i=n(window.CSS.escape(a.name));else try{i=n(a.name)}catch{return!1}var r=EF(i,a.form);return!r||r===a},CF=function(a){return ff(a)&&a.type==="radio"},xF=function(a){return CF(a)&&!SF(a)},NF=function(a){var t,n=a&&Kr(a),i=(t=n)===null||t===void 0?void 0:t.host,r=!1;if(n&&n!==a){var l,s,d;for(r=!!((l=i)!==null&&l!==void 0&&(s=l.ownerDocument)!==null&&s!==void 0&&s.contains(i)||a!=null&&(d=a.ownerDocument)!==null&&d!==void 0&&d.contains(a));!r&&i;){var c,u,m;n=Kr(i),i=(c=n)===null||c===void 0?void 0:c.host,r=!!((u=i)!==null&&u!==void 0&&(m=u.ownerDocument)!==null&&m!==void 0&&m.contains(i))}}return r},Vu=function(a){var t=a.getBoundingClientRect(),n=t.width,i=t.height;return n===0&&i===0},VF=function(a,t){var n=t.displayCheck,i=t.getShadowRoot;if(getComputedStyle(a).visibility==="hidden")return!0;var r=no.call(a,"details>summary:first-of-type"),l=r?a.parentElement:a;if(no.call(l,"details:not([open]) *"))return!0;if(!n||n==="full"||n==="legacy-full"){if(typeof i=="function"){for(var s=a;a;){var d=a.parentElement,c=Kr(a);if(d&&!d.shadowRoot&&i(d)===!0)return Vu(a);a.assignedSlot?a=a.assignedSlot:!d&&c!==a.ownerDocument?a=c.host:a=d}a=s}if(NF(a))return!a.getClientRects().length;if(n!=="legacy-full")return!0}else if(n==="non-zero-area")return Vu(a);return!1},TF=function(a){if(/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(a.tagName))for(var t=a.parentElement;t;){if(t.tagName==="FIELDSET"&&t.disabled){for(var n=0;n<t.children.length;n++){var i=t.children.item(n);if(i.tagName==="LEGEND")return no.call(t,"fieldset[disabled] *")?!0:!i.contains(a)}return!0}t=t.parentElement}return!1},qr=function(a,t){return!(t.disabled||Jr(t)||kF(t)||VF(t,a)||_F(t)||TF(t))},Js=function(a,t){return!(xF(t)||Gn(t)<0||!qr(a,t))},BF=function(a){var t=parseInt(a.getAttribute("tabindex"),10);return!!(isNaN(t)||t>=0)},IF=function o(a){var t=[],n=[];return a.forEach(function(i,r){var l=!!i.scopeParent,s=l?i.scopeParent:i,d=yF(s,l),c=l?o(i.candidates):s;d===0?l?t.push.apply(t,c):t.push(s):n.push({documentOrder:r,tabIndex:d,item:i,isScope:l,content:c})}),n.sort(wF).reduce(function(i,r){return r.isScope?i.push.apply(i,r.content):i.push(r.content),i},[]).concat(t)},MF=function(a,t){t=t||{};var n;return t.getShadowRoot?n=mf([a],t.includeContainer,{filter:Js.bind(null,t),flatten:!1,getShadowRoot:t.getShadowRoot,shadowRootFilter:BF}):n=uf(a,t.includeContainer,Js.bind(null,t)),IF(n)},$F=function(a,t){t=t||{};var n;return t.getShadowRoot?n=mf([a],t.includeContainer,{filter:qr.bind(null,t),flatten:!0,getShadowRoot:t.getShadowRoot}):n=uf(a,t.includeContainer,qr.bind(null,t)),n},Co=function(a,t){if(t=t||{},!a)throw new Error("No node provided");return no.call(a,Xr)===!1?!1:Js(t,a)},FF=df.concat("iframe").join(","),rs=function(a,t){if(t=t||{},!a)throw new Error("No node provided");return no.call(a,FF)===!1?!1:qr(t,a)};/*!
353
- * focus-trap 7.6.5
354
- * @license MIT, https://github.com/focus-trap/focus-trap/blob/master/LICENSE
355
- */function qs(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 DF(o){if(Array.isArray(o))return qs(o)}function AF(o,a,t){return(a=OF(a))in o?Object.defineProperty(o,a,{value:t,enumerable:!0,configurable:!0,writable:!0}):o[a]=t,o}function RF(o){if(typeof Symbol<"u"&&o[Symbol.iterator]!=null||o["@@iterator"]!=null)return Array.from(o)}function LF(){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 Tu(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 Bu(o){for(var a=1;a<arguments.length;a++){var t=arguments[a]!=null?arguments[a]:{};a%2?Tu(Object(t),!0).forEach(function(n){AF(o,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(t)):Tu(Object(t)).forEach(function(n){Object.defineProperty(o,n,Object.getOwnPropertyDescriptor(t,n))})}return o}function PF(o){return DF(o)||RF(o)||zF(o)||LF()}function UF(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 OF(o){var a=UF(o,"string");return typeof a=="symbol"?a:a+""}function zF(o,a){if(o){if(typeof o=="string")return qs(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)?qs(o,a):void 0}}var Iu={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)}},jF=function(a){return a.tagName&&a.tagName.toLowerCase()==="input"&&typeof a.select=="function"},WF=function(a){return(a==null?void 0:a.key)==="Escape"||(a==null?void 0:a.key)==="Esc"||(a==null?void 0:a.keyCode)===27},Ni=function(a){return(a==null?void 0:a.key)==="Tab"||(a==null?void 0:a.keyCode)===9},HF=function(a){return Ni(a)&&!a.shiftKey},ZF=function(a){return Ni(a)&&a.shiftKey},Mu=function(a){return setTimeout(a,0)},di=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},br=function(a){return a.target.shadowRoot&&typeof a.composedPath=="function"?a.composedPath()[0]:a.target},GF=[],XF=function(a,t){var n=(t==null?void 0:t.document)||document,i=(t==null?void 0:t.trapStack)||GF,r=Bu({returnFocusOnDeactivate:!0,escapeDeactivates:!0,delayInitialFocus:!0,isKeyForward:HF,isKeyBackward:ZF},t),l={containers:[],containerGroups:[],tabbableGroups:[],nodeFocusedBeforeActivation:null,mostRecentlyFocusedNode:null,active:!1,paused:!1,manuallyPaused:!1,delayInitialFocusTimer:void 0,recentNavEvent:void 0},s,d=function(_,A,P){return _&&_[A]!==void 0?_[A]:r[P||A]},c=function(_,A){var P=typeof(A==null?void 0:A.composedPath)=="function"?A.composedPath():void 0;return l.containerGroups.findIndex(function(D){var z=D.container,M=D.tabbableNodes;return z.contains(_)||(P==null?void 0:P.includes(z))||M.find(function(Z){return Z===_})})},u=function(_){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},P=A.hasFallback,D=P===void 0?!1:P,z=A.params,M=z===void 0?[]:z,Z=r[_];if(typeof Z=="function"&&(Z=Z.apply(void 0,PF(M))),Z===!0&&(Z=void 0),!Z){if(Z===void 0||Z===!1)return Z;throw new Error("`".concat(_,"` was specified but was not a node, or did not return a node"))}var O=Z;if(typeof Z=="string"){try{O=n.querySelector(Z)}catch(K){throw new Error("`".concat(_,'` appears to be an invalid selector; error="').concat(K.message,'"'))}if(!O&&!D)throw new Error("`".concat(_,"` as selector refers to no known node"))}return O},m=function(){var _=u("initialFocus",{hasFallback:!0});if(_===!1)return!1;if(_===void 0||_&&!rs(_,r.tabbableOptions))if(c(n.activeElement)>=0)_=n.activeElement;else{var A=l.tabbableGroups[0],P=A&&A.firstTabbableNode;_=P||u("fallbackFocus")}else _===null&&(_=u("fallbackFocus"));if(!_)throw new Error("Your focus-trap needs to have at least one focusable element");return _},p=function(){if(l.containerGroups=l.containers.map(function(_){var A=MF(_,r.tabbableOptions),P=$F(_,r.tabbableOptions),D=A.length>0?A[0]:void 0,z=A.length>0?A[A.length-1]:void 0,M=P.find(function(K){return Co(K)}),Z=P.slice().reverse().find(function(K){return Co(K)}),O=!!A.find(function(K){return Gn(K)>0});return{container:_,tabbableNodes:A,focusableNodes:P,posTabIndexesFound:O,firstTabbableNode:D,lastTabbableNode:z,firstDomTabbableNode:M,lastDomTabbableNode:Z,nextTabbableNode:function(de){var Ne=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,ce=A.indexOf(de);return ce<0?Ne?P.slice(P.indexOf(de)+1).find(function(le){return Co(le)}):P.slice(0,P.indexOf(de)).reverse().find(function(le){return Co(le)}):A[ce+(Ne?1:-1)]}}}),l.tabbableGroups=l.containerGroups.filter(function(_){return _.tabbableNodes.length>0}),l.tabbableGroups.length<=0&&!u("fallbackFocus"))throw new Error("Your focus-trap must have at least one container with at least one tabbable node in it at all times");if(l.containerGroups.find(function(_){return _.posTabIndexesFound})&&l.containerGroups.length>1)throw new Error("At least one node with a positive tabindex was found in one of your focus-trap's multiple containers. Positive tabindexes are only supported in single-container focus-traps.")},f=function(_){var A=_.activeElement;if(A)return A.shadowRoot&&A.shadowRoot.activeElement!==null?f(A.shadowRoot):A},h=function(_){if(_!==!1&&_!==f(document)){if(!_||!_.focus){h(m());return}_.focus({preventScroll:!!r.preventScroll}),l.mostRecentlyFocusedNode=_,jF(_)&&_.select()}},v=function(_){var A=u("setReturnFocus",{params:[_]});return A||(A===!1?!1:_)},k=function(_){var A=_.target,P=_.event,D=_.isBackward,z=D===void 0?!1:D;A=A||br(P),p();var M=null;if(l.tabbableGroups.length>0){var Z=c(A,P),O=Z>=0?l.containerGroups[Z]:void 0;if(Z<0)z?M=l.tabbableGroups[l.tabbableGroups.length-1].lastTabbableNode:M=l.tabbableGroups[0].firstTabbableNode;else if(z){var K=l.tabbableGroups.findIndex(function(C){var U=C.firstTabbableNode;return A===U});if(K<0&&(O.container===A||rs(A,r.tabbableOptions)&&!Co(A,r.tabbableOptions)&&!O.nextTabbableNode(A,!1))&&(K=Z),K>=0){var de=K===0?l.tabbableGroups.length-1:K-1,Ne=l.tabbableGroups[de];M=Gn(A)>=0?Ne.lastTabbableNode:Ne.lastDomTabbableNode}else Ni(P)||(M=O.nextTabbableNode(A,!1))}else{var ce=l.tabbableGroups.findIndex(function(C){var U=C.lastTabbableNode;return A===U});if(ce<0&&(O.container===A||rs(A,r.tabbableOptions)&&!Co(A,r.tabbableOptions)&&!O.nextTabbableNode(A))&&(ce=Z),ce>=0){var le=ce===l.tabbableGroups.length-1?0:ce+1,W=l.tabbableGroups[le];M=Gn(A)>=0?W.firstTabbableNode:W.firstDomTabbableNode}else Ni(P)||(M=O.nextTabbableNode(A))}}else M=u("fallbackFocus");return M},y=function(_){var A=br(_);if(!(c(A,_)>=0)){if(di(r.clickOutsideDeactivates,_)){s.deactivate({returnFocus:r.returnFocusOnDeactivate});return}di(r.allowOutsideClick,_)||_.preventDefault()}},w=function(_){var A=br(_),P=c(A,_)>=0;if(P||A instanceof Document)P&&(l.mostRecentlyFocusedNode=A);else{_.stopImmediatePropagation();var D,z=!0;if(l.mostRecentlyFocusedNode)if(Gn(l.mostRecentlyFocusedNode)>0){var M=c(l.mostRecentlyFocusedNode),Z=l.containerGroups[M].tabbableNodes;if(Z.length>0){var O=Z.findIndex(function(K){return K===l.mostRecentlyFocusedNode});O>=0&&(r.isKeyForward(l.recentNavEvent)?O+1<Z.length&&(D=Z[O+1],z=!1):O-1>=0&&(D=Z[O-1],z=!1))}}else l.containerGroups.some(function(K){return K.tabbableNodes.some(function(de){return Gn(de)>0})})||(z=!1);else z=!1;z&&(D=k({target:l.mostRecentlyFocusedNode,isBackward:r.isKeyBackward(l.recentNavEvent)})),h(D||l.mostRecentlyFocusedNode||m())}l.recentNavEvent=void 0},g=function(_){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;l.recentNavEvent=_;var P=k({event:_,isBackward:A});P&&(Ni(_)&&_.preventDefault(),h(P))},b=function(_){(r.isKeyForward(_)||r.isKeyBackward(_))&&g(_,r.isKeyBackward(_))},R=function(_){WF(_)&&di(r.escapeDeactivates,_)!==!1&&(_.preventDefault(),s.deactivate())},V=function(_){var A=br(_);c(A,_)>=0||di(r.clickOutsideDeactivates,_)||di(r.allowOutsideClick,_)||(_.preventDefault(),_.stopImmediatePropagation())},I=function(){if(l.active)return Iu.activateTrap(i,s),l.delayInitialFocusTimer=r.delayInitialFocus?Mu(function(){h(m())}):h(m()),n.addEventListener("focusin",w,!0),n.addEventListener("mousedown",y,{capture:!0,passive:!1}),n.addEventListener("touchstart",y,{capture:!0,passive:!1}),n.addEventListener("click",V,{capture:!0,passive:!1}),n.addEventListener("keydown",b,{capture:!0,passive:!1}),n.addEventListener("keydown",R),s},x=function(){if(l.active)return n.removeEventListener("focusin",w,!0),n.removeEventListener("mousedown",y,!0),n.removeEventListener("touchstart",y,!0),n.removeEventListener("click",V,!0),n.removeEventListener("keydown",b,!0),n.removeEventListener("keydown",R),s},T=function(_){var A=_.some(function(P){var D=Array.from(P.removedNodes);return D.some(function(z){return z===l.mostRecentlyFocusedNode})});A&&h(m())},$=typeof window<"u"&&"MutationObserver"in window?new MutationObserver(T):void 0,S=function(){$&&($.disconnect(),l.active&&!l.paused&&l.containers.map(function(_){$.observe(_,{subtree:!0,childList:!0})}))};return s={get active(){return l.active},get paused(){return l.paused},activate:function(_){if(l.active)return this;var A=d(_,"onActivate"),P=d(_,"onPostActivate"),D=d(_,"checkCanFocusTrap");D||p(),l.active=!0,l.paused=!1,l.nodeFocusedBeforeActivation=f(n),A==null||A();var z=function(){D&&p(),I(),S(),P==null||P()};return D?(D(l.containers.concat()).then(z,z),this):(z(),this)},deactivate:function(_){if(!l.active)return this;var A=Bu({onDeactivate:r.onDeactivate,onPostDeactivate:r.onPostDeactivate,checkCanReturnFocus:r.checkCanReturnFocus},_);clearTimeout(l.delayInitialFocusTimer),l.delayInitialFocusTimer=void 0,x(),l.active=!1,l.paused=!1,S(),Iu.deactivateTrap(i,s);var P=d(A,"onDeactivate"),D=d(A,"onPostDeactivate"),z=d(A,"checkCanReturnFocus"),M=d(A,"returnFocus","returnFocusOnDeactivate");P==null||P();var Z=function(){Mu(function(){M&&h(v(l.nodeFocusedBeforeActivation)),D==null||D()})};return M&&z?(z(v(l.nodeFocusedBeforeActivation)).then(Z,Z),this):(Z(),this)},pause:function(_){return l.active?(l.manuallyPaused=!0,this._setPausedState(!0,_)):this},unpause:function(_){return l.active?(l.manuallyPaused=!1,i[i.length-1]!==this?this:this._setPausedState(!1,_)):this},updateContainerElements:function(_){var A=[].concat(_).filter(Boolean);return l.containers=A.map(function(P){return typeof P=="string"?n.querySelector(P):P}),l.active&&p(),S(),this}},Object.defineProperties(s,{_isManuallyPaused:{value:function(){return l.manuallyPaused}},_setPausedState:{value:function(_,A){if(l.paused===_)return this;if(l.paused=_,_){var P=d(A,"onPause"),D=d(A,"onPostPause");P==null||P(),x(),S(),D==null||D()}else{var z=d(A,"onUnpause"),M=d(A,"onPostUnpause");z==null||z(),p(),I(),S(),M==null||M()}return this}}}),s.updateContainerElements(a),s};const KF=["aria-labelledby"],JF={class:"media-preview-sheet__header"},qF=["id"],YF=["aria-label"],QF=["src","alt"],e8=["src"],t8={class:"media-preview-sheet__actions"},a8=["disabled","aria-label"],n8=["aria-label","aria-pressed"],o8=["disabled","aria-label"],i8=e.defineComponent({__name:"MediaPreviewSheet",props:{open:{type:Boolean,default:!1},media:{default:null},canGoPrevious:{type:Boolean,default:!1},canGoNext:{type:Boolean,default:!1},selected:{type:Boolean,default:!1},closeLabel:{default:"Close"},previousLabel:{default:"Previous"},nextLabel:{default:"Next"},selectLabel:{default:"Select"},deselectLabel:{default:"Deselect"}},emits:["close","previous","next","toggleSelect"],setup(o,{emit:a}){const t=o,n=a,i=e.useId(),r=e.ref(null),l=e.ref(null);let s=null,d=null;const c=e.computed(()=>{var $;return(($=t.media)==null?void 0:$.mime_type.startsWith("image/"))===!0}),u=/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/ig,m=/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i,p=e.computed(()=>t.media?t.media.preview_url??t.media.original_url:"");function f($){const S=$.replace(/\.[^.]+$/,""),_=S.replace(u,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return _!==""?_:S||$}function h($){var A,P;const S=(A=$.name)==null?void 0:A.trim(),B=$.file_name.replace(/\.[^.]+$/,"");if(S!==void 0&&S!==""&&S!==$.file_name&&S!==B&&!m.test(S))return S;const _=(P=$.alt_text)==null?void 0:P.trim();return _!==void 0&&_!==""?_:f(S||$.file_name)}const v=e.computed(()=>t.media?h(t.media):"media"),k=e.computed(()=>t.media?`Preview ${v.value}`:"Media preview"),y=e.computed(()=>t.media?`Close preview of ${v.value}`:"Close preview"),w=e.computed(()=>t.canGoPrevious?"Previous media":"No previous media"),g=e.computed(()=>t.canGoNext?"Next media":"No next media"),b=e.computed(()=>{const $=t.selected?t.deselectLabel:t.selectLabel;return t.media?t.selected?`${t.deselectLabel} ${v.value}`:`${t.selectLabel} ${v.value}`:$}),R=e.computed(()=>t.selected?t.deselectLabel:t.selectLabel),V=()=>{t.media&&n("toggleSelect",t.media)},I=$=>{if($.key==="Escape"){$.preventDefault(),n("close");return}if($.key==="ArrowLeft"&&t.canGoPrevious){$.preventDefault(),n("previous");return}$.key==="ArrowRight"&&t.canGoNext&&($.preventDefault(),n("next"))},x=()=>{if(s){try{s.deactivate({returnFocus:!1})}catch{}s=null}},T=()=>{const $=d;d=null,$&&typeof $.focus=="function"&&e.nextTick(()=>{$.focus()})};return e.watch(()=>t.open&&t.media!==null,async $=>{var S;if($){d=document.activeElement instanceof HTMLElement?document.activeElement:null,await e.nextTick();const B=r.value;if(B)try{s=XF(B,{initialFocus:()=>l.value??B,escapeDeactivates:!1,clickOutsideDeactivates:!1,returnFocusOnDeactivate:!1,allowOutsideClick:!0}),s.activate()}catch{(S=l.value)==null||S.focus()}}else x(),T()},{immediate:!0}),e.onBeforeUnmount(()=>{x()}),($,S)=>(e.openBlock(),e.createBlock(e.Teleport,{to:"body"},[$.open&&$.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:I},[e.createElementVNode("header",JF,[e.createElementVNode("strong",{id:e.unref(i),"data-testid":"media-preview-sheet-title"},e.toDisplayString(k.value),9,qF),e.createElementVNode("button",{ref_key:"closeButtonRef",ref:l,type:"button",class:"media-preview-sheet__close","aria-label":y.value,"data-testid":"btn-media-preview-close",onClick:S[0]||(S[0]=B=>n("close"))},e.toDisplayString($.closeLabel),9,YF)]),c.value?(e.openBlock(),e.createElementBlock("img",{key:0,class:"media-preview-sheet__image",src:p.value,alt:$.media.alt_text||v.value},null,8,QF)):(e.openBlock(),e.createElementBlock("video",{key:1,class:"media-preview-sheet__video",src:p.value,controls:""},null,8,e8)),e.createElementVNode("div",t8,[e.createElementVNode("button",{type:"button",class:"media-preview-sheet__nav",disabled:!$.canGoPrevious,"aria-label":w.value,"data-testid":"btn-media-preview-previous",onClick:S[1]||(S[1]=B=>n("previous"))},e.toDisplayString($.previousLabel),9,a8),e.createElementVNode("button",{type:"button",class:"media-preview-sheet__select","aria-label":b.value,"aria-pressed":$.selected,"data-testid":"btn-media-preview-select",onClick:V},e.toDisplayString(R.value),9,n8),e.createElementVNode("button",{type:"button",class:"media-preview-sheet__nav",disabled:!$.canGoNext,"aria-label":g.value,"data-testid":"btn-media-preview-next",onClick:S[2]||(S[2]=B=>n("next"))},e.toDisplayString($.nextLabel),9,o8)])],40,KF)):e.createCommentVNode("",!0)]))}}),Md=$e(i8,[["__scopeId","data-v-fa05530d"]]),r8={key:0,class:"media-album-grid","data-testid":"media-source-sheet"},l8={class:"media-album-grid__items"},s8={class:"media-album-grid__card-name"},d8={class:"media-album-grid__card-name"},c8=["data-testid","onClick"],u8={class:"media-album-grid__card-name"},m8={key:0,class:"media-album-grid__card-meta"},p8={key:0,class:"media-album-grid__empty"},f8=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",r8,[e.createElementVNode("div",l8,[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",s8,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",d8,e.toDisplayString(n.viewLibraryLabel),1),i[4]||(i[4]=e.createElementVNode("span",{class:"media-album-grid__card-meta"},"All media",-1))],2),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.albums,r=>(e.openBlock(),e.createElementBlock("button",{key:r.id,type:"button",class:e.normalizeClass(["media-album-grid__card",{"is-active":n.currentView.scope==="album"&&n.currentView.albumId===r.id}]),"data-testid":`btn-media-source-album-${r.id}`,onClick:l=>t("selectAlbum",r)},[i[5]||(i[5]=e.createElementVNode("div",{class:"media-album-grid__card-icon"},[e.createElementVNode("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round"},[e.createElementVNode("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})])],-1)),e.createElementVNode("span",u8,e.toDisplayString(r.name),1),r.mediaCount!==void 0?(e.openBlock(),e.createElementBlock("span",m8,e.toDisplayString(r.mediaCount)+" item"+e.toDisplayString(r.mediaCount===1?"":"s"),1)):e.createCommentVNode("",!0)],10,c8))),128))]),n.albums.length===0?(e.openBlock(),e.createElementBlock("p",p8," No albums yet. ")):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)}}),hf=$e(f8,[["__scopeId","data-v-129f67b1"]]),h8={key:0,class:"media-upload-sheet","data-testid":"media-upload-sheet"},v8={class:"media-upload-sheet__dropzone-text"},g8={key:0,class:"media-upload-sheet__dropzone-helper","data-testid":"text-media-upload-sheet-helper"},b8={class:"media-upload-sheet__sr-only"},y8=["accept","aria-label"],w8=["aria-label"],k8={class:"media-upload-sheet__queue-row"},_8={key:0,class:"media-upload-sheet__preview"},E8=["src","alt","data-testid"],S8={class:"media-upload-sheet__queue-body"},C8={class:"media-upload-sheet__queue-info"},x8={class:"media-upload-sheet__queue-status"},N8=["aria-valuenow","aria-label","data-testid"],V8=["aria-label"],T8=e.defineComponent({__name:"MediaUploadSheet",props:{open:{type:Boolean,default:!1},queue:{},accept:{default:""},uploadLabel:{default:"Upload"},dropzoneLabel:{default:"Drop files here or browse"},dropzoneHelperText:{default:""},fileInputLabel:{default:"Choose media files"},closeButtonAriaLabel:{default:"Close upload panel"},closeButtonLabel:{default:"Done"},progressAriaLabel:{}},emits:["close","filesSelected"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!1),r=p=>{var h;return t.progressAriaLabel!==void 0?t.progressAriaLabel(p):`Uploading ${((h=p.file)==null?void 0:h.name)??"file"}`},l=p=>{const f=Number.isFinite(p.progress)?p.progress:0;return f<0?0:f>100?100:Math.round(f)},s=e.computed(()=>t.queue.length===0?"":`${t.queue.length} upload${t.queue.length===1?"":"s"} in progress`),d=p=>{const f=p.target;!(f instanceof HTMLInputElement)||f.files===null||(n("filesSelected",Array.from(f.files)),f.value="")},c=p=>{p.preventDefault(),i.value=!0},u=()=>{i.value=!1},m=p=>{var f;p.preventDefault(),i.value=!1,(f=p.dataTransfer)!=null&&f.files&&p.dataTransfer.files.length>0&&n("filesSelected",Array.from(p.dataTransfer.files))};return(p,f)=>p.open?(e.openBlock(),e.createElementBlock("section",h8,[e.createElementVNode("label",{class:e.normalizeClass(["media-upload-sheet__dropzone",{"is-drag-over":i.value}]),onDragover:c,onDragleave:u,onDrop:m},[f[1]||(f[1]=e.createStaticVNode('<div class="media-upload-sheet__dropzone-icon" data-v-df614629><svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" data-v-df614629><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" data-v-df614629></path><polyline points="17 8 12 3 7 8" data-v-df614629></polyline><line x1="12" y1="3" x2="12" y2="15" data-v-df614629></line></svg></div>',1)),e.createElementVNode("span",v8,e.toDisplayString(p.dropzoneLabel),1),p.dropzoneHelperText?(e.openBlock(),e.createElementBlock("span",g8,e.toDisplayString(p.dropzoneHelperText),1)):e.createCommentVNode("",!0),e.createElementVNode("span",b8,e.toDisplayString(p.fileInputLabel),1),e.createElementVNode("input",{type:"file",accept:p.accept,multiple:"",class:"media-upload-sheet__file-input","data-testid":"input-media-upload-sheet","aria-label":p.fileInputLabel,onChange:d},null,40,y8)],34),p.queue.length>0?(e.openBlock(),e.createElementBlock("ul",{key:0,class:"media-upload-sheet__queue","aria-live":"polite","aria-label":s.value,"data-testid":"list-media-upload-sheet-queue"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(p.queue,h=>(e.openBlock(),e.createElementBlock("li",{key:h.id,class:"media-upload-sheet__queue-item"},[e.createElementVNode("div",k8,[h.previewUrl?(e.openBlock(),e.createElementBlock("div",_8,[e.createElementVNode("img",{src:h.previewUrl,alt:`Preview of ${h.file.name}`,"data-testid":`img-media-upload-sheet-preview-${h.id}`},null,8,E8)])):e.createCommentVNode("",!0),e.createElementVNode("div",S8,[e.createElementVNode("div",C8,[e.createElementVNode("strong",null,e.toDisplayString(h.file.name),1),e.createElementVNode("span",x8,e.toDisplayString(h.status),1)]),e.createElementVNode("div",{class:"media-upload-sheet__progress-bar",role:"progressbar","aria-valuemin":"0","aria-valuemax":"100","aria-valuenow":l(h),"aria-label":r(h),"data-testid":`progress-media-upload-sheet-${h.id}`},[e.createElementVNode("div",{class:"media-upload-sheet__progress-fill",style:e.normalizeStyle({width:`${l(h)}%`})},null,4)],8,N8)])])]))),128))],8,w8)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",class:"media-upload-sheet__close-btn","aria-label":p.closeButtonAriaLabel,"data-testid":"btn-close-upload-sheet",onClick:f[0]||(f[0]=h=>n("close"))},e.toDisplayString(p.closeButtonLabel),9,V8)])):e.createCommentVNode("",!0)}}),vf=$e(T8,[["__scopeId","data-v-df614629"]]),B8=["aria-label","aria-pressed","data-testid"],I8=["src","alt"],M8={key:1,class:"media-thumbnail-cell__video"},$8={class:"media-thumbnail-cell__video-name"},F8={key:2,class:"media-thumbnail-cell__selected-badge"},D8={key:3,class:"media-thumbnail-cell__status-badge"},A8=["aria-label"],R8=e.defineComponent({__name:"MediaThumbnailCell",props:{media:{},selected:{type:Boolean,default:!1},status:{},testId:{default:"media-library-thumbnail"}},emits:["toggle","preview"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>t.media.thumbnail_url??t.media.preview_url??t.media.original_url),r=e.computed(()=>t.media.mime_type.startsWith("image/")),l=e.computed(()=>{switch(t.status){case"missing":return"Unavailable";case"forbidden":return"Restricted";case"uploading":return"Uploading";case"failed":return"Failed";case"file_lost":return"Needs file";default:return null}}),s=e.computed(()=>{const u=t.media.file_name;return t.selected?`Deselect ${u}`:`Select ${u}`}),d=()=>{n("toggle",t.media)},c=()=>{n("preview",t.media)};return(u,m)=>(e.openBlock(),e.createElementBlock("article",{class:e.normalizeClass(["media-thumbnail-cell",{"is-selected":u.selected,"has-status":l.value!==null}])},[e.createElementVNode("button",{type:"button",class:"media-thumbnail-cell__button","aria-label":s.value,"aria-pressed":u.selected?"true":"false","data-testid":u.testId,onClick:d},[r.value?(e.openBlock(),e.createElementBlock("img",{key:0,class:"media-thumbnail-cell__image",src:i.value,alt:u.media.file_name},null,8,I8)):(e.openBlock(),e.createElementBlock("div",M8,[m[0]||(m[0]=e.createElementVNode("span",{class:"media-thumbnail-cell__video-label"},"Video",-1)),e.createElementVNode("span",$8,e.toDisplayString(u.media.file_name),1)])),u.selected?(e.openBlock(),e.createElementBlock("span",F8," Selected ")):e.createCommentVNode("",!0),l.value!==null?(e.openBlock(),e.createElementBlock("span",D8,e.toDisplayString(l.value),1)):e.createCommentVNode("",!0)],8,B8),e.createElementVNode("button",{type:"button",class:"media-thumbnail-cell__preview-button","aria-label":`Preview ${u.media.file_name}`,onClick:c}," Preview ",8,A8)],2))}}),gf=$e(R8,[["__scopeId","data-v-edd4f0ad"]]),L8={class:"virtual-media-grid"},P8={key:0,class:"virtual-media-grid__state","data-testid":"media-grid-loading"},U8={key:1,class:"virtual-media-grid__state","data-testid":"media-grid-empty"},O8={key:2,class:"virtual-media-grid__items"},z8=["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(l=>l.id===r)}return(r,l)=>(e.openBlock(),e.createElementBlock("div",L8,[r.loading&&r.items.length===0?(e.openBlock(),e.createElementBlock("div",P8,e.toDisplayString(r.loadingMessage),1)):r.items.length===0?(e.openBlock(),e.createElementBlock("div",U8,e.toDisplayString(r.emptyMessage),1)):(e.openBlock(),e.createElementBlock("div",O8,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.items,s=>{var d,c;return e.openBlock(),e.createBlock(gf,{key:s.uuid,media:s,selected:((d=i(s.uuid))==null?void 0:d.status)==="ready",status:(c=i(s.uuid))==null?void 0:c.status,"test-id":`${r.testIdPrefix}-${s.uuid}`,onToggle:l[0]||(l[0]=u=>n("toggle",u)),onPreview:l[1]||(l[1]=u=>n("preview",u))},null,8,["media","selected","status","test-id"])}),128))])),r.hasMore?(e.openBlock(),e.createElementBlock("button",{key:3,type:"button",class:"virtual-media-grid__load-more",disabled:r.loadingMore,"data-testid":"btn-media-grid-load-more",onClick:l[2]||(l[2]=s=>n("loadMore"))},e.toDisplayString(r.loadingMore?r.loadingMoreLabel:r.loadMoreLabel),9,z8)):e.createCommentVNode("",!0)]))}}),bf=$e(j8,[["__scopeId","data-v-34667f65"]]);function Yr(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 yf(o){var t;const a=o.split(".");return a.length>1?`.${(t=a.pop())==null?void 0:t.toLowerCase()}`:""}function $d(o){return o.type.startsWith("image/")}async function wf(o){return $d(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 kf(o,a){const t=[];if(a.maxFileSize&&o.size>a.maxFileSize&&t.push({field:"size",message:`File exceeds maximum size of ${Yr(a.maxFileSize)}`,code:"MAX_FILE_SIZE"}),a.minFileSize&&o.size<a.minFileSize&&t.push({field:"size",message:`File is smaller than minimum size of ${Yr(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=yf(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($d(o)&&(a.maxDimensions||a.minDimensions)){const n=await wf(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 Fd(o={}){const a=e.ref(o.rules||{});function t(d){a.value=d}async function n(d){return kf(d,a.value)}async function i(d){const c=new Map;return await Promise.all(d.map(async u=>{const m=await n(u);c.set(u,m)})),c}function r(d,c){return a.value.maxItems?c+d<=a.value.maxItems:!0}const l=e.computed(()=>{const d=[];return a.value.acceptedMimeTypes&&d.push(...a.value.acceptedMimeTypes),a.value.acceptedExtensions&&d.push(...a.value.acceptedExtensions),d.join(",")});function s(d){return!a.value.acceptedMimeTypes||a.value.acceptedMimeTypes.length===0?!0:a.value.acceptedMimeTypes.some(c=>c.endsWith("/*")?d.startsWith(c.slice(0,-1)):d===c)}return{rules:a,setRules:t,validateFile:n,validateFiles:i,canAddFiles:r,acceptString:l,isMimeTypeAllowed:s}}function W8(){return`upload-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function H8(o){if(o.type.startsWith("image/"))return URL.createObjectURL(o)}function Dd(o){const{adapter:a,maxConcurrent:t=3,rules:n,collection:i,onUploadStart:r,onUploadProgress:l,onUploadComplete:s,onUploadError:d,onQueueComplete:c,postUpload:u}=o,m=e.ref(new Map),p=e.ref(new Set),f=n?{rules:n}:{},{validateFile:h}=Fd(f);async function v(){if(p.value.size>=t)return;const B=Array.from(m.value.entries()).find(([P,D])=>D.status==="pending"&&!p.value.has(P));if(!B){Array.from(m.value.values()).every(D=>D.status==="completed"||D.status==="error")&&m.value.size>0&&(c==null||c());return}const[_,A]=B;await k(_,A)}async function k(B,_){p.value.add(B),_.status="uploading",_.abortController=new AbortController,m.value.set(B,{..._}),r==null||r(_);try{const A={onProgress:D=>{_.progress=D,m.value.set(B,{..._}),l==null||l(_)},signal:_.abortController.signal};i&&(A.collection=i);const P=await a.upload(_.file,A);u&&(_.status="attaching",m.value.set(B,{..._}),l==null||l(_),await u(_,P.media,a)),_.status="completed",_.progress=100,_.media=P.media,m.value.set(B,{..._}),s==null||s(_,P.media)}catch(A){A.name==="AbortError"?m.value.delete(B):(_.status="error",_.error=A.message,m.value.set(B,{..._}),d==null||d(_,A))}finally{p.value.delete(B),delete _.abortController,v()}}async function y(B){var P;const _=Array.from(B),A=[];for(const D of _){const z=await h(D),M=W8(),Z=H8(D),O={id:M,file:D,progress:0,status:z.valid?"pending":"error"};!z.valid&&((P=z.errors[0])!=null&&P.message)&&(O.error=z.errors[0].message),Z&&(O.previewUrl=Z),m.value.set(M,O);const K={media:null,clientId:M,name:D.name,order:0,upload:O,errors:z.errors};A.push(K)}for(let D=0;D<t;D++)v();return A}function w(B){const _=m.value.get(B);_&&(_.abortController&&_.abortController.abort(),_.previewUrl&&URL.revokeObjectURL(_.previewUrl),m.value.delete(B),p.value.delete(B),v())}async function g(B){const _=m.value.get(B);!_||_.status!=="error"||(_.status="pending",_.progress=0,delete _.error,m.value.set(B,{..._}),v())}function b(){for(const[B,_]of m.value.entries())(_.status==="completed"||_.status==="error")&&(_.previewUrl&&URL.revokeObjectURL(_.previewUrl),m.value.delete(B))}function R(){for(const B of m.value.values())B.abortController&&B.abortController.abort(),B.previewUrl&&URL.revokeObjectURL(B.previewUrl);m.value.clear(),p.value.clear()}function V(B){return m.value.get(B)}const I=e.computed(()=>p.value.size>0),x=e.computed(()=>p.value.size),T=e.computed(()=>Array.from(m.value.values()).filter(B=>B.status==="pending").length),$=e.computed(()=>m.value.size===0?!0:Array.from(m.value.values()).every(B=>B.status==="completed"||B.status==="error")),S=e.computed(()=>Array.from(m.value.values()));return{uploads:m,isUploading:I,activeCount:x,pendingCount:T,isComplete:$,addFiles:y,cancelUpload:w,retryUpload:g,clearCompleted:b,clearAll:R,getUpload:V,uploadsArray:S}}function oo(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Di(o){return typeof o=="string"?o:null}function ci(o){return typeof o=="number"?o:null}function Z8(o){return typeof o=="boolean"?o:null}function _f(o){return oo(o)&&typeof o.uuid=="string"&&typeof o.file_name=="string"&&typeof o.mime_type=="string"&&(typeof o.original_url=="string"||o.original_url===null)&&typeof o.size=="number"&&typeof o.disk=="string"&&typeof o.created_at=="string"&&typeof o.updated_at=="string"}function G8(o){return!oo(o)||typeof o.id!="string"||typeof o.status!="string"?null:o.status==="ready"?_f(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 X8(o){return oo(o)?{next_cursor:Di(o.next_cursor),previous_cursor:Di(o.previous_cursor),has_more:Z8(o.has_more)??!1,per_page:ci(o.per_page),count:ci(o.count),total:ci(o.total),current_page:ci(o.current_page),last_page:ci(o.last_page)}:null}function $u(o){const a=oo(o)?o:{},t=Array.isArray(a.data)?a.data.filter(_f):[],n=oo(a.meta)?a.meta:{},i=X8(n.pagination),r=(i==null?void 0:i.next_cursor)??Di(n.next_cursor)??Di(n.cursor),l=(i==null?void 0:i.has_more)??n.has_more===!0,s=Array.isArray(a.hydrated)?a.hydrated.map(G8).filter(c=>c!==null):[],d={cursor:r,has_more:l};return i!==null&&(d.pagination=i),{data:t,meta:d,hydrated:s}}function Fu(o,a,t,n,i,r){const l={view:o.scope==="album"?{scope:"album",album_id:o.albumId}:{scope:o.scope},per_page:t,sort:a.sort??"newest"};return a.query&&a.query.trim()!==""&&(l.query=a.query.trim()),a.kinds&&a.kinds.length>0&&(l.kinds=a.kinds),a.created_after&&a.created_after.trim()!==""&&(l.created_after=a.created_after.trim()),a.created_before&&a.created_before.trim()!==""&&(l.created_before=a.created_before.trim()),(a.usage_status==="used"||a.usage_status==="not_used")&&(l.usage_status=a.usage_status),(a.unfiled_only===!0||o.scope==="unfiled")&&(l.unfiled_only=1),a.selected_uuids&&a.selected_uuids.length>0&&(l.selected_uuids=[...a.selected_uuids]),r!=null?(l.page=r,l.include_total=1):n!==null&&(l.cursor=n),i&&i.length>0&&(l.hydrate_ids=i),l}function Du(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 K8(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 J8(o){var a;return o instanceof Error?((a=o.response)==null?void 0:a.data)??null:null}function q8(o){if(!oo(o))return[];const a=[];for(const t of Object.values(o)){if(typeof t=="string"&&t.trim()!==""){a.push(t.trim());continue}if(Array.isArray(t))for(const n of t){if(typeof n!="string")continue;const i=n.trim();i!==""&&a.push(i)}}return Array.from(new Set(a))}function Y8(o){var r;const a=J8(o),t=oo(a)?a:null,n=((r=Di(t==null?void 0:t.message))==null?void 0:r.trim())??null,i=q8(t==null?void 0:t.errors);return n!==null&&i.length>0?n==="Validation failed"?i.join(" "):i.every(s=>n.includes(s))?n:`${n} ${i.join(" ")}`:n!==null?n:i.length>0?i.join(" "):o instanceof Error?o.message:"Failed to load media."}function Au(o,a){const t=Y8(a),n=K8(a);return{code:n===403?"permission_denied":o,message:t,retriable:n!==403,cause:a}}function Ad(o){const a=()=>{const V=o.perPage!==void 0?e.toValue(o.perPage):40;return V>0?V:40},t=()=>{const V=o.page!==void 0?e.toValue(o.page):null;return V==null?null:V>0?V:1},n=e.ref([]),i=e.ref([]),r=e.ref(null),l=e.ref(!1),s=e.ref(!1),d=e.ref(!1),c=e.ref(!1),u=e.ref(null),m=e.ref(null),p=e.ref(null),f=e.ref(null);let h=null,v=0;const k=async(V,I)=>{v+=1;const x=v;h==null||h.abort();const T=new AbortController;h=T,V?d.value=!0:s.value=!0,u.value=null,c.value=!1;const $=I??t(),S=$!==null;try{const B=await o.httpClient.get("/v1/media/library",{params:Fu(o.view.value,o.filters.value,a(),S?null:V?r.value:null,void 0,$),signal:T.signal});if(x!==v)return;const _=$u(B);n.value=V&&!S?Du([...n.value,..._.data]):_.data,i.value=_.hydrated,r.value=_.meta.cursor,l.value=_.meta.has_more;const A=_.meta.pagination;m.value=(A==null?void 0:A.total)??null,p.value=(A==null?void 0:A.current_page)??(S&&$!==null?$:null);const P=(A==null?void 0:A.per_page)??a();f.value=(A==null?void 0:A.last_page)??(m.value!==null&&P>0?Math.max(1,Math.ceil(m.value/P)):null)}catch(B){if(T.signal.aborted||x!==v)return;const _=Au(V?"load_more_failed":"query_failed",B);u.value=_,c.value=_.code==="permission_denied",V||(n.value=[],r.value=null,l.value=!1)}finally{x===v&&(s.value=!1,d.value=!1)}},y=async V=>{if(V.length===0)return i.value=[],[];try{const I=await o.httpClient.get("/v1/media/library",{params:Fu(o.view.value,o.filters.value,1,null,V)}),x=$u(I);return i.value=x.hydrated,x.hydrated}catch(I){return u.value=Au("hydration_failed",I),[]}},w=V=>{n.value=Du([V,...n.value])},g=async()=>{!l.value||d.value||t()===null&&await k(!0)};return{items:n,hydrated:i,cursor:r,hasMore:l,loading:s,loadingMore:d,permissionDenied:c,error:u,total:m,currentPage:p,totalPages:f,loadInitial:async()=>{r.value=null,await k(!1)},loadMore:g,loadAll:async V=>{const I=(V==null?void 0:V.maxItems)??5e3;if(!(s.value||d.value))for(;l.value&&n.value.length<I;){const x=n.value.length;if(await g(),u.value!==null||n.value.length===x)return}},goToPage:async V=>{!Number.isFinite(V)||V<1||s.value||d.value||await k(!1,V)},refresh:async()=>{r.value=null,await k(!1)},hydrateSelection:y,prepend:w}}const Q8="mediables.media-library.";function e6(o){return!o||o.key.trim()===""?null:`${Q8}${o.key}`}function ls(){return typeof window>"u"||typeof window.sessionStorage>"u"?null:window.sessionStorage}function t6(o,a){const t=Date.parse(o);return Number.isFinite(t)?Date.now()-t>a*60*1e3:!0}function Ef(o){const a=e6(o),t=(o==null?void 0:o.ttlMinutes)??30,n=`${(o==null?void 0:o.key)??"media-library"}:${Date.now()}`;return{restore:()=>{if(a===null)return null;const s=ls();if(s===null)return null;const d=s.getItem(a);if(d===null)return null;let c;try{c=JSON.parse(d)}catch{return s.removeItem(a),null}if(typeof c!="object"||c===null||Array.isArray(c))return s.removeItem(a),null;const u=c;if(u.version!==1||typeof u.savedAt!="string"||t6(u.savedAt,t))return s.removeItem(a),null;const m={selectedIds:Array.isArray(u.selectedIds)?u.selectedIds.filter(p=>typeof p=="string"&&p.trim()!==""):[]};return((o==null?void 0:o.restoreView)??!0)&&u.view&&(m.view=u.view),u.filters&&(m.filters=u.filters),m},save:s=>{if(a===null)return;const d=ls();if(d===null)return;const c={version:1,savedAt:new Date().toISOString(),selectedIds:[...s.selectedIds]};((o==null?void 0:o.restoreView)??!0)&&s.view&&(c.view=s.view),s.filters&&(c.filters=s.filters),d.setItem(a,JSON.stringify(c))},clear:()=>{if(a===null)return;const s=ls();s==null||s.removeItem(a)},sessionId:n}}function Sf(o){const a=e.ref(o);return{state:a,transition:n=>{a.value=n}}}function Cf(o){return{emitMetric:(t,n)=>{const i={name:t,timestamp:new Date().toISOString()};n!==void 0&&(i.payload=n),o==null||o(i)}}}function Mo(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function a6(o){const a=Mo(o)?o:{};return(Array.isArray(a.data)?a.data:Mo(a.data)&&Array.isArray(a.data.data)?a.data.data:Array.isArray(o)?o:[]).map(n=>{if(!Mo(n)||typeof n.id!="string"||typeof n.name!="string")return null;const i={id:n.id,name:n.name};return typeof n.description=="string"&&n.description.trim()!==""&&(i.description=n.description),typeof n.media_count=="number"&&(i.mediaCount=n.media_count),i}).filter(n=>n!==null)}function n6(o){const a=Mo(o)?o:{},t=Mo(a.data)?a.data:Mo(o)?o:null;if(t===null||typeof t.id!="string"||typeof t.name!="string")return null;const n={id:t.id,name:t.name};return typeof t.description=="string"&&t.description.trim()!==""&&(n.description=t.description),n}function o6(o){return o==="ready"||o==="uploading"||o==="failed"}function Un(o,a="ready"){return{id:o.uuid,media:o,status:a,countsTowardMax:o6(a)}}function i6(o,a){return o.scope==="library"?!0:o.scope!=="album"?!1:a.type==="album"&&a.albumId===o.albumId}function r6(o,a){return o.scope==="library"?a.type==="library"||a.type==="album":o.scope!=="album"?!1:a.type==="album"&&a.albumId===o.albumId}function ss(o){return{code:"configuration_error",message:o,retriable:!1}}const xf="/v1/albums";function l6(o){var a;return((a=o.deps.albumEndpoints)==null?void 0:a.list)??xf}function s6(o){var a,t;return((a=o.deps.albumEndpoints)==null?void 0:a.create)??((t=o.deps.albumEndpoints)==null?void 0:t.list)??xf}function d6(o){return typeof o!="string"||o.length===0?"document":o.startsWith("image/")?"image":o.startsWith("video/")?"video":o.startsWith("audio/")?"audio":"document"}function c6(o,a){return a.length===0||o===null?!0:a.includes(d6(o.mime_type))}function Ru(o){return{...o??{},...(o==null?void 0:o.kinds)!==void 0?{kinds:[...o.kinds]}:{},...(o==null?void 0:o.selected_uuids)!==void 0?{selected_uuids:[...o.selected_uuids]}:{}}}function Nf(o){var W,C;const a=o.selectionMode??"multiple",t=o.maxSelection,n=o.uploadBehavior??"adapter",i=e.ref(o.initialView??{scope:"library"}),r=((W=o.initialFilters)==null?void 0:W.kinds)??(o.allowedMediaKinds&&o.allowedMediaKinds.length>0?[...o.allowedMediaKinds]:void 0),l=e.ref({...Ru(o.initialFilters),sort:((C=o.initialFilters)==null?void 0:C.sort)??"newest",...r?{kinds:r}:{}}),s=o.allowedMediaKinds?[...o.allowedMediaKinds]:[],d=e.ref([]),c=e.ref([]),u=e.ref(null),m=e.ref(null),p=Ef(o.sessionPolicy),{emitMetric:f}=Cf(o.telemetry),h=Sf("idle"),v=Ad({httpClient:o.deps.httpClient,view:i,filters:l}),k=e.computed(()=>c.value.map(U=>U.id)),y=e.computed(()=>{const U=u.value;return U===null?null:v.items.value[U]??null}),w=e.computed(()=>o.uploadTarget??{type:"library"}),g=Dd({adapter:o.deps.uploadAdapter??{name:"missing-upload-adapter",upload:async()=>{throw new Error("Upload adapter is not configured.")},attach:async()=>{},attachMany:async()=>{},detach:async()=>{},reorder:async()=>{},fetchModelMedia:async()=>[],getUrl:U=>U.original_url,getThumbnailUrl:U=>U.thumbnail_url??U.preview_url??U.original_url},postUpload:async(U,j,re)=>{const ue=w.value;ue.type!=="album"||!ue.albumId||await re.attach(j.uuid,{modelType:"album",modelId:ue.albumId})},onUploadComplete:(U,j)=>{const re=w.value;i6(i.value,re)&&v.prepend(j),o.autoSelectUploaded&&r6(i.value,re)&&$(j),f("upload-complete",{mediaId:j.uuid,targetType:re.type,targetAlbumId:re.albumId})},onUploadError:(U,j)=>{m.value={code:"upload_failed",message:j.message,retriable:!0,cause:j}}}),b=e.computed(()=>g.isUploading.value),R=()=>{p.save({selectedIds:[...k.value],view:i.value,filters:l.value})},V=async U=>{const j=await v.hydrateSelection(U);c.value=j.map(re=>re.status==="ready"&&re.media?Un(re.media):{id:re.id,media:null,status:re.status,countsTowardMax:!1})},I=e.computed(()=>c.value.filter(U=>U.countsTowardMax).length),x=()=>a==="single"||t===void 0?!0:I.value<t,T=U=>{if(c.value.findIndex(re=>re.id===U.uuid)>=0){a==="multiple"?c.value=c.value.filter(re=>re.id!==U.uuid):c.value=[Un(U)],R();return}if(!x()){m.value={code:"selection_invalid",message:t!==void 0?`You can only select up to ${t} items.`:"You cannot select more items.",retriable:!0};return}a==="single"?c.value=[Un(U)]:c.value=[...c.value,Un(U)],m.value=null,R()},$=U=>{const j=c.value.findIndex(re=>re.id===U.uuid);if(j>=0){c.value=c.value.map((re,ue)=>ue===j?Un(U):re),m.value=null,R();return}if(!x()){m.value={code:"selection_invalid",message:t!==void 0?`You can only select up to ${t} items.`:"You cannot select more items.",retriable:!0};return}a==="single"?c.value=[Un(U)]:c.value=[...c.value,Un(U)],m.value=null,R()},S=async()=>{var j;h.transition("restoring");const U=p.restore();if(U===null){h.transition("ready");return}U.view&&(i.value=U.view),U.filters&&(l.value={...Ru(U.filters),sort:U.filters.sort??"newest"}),await v.loadInitial(),(((j=o.sessionPolicy)==null?void 0:j.restoreSelection)??!0)&&await V(U.selectedIds),h.transition("ready")};e.watch(()=>v.error.value,U=>{U!==null&&(m.value=U,h.transition("error"))});const B=async()=>{m.value=null,h.transition("idle"),await S(),v.items.value.length===0&&!v.loading.value&&!v.permissionDenied.value&&await v.loadInitial();const U=o.defaultSelectedIds??[];c.value.length===0&&U.length>0&&await V(U),h.transition("ready")},_=async(U,j="user")=>{const re=i.value;i.value=U,j==="user"&&o.preserveSelectionOnViewChange===!1&&(c.value=[]),f("view-change",{from:re.scope,to:U.scope,reason:j}),await v.loadInitial(),R()},A=async()=>{const U=await o.deps.httpClient.get(l6(o));d.value=a6(U)},P=async(U,j)=>{try{const re={name:U,visibility:"private"};j&&j.trim()!==""&&(re.parent_id=j);const ue=await o.deps.httpClient.post(s6(o),re),Xe=n6(ue);return Xe===null?ss("Album creation response was invalid."):(d.value=[Xe,...d.value.filter(be=>be.id!==Xe.id)],await _({scope:"album",albumId:Xe.id,albumName:Xe.name},"inline-album-created"),Xe)}catch(re){const ue={code:"album_create_failed",message:re instanceof Error?re.message:"Album creation failed.",retriable:!0,cause:re};return m.value=ue,ue}},D=async U=>{if(!o.enableUpload){m.value=ss("Uploads are not enabled for this picker.");return}if(n!=="delegate"){if(!o.deps.uploadAdapter){m.value=ss("Uploads require a configured upload adapter.");return}await g.addFiles(U)}},z=()=>{var re;if(s.length>0&&c.value.find(Xe=>Xe.media!==null&&!c6(Xe.media,s))){const be={code:"selection_invalid",message:`Selected media is not allowed here. Choose one of: ${s.join(", ")}.`,retriable:!0};return m.value=be,be}const U=((re=o.validateSelection)==null?void 0:re.call(o,c.value))??null;if(U!==null){const ue={code:"selection_invalid",message:U,retriable:!0};return m.value=ue,ue}if(c.value.filter(ue=>ue.status==="ready"&&ue.media!==null).length===0){const ue={code:"selection_invalid",message:"Select at least one available media item.",retriable:!0};return m.value=ue,ue}return{orderedIds:k.value,items:[...c.value],view:i.value,filters:l.value,dirty:!0,sessionId:p.sessionId}},M=U=>{const j=v.items.value.findIndex(re=>re.uuid===U.uuid);u.value=j>=0?j:null},Z=()=>{u.value=null},O=()=>{u.value===null||u.value<=0||(u.value-=1)},K=()=>{u.value===null||u.value>=v.items.value.length-1||(u.value+=1)},de=U=>{c.value=c.value.filter(j=>j.id!==U),R()},Ne=async()=>{await v.refresh()},ce=async U=>{l.value={...l.value,...U&&U.trim()!==""?{query:U.trim()}:{}},(!U||U.trim()==="")&&delete l.value.query,await v.loadInitial(),R()},le=async()=>{await _({scope:"library"},"permission-unavailable")};return{view:i,filters:l,albums:d,selectedItems:c,orderedIds:k,queryItems:v.items,cursor:v.cursor,hasMore:v.hasMore,loading:v.loading,loadingMore:v.loadingMore,permissionDenied:v.permissionDenied,error:m,uploadQueue:g.uploadsArray,isUploading:b,previewIndex:u,previewItem:y,initialize:B,refresh:Ne,loadMore:v.loadMore,setQuery:ce,setView:_,toggleSelection:T,removeSelected:de,confirmSelection:z,openPreview:M,closePreview:Z,showPreviousPreview:O,showNextPreview:K,loadAlbums:A,createAlbum:P,addUploadFiles:D,goToLibrary:le,sessionId:p.sessionId}}const u6=["data-testid"],m6={class:"mlp-location-bar"},p6={class:"mlp-location-bar__left"},f6={class:"mlp-location-bar__label"},h6={class:"mlp-tabs","data-testid":"media-picker-tabs"},v6={key:0,class:"mlp-search-row"},g6=["placeholder"],b6={key:2,class:"mlp-overlay-panel"},y6={key:0,class:"mlp-error","data-testid":"media-picker-error"},w6={key:5,class:"mlp-bottom-bar"},k6={key:0,class:"mlp-bottom-bar__selection"},_6={class:"mlp-bottom-bar__count"},E6={class:"mlp-bottom-bar__thumbs"},S6=["src","alt"],C6={key:1,class:"mlp-bottom-bar__thumb-placeholder"},x6=["aria-label","onClick"],N6={class:"mlp-bottom-bar__actions"},V6=e.defineComponent({__name:"MediaLibraryPicker",props:{deps:{},mode:{default:"picker-multi"},capabilities:{default:()=>({})},itemFilter:{},modelValue:{default:()=>[]},defaultSelectedIds:{default:()=>[]},selectionMode:{default:"multiple"},maxSelection:{},preserveSelectionOnViewChange:{type:Boolean,default:!0},initialView:{default:()=>({scope:"library"})},initialFilters:{default:()=>({sort:"newest"})},enableUpload:{type:Boolean,default:!1},uploadBehavior:{default:"adapter"},enablePreview:{type:Boolean,default:!0},enableAlbumCreation:{type:Boolean,default:!1},allowedMediaKinds:{},accept:{},validateSelection:{},uploadTarget:{},autoSelectUploaded:{type:Boolean,default:!1},createAlbumDefaultVisibility:{default:"private"},sessionPolicy:{},labels:{default:()=>({})},showFooter:{type:Boolean,default:!0},testIdPrefix:{default:"media-picker"},telemetry:{}},emits:["update:modelValue","confirm","cancel","selection-change","select","view-change","error","metric","request-upload-files"],setup(o,{expose:a,emit:t}){const n=o,i=t,r=e.computed(()=>{var C,U,j,re,ue,Xe,be,Ee,ye,xe,Ce,Re,ze,rt,at,Dt,ht,St,ut,lt,Ct,Se,J,oe,De,fe,Ae,Ye,st,Bt,Vt,Lt,Pt,zt,Ot,jt,oa,Q,ge;return{title:((C=n.labels)==null?void 0:C.title)??"Media library",searchPlaceholder:((U=n.labels)==null?void 0:U.searchPlaceholder)??"Search your media",viewLibrary:((j=n.labels)==null?void 0:j.viewLibrary)??"Library",browseAlbums:((re=n.labels)==null?void 0:re.browseAlbums)??"Albums",createAlbum:((ue=n.labels)==null?void 0:ue.createAlbum)??"Create album",createAlbumNameLabel:((Xe=n.labels)==null?void 0:Xe.createAlbumNameLabel)??"Album name",emptyLibrary:((be=n.labels)==null?void 0:be.emptyLibrary)??"No media found in your library.",emptyAlbum:((Ee=n.labels)==null?void 0:Ee.emptyAlbum)??"No media found in this album.",networkError:((ye=n.labels)==null?void 0:ye.networkError)??"Unable to load media right now.",retry:((xe=n.labels)==null?void 0:xe.retry)??"Retry",selectedCount:((Ce=n.labels)==null?void 0:Ce.selectedCount)??(me=>`${me} selected`),confirmAction:((Re=n.labels)==null?void 0:Re.confirmAction)??"Attach selected",cancel:((ze=n.labels)==null?void 0:ze.cancel)??"Cancel",dismiss:((rt=n.labels)==null?void 0:rt.dismiss)??"Remove",uploadLabel:((at=n.labels)==null?void 0:at.uploadLabel)??"Upload",albumUnavailableTitle:((Dt=n.labels)==null?void 0:Dt.albumUnavailableTitle)??"Album unavailable",albumUnavailableBody:((ht=n.labels)==null?void 0:ht.albumUnavailableBody)??"You no longer have access to this album.",goToLibrary:((St=n.labels)==null?void 0:St.goToLibrary)??"Go to library",allMediaTab:((ut=n.labels)==null?void 0:ut.allMediaTab)??"All Media",loadingMedia:((lt=n.labels)==null?void 0:lt.loadingMedia)??"Loading media…",loadMore:((Ct=n.labels)==null?void 0:Ct.loadMore)??"Load more",loadingMore:((Se=n.labels)==null?void 0:Se.loadingMore)??"Loading…",uploadDropzone:((J=n.labels)==null?void 0:J.uploadDropzone)??"Drop files here or browse",uploadDropzoneHelper:((oe=n.labels)==null?void 0:oe.uploadDropzoneHelper)??"",uploadDone:((De=n.labels)==null?void 0:De.uploadDone)??"Done",uploadDoneAria:((fe=n.labels)==null?void 0:fe.uploadDoneAria)??"Close upload panel",uploadFileInputLabel:((Ae=n.labels)==null?void 0:Ae.uploadFileInputLabel)??"Choose media files",previewClose:((Ye=n.labels)==null?void 0:Ye.previewClose)??"Close preview",previewPrevious:((st=n.labels)==null?void 0:st.previewPrevious)??"Previous media",previewNext:((Bt=n.labels)==null?void 0:Bt.previewNext)??"Next media",previewSelect:((Vt=n.labels)==null?void 0:Vt.previewSelect)??"Select media",previewDeselect:((Lt=n.labels)==null?void 0:Lt.previewDeselect)??"Deselect media",selectAction:((Pt=n.labels)==null?void 0:Pt.selectAction)??"Select",allMedia:((zt=n.labels)==null?void 0:zt.allMedia)??((Ot=n.labels)==null?void 0:Ot.allMediaTab)??"All media",unfiled:((jt=n.labels)==null?void 0:jt.unfiled)??"Unfiled",pageTitle:((oa=n.labels)==null?void 0:oa.pageTitle)??((Q=n.labels)==null?void 0:Q.title)??"Media library",albumLabel:((ge=n.labels)==null?void 0:ge.albumLabel)??"Album"}}),l=e.computed(()=>n.mode),s=e.computed(()=>l.value==="picker-single"?"single":n.selectionMode),d=e.computed(()=>n.showFooter===!0&&l.value!=="picker-single"),c=e.computed(()=>n.enablePreview===!0&&l.value!=="picker-single"),u={deps:n.deps,selectionMode:s.value,initialView:n.initialView,initialFilters:n.initialFilters,...n.maxSelection!==void 0?{maxSelection:n.maxSelection}:{},...n.modelValue.length>0||n.defaultSelectedIds.length>0?{defaultSelectedIds:n.modelValue.length>0?n.modelValue:n.defaultSelectedIds}:{},...n.sessionPolicy?{sessionPolicy:n.sessionPolicy}:{},...n.enableUpload?{enableUpload:!0}:{},uploadBehavior:n.uploadBehavior,...n.uploadTarget?{uploadTarget:n.uploadTarget}:{},...n.autoSelectUploaded?{autoSelectUploaded:!0}:{},...n.validateSelection?{validateSelection:n.validateSelection}:{},...n.allowedMediaKinds&&n.allowedMediaKinds.length>0?{allowedMediaKinds:n.allowedMediaKinds}:{},preserveSelectionOnViewChange:n.preserveSelectionOnViewChange,telemetry:C=>{var U;(U=n.telemetry)==null||U.call(n,C),i("metric",C)}},m=Nf(u),p=e.ref(n.initialFilters.query??""),f=e.ref(n.enableUpload?"upload":"media"),h=e.ref(!1),v=JSON.stringify(n.modelValue.length>0?n.modelValue:n.defaultSelectedIds);let k=null;const y=e.computed(()=>JSON.stringify(m.orderedIds.value)!==v),w=e.computed(()=>m.view.value.scope==="album"?r.value.emptyAlbum:r.value.emptyLibrary),g=e.computed(()=>r.value.selectedCount(m.selectedItems.value.length));function b(C){return typeof C=="boolean"?{allowed:C}:typeof C=="string"?{allowed:!1,reason:C}:C}function R(C){return n.itemFilter?b(n.itemFilter(C)):{allowed:!0}}const V=e.computed(()=>n.itemFilter?m.queryItems.value.filter(C=>R(C).allowed):m.queryItems.value),I=e.computed(()=>m.view.value.scope==="album"?m.view.value.albumName??"Album":r.value.viewLibrary),x=e.computed(()=>m.view.value.scope==="album"),T=()=>{k!==null&&(window.clearTimeout(k),k=null)},$=()=>{i("update:modelValue",[...m.orderedIds.value]),i("selection-change",{orderedIds:[...m.orderedIds.value],items:[...m.selectedItems.value],dirty:y.value})},S=C=>{C!==null&&i("error",C)},B=C=>typeof C.code=="string",_=C=>typeof C=="object"&&C!==null&&"code"in C&&typeof C.code=="string",A=()=>{const C=m.confirmSelection();if(B(C)){S(C);return}i("confirm",{...C,dirty:y.value})},P=C=>{const U=R(C);if(!U.allowed){S({code:"selection_invalid",message:U.reason??"This media item is not available for this picker.",retriable:!0});return}m.toggleSelection(C),l.value==="picker-single"&&i("select",C)},D=(C="user")=>{i("cancel",{dirty:y.value,reason:C,sessionId:m.sessionId})},z=async()=>{f.value="albums",await m.loadAlbums()},M=async()=>{await m.goToLibrary(),f.value="albums",await m.loadAlbums()},Z=C=>{m.setView({scope:"album",albumId:C.id,albumName:C.name}),f.value="media"},O=async(C,U)=>{const j=m.view.value,re=await m.createAlbum(C,U);if(_(re)){S(re);return}h.value=!1,f.value="media",i("view-change",{from:j,to:{scope:"album",albumId:re.id,albumName:re.name},reason:"inline-album-created",restoredFromSession:!1})},K=async C=>{if(n.uploadBehavior==="delegate"){i("request-upload-files",{files:[...C],view:m.view.value,filters:m.filters.value,sessionId:m.sessionId});return}await m.addUploadFiles(C)};function de(C){var U;return C?C.thumbnail_url??((U=C.conversion_urls)==null?void 0:U.thumb)??C.preview_url??C.original_url??C.url??null:null}function Ne(C){return C!=null&&C.mime_type?C.mime_type.startsWith("image/"):!1}e.watch(()=>p.value,C=>{T(),k=window.setTimeout(()=>{m.setQuery(C)},250)}),e.watch(()=>m.selectedItems.value,()=>{$()},{deep:!0}),e.watch(()=>m.error.value,C=>{S(C)}),e.watch(()=>n.enableUpload,C=>{!C&&f.value==="upload"&&(f.value="media")}),e.onMounted(()=>{m.initialize()}),e.onBeforeUnmount(()=>{T()}),a({refresh:m.refresh});function ce(C){if(C==="albums"){z();return}if(C==="upload"&&!n.enableUpload){f.value="media";return}f.value=C}const le=e.computed(()=>({activeTab:f.value,setActiveTab:ce,enableUpload:n.enableUpload,labels:{uploadLabel:r.value.uploadLabel,allMediaTab:r.value.allMediaTab,browseAlbums:r.value.browseAlbums}})),W=e.computed(()=>({query:p.value,setQuery:C=>{p.value=C},placeholder:r.value.searchPlaceholder}));return(C,U)=>(e.openBlock(),e.createElementBlock("section",{class:"media-library-picker","data-testid":C.testIdPrefix},[e.createElementVNode("header",m6,[e.createElementVNode("div",p6,[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:M},[...U[8]||(U[8]=[e.createElementVNode("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"},[e.createElementVNode("polyline",{points:"15 18 9 12 15 6"})],-1)])])):e.createCommentVNode("",!0),e.createElementVNode("span",f6,e.toDisplayString(I.value),1)])]),e.renderSlot(C.$slots,"tabs",e.normalizeProps(e.guardReactiveProps(le.value)),()=>[e.createElementVNode("nav",h6,[C.enableUpload?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:e.normalizeClass(["mlp-tabs__tab",{"is-active":f.value==="upload"}]),"data-testid":"tab-media-picker-upload",onClick:U[0]||(U[0]=j=>f.value="upload")},e.toDisplayString(r.value.uploadLabel),3)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["mlp-tabs__tab",{"is-active":f.value==="media"}]),"data-testid":"tab-media-picker-all",onClick:U[1]||(U[1]=j=>f.value="media")},e.toDisplayString(r.value.allMediaTab),3),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["mlp-tabs__tab",{"is-active":f.value==="albums"}]),"data-testid":"tab-media-picker-albums",onClick:z},e.toDisplayString(r.value.browseAlbums),3)])],!0),f.value==="media"||f.value==="albums"?(e.openBlock(),e.createElementBlock("div",v6,[e.renderSlot(C.$slots,"search",e.normalizeProps(e.guardReactiveProps(W.value)),()=>[U[9]||(U[9]=e.createElementVNode("svg",{class:"mlp-search-row__icon",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"},[e.createElementVNode("circle",{cx:"11",cy:"11",r:"8"}),e.createElementVNode("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})],-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":U[2]||(U[2]=j=>p.value=j),class:"mlp-search-row__input",type:"search",placeholder:r.value.searchPlaceholder,"data-testid":"input-media-picker-search"},null,8,g6),[[e.vModelText,p.value]])],!0)])):e.createCommentVNode("",!0),C.enableUpload&&f.value==="upload"?(e.openBlock(),e.createBlock(vf,{key:1,open:!0,queue:e.unref(m).uploadQueue.value,accept:C.accept,"upload-label":r.value.uploadLabel,"dropzone-label":r.value.uploadDropzone,"dropzone-helper-text":r.value.uploadDropzoneHelper,"file-input-label":r.value.uploadFileInputLabel,"close-button-label":r.value.uploadDone,"close-button-aria-label":r.value.uploadDoneAria,onClose:U[3]||(U[3]=j=>f.value="media"),onFilesSelected:K},null,8,["queue","accept","upload-label","dropzone-label","dropzone-helper-text","file-input-label","close-button-label","close-button-aria-label"])):e.createCommentVNode("",!0),h.value?(e.openBlock(),e.createElementBlock("div",b6,[e.createVNode(Id,{open:h.value,"name-label":r.value.createAlbumNameLabel,albums:e.unref(m).albums.value,onCancel:U[4]||(U[4]=j=>h.value=!1),onCreate:O},null,8,["open","name-label","albums"])])):e.createCommentVNode("",!0),e.unref(m).permissionDenied.value&&e.unref(m).view.value.scope==="album"?(e.openBlock(),e.createBlock(sf,{key:3,title:r.value.albumUnavailableTitle,body:r.value.albumUnavailableBody,"action-label":r.value.goToLibrary,onGoToLibrary:e.unref(m).goToLibrary},null,8,["title","body","action-label","onGoToLibrary"])):e.createCommentVNode("",!0),!e.unref(m).permissionDenied.value||e.unref(m).view.value.scope!=="album"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:4},[e.unref(m).error.value?(e.openBlock(),e.createElementBlock("div",y6,[e.createElementVNode("p",null,e.toDisplayString(e.unref(m).error.value.message||r.value.networkError),1),e.createElementVNode("button",{type:"button",class:"mlp-error__retry",onClick:U[5]||(U[5]=(...j)=>e.unref(m).refresh&&e.unref(m).refresh(...j))},e.toDisplayString(r.value.retry),1)])):e.createCommentVNode("",!0),f.value==="media"?(e.openBlock(),e.createBlock(bf,{key:1,items:V.value,"selected-items":e.unref(m).selectedItems.value,loading:e.unref(m).loading.value,"loading-more":e.unref(m).loadingMore.value,"has-more":e.unref(m).hasMore.value,"empty-message":w.value,"loading-message":r.value.loadingMedia,"load-more-label":r.value.loadMore,"loading-more-label":r.value.loadingMore,"test-id-prefix":`${C.testIdPrefix}-item`,onToggle:P,onPreview:e.unref(m).openPreview,onLoadMore:e.unref(m).loadMore},null,8,["items","selected-items","loading","loading-more","has-more","empty-message","loading-message","load-more-label","loading-more-label","test-id-prefix","onPreview","onLoadMore"])):f.value==="albums"?(e.openBlock(),e.createBlock(hf,{key:2,open:!0,"current-view":e.unref(m).view.value,albums:e.unref(m).albums.value,"view-library-label":r.value.viewLibrary,"browse-albums-label":r.value.browseAlbums,"create-album-label":r.value.createAlbum,"enable-album-creation":C.enableAlbumCreation,onSelectLibrary:M,onSelectAlbum:Z,onCreateAlbum:U[6]||(U[6]=j=>h.value=!0)},null,8,["current-view","albums","view-library-label","browse-albums-label","create-album-label","enable-album-creation"])):e.createCommentVNode("",!0)],64)):e.createCommentVNode("",!0),d.value?(e.openBlock(),e.createElementBlock("footer",w6,[e.unref(m).selectedItems.value.length>0?(e.openBlock(),e.createElementBlock("div",k6,[e.createElementVNode("span",_6,e.toDisplayString(g.value),1),e.createElementVNode("div",E6,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(m).selectedItems.value,j=>{var re,ue,Xe;return e.openBlock(),e.createElementBlock("div",{key:j.id,class:"mlp-bottom-bar__thumb-item"},[Ne(j.media)&&de(j.media)?(e.openBlock(),e.createElementBlock("img",{key:0,src:de(j.media),alt:((re=j.media)==null?void 0:re.alt_text)??((ue=j.media)==null?void 0:ue.file_name)??"Selected",class:"mlp-bottom-bar__thumb-img"},null,8,S6)):(e.openBlock(),e.createElementBlock("div",C6,[...U[10]||(U[10]=[e.createElementVNode("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.5"},[e.createElementVNode("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.createElementVNode("polyline",{points:"14 2 14 8 20 8"})],-1)])])),e.createElementVNode("button",{type:"button",class:"mlp-bottom-bar__thumb-remove","aria-label":`${r.value.dismiss} ${((Xe=j.media)==null?void 0:Xe.file_name)??j.id}`,"data-testid":"btn-media-picker-remove-selected",onClick:be=>e.unref(m).removeSelected(j.id)},[...U[11]||(U[11]=[e.createElementVNode("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"3","stroke-linecap":"round"},[e.createElementVNode("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.createElementVNode("line",{x1:"6",y1:"6",x2:"18",y2:"18"})],-1)])],8,x6)])}),128))])])):e.createCommentVNode("",!0),e.createElementVNode("div",N6,[e.createElementVNode("button",{type:"button",class:"mlp-bottom-bar__cancel","data-testid":"btn-media-picker-cancel",onClick:U[7]||(U[7]=j=>D())},e.toDisplayString(r.value.cancel),1),e.createElementVNode("button",{type:"button",class:"mlp-bottom-bar__confirm","data-testid":"btn-media-picker-confirm",onClick:A},e.toDisplayString(r.value.confirmAction),1)])])):e.createCommentVNode("",!0),c.value?(e.openBlock(),e.createBlock(Md,{key:6,open:e.unref(m).previewItem.value!==null,media:e.unref(m).previewItem.value,"can-go-previous":e.unref(m).previewIndex.value!==null&&e.unref(m).previewIndex.value>0,"can-go-next":e.unref(m).previewIndex.value!==null&&e.unref(m).previewIndex.value<e.unref(m).queryItems.value.length-1,selected:e.unref(m).previewItem.value!==null&&e.unref(m).orderedIds.value.includes(e.unref(m).previewItem.value.uuid),"close-label":r.value.previewClose,"previous-label":r.value.previewPrevious,"next-label":r.value.previewNext,"select-label":r.value.previewSelect,"deselect-label":r.value.previewDeselect,onClose:e.unref(m).closePreview,onPrevious:e.unref(m).showPreviousPreview,onNext:e.unref(m).showNextPreview,onToggleSelect:e.unref(m).toggleSelection},null,8,["open","media","can-go-previous","can-go-next","selected","close-label","previous-label","next-label","select-label","deselect-label","onClose","onPrevious","onNext","onToggleSelect"])):e.createCommentVNode("",!0)],8,u6))}}),Vf=$e(V6,[["__scopeId","data-v-307fef12"]]),T6={key:0,class:"media-library-picker-modal","data-testid":"media-library-picker-modal"},B6={class:"media-library-picker-modal__panel"},I6=e.defineComponent({__name:"MediaLibraryPickerModal",props:{deps:{},mode:{},capabilities:{},itemFilter:{},modelValue:{},defaultSelectedIds:{},selectionMode:{},maxSelection:{},preserveSelectionOnViewChange:{type:Boolean},initialView:{},initialFilters:{},enableUpload:{type:Boolean},uploadBehavior:{},enablePreview:{type:Boolean},enableAlbumCreation:{type:Boolean},allowedMediaKinds:{},accept:{},validateSelection:{},uploadTarget:{},autoSelectUploaded:{type:Boolean},createAlbumDefaultVisibility:{},sessionPolicy:{},labels:{},showFooter:{type:Boolean},testIdPrefix:{},telemetry:{},isOpen:{type:Boolean,default:!1},closeOnBackdrop:{type:Boolean,default:!0}},emits:["update:modelValue","confirm","cancel","close"],setup(o,{emit:a}){const t=o,n=a,i=()=>{t.closeOnBackdrop&&n("close")};return(r,l)=>r.isOpen?(e.openBlock(),e.createElementBlock("div",T6,[e.createElementVNode("button",{type:"button",class:"media-library-picker-modal__backdrop","aria-label":"Close media picker",onClick:i}),e.createElementVNode("div",B6,[e.createVNode(Vf,e.mergeProps(t,{"onUpdate:modelValue":l[0]||(l[0]=s=>n("update:modelValue",s)),onConfirm:l[1]||(l[1]=s=>n("confirm",s)),onCancel:l[2]||(l[2]=s=>n("cancel",s))}),null,16)])])):e.createCommentVNode("",!0)}}),M6=$e(I6,[["__scopeId","data-v-a92e8703"]]),$6=["aria-label"],F6={class:"media-album-picker-modal__panel"},D6={class:"media-album-picker-modal__header"},A6={key:0,class:"media-album-picker-modal__selection","data-testid":"media-album-picker-selection"},R6={class:"media-album-picker-modal__actions"},L6=["disabled"],P6=e.defineComponent({__name:"MediaAlbumPickerModal",props:{open:{type:Boolean},selectedCount:{},labels:{default:()=>({})}},emits:["cancel","confirm","error"],setup(o,{emit:a}){const t=o,n=a,i=Vl(),r=e.ref(null),l=e.computed(()=>{var u,m,p,f,h,v,k;return{title:((u=t.labels)==null?void 0:u.title)??"Add to album",body:((m=t.labels)==null?void 0:m.body)??`Choose an album for ${t.selectedCount} selected item${t.selectedCount===1?"":"s"}.`,confirm:((p=t.labels)==null?void 0:p.confirm)??"Add",cancel:((f=t.labels)==null?void 0:f.cancel)??"Cancel",selectedAlbum:((h=t.labels)==null?void 0:h.selectedAlbum)??(y=>`Selected: ${y}`),createNew:((v=t.labels)==null?void 0:v.createNew)??"+ Create new album",createNewPrompt:((k=t.labels)==null?void 0:k.createNewPrompt)??"Name this album"}});e.watch(()=>t.open,u=>{u||(r.value=null)});function s(u){r.value=u}function d(){r.value!==null&&n("confirm",r.value.id)}async function c(){if(typeof window>"u")return;const u=window.prompt(l.value.createNewPrompt);if(u===null)return;const m=u.trim();if(m!=="")try{const p=await i.createAlbum({name:m});p!=null&&(r.value=p,n("confirm",p.id))}catch(p){n("error",p instanceof Error?p:new Error(String(p)))}}return(u,m)=>{var p;return t.open?(e.openBlock(),e.createElementBlock("div",{key:0,class:"media-album-picker-modal","data-testid":"media-album-picker-modal",role:"dialog","aria-modal":"true","aria-label":l.value.title},[e.createElementVNode("div",F6,[e.createElementVNode("header",D6,[e.createElementVNode("h2",null,e.toDisplayString(l.value.title),1),e.createElementVNode("p",null,e.toDisplayString(l.value.body),1)]),e.createElementVNode("button",{type:"button",class:"media-album-picker-modal__create-new","data-testid":"btn-media-album-picker-create-new",onClick:m[0]||(m[0]=f=>void c())},e.toDisplayString(l.value.createNew),1),e.createVNode(Tl,{class:"media-album-picker-modal__tree","model-value":((p=r.value)==null?void 0:p.id)??null,draggable:!1,compact:!0,"data-testid":"media-album-picker-tree",onAlbumSelected:s},null,8,["model-value"]),r.value!==null?(e.openBlock(),e.createElementBlock("p",A6,e.toDisplayString(l.value.selectedAlbum(r.value.name)),1)):e.createCommentVNode("",!0),e.createElementVNode("footer",R6,[e.createElementVNode("button",{type:"button","data-testid":"btn-media-album-picker-cancel",onClick:m[1]||(m[1]=f=>n("cancel"))},e.toDisplayString(l.value.cancel),1),e.createElementVNode("button",{type:"button","data-testid":"btn-media-album-picker-confirm",disabled:r.value===null,onClick:d},e.toDisplayString(l.value.confirm),9,L6)])])],8,$6)):e.createCommentVNode("",!0)}}}),Tf=$e(P6,[["__scopeId","data-v-acdcde4b"]]),U6={key:0,class:"media-bulk-action-bar","data-testid":"media-bulk-action-bar","aria-live":"polite"},O6={class:"media-bulk-action-bar__actions"},z6=["disabled"],j6=e.defineComponent({__name:"MediaBulkActionBar",props:{selectedCount:{},crossPageCount:{default:0},overCap:{type:Boolean,default:!1},totalMatching:{default:null},scope:{},sourceAlbum:{default:null},capabilities:{default:()=>({})},labels:{default:()=>({})}},emits:["bulk-add-to-album","bulk-move-between-albums","bulk-remove-from-current-album","bulk-move-to-trash","bulk-create-post","bulk-create-gallery","bulk-restore","bulk-purge","bulk-download","clear","inspect"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>{var s,d,c,u,m,p,f,h,v,k,y,w,g,b;return{selectedCount:((s=t.labels)==null?void 0:s.selectedCount)??(R=>`${R} selected`),selectedAcrossPages:((d=t.labels)==null?void 0:d.selectedAcrossPages)??((R,V)=>`${R} selected, including ${V} not on this page`),cappedSelection:((c=t.labels)==null?void 0:c.cappedSelection)??((R,V)=>`Selected first ${R} of ${V??"many"} matching items`),addToAlbum:((u=t.labels)==null?void 0:u.addToAlbum)??"Add to album",moveBetweenAlbums:((m=t.labels)==null?void 0:m.moveBetweenAlbums)??(R=>`Move from ${R} to...`),removeFromCurrentAlbum:((p=t.labels)==null?void 0:p.removeFromCurrentAlbum)??"Remove from this album",moveToTrash:((f=t.labels)==null?void 0:f.moveToTrash)??"Move to trash",createPost:((h=t.labels)==null?void 0:h.createPost)??"Create post",createGallery:((v=t.labels)==null?void 0:v.createGallery)??"Create gallery",restore:((k=t.labels)==null?void 0:k.restore)??"Restore",purge:((y=t.labels)==null?void 0:y.purge)??"Delete forever",download:((w=t.labels)==null?void 0:w.download)??"Download",inspect:((g=t.labels)==null?void 0:g.inspect)??"Inspect",clear:((b=t.labels)==null?void 0:b.clear)??"Clear"}}),r=e.computed(()=>t.overCap?i.value.cappedSelection(t.selectedCount,t.totalMatching):t.crossPageCount>0?i.value.selectedAcrossPages(t.selectedCount,t.crossPageCount):i.value.selectedCount(t.selectedCount)),l=e.computed(()=>t.sourceAlbum?i.value.moveBetweenAlbums(t.sourceAlbum.name):i.value.addToAlbum);return(s,d)=>(e.openBlock(),e.createBlock(e.Transition,{name:"media-bulk-action-bar"},{default:e.withCtx(()=>[t.selectedCount>0?(e.openBlock(),e.createElementBlock("aside",U6,[e.createElementVNode("button",{type:"button",class:"media-bulk-action-bar__count","data-testid":"media-bulk-action-count",onClick:d[0]||(d[0]=c=>n("inspect"))},e.toDisplayString(r.value),1),e.createElementVNode("div",O6,[t.scope!=="trash"&&t.capabilities.allowAddToAlbum===!0?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button","data-testid":"btn-media-bulk-add-album",onClick:d[1]||(d[1]=c=>t.scope==="album"?n("bulk-move-between-albums"):n("bulk-add-to-album"))},e.toDisplayString(t.scope==="album"?l.value:i.value.addToAlbum),1)):e.createCommentVNode("",!0),t.scope!=="trash"&&t.capabilities.allowCreatePost===!0?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button","data-testid":"btn-media-bulk-create-post",onClick:d[2]||(d[2]=c=>n("bulk-create-post"))},e.toDisplayString(i.value.createPost),1)):e.createCommentVNode("",!0),t.scope!=="trash"&&t.capabilities.allowCreateGallery===!0?(e.openBlock(),e.createElementBlock("button",{key:2,type:"button","data-testid":"btn-media-bulk-create-gallery",onClick:d[3]||(d[3]=c=>n("bulk-create-gallery"))},e.toDisplayString(i.value.createGallery),1)):e.createCommentVNode("",!0),t.scope==="album"?(e.openBlock(),e.createElementBlock("button",{key:3,type:"button","data-testid":"btn-media-bulk-remove-current-album",onClick:d[4]||(d[4]=c=>n("bulk-remove-from-current-album"))},e.toDisplayString(i.value.removeFromCurrentAlbum),1)):e.createCommentVNode("",!0),t.scope!=="trash"?(e.openBlock(),e.createElementBlock("button",{key:4,type:"button","data-testid":"btn-media-bulk-trash",onClick:d[5]||(d[5]=c=>n("bulk-move-to-trash"))},e.toDisplayString(i.value.moveToTrash),1)):e.createCommentVNode("",!0),t.scope==="trash"?(e.openBlock(),e.createElementBlock("button",{key:5,type:"button","data-testid":"btn-media-bulk-restore",onClick:d[6]||(d[6]=c=>n("bulk-restore"))},e.toDisplayString(i.value.restore),1)):e.createCommentVNode("",!0),t.scope==="trash"?(e.openBlock(),e.createElementBlock("button",{key:6,type:"button","data-testid":"btn-media-bulk-purge",onClick:d[7]||(d[7]=c=>n("bulk-purge"))},e.toDisplayString(i.value.purge),1)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button","data-testid":"btn-media-bulk-download",disabled:t.capabilities.allowDownloadZip!==!0,onClick:d[8]||(d[8]=c=>n("bulk-download"))},e.toDisplayString(i.value.download),9,z6),e.createElementVNode("button",{type:"button","data-testid":"btn-media-bulk-clear",onClick:d[9]||(d[9]=c=>n("clear"))},e.toDisplayString(i.value.clear),1)])])):e.createCommentVNode("",!0)]),_:1}))}}),Rd=$e(j6,[["__scopeId","data-v-56ce7c5e"]]),W6={class:"media-library-toolbar__group"},H6=["aria-expanded"],Z6={key:0,class:"media-library-toolbar__menu",role:"menu","data-testid":"media-library-toolbar-sort-menu"},G6={class:"media-library-toolbar__group"},X6=["aria-expanded"],K6={key:0,class:"media-library-toolbar__menu",role:"menu","data-testid":"media-library-toolbar-jump-menu"},J6={key:0,class:"media-library-toolbar__menu-status"},q6={key:1,class:"media-library-toolbar__menu-status"},Y6=["data-testid","onClick"],Q6={"aria-hidden":"true"},eD={class:"media-library-toolbar__group"},tD=["aria-expanded"],aD={key:0,class:"media-library-toolbar__menu",role:"menu","data-testid":"media-library-toolbar-density-menu"},nD=e.defineComponent({__name:"MediaLibraryToolbar",props:{sort:{default:"newest"},density:{default:"comfortable"},hasDateFilter:{type:Boolean,default:!1},httpClient:{},timelineEndpoint:{default:"/v1/media/library/timeline"},labels:{default:()=>({})}},emits:["update:sort","update:density","jump-to","jump-to-all","upload-files"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>{var T,$,S,B,_,A,P,D,z,M,Z,O;return{sort:((T=t.labels)==null?void 0:T.sort)??"Sort",sortNewest:(($=t.labels)==null?void 0:$.sortNewest)??"Newest",sortOldest:((S=t.labels)==null?void 0:S.sortOldest)??"Oldest",sortName:((B=t.labels)==null?void 0:B.sortName)??"Name A–Z",sortLargest:((_=t.labels)==null?void 0:_.sortLargest)??"Largest first",jumpTo:((A=t.labels)==null?void 0:A.jumpTo)??"Jump to",jumpToAll:((P=t.labels)==null?void 0:P.jumpToAll)??"All time",jumpToEmpty:((D=t.labels)==null?void 0:D.jumpToEmpty)??"No history yet",density:((z=t.labels)==null?void 0:z.density)??"Density",densityComfortable:((M=t.labels)==null?void 0:M.densityComfortable)??"Comfortable",densityCompact:((Z=t.labels)==null?void 0:Z.densityCompact)??"Compact",upload:((O=t.labels)==null?void 0:O.upload)??"Upload"}}),r=e.ref(null);function l(){var T;(T=r.value)==null||T.click()}function s(T){const $=T.target;!($ instanceof HTMLInputElement)||$.files===null||$.files.length===0||(n("upload-files",Array.from($.files)),$.value="")}const d=e.ref(null),c=e.ref(null);function u(T){d.value=d.value===T?null:T}function m(){d.value=null}function p(T){if(d.value===null)return;const $=c.value;$!==null&&(T.target instanceof Node&&$.contains(T.target)||m())}function f(T){d.value!==null&&T.key==="Escape"&&m()}const h=e.computed(()=>{switch(t.sort){case"oldest":return i.value.sortOldest;case"name":return i.value.sortName;case"largest":return i.value.sortLargest;default:return i.value.sortNewest}}),v=e.computed(()=>t.density==="compact"?i.value.densityCompact:i.value.densityComfortable);function k(T){m(),n("update:sort",T)}function y(T){m(),n("update:density",T)}const w=e.ref([]),g=e.ref(!1),b=e.ref(!1);async function R(){if(!(g.value||b.value||t.httpClient===void 0)){b.value=!0;try{const T=await t.httpClient.get(t.timelineEndpoint),$=T.data,S=($==null?void 0:$.buckets)??T.buckets??[];w.value=Array.isArray(S)?S:[],g.value=!0}finally{b.value=!1}}}async function V(){u("jump"),d.value==="jump"&&await R()}function I(T){m(),n("jump-to",T)}function x(){m(),n("jump-to-all")}return e.onMounted(()=>{typeof window<"u"&&(document.addEventListener("pointerdown",p,!0),document.addEventListener("keydown",f))}),e.onBeforeUnmount(()=>{typeof window<"u"&&(document.removeEventListener("pointerdown",p,!0),document.removeEventListener("keydown",f))}),(T,$)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"toolbarRoot",ref:c,class:"media-library-toolbar","data-testid":"media-library-toolbar"},[e.createElementVNode("button",{type:"button",class:"media-library-toolbar__upload","data-testid":"btn-media-toolbar-upload",onClick:l}," ⤴ "+e.toDisplayString(i.value.upload),1),e.createElementVNode("input",{ref_key:"fileInputRef",ref:r,type:"file",multiple:"",accept:"image/*,video/*","data-testid":"input-media-toolbar-upload",class:"media-library-toolbar__file-input",onChange:s},null,544),e.createElementVNode("div",W6,[e.createElementVNode("button",{type:"button",class:"media-library-toolbar__trigger","data-testid":"btn-media-toolbar-sort","aria-expanded":d.value==="sort"?"true":"false",onClick:$[0]||($[0]=S=>u("sort"))},e.toDisplayString(i.value.sort)+": "+e.toDisplayString(h.value),9,H6),d.value==="sort"?(e.openBlock(),e.createElementBlock("div",Z6,[e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-sort-newest",onClick:$[1]||($[1]=S=>k("newest"))},e.toDisplayString(i.value.sortNewest),1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-sort-oldest",onClick:$[2]||($[2]=S=>k("oldest"))},e.toDisplayString(i.value.sortOldest),1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-sort-name",onClick:$[3]||($[3]=S=>k("name"))},e.toDisplayString(i.value.sortName),1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-sort-largest",onClick:$[4]||($[4]=S=>k("largest"))},e.toDisplayString(i.value.sortLargest),1)])):e.createCommentVNode("",!0)]),e.createElementVNode("div",G6,[e.createElementVNode("button",{type:"button",class:"media-library-toolbar__trigger","data-testid":"btn-media-toolbar-jump-to","aria-expanded":d.value==="jump"?"true":"false",onClick:$[5]||($[5]=S=>void V())},e.toDisplayString(i.value.jumpTo),9,X6),d.value==="jump"?(e.openBlock(),e.createElementBlock("div",K6,[e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-jump-all",onClick:x},e.toDisplayString(i.value.jumpToAll),1),b.value?(e.openBlock(),e.createElementBlock("p",J6,"Loading…")):g.value&&w.value.length===0?(e.openBlock(),e.createElementBlock("p",q6,e.toDisplayString(i.value.jumpToEmpty),1)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(w.value,S=>(e.openBlock(),e.createElementBlock("button",{key:S.starts_at,type:"button",role:"menuitem","data-testid":`opt-jump-${S.starts_at}`,onClick:B=>I(S)},[e.createTextVNode(e.toDisplayString(S.label)+" ",1),e.createElementVNode("span",Q6,"("+e.toDisplayString(S.count)+")",1)],8,Y6))),128))])):e.createCommentVNode("",!0)]),e.createElementVNode("div",eD,[e.createElementVNode("button",{type:"button",class:"media-library-toolbar__trigger","data-testid":"btn-media-toolbar-density","aria-expanded":d.value==="density"?"true":"false",onClick:$[6]||($[6]=S=>u("density"))},e.toDisplayString(i.value.density)+": "+e.toDisplayString(v.value),9,tD),d.value==="density"?(e.openBlock(),e.createElementBlock("div",aD,[e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-density-comfortable",onClick:$[7]||($[7]=S=>y("comfortable"))},e.toDisplayString(i.value.densityComfortable),1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-density-compact",onClick:$[8]||($[8]=S=>y("compact"))},e.toDisplayString(i.value.densityCompact),1)])):e.createCommentVNode("",!0)])],512))}}),Bf=$e(nD,[["__scopeId","data-v-564647c0"]]),oD={class:"media-shortcut-help__panel"},iD={class:"media-shortcut-help__header"},rD=e.defineComponent({__name:"MediaShortcutHelp",props:{open:{type:Boolean},shortcuts:{default:()=>[{key:"j / k",label:"Move focus",group:"Navigation"},{key:"x",label:"Toggle selection",group:"Selection"},{key:"?",label:"Open shortcuts",group:"Help"},{key:"Esc",label:"Close panel",group:"Navigation"}]},title:{default:"Shortcuts"},closeLabel:{default:"Close"}},emits:["close"],setup(o,{emit:a}){const t=o,n=a;function i(){const r=new Map;for(const l of t.shortcuts)r.set(l.group,[...r.get(l.group)??[],l]);return Array.from(r.entries()).map(([l,s])=>({group:l,shortcuts:s}))}return(r,l)=>t.open?(e.openBlock(),e.createElementBlock("div",{key:0,class:"media-shortcut-help",role:"dialog","aria-modal":"true","data-testid":"media-shortcut-help",onKeydown:l[1]||(l[1]=e.withKeys(s=>n("close"),["escape"]))},[e.createElementVNode("div",oD,[e.createElementVNode("header",iD,[e.createElementVNode("h3",null,e.toDisplayString(t.title),1),e.createElementVNode("button",{type:"button","data-testid":"btn-media-shortcut-close",onClick:l[0]||(l[0]=s=>n("close"))},e.toDisplayString(t.closeLabel),1)]),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i(),s=>(e.openBlock(),e.createElementBlock("section",{key:s.group,class:"media-shortcut-help__group"},[e.createElementVNode("h4",null,e.toDisplayString(s.group),1),e.createElementVNode("dl",null,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(s.shortcuts,d=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:`${s.group}-${d.key}`},[e.createElementVNode("dt",null,[e.createElementVNode("kbd",null,e.toDisplayString(d.key),1)]),e.createElementVNode("dd",null,e.toDisplayString(d.label),1)],64))),128))])]))),128))])],32)):e.createCommentVNode("",!0)}}),If=$e(rD,[["__scopeId","data-v-abcdccb6"]]),lD="/v1/media/upload";function Mf(o){const a=o.endpoint??lD,t=e.ref([]),n=e.computed(()=>t.value.some(u=>u.status==="uploading"||u.status==="queued"));function i(){return`upload-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function r(u){if(u.type.startsWith("image/")&&typeof URL<"u")try{return URL.createObjectURL(u)}catch{return}}function l(u){t.value=t.value.filter(m=>m.cid!==u)}async function s(u){const m=i(),p=r(u),f={cid:m,fileName:u.name,size:u.size,status:"uploading",progress:0,...p!==void 0?{previewUrl:p}:{}};t.value=[f,...t.value];const h=new FormData;h.append("file",u);try{const v=await o.httpClient.post(a,h),k=v.data??v;return t.value=t.value.map(y=>y.cid===m?{...y,status:"success",progress:100}:y),typeof o.onMediaUploaded=="function"&&k&&typeof k.uuid=="string"&&await o.onMediaUploaded(k),setTimeout(()=>l(m),350),t.value.find(y=>y.cid===m)??f}catch(v){const k=v instanceof Error?v.message:"Upload failed";return t.value=t.value.map(y=>y.cid===m?{...y,status:"error",errorMessage:k}:y),t.value.find(y=>y.cid===m)??f}finally{if(p!==void 0&&typeof URL<"u")try{URL.revokeObjectURL(p)}catch{}}}async function d(u){const m=Array.from(u);return Promise.all(m.map(p=>s(p)))}function c(){t.value=[]}return{uploads:t,hasActiveUploads:n,uploadFile:s,uploadFiles:d,dismiss:l,clear:c}}const sD={class:"media-usage-list","data-testid":"media-usage-list"},dD={class:"media-usage-list__title"},cD={key:0,class:"media-usage-list__empty","data-testid":"media-usage-loading"},uD={key:1,class:"media-usage-list__empty","data-testid":"media-usage-empty"},mD={key:2,class:"media-usage-list__items"},pD=["data-testid"],fD=["href"],hD={key:1},vD={key:2,class:"media-usage-list__count"},gD=e.defineComponent({__name:"MediaUsageList",props:{media:{},httpClient:{},items:{default:()=>[]},title:{default:"Used in"},emptyLabel:{default:"No visible usages"}},setup(o){const a=o,t=e.ref(!1),n=e.ref([]),i=e.computed(()=>a.items.length>0?a.items:n.value);function r(s){var m;if(typeof s!="object"||s===null||!("data"in s))return[];const d=s.data;if(!Array.isArray(d))return[];const c=d[0];return(Array.isArray((m=c==null?void 0:c.report)==null?void 0:m.blocks)?c.report.blocks:[]).map((p,f)=>({id:`${p.type??"usage"}-${f}`,label:p.context??p.type??"Usage"}))}async function l(){if(!a.httpClient||a.media===null){n.value=[];return}t.value=!0;try{const s=await a.httpClient.post("/v1/media/deletion/check",{uuids:[a.media.uuid]});n.value=r(s)}finally{t.value=!1}}return e.watch(()=>{var s;return(s=a.media)==null?void 0:s.uuid},()=>{l()}),e.onMounted(()=>{l()}),(s,d)=>(e.openBlock(),e.createElementBlock("section",sD,[e.createElementVNode("h4",dD,e.toDisplayString(a.title),1),t.value?(e.openBlock(),e.createElementBlock("p",cD," Loading... ")):i.value.length===0?(e.openBlock(),e.createElementBlock("p",uD,e.toDisplayString(a.emptyLabel),1)):(e.openBlock(),e.createElementBlock("ul",mD,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,c=>(e.openBlock(),e.createElementBlock("li",{key:c.id,class:"media-usage-list__item","data-testid":`media-usage-${c.id}`},[c.href?(e.openBlock(),e.createElementBlock("a",{key:0,href:c.href},e.toDisplayString(c.label),9,fD)):(e.openBlock(),e.createElementBlock("span",hD,e.toDisplayString(c.label),1)),typeof c.count=="number"?(e.openBlock(),e.createElementBlock("span",vD,e.toDisplayString(c.count),1)):e.createCommentVNode("",!0)],8,pD))),128))]))]))}}),$f=$e(gD,[["__scopeId","data-v-ef6f09cf"]]),bD={class:"media-variant-strip","data-testid":"media-variant-strip"},yD={class:"media-variant-strip__title"},wD={key:0,class:"media-variant-strip__empty"},kD={key:1,class:"media-variant-strip__empty"},_D={key:2,class:"media-variant-strip__list"},ED=["data-testid"],SD=["src","alt"],CD={key:1,class:"media-variant-strip__placeholder"},xD={class:"media-variant-strip__label"},ND=e.defineComponent({__name:"MediaVariantStrip",props:{media:{},httpClient:{},variants:{default:()=>[]},title:{default:"Variants"}},setup(o){const a=o,t=e.ref(!1),n=e.ref([]),i=e.computed(()=>{const c=a.variants.length>0?a.variants:n.value;return a.media?[a.media,...c.filter(u=>{var m;return u.uuid!==((m=a.media)==null?void 0:m.uuid)})]:c});function r(c){if(typeof c!="object"||c===null||!("data"in c))return[];const u=c.data;return Array.isArray(u)?u.filter(m=>typeof m=="object"&&m!==null&&typeof m.uuid=="string"&&typeof m.file_name=="string"):[]}async function l(){if(!a.httpClient||a.media===null){n.value=[];return}t.value=!0;try{const c=await a.httpClient.get(`/v1/media/${encodeURIComponent(a.media.uuid)}/variants`);n.value=r(c)}finally{t.value=!1}}function s(c){return c.thumbnail_url??c.preview_url??c.original_url??null}function d(c,u){if(c===0)return"Current";if(c===1)return"Original";const m=new Date(u.created_at);if(Number.isNaN(m.getTime()))return"Edited";const p=Math.max(0,Math.round((Date.now()-m.getTime())/864e5));return p===0?"Edited today":p===1?"Edited 1 day ago":`Edited ${p} days ago`}return e.watch(()=>{var c;return(c=a.media)==null?void 0:c.uuid},()=>{l()}),e.onMounted(()=>{l()}),(c,u)=>(e.openBlock(),e.createElementBlock("section",bD,[e.createElementVNode("h4",yD,e.toDisplayString(a.title),1),t.value?(e.openBlock(),e.createElementBlock("p",wD,"Loading...")):i.value.length<=1?(e.openBlock(),e.createElementBlock("p",kD," No edits ")):(e.openBlock(),e.createElementBlock("ol",_D,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,(m,p)=>(e.openBlock(),e.createElementBlock("li",{key:m.uuid,class:"media-variant-strip__item","data-testid":`media-variant-${m.uuid}`},[s(m)?(e.openBlock(),e.createElementBlock("img",{key:0,src:s(m)??"",alt:m.alt_text??m.file_name},null,8,SD)):(e.openBlock(),e.createElementBlock("span",CD,e.toDisplayString(m.file_name),1)),e.createElementVNode("span",xD,e.toDisplayString(d(p,m)),1)],8,ED))),128))]))]))}}),Ff=$e(ND,[["__scopeId","data-v-adb529cb"]]),VD=/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/ig,Lu=/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i;function Pu(o){const a=o.replace(/\.[^.]+$/,""),t=a.replace(VD,""),n=t.replace(/(?:[-_\s]+edited)+$/i,""),i=t.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/(?:[-_\s]+edited)+$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return i!==""?i:n||a||o}function Uu(o,a){var n;const t=(n=o.custom_properties)==null?void 0:n[a];return typeof t=="string"&&t.trim()!==""?t.trim():null}function Df(o){const a=Uu(o,"display_name");if(a!==null&&!Lu.test(a))return a;const t=Uu(o,"original_filename");return t!==null&&!Lu.test(t)?Pu(t):Pu(o.file_name)}const TD=["role","aria-modal"],BD={class:"media-inspector-panel__header"},ID={key:0,class:"media-inspector-panel__raw-name"},MD={class:"media-inspector-panel__preview"},$D=["src","alt"],FD={class:"media-inspector-panel__meta"},DD={class:"media-inspector-panel__actions"},AD={class:"media-inspector-panel__actions"},RD=["disabled"],LD={key:2,class:"media-inspector-panel__empty"},PD=e.defineComponent({__name:"MediaInspectorPanel",props:{target:{},httpClient:{},capabilities:{default:()=>({})},inAlbumScope:{type:Boolean,default:!1},labels:{default:()=>({})},mode:{default:"pinned"}},emits:["edit","replace","download","set-visibility","move-to-trash","remove-from-this-album","remove-from-albums","set-as-album-cover","bulk-add-to-album","bulk-create-album","bulk-move-to-trash","bulk-download","close"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(null),r=e.ref(null);e.watch(()=>t.target,(u,m)=>{const p=m==null,f=u==null;if(p&&!f){typeof document<"u"&&document.activeElement instanceof HTMLElement&&(r.value=document.activeElement),e.nextTick(()=>{var h;(h=i.value)==null||h.focus()});return}if(!p&&f){const h=r.value;r.value=null,h instanceof HTMLElement&&h.focus()}});function l(u){t.mode==="overlay"&&u.key==="Escape"&&(u.stopPropagation(),n("close"))}const s=e.computed(()=>t.mode==="overlay"?"dialog":"complementary"),d=e.computed(()=>{var u,m,p,f,h,v,k,y,w,g,b,R,V;return{title:((u=t.labels)==null?void 0:u.title)??"Inspector",emptyTitle:((m=t.labels)==null?void 0:m.emptyTitle)??"Select media to inspect",multiTitle:((p=t.labels)==null?void 0:p.multiTitle)??(I=>`${I} selected`),edit:((f=t.labels)==null?void 0:f.edit)??"Edit",replace:((h=t.labels)==null?void 0:h.replace)??"Replace",download:((v=t.labels)==null?void 0:v.download)??"Download",setVisibility:((k=t.labels)==null?void 0:k.setVisibility)??"Set visibility",moveToTrash:((y=t.labels)==null?void 0:y.moveToTrash)??"Move to trash",removeFromThisAlbum:((w=t.labels)==null?void 0:w.removeFromThisAlbum)??"Remove from this album",removeFromAlbums:((g=t.labels)==null?void 0:g.removeFromAlbums)??"Remove from album...",addToAlbum:((b=t.labels)==null?void 0:b.addToAlbum)??"Add to album",createAlbum:((R=t.labels)==null?void 0:R.createAlbum)??"Create album from selection",setAsAlbumCover:((V=t.labels)==null?void 0:V.setAsAlbumCover)??"Set as album cover"}}),c=e.computed(()=>{var u;return((u=t.target)==null?void 0:u.kind)==="single"?t.target.media:null});return(u,m)=>{var p;return e.openBlock(),e.createElementBlock("aside",{class:"media-inspector-panel","data-testid":"media-inspector-panel",role:s.value,"aria-modal":t.mode==="overlay"?"true":void 0,"aria-labelledby":"media-inspector-heading",onKeydown:l},[c.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("header",BD,[e.createElementVNode("h3",{id:"media-inspector-heading",ref_key:"headingRef",ref:i,tabindex:"-1"},e.toDisplayString(e.unref(Df)(c.value)),513),c.value.file_name?(e.openBlock(),e.createElementBlock("p",ID,e.toDisplayString(c.value.file_name),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",MD,[c.value.thumbnail_url??c.value.preview_url??c.value.original_url?(e.openBlock(),e.createElementBlock("img",{key:0,src:c.value.thumbnail_url??c.value.preview_url??c.value.original_url,alt:c.value.alt_text??c.value.file_name},null,8,$D)):e.createCommentVNode("",!0)]),e.createElementVNode("dl",FD,[e.createElementVNode("div",null,[m[12]||(m[12]=e.createElementVNode("dt",null,"Type",-1)),e.createElementVNode("dd",null,e.toDisplayString(c.value.mime_type),1)]),e.createElementVNode("div",null,[m[13]||(m[13]=e.createElementVNode("dt",null,"Size",-1)),e.createElementVNode("dd",null,e.toDisplayString(c.value.formatted_size??c.value.size),1)])]),e.createVNode($f,{media:c.value,"http-client":t.httpClient},null,8,["media","http-client"]),e.createVNode(Ff,{media:c.value,"http-client":t.httpClient},null,8,["media","http-client"]),e.createElementVNode("div",DD,[t.capabilities.allowImageEdit||t.capabilities.allowVideoEdit?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",onClick:m[0]||(m[0]=f=>n("edit",c.value))},e.toDisplayString(d.value.edit),1)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",onClick:m[1]||(m[1]=f=>n("replace",c.value))},e.toDisplayString(d.value.replace),1),e.createElementVNode("button",{type:"button",onClick:m[2]||(m[2]=f=>n("download",c.value))},e.toDisplayString(d.value.download),1),t.capabilities.allowVisibilityChange?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button",onClick:m[3]||(m[3]=f=>n("set-visibility",c.value))},e.toDisplayString(d.value.setVisibility),1)):e.createCommentVNode("",!0),t.inAlbumScope?(e.openBlock(),e.createElementBlock("button",{key:2,type:"button","data-testid":"btn-set-as-album-cover",onClick:m[4]||(m[4]=f=>n("set-as-album-cover",c.value))},e.toDisplayString(d.value.setAsAlbumCover),1)):e.createCommentVNode("",!0),t.inAlbumScope?(e.openBlock(),e.createElementBlock("button",{key:3,type:"button",onClick:m[5]||(m[5]=f=>n("remove-from-this-album",c.value))},e.toDisplayString(d.value.removeFromThisAlbum),1)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",onClick:m[6]||(m[6]=f=>n("remove-from-albums",c.value))},e.toDisplayString(d.value.removeFromAlbums),1),e.createElementVNode("button",{type:"button",onClick:m[7]||(m[7]=f=>n("move-to-trash",c.value))},e.toDisplayString(d.value.moveToTrash),1)])],64)):((p=t.target)==null?void 0:p.kind)==="multi"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[e.createElementVNode("h3",{id:"media-inspector-heading",ref_key:"headingRef",ref:i,tabindex:"-1"},e.toDisplayString(d.value.multiTitle(t.target.count)),513),e.createElementVNode("div",AD,[e.createElementVNode("button",{type:"button",onClick:m[8]||(m[8]=f=>n("bulk-add-to-album"))},e.toDisplayString(d.value.addToAlbum),1),e.createElementVNode("button",{type:"button",onClick:m[9]||(m[9]=f=>n("bulk-create-album"))},e.toDisplayString(d.value.createAlbum),1),e.createElementVNode("button",{type:"button",onClick:m[10]||(m[10]=f=>n("bulk-move-to-trash"))},e.toDisplayString(d.value.moveToTrash),1),e.createElementVNode("button",{type:"button",disabled:t.capabilities.allowDownloadZip!==!0,onClick:m[11]||(m[11]=f=>n("bulk-download"))},e.toDisplayString(d.value.download),9,RD)])],64)):(e.openBlock(),e.createElementBlock("p",LD,e.toDisplayString(d.value.emptyTitle),1))],40,TD)}}}),Af=$e(PD,[["__scopeId","data-v-2646f914"]]),UD={class:"media-filter-chips","data-testid":"media-filter-chips"},OD={class:"media-filter-chips__scroll"},zD={key:0,class:"media-filter-chips__chip media-filter-chips__chip--scope","data-testid":"media-filter-scope-chip"},jD=["data-testid","onClick"],WD={class:"media-filter-chips__add-wrap"},HD=["aria-expanded"],ZD={key:0,class:"media-filter-chips__menu","data-testid":"media-filter-menu"},GD=e.defineComponent({__name:"MediaFilterChips",props:{filters:{},scopeLabel:{default:""},labels:{default:()=>({})}},emits:["update:filters","change","clear"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!1),r=e.computed(()=>{var w,g,b,R,V,I,x,T,$,S,B;return{addFilter:((w=t.labels)==null?void 0:w.addFilter)??"Filter",clearAll:((g=t.labels)==null?void 0:g.clearAll)??"Clear all filters",typeLabel:((b=t.labels)==null?void 0:b.typeLabel)??"Type",usageLabel:((R=t.labels)==null?void 0:R.usageLabel)??"Usage",imageLabel:((V=t.labels)==null?void 0:V.imageLabel)??"Image",videoLabel:((I=t.labels)==null?void 0:I.videoLabel)??"Video",usedLabel:((x=t.labels)==null?void 0:x.usedLabel)??"Used",notUsedLabel:((T=t.labels)==null?void 0:T.notUsedLabel)??"Not used",dateAfterLabel:(($=t.labels)==null?void 0:$.dateAfterLabel)??"After",dateBeforeLabel:((S=t.labels)==null?void 0:S.dateBeforeLabel)??"Before",searchLabel:((B=t.labels)==null?void 0:B.searchLabel)??"Search"}});function l(){return{...t.filters,...t.filters.kinds!==void 0?{kinds:[...t.filters.kinds]}:{},...t.filters.selected_uuids!==void 0?{selected_uuids:[...t.filters.selected_uuids]}:{}}}function s(w){n("update:filters",w),n("change",w)}function d(w){const g=l(),b=(g.kinds??[]).filter(R=>R!==w);b.length>0?g.kinds=b:delete g.kinds,s(g)}function c(w){const g=l(),b=new Set(g.kinds??[]);b.add(w),g.kinds=Array.from(b),s(g),i.value=!1}function u(){const w=l();delete w.usage_status,s(w)}function m(w){const g=l();g.usage_status=w,s(g),i.value=!1}function p(w){const g=new Date;return g.setHours(0,0,0,0),g.setDate(g.getDate()-w),g.toISOString()}function f(){const w=new Date;return new Date(w.getFullYear(),0,1).toISOString()}function h(w,g=null){const b=l();w===null?delete b.created_after:b.created_after=w,g===null?delete b.created_before:b.created_before=g,s(b),i.value=!1}function v(w){const g=l();delete g[w],s(g)}function k(){s({sort:t.filters.sort??"newest"}),n("clear")}const y=e.computed(()=>{const w=[];for(const g of t.filters.kinds??[]){const b=g==="image"?r.value.imageLabel:g==="video"?r.value.videoLabel:String(g);w.push({key:`kind-${g}`,label:`${r.value.typeLabel}: ${b}`,remove:()=>d(g)})}return(t.filters.usage_status==="used"||t.filters.usage_status==="not_used")&&w.push({key:"usage",label:`${r.value.usageLabel}: ${t.filters.usage_status==="used"?r.value.usedLabel:r.value.notUsedLabel}`,remove:u}),t.filters.created_after&&w.push({key:"created-after",label:`${r.value.dateAfterLabel}: ${t.filters.created_after}`,remove:()=>v("created_after")}),t.filters.created_before&&w.push({key:"created-before",label:`${r.value.dateBeforeLabel}: ${t.filters.created_before}`,remove:()=>v("created_before")}),t.filters.query&&t.filters.query.trim()!==""&&w.push({key:"query",label:`${r.value.searchLabel}: "${t.filters.query.trim()}"`,remove:()=>v("query")}),w});return(w,g)=>(e.openBlock(),e.createElementBlock("div",UD,[e.createElementVNode("div",OD,[t.scopeLabel!==""?(e.openBlock(),e.createElementBlock("span",zD,e.toDisplayString(t.scopeLabel),1)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(y.value,b=>(e.openBlock(),e.createElementBlock("button",{key:b.key,type:"button",class:"media-filter-chips__chip","data-testid":`media-filter-chip-${b.key}`,onClick:b.remove},[e.createElementVNode("span",null,e.toDisplayString(b.label),1),g[8]||(g[8]=e.createElementVNode("span",{"aria-hidden":"true"},"×",-1))],8,jD))),128)),y.value.length>=2?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button",class:"media-filter-chips__clear","data-testid":"btn-media-filter-clear-all",onClick:k},e.toDisplayString(r.value.clearAll),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",WD,[e.createElementVNode("button",{type:"button",class:"media-filter-chips__add","data-testid":"btn-media-filter-add","aria-expanded":i.value?"true":"false",onClick:g[0]||(g[0]=b=>i.value=!i.value)}," + "+e.toDisplayString(r.value.addFilter),9,HD),i.value?(e.openBlock(),e.createElementBlock("div",ZD,[e.createElementVNode("button",{type:"button","data-testid":"opt-filter-image",onClick:g[1]||(g[1]=b=>c("image"))},e.toDisplayString(r.value.typeLabel)+": "+e.toDisplayString(r.value.imageLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-video",onClick:g[2]||(g[2]=b=>c("video"))},e.toDisplayString(r.value.typeLabel)+": "+e.toDisplayString(r.value.videoLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-used",onClick:g[3]||(g[3]=b=>m("used"))},e.toDisplayString(r.value.usageLabel)+": "+e.toDisplayString(r.value.usedLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-not-used",onClick:g[4]||(g[4]=b=>m("not_used"))},e.toDisplayString(r.value.usageLabel)+": "+e.toDisplayString(r.value.notUsedLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-date-7d",onClick:g[5]||(g[5]=b=>h(p(7)))},"Date: Last 7 days"),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-date-30d",onClick:g[6]||(g[6]=b=>h(p(30)))},"Date: Last 30 days"),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-date-year",onClick:g[7]||(g[7]=b=>h(f()))},"Date: This year")])):e.createCommentVNode("",!0)])]))}}),Rf=$e(GD,[["__scopeId","data-v-4861e8d7"]]);class Ld extends Error{constructor(a,t="Media deletion requires explicit confirmation."){super(t),this.name="RequiresConfirmationError",this.softBlocks=a}}const XD="/v1/media/deletion/check",KD="/v1/media/deletion/delete",yr=100;function Ou(o){const a=new Set,t=[];for(const n of o){const i=n.trim().toLowerCase();i===""||a.has(i)||(a.add(i),t.push(i))}return t.sort()}function Lf(o){const a=o.checkEndpoint??XD,t=o.deleteEndpoint??KD,n=e.ref(!1),i=e.ref(!1),r=e.ref(null),l=e.ref(null),s=e.ref(null);async function d(f){s.value=null;const h=Ou(f);if(h.length===0)return r.value=[],[];if(h.length>yr){const v=new Error(`Cannot check more than ${yr} media items at once.`);throw s.value=v,v}n.value=!0;try{const v=await o.httpClient.post(a,{uuids:h}),k=((v==null?void 0:v.data)??[]).map(y=>{var w,g,b,R;return{uuid:y.uuid,canDelete:((w=y.report)==null?void 0:w.canDelete)??!1,blocks:Array.isArray((g=y.report)==null?void 0:g.blocks)?y.report.blocks:[],cascade:Array.isArray((b=y.report)==null?void 0:b.cascade)?y.report.cascade:[],variantCount:typeof((R=y.report)==null?void 0:R.variantCount)=="number"?y.report.variantCount:0}});return r.value=k,k}catch(v){throw s.value=v instanceof Error?v:new Error(String(v)),s.value}finally{n.value=!1}}async function c(f,h={}){s.value=null;const v=Ou(f);if(v.length===0){const k={results:[],summary:{}};return l.value=k,k}if(v.length>yr){const k=new Error(`Cannot delete more than ${yr} media items at once.`);throw s.value=k,k}i.value=!0;try{const k=await o.httpClient.post(t,{uuids:v,force:h.force===!0,confirmed:h.confirmed===!0}),y={results:Array.isArray(k==null?void 0:k.results)?k.results:[],summary:(k==null?void 0:k.summary)??{}};return l.value=y,y}catch(k){const y=u(k);if(y&&y.requires_confirmation===!0){const w=m(y.soft_blocks),g=new Ld(w);throw s.value=g,g}throw s.value=k instanceof Error?k:new Error(String(k)),s.value}finally{i.value=!1}}function u(f){if(typeof f!="object"||f===null)return null;const h=f;if(h.response&&typeof h.response=="object"&&h.response.data&&typeof h.response.data=="object")return h.response.data;const v=f;return"requires_confirmation"in v||"soft_blocks"in v?v:null}function m(f){if(typeof f!="object"||f===null)return{};const h={};for(const[v,k]of Object.entries(f)){if(!Array.isArray(k))continue;const y=[];for(const w of k){if(typeof w!="object"||w===null)continue;const g=w;typeof g.type=="string"&&typeof g.context=="string"&&y.push({type:g.type,context:g.context})}h[v]=y}return h}function p(){r.value=null,l.value=null,s.value=null}return{isChecking:n,isDeleting:i,lastReport:r,lastResponse:l,error:s,checkDependencies:d,deleteMany:c,reset:p}}const JD="/v1/user/media/trash";function qD(o){return`/v1/user/media/${encodeURIComponent(o)}/restore`}function YD(o){return`/v1/user/media/${encodeURIComponent(o)}/purge`}function Pd(o){const a=o.listEndpoint??JD,t=o.buildRestoreEndpoint??qD,n=o.buildPurgeEndpoint??YD,i=o.perPage??50,r=e.ref([]),l=e.ref(0),s=e.ref(1),d=e.ref(!1),c=e.ref(!1),u=e.ref(!1),m=e.ref(null);async function p(k=1){var y,w;m.value=null,d.value=!0;try{const g=await o.httpClient.get(a,{params:{page:k,per_page:i}});r.value=Array.isArray(g==null?void 0:g.data)?g.data:[],l.value=typeof((y=g==null?void 0:g.meta)==null?void 0:y.total)=="number"?g.meta.total:0,s.value=typeof((w=g==null?void 0:g.meta)==null?void 0:w.current_page)=="number"?g.meta.current_page:k}catch(g){throw m.value=g instanceof Error?g:new Error(String(g)),m.value}finally{d.value=!1}}async function f(k){m.value=null,c.value=!0;try{const y=await o.httpClient.post(t(k)),w={status:(y==null?void 0:y.status)??"failed",data:(y==null?void 0:y.data)??null,duplicate_uuid:(y==null?void 0:y.duplicate_uuid)??null};return typeof(y==null?void 0:y.message)=="string"&&(w.message=y.message),w.status==="restored"&&(r.value=r.value.filter(g=>g.uuid!==k),l.value=Math.max(0,l.value-1)),w}catch(y){const w=zu(y);if(w&&typeof w.status=="string"){const g={status:w.status,duplicate_uuid:typeof w.duplicate_uuid=="string"?w.duplicate_uuid:null};return typeof w.message=="string"&&(g.message=w.message),g}throw m.value=y instanceof Error?y:new Error(String(y)),m.value}finally{c.value=!1}}async function h(k){m.value=null,u.value=!0;try{if(typeof o.httpClient.delete!="function")throw new Error("Media trash purge requires an HTTP client with delete support.");const y=await o.httpClient.delete(n(k)),w={status:(y==null?void 0:y.status)??"failed"};return typeof(y==null?void 0:y.message)=="string"&&(w.message=y.message),w.status==="purging"&&(r.value=r.value.filter(g=>g.uuid!==k),l.value=Math.max(0,l.value-1)),w}catch(y){const w=zu(y);if(w&&typeof w.status=="string"){const g={status:w.status};return typeof w.message=="string"&&(g.message=w.message),g}throw m.value=y instanceof Error?y:new Error(String(y)),m.value}finally{u.value=!1}}function v(){r.value=[],l.value=0,s.value=1,m.value=null}return{items:r,total:l,currentPage:s,isLoading:d,isRestoring:c,isPurging:u,error:m,fetch:p,restore:f,purge:h,reset:v}}function zu(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 QD={class:"media-management-view","data-testid":"media-management-view"},eA={key:0,class:"media-management-view__header"},tA={class:"media-management-view__title"},aA={class:"media-management-view__actions"},nA={key:0,class:"media-management-view__badge"},oA={key:1,class:"media-management-view__panel","data-testid":"panel-library"},iA={key:0,class:"media-management-view__view-mode",role:"radiogroup","aria-label":"Media library layout","data-testid":"media-management-layout-mode"},rA=["aria-checked"],lA=["aria-checked"],sA={key:1,class:"media-management-view__status","data-testid":"library-loading"},dA={key:2,class:"media-management-view__status media-management-view__status--error","data-testid":"library-error"},cA={key:3,class:"media-management-view__empty","data-testid":"library-empty"},uA={class:"media-management-view__empty-state"},mA={class:"media-management-view__empty-title","data-testid":"library-empty-title"},pA={class:"media-management-view__empty-description","data-testid":"library-empty-description"},fA={key:4,class:"media-management-view__table","data-testid":"library-table"},hA={scope:"col","data-testid":"table-header-select"},vA={class:"media-management-view__checkbox-label"},gA=["checked",".indeterminate","aria-label"],bA={class:"media-management-view__sr-only"},yA={scope:"col","data-testid":"table-header-thumbnail"},wA={scope:"col","data-testid":"table-header-name"},kA={scope:"col","data-testid":"table-header-type"},_A={scope:"col","data-testid":"table-header-created"},EA={scope:"col","data-testid":"table-header-size"},SA={scope:"col","data-testid":"table-header-status"},CA={scope:"col","data-testid":"table-header-actions"},xA=["data-testid"],NA={class:"media-management-view__checkbox-label"},VA=["checked","aria-label","data-testid","onChange"],TA=["data-testid","onClick"],BA=["src","alt","onError"],IA=["data-testid"],MA=["title","data-testid"],$A=["data-testid"],FA=["data-testid"],DA={class:"media-management-view__item-actions"},AA=["onKeydown"],RA=["data-testid","aria-label","aria-expanded","onClick"],LA=["data-testid"],PA=["data-testid","onClick"],UA={key:5,class:"media-management-view__grid","data-testid":"library-grid"},OA=["data-testid"],zA=["data-testid","aria-pressed","onClick"],jA=["src","alt","onError"],WA=["data-testid"],HA={class:"media-management-view__selection-corner"},ZA={class:"media-management-view__sr-only"},GA=["checked","data-testid","onChange"],XA={class:"media-management-view__item-meta"},KA=["title","data-testid"],JA=["data-testid"],qA=["data-testid"],YA={key:2,class:"media-management-view__item-badge","data-testid":"badge-orphaned"},QA=["data-testid"],eR={class:"media-management-view__item-actions media-management-view__item-actions--grid"},tR=["onKeydown"],aR=["data-testid","aria-label","aria-expanded","onClick"],nR=["data-testid"],oR=["data-testid","onClick"],iR={class:"media-management-view__bulk-bar","data-testid":"bulk-bar"},rR={"data-testid":"bulk-count"},lR=["disabled"],sR={key:7,class:"media-management-view__pagination","data-testid":"media-management-pagination"},dR={class:"media-management-view__pagination-count","data-testid":"media-management-pagination-count","aria-live":"polite"},cR={key:0,class:"media-management-view__page-size",role:"group","aria-label":"Items per page","data-testid":"media-management-page-size"},uR=["value","disabled"],mR=["value","data-testid"],pR=["disabled"],fR={key:2,class:"media-management-view__page-bar","aria-label":"Media library pagination","data-testid":"media-management-page-bar"},hR=["disabled"],vR=["data-testid","disabled","aria-current","aria-label","onClick"],gR=["disabled"],bR={key:2,class:"media-management-view__panel","data-testid":"panel-trash"},yR={key:0,class:"media-management-view__status","data-testid":"trash-loading"},wR={key:1,class:"media-management-view__empty","data-testid":"trash-empty"},kR={class:"media-management-view__empty-state"},_R={class:"media-management-view__empty-title","data-testid":"trash-empty-title"},ER={class:"media-management-view__empty-description","data-testid":"trash-empty-description"},SR={key:2,class:"media-management-view__grid","data-testid":"trash-grid"},CR=["data-testid"],xR={class:"media-management-view__item-thumb"},NR=["src","alt","onError"],VR=["data-testid"],TR={class:"media-management-view__item-meta"},BR={class:"media-management-view__item-name"},IR={key:0,class:"media-management-view__item-meta-line"},MR=["data-testid","disabled","onClick"],$R=["data-testid"],FR=e.defineComponent({__name:"MediaManagementView",props:{httpClient:{},capabilities:{default:()=>({})},labels:{default:()=>({})},filters:{},initialView:{},perPage:{},pageSizeOptions:{default:()=>[]},showAllOption:{type:Boolean,default:!1},loadAllMaxItems:{},paginated:{type:Boolean,default:!1},groupVariants:{type:Boolean,default:!0},paginationWindow:{default:7},initialLayoutMode:{},layoutMode:{},confirmBulkDelete:{},confirmDestructiveAction:{},onRestoreCollision:{}},emits:["deleted","restored","restore-conflict","create-post","create-gallery","add-to-album","edit","update:layoutMode","error"],setup(o,{expose:a,emit:t}){const n=o,i=t,r=e.computed(()=>({showTrash:!0,showHeader:!0,showLayoutSwitcher:!0,allowBulkDelete:!0,allowPreview:!0,allowCreatePost:!1,allowCreateGallery:!1,allowAddToAlbum:!1,allowImageEdit:!1,allowVideoEdit:!1,showOwner:!1,showRawFileName:!1,...n.capabilities})),l=e.computed(()=>{var X,we,ne,Fe,It,At,Mt,mt,pt,Qt,yt,Wt,_a,G,q,pe,he,Te,He,ot,Je,Ze,dt,ft,Qe,ea,Ft,Pa,Fa,co,Da,on,Ua,ha,In,uo,Mn,mo,hn;return{title:((X=n.labels)==null?void 0:X.title)??"My Media",libraryTab:((we=n.labels)==null?void 0:we.libraryTab)??"Library",trashTab:((ne=n.labels)==null?void 0:ne.trashTab)??"Trash",loading:((Fe=n.labels)==null?void 0:Fe.loading)??"Loading…",emptyLibrary:((It=n.labels)==null?void 0:It.emptyLibrary)??"No media yet — upload your first creation.",emptyLibraryTitle:((At=n.labels)==null?void 0:At.emptyLibraryTitle)??"Your media library is ready",emptyLibraryDescription:((Mt=n.labels)==null?void 0:Mt.emptyLibraryDescription)??"Images and videos you upload for creations are saved here so you can reuse them later.",emptyTrash:((mt=n.labels)==null?void 0:mt.emptyTrash)??"Trash is empty.",emptyTrashTitle:((pt=n.labels)==null?void 0:pt.emptyTrashTitle)??"No media in trash",emptyTrashDescription:((Qt=n.labels)==null?void 0:Qt.emptyTrashDescription)??"Deleted files appear here for 30 days before permanent removal.",orphanedBadge:((yt=n.labels)==null?void 0:yt.orphanedBadge)??"Not in use",selectedCount:((Wt=n.labels)==null?void 0:Wt.selectedCount)??(Oa=>`${Oa} selected`),deleteButton:((_a=n.labels)==null?void 0:_a.deleteButton)??"Delete",createPostButton:((G=n.labels)==null?void 0:G.createPostButton)??"Create Post",createGalleryButton:((q=n.labels)==null?void 0:q.createGalleryButton)??"Create Gallery",addToAlbumButton:((pe=n.labels)==null?void 0:pe.addToAlbumButton)??"Add to Album",previewButton:((he=n.labels)==null?void 0:he.previewButton)??"Preview",previewCloseButton:((Te=n.labels)==null?void 0:Te.previewCloseButton)??"Close",previewPreviousButton:((He=n.labels)==null?void 0:He.previewPreviousButton)??"Previous",previewNextButton:((ot=n.labels)==null?void 0:ot.previewNextButton)??"Next",previewSelectButton:((Je=n.labels)==null?void 0:Je.previewSelectButton)??"Select",previewDeselectButton:((Ze=n.labels)==null?void 0:Ze.previewDeselectButton)??"Deselect",editButton:((dt=n.labels)==null?void 0:dt.editButton)??"Edit",loadMoreButton:((ft=n.labels)==null?void 0:ft.loadMoreButton)??"Load more",loadingMoreButton:((Qe=n.labels)==null?void 0:Qe.loadingMoreButton)??"Loading more...",restoreButton:((ea=n.labels)==null?void 0:ea.restoreButton)??"Restore",restoreUnavailable:((Ft=n.labels)==null?void 0:Ft.restoreUnavailable)??"Restore unavailable",gridView:((Pa=n.labels)==null?void 0:Pa.gridView)??"Grid",tableView:((Fa=n.labels)==null?void 0:Fa.tableView)??"Table",tableSelectHeader:((co=n.labels)==null?void 0:co.tableSelectHeader)??"Select",tableThumbnailHeader:((Da=n.labels)==null?void 0:Da.tableThumbnailHeader)??"Preview",tableNameHeader:((on=n.labels)==null?void 0:on.tableNameHeader)??"Name",tableTypeHeader:((Ua=n.labels)==null?void 0:Ua.tableTypeHeader)??"Type",tableCreatedHeader:((ha=n.labels)==null?void 0:ha.tableCreatedHeader)??"Uploaded",tableSizeHeader:((In=n.labels)==null?void 0:In.tableSizeHeader)??"Size",tableStatusHeader:((uo=n.labels)==null?void 0:uo.tableStatusHeader)??"Status",tableActionsHeader:((Mn=n.labels)==null?void 0:Mn.tableActionsHeader)??"Actions",purgeAfter:((mo=n.labels)==null?void 0:mo.purgeAfter)??(Oa=>`Purges ${Oa}`),ownerLabel:((hn=n.labels)==null?void 0:hn.ownerLabel)??(Oa=>`User ${Oa.user_id??""}`)}}),s=e.computed(()=>l.value.title),d=e.computed(()=>l.value.libraryTab),c=e.computed(()=>l.value.trashTab),u=e.computed(()=>l.value.loading),m=e.computed(()=>l.value.emptyLibraryTitle),p=e.computed(()=>l.value.emptyLibraryDescription),f=e.computed(()=>l.value.emptyTrashTitle),h=e.computed(()=>l.value.emptyTrashDescription),v=e.computed(()=>l.value.orphanedBadge),k=e.computed(()=>l.value.deleteButton),y=e.computed(()=>l.value.restoreButton),w=e.computed(()=>l.value.restoreUnavailable),g=e.computed(()=>l.value.gridView),b=e.computed(()=>l.value.tableView);function R(X){const we=r.value.canRestore;return we?we(X):!0}const V=e.ref("library"),I=e.ref(n.layoutMode??n.initialLayoutMode??"grid"),x=e.ref(null),T=e.ref(null);function $(X){return{...X??{},...(X==null?void 0:X.kinds)!==void 0?{kinds:[...X.kinds]}:{}}}const S=e.ref(n.initialView??{scope:"library"}),B=e.ref($(n.filters)),_=e.ref(n.perPage??50),A=e.ref(!1),P=e.ref(n.paginated?1:null),D=Ad({httpClient:n.httpClient,view:S,filters:B,perPage:_,page:P}),z=e.computed(()=>n.groupVariants!==!0?D.items.value:D.items.value.filter(X=>typeof X.parent_media_uuid!="string"||X.parent_media_uuid.trim()==="")),M=e.computed(()=>D.loading.value),Z=e.computed(()=>{var X;return((X=D.error.value)==null?void 0:X.message)??null}),O=e.computed(()=>r.value.allowBulkDelete!==!1||r.value.allowCreatePost===!0||r.value.allowCreateGallery===!0||r.value.allowAddToAlbum===!0),K=e.computed(()=>{const X=x.value;return X===null?null:z.value[X]??null}),de=tl(z),Ne=Lf({httpClient:n.httpClient}),ce=Pd({httpClient:n.httpClient});function le(X){return l.value.selectedCount(X)}function W(X){return l.value.purgeAfter(X)}function C(X){return l.value.ownerLabel(X)}const U=e.computed(()=>{const X=z.value.length;return X===0?"":D.hasMore.value?X===1?"Showing 1 item":`Showing ${X} items`:X===1?"Showing all 1 item":`Showing all ${X} items`});function j(X){I.value!==X&&(Ot(),I.value=X,i("update:layoutMode",X))}function re(X){return X.mime_type.startsWith("image/")}function ue(X){return X.mime_type.startsWith("video/")}function Xe(X){return re(X)?"image":ue(X)?"video":null}function be(X){return re(X)?r.value.allowImageEdit===!0:ue(X)?r.value.allowVideoEdit===!0:!1}const Ee=Df;function ye(X){return typeof X.variant_count=="number"&&Number.isFinite(X.variant_count)?Math.max(0,X.variant_count):0}function xe(X){return X===1?"1 edit":`${X} edits`}function Ce(X){return re(X)?"Image":ue(X)?"Video":X.mime_type.startsWith("audio/")?"Audio":"File"}function Re(X){if(typeof X.formatted_size=="string"&&X.formatted_size.trim()!=="")return X.formatted_size;if(!Number.isFinite(X.size)||X.size<=0)return"";const we=["B","KB","MB","GB"];let ne=X.size,Fe=0;for(;ne>=1024&&Fe<we.length-1;)ne/=1024,Fe+=1;return`${ne>=10||Fe===0?Math.round(ne):ne.toFixed(1)} ${we[Fe]}`}function ze(X){const we=new Date(X.created_at);return Number.isNaN(we.getTime())?X.created_at:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(we)}function rt(X){return X.deletion_status==="active"||X.deletion_status===void 0||X.deletion_status===null?"Ready":X.deletion_status.replace(/_/g," ").replace(/\b\w/g,we=>we.toUpperCase())}function at(X){if(typeof X.thumbnail_url=="string"&&X.thumbnail_url.length>0)return X.thumbnail_url;const we=typeof X.mime_type=="string"&&X.mime_type.startsWith("image/"),ne=typeof X.mime_type=="string"&&X.mime_type.startsWith("video/");return we?X.original_url||null:ne&&typeof X.preview_url=="string"&&X.preview_url.length>0?X.preview_url:null}function Dt(X){return typeof X.mime_type=="string"&&X.mime_type.startsWith("video/")?`Video — ${X.file_name}`:X.file_name}const ht=e.ref(new Set);function St(X){if(ht.value.has(X.uuid))return;const we=new Set(ht.value);we.add(X.uuid),ht.value=we}function ut(X){if(r.value.allowPreview===!1)return;const we=z.value.findIndex(ne=>ne.uuid===X.uuid);x.value=we>=0?we:null}function lt(){x.value=null}function Ct(){x.value===null||x.value<=0||(x.value-=1)}function Se(){x.value===null||x.value>=z.value.length-1||(x.value+=1)}async function J(){try{await D.loadMore()}catch(X){i("error",X instanceof Error?X:new Error(String(X)))}}const oe=e.computed(()=>{const X=D.totalPages.value??0,we=D.currentPage.value??1;if(X<=1)return[];const ne=Math.max(3,n.paginationWindow);if(X<=ne)return Array.from({length:X},(pt,Qt)=>({kind:"page",key:`p-${Qt+1}`,value:Qt+1}));const Fe=ne-2,It=Math.floor(Fe/2);let At=Math.max(2,we-It),Mt=Math.min(X-1,At+Fe-1);Mt===X-1&&(At=Math.max(2,Mt-Fe+1));const mt=[{kind:"page",key:"p-1",value:1}];At>2&&mt.push({kind:"ellipsis",key:"el-left"});for(let pt=At;pt<=Mt;pt++)mt.push({kind:"page",key:`p-${pt}`,value:pt});return Mt<X-1&&mt.push({kind:"ellipsis",key:"el-right"}),mt.push({kind:"page",key:`p-${X}`,value:X}),mt});async function De(X){if(!(X===D.currentPage.value||D.loading.value)){P.value=X;try{await D.goToPage(X)}catch(we){i("error",we instanceof Error?we:new Error(String(we)))}}}async function fe(X){const we=D.currentPage.value??1,ne=D.totalPages.value??1,Fe=Math.min(Math.max(1,we+X),ne);Fe!==we&&await De(Fe)}const Ae=e.computed(()=>{const X=n.pageSizeOptions.map(we=>({value:String(we),label:String(we)}));return X.length===0&&!n.showAllOption?[]:(n.showAllOption&&X.push({value:"all",label:"All"}),X)}),Ye=e.computed(()=>A.value?"all":String(_.value));async function st(X){const we=X.target;if(!(we instanceof HTMLSelectElement))return;const ne=we.value;try{if(ne==="all"){const Fe=n.pageSizeOptions,It=Fe.length>0?Math.max(...Fe):_.value;P.value=null,_.value=It,A.value=!1,await D.refresh();const At=n.loadAllMaxItems!==void 0?{maxItems:n.loadAllMaxItems}:void 0;await D.loadAll(At),A.value=!D.hasMore.value}else{const Fe=Number.parseInt(ne,10);Number.isFinite(Fe)&&Fe>0&&(_.value=Fe),A.value=!1,n.paginated&&(P.value=1),await D.refresh()}}catch(Fe){i("error",Fe instanceof Error?Fe:new Error(String(Fe)))}}function Bt(X,we){i("create-post",{mediaIds:X.map(ne=>ne.uuid),items:X,source:we})}function Vt(X,we){i("create-gallery",{mediaIds:X.map(ne=>ne.uuid),items:X,source:we})}function Lt(X,we){i("add-to-album",{mediaIds:X.map(ne=>ne.uuid),items:X,source:we})}function Pt(X){const we=Xe(X);we===null||!be(X)||i("edit",{media:X,kind:we})}function zt(X){T.value=T.value===X?null:X}function Ot(){T.value=null}function jt(X){X.run(),Ot()}function oa(X){const we=[];return r.value.allowPreview!==!1&&we.push({id:"preview",label:l.value.previewButton,testId:`btn-preview-${X.uuid}`,run:()=>ut(X)}),be(X)&&we.push({id:"edit",label:l.value.editButton,testId:`btn-edit-${X.uuid}`,run:()=>Pt(X)}),r.value.allowCreatePost===!0&&we.push({id:"create-post",label:l.value.createPostButton,testId:`btn-create-post-${X.uuid}`,run:()=>Bt([X],"item")}),r.value.allowCreateGallery===!0&&we.push({id:"create-gallery",label:l.value.createGalleryButton,testId:`btn-create-gallery-${X.uuid}`,run:()=>Vt([X],"item")}),r.value.allowAddToAlbum===!0&&we.push({id:"add-to-album",label:l.value.addToAlbumButton,testId:`btn-add-to-album-${X.uuid}`,run:()=>Lt([X],"item")}),we}async function Q(X){const we=X.results.filter(ne=>ne.status==="trashed"||ne.status==="already_trashed").map(ne=>ne.uuid);if(we.length!==0){for(const ne of we)de.deselect(ne);i("deleted",we),await D.refresh(),r.value.showTrash!==!1&&await ce.fetch(ce.currentPage.value).catch(()=>{})}}function ge(X){const we=new Set;for(const It of X)for(const At of It.blocks)At.context&&we.add(At.context);const ne=Array.from(we),Fe=ne.length>0?`This media is still attached to: ${ne.map(It=>`"${It}"`).join(", ")}. Remove from those and delete?`:"This media is still attached to other items. Remove from those and delete?";return window.confirm(Fe)}function me(X){return Object.entries(X).map(([we,ne])=>({uuid:we,blocks:ne}))}async function se(){const X=de.selectedItems.value;if(X.length===0)return;const we=r.value.canDelete?X.filter(Fe=>r.value.canDelete(Fe)):X;if(we.length===0||n.confirmBulkDelete&&!await n.confirmBulkDelete(we))return;const ne=we.map(Fe=>Fe.uuid);try{const Fe=await Ne.deleteMany(ne);await Q(Fe)}catch(Fe){if(Fe instanceof Ld){const It=me(Fe.softBlocks);if(!(n.confirmDestructiveAction?await n.confirmDestructiveAction({items:we,softBlocks:It}):ge(It)))return;try{const Mt=await Ne.deleteMany(ne,{confirmed:!0});await Q(Mt)}catch(Mt){i("error",Mt instanceof Error?Mt:new Error(String(Mt)))}return}i("error",Fe instanceof Error?Fe:new Error(String(Fe)))}}async function Ve(X){var ne;const we=ce.items.value.find(Fe=>Fe.uuid===X);if(!(we&&!R(we)))try{const Fe=await ce.restore(X);if(Fe.status==="restored"){i("restored",X),await D.refresh().catch(()=>{});return}if(Fe.status==="duplicate_conflict"){i("restore-conflict",{uuid:X,duplicateUuid:Fe.duplicate_uuid??null}),(ne=n.onRestoreCollision)==null||ne.call(n,X,Fe.duplicate_uuid??null);return}}catch(Fe){i("error",Fe instanceof Error?Fe:new Error(String(Fe)))}}async function Pe(){V.value="trash",ce.items.value.length===0&&!ce.isLoading.value&&await ce.fetch().catch(X=>{i("error",X instanceof Error?X:new Error(String(X)))})}function et(X){if(X==="trash"){Pe();return}V.value=X}const gt=e.computed(()=>({activeTab:V.value,setActiveTab:et,trashCount:ce.total.value,showTrash:r.value.showTrash!==!1,labels:{libraryTab:l.value.libraryTab,trashTab:l.value.trashTab}})),Tt=e.computed(()=>({selectedCount:de.selectedCount.value,selectedItemIds:Array.from(de.selectedIds.value),selectedItems:de.selectedItems.value,crossPageCount:de.crossPageCount.value,isDeleting:Ne.isDeleting.value,onBulkDelete:se,...r.value.allowCreatePost===!0?{onCreatePost:()=>Bt(de.selectedItems.value,"bulk")}:{},...r.value.allowCreateGallery===!0?{onCreateGallery:()=>Vt(de.selectedItems.value,"bulk")}:{},...r.value.allowAddToAlbum===!0?{onAddToAlbum:()=>Lt(de.selectedItems.value,"bulk")}:{},clearSelection:de.clear,labels:{deleteButton:l.value.deleteButton,...r.value.allowCreatePost===!0?{createPostButton:l.value.createPostButton}:{},...r.value.allowCreateGallery===!0?{createGalleryButton:l.value.createGalleryButton}:{},...r.value.allowAddToAlbum===!0?{addToAlbumButton:l.value.addToAlbumButton}:{},selectedCount:l.value.selectedCount}})),xt=e.computed(()=>({filters:B.value,view:S.value,total:D.total.value,shown:z.value.length,loading:D.loading.value}));function _t(X){return{media:X,selected:de.isSelected(X.uuid),canEdit:be(X),onPreview:()=>ut(X),...be(X)?{onEdit:()=>Pt(X)}:{},...r.value.allowCreatePost===!0?{onCreatePost:()=>Bt([X],"item")}:{},...r.value.allowCreateGallery===!0?{onCreateGallery:()=>Vt([X],"item")}:{},...r.value.allowAddToAlbum===!0?{onAddToAlbum:()=>Lt([X],"item")}:{},labels:{previewButton:l.value.previewButton,editButton:l.value.editButton,createPostButton:l.value.createPostButton,createGalleryButton:l.value.createGalleryButton,addToAlbumButton:l.value.addToAlbumButton}}}function Xt(X){return{media:X,canRestore:R(X),isRestoring:ce.isRestoring.value,onRestore:()=>Ve(X.uuid),labels:{restoreButton:l.value.restoreButton,restoreUnavailable:l.value.restoreUnavailable}}}return e.watch(V,async X=>{X==="library"&&z.value.length===0&&!M.value&&await D.refresh().catch(()=>{})}),e.watch(()=>n.layoutMode,X=>{X!==void 0&&(I.value=X)}),e.watch(()=>n.filters,async X=>{B.value=$(X),de.clear(),lt(),await D.refresh().catch(we=>{i("error",we instanceof Error?we:new Error(String(we)))})},{deep:!0}),e.onMounted(async()=>{await D.refresh().catch(X=>{i("error",X instanceof Error?X:new Error(String(X)))}),r.value.showTrash!==!1&&ce.fetch().catch(()=>{})}),a({refresh:()=>D.refresh(),refreshTrash:()=>ce.fetch(),selection:de,deletion:Ne,trash:ce}),(X,we)=>(e.openBlock(),e.createElementBlock("div",QD,[r.value.showHeader!==!1?(e.openBlock(),e.createElementBlock("header",eA,[e.createElementVNode("h2",tA,e.toDisplayString(s.value),1),e.createElementVNode("div",aA,[e.renderSlot(X.$slots,"tabs",e.normalizeProps(e.guardReactiveProps(gt.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":V.value==="library"}]),"data-testid":"tab-library",onClick:we[0]||(we[0]=ne=>V.value="library")},e.toDisplayString(d.value),3),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["media-management-view__tab-button",{"is-active":V.value==="trash"}]),"data-testid":"tab-trash",onClick:Pe},[e.createTextVNode(e.toDisplayString(c.value)+" ",1),e.unref(ce).total.value>0?(e.openBlock(),e.createElementBlock("span",nA,e.toDisplayString(e.unref(ce).total.value),1)):e.createCommentVNode("",!0)],2)],64)):e.createCommentVNode("",!0)],!0)])])):e.createCommentVNode("",!0),V.value==="library"?(e.openBlock(),e.createElementBlock("section",oA,[r.value.showLayoutSwitcher!==!1?(e.openBlock(),e.createElementBlock("div",iA,[e.createElementVNode("button",{type:"button",role:"radio",class:e.normalizeClass(["media-management-view__view-mode-button",{"is-active":I.value==="grid"}]),"aria-checked":I.value==="grid"?"true":"false","data-testid":"view-mode-grid",onClick:we[1]||(we[1]=ne=>j("grid"))},e.toDisplayString(g.value),11,rA),e.createElementVNode("button",{type:"button",role:"radio",class:e.normalizeClass(["media-management-view__view-mode-button",{"is-active":I.value==="table"}]),"aria-checked":I.value==="table"?"true":"false","data-testid":"view-mode-table",onClick:we[2]||(we[2]=ne=>j("table"))},e.toDisplayString(b.value),11,lA)])):e.createCommentVNode("",!0),e.renderSlot(X.$slots,"filter-bar",e.normalizeProps(e.guardReactiveProps(xt.value)),void 0,!0),M.value?(e.openBlock(),e.createElementBlock("div",sA,e.toDisplayString(u.value),1)):Z.value?(e.openBlock(),e.createElementBlock("div",dA,e.toDisplayString(Z.value),1)):z.value.length===0?(e.openBlock(),e.createElementBlock("div",cA,[e.renderSlot(X.$slots,"empty-library",{},()=>[e.createElementVNode("div",uA,[e.createElementVNode("p",mA,e.toDisplayString(m.value),1),e.createElementVNode("p",pA,e.toDisplayString(p.value),1)])],!0)])):I.value==="table"?(e.openBlock(),e.createElementBlock("table",fA,[e.createElementVNode("thead",null,[e.createElementVNode("tr",null,[e.createElementVNode("th",hA,[e.createElementVNode("label",vA,[e.createElementVNode("input",{class:"media-management-view__checkbox",type:"checkbox",checked:e.unref(de).isAllSelected.value,".indeterminate":e.unref(de).isSomeSelected.value&&!e.unref(de).isAllSelected.value,"aria-label":l.value.tableSelectHeader,"data-testid":"checkbox-select-all",onChange:we[3]||(we[3]=(...ne)=>e.unref(de).toggleAll&&e.unref(de).toggleAll(...ne))},null,40,gA),e.createElementVNode("span",bA,e.toDisplayString(l.value.tableSelectHeader),1)])]),e.createElementVNode("th",yA,e.toDisplayString(l.value.tableThumbnailHeader),1),e.createElementVNode("th",wA,e.toDisplayString(l.value.tableNameHeader),1),e.createElementVNode("th",kA,e.toDisplayString(l.value.tableTypeHeader),1),e.createElementVNode("th",_A,e.toDisplayString(l.value.tableCreatedHeader),1),e.createElementVNode("th",EA,e.toDisplayString(l.value.tableSizeHeader),1),e.createElementVNode("th",SA,e.toDisplayString(l.value.tableStatusHeader),1),e.createElementVNode("th",CA,e.toDisplayString(l.value.tableActionsHeader),1)])]),e.createElementVNode("tbody",null,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(z.value,ne=>(e.openBlock(),e.createElementBlock("tr",{key:ne.uuid,class:e.normalizeClass({"is-selected":e.unref(de).isSelected(ne.uuid),"has-open-actions":T.value===ne.uuid}),"data-testid":`media-row-${ne.uuid}`},[e.createElementVNode("td",null,[e.createElementVNode("label",NA,[e.createElementVNode("input",{class:"media-management-view__checkbox",type:"checkbox",checked:e.unref(de).isSelected(ne.uuid),"aria-label":`${l.value.tableSelectHeader} ${e.unref(Ee)(ne)}`,"data-testid":`checkbox-select-${ne.uuid}`,onChange:Fe=>e.unref(de).toggle(ne.uuid)},null,40,VA)])]),e.createElementVNode("td",null,[e.createElementVNode("button",{type:"button",class:"media-management-view__table-thumb","data-testid":`btn-preview-thumb-${ne.uuid}`,onClick:Fe=>ut(ne)},[at(ne)&&!ht.value.has(ne.uuid)?(e.openBlock(),e.createElementBlock("img",{key:0,src:at(ne)??"",alt:ne.alt_text||ne.file_name,loading:"lazy",onError:Fe=>St(ne)},null,40,BA)):(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__item-placeholder","data-testid":`placeholder-${ne.uuid}`},e.toDisplayString(Dt(ne)),9,IA))],8,TA)]),e.createElementVNode("td",null,[e.createElementVNode("span",{class:"media-management-view__display-name",title:ne.file_name,"data-testid":`media-display-name-${ne.uuid}`},e.toDisplayString(e.unref(Ee)(ne)),9,MA),ye(ne)>0?(e.openBlock(),e.createElementBlock("span",{key:0,class:"media-management-view__variant-badge","data-testid":`media-variant-badge-${ne.uuid}`},e.toDisplayString(xe(ye(ne))),9,$A)):e.createCommentVNode("",!0),r.value.showRawFileName===!0?(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__raw-filename","data-testid":`media-raw-filename-${ne.uuid}`},e.toDisplayString(ne.file_name),9,FA)):e.createCommentVNode("",!0)]),e.createElementVNode("td",null,e.toDisplayString(Ce(ne)),1),e.createElementVNode("td",null,e.toDisplayString(ze(ne)),1),e.createElementVNode("td",null,e.toDisplayString(Re(ne)),1),e.createElementVNode("td",null,e.toDisplayString(rt(ne)),1),e.createElementVNode("td",null,[e.renderSlot(X.$slots,"item-actions",e.mergeProps({ref_for:!0},_t(ne)),()=>[e.createElementVNode("div",DA,[e.createElementVNode("div",{class:"media-management-view__action-menu",onKeydown:e.withKeys(e.withModifiers(Ot,["stop"]),["escape"])},[e.createElementVNode("button",{type:"button",class:"media-management-view__action-menu-trigger","data-testid":`btn-actions-menu-${ne.uuid}`,"aria-label":`Actions for ${e.unref(Ee)(ne)}`,"aria-haspopup":"menu","aria-expanded":T.value===ne.uuid?"true":"false",onClick:Fe=>zt(ne.uuid)}," ... ",8,RA),T.value===ne.uuid?(e.openBlock(),e.createElementBlock("div",{key:0,class:"media-management-view__action-menu-panel",role:"menu","data-testid":`media-item-actions-menu-${ne.uuid}`},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(oa(ne),Fe=>(e.openBlock(),e.createElementBlock("button",{key:Fe.id,type:"button",class:"media-management-view__action-menu-item",role:"menuitem","data-testid":Fe.testId,onClick:It=>jt(Fe)},e.toDisplayString(Fe.label),9,PA))),128))],8,LA)):e.createCommentVNode("",!0)],40,AA)])],!0)])],10,xA))),128))])])):(e.openBlock(),e.createElementBlock("ul",UA,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(z.value,ne=>(e.openBlock(),e.createElementBlock("li",{key:ne.uuid,class:e.normalizeClass(["media-management-view__item",{"is-selected":e.unref(de).isSelected(ne.uuid),"has-open-actions":T.value===ne.uuid}]),"data-testid":`media-item-${ne.uuid}`},[e.createElementVNode("button",{type:"button",class:"media-management-view__item-thumb","data-testid":`btn-select-${ne.uuid}`,"aria-pressed":e.unref(de).isSelected(ne.uuid),onClick:Fe=>e.unref(de).toggle(ne.uuid)},[at(ne)&&!ht.value.has(ne.uuid)?(e.openBlock(),e.createElementBlock("img",{key:0,src:at(ne)??"",alt:ne.alt_text||ne.file_name,loading:"lazy",onError:Fe=>St(ne)},null,40,jA)):(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__item-placeholder","data-testid":`placeholder-${ne.uuid}`},e.toDisplayString(Dt(ne)),9,WA))],8,zA),e.createElementVNode("label",HA,[e.createElementVNode("span",ZA,e.toDisplayString(l.value.tableSelectHeader)+" "+e.toDisplayString(e.unref(Ee)(ne)),1),e.createElementVNode("input",{class:"media-management-view__checkbox media-management-view__checkbox--overlay",type:"checkbox",checked:e.unref(de).isSelected(ne.uuid),"data-testid":`checkbox-select-${ne.uuid}`,onClick:we[4]||(we[4]=e.withModifiers(()=>{},["stop"])),onChange:Fe=>e.unref(de).toggle(ne.uuid)},null,40,GA)]),e.createElementVNode("div",XA,[e.createElementVNode("span",{class:"media-management-view__item-name",title:ne.file_name,"data-testid":`media-display-name-${ne.uuid}`},e.toDisplayString(e.unref(Ee)(ne)),9,KA),r.value.showRawFileName===!0?(e.openBlock(),e.createElementBlock("span",{key:0,class:"media-management-view__raw-filename","data-testid":`media-raw-filename-${ne.uuid}`},e.toDisplayString(ne.file_name),9,JA)):e.createCommentVNode("",!0),r.value.showOwner&&ne.user_id?(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__item-owner","data-testid":`owner-${ne.uuid}`},e.toDisplayString(C(ne)),9,qA)):e.createCommentVNode("",!0),ne.is_orphaned?(e.openBlock(),e.createElementBlock("span",YA,e.toDisplayString(v.value),1)):e.createCommentVNode("",!0),ye(ne)>0?(e.openBlock(),e.createElementBlock("span",{key:3,class:"media-management-view__variant-badge","data-testid":`media-variant-badge-${ne.uuid}`},e.toDisplayString(xe(ye(ne))),9,QA)):e.createCommentVNode("",!0)]),e.renderSlot(X.$slots,"item-actions",e.mergeProps({ref_for:!0},_t(ne)),()=>[e.createElementVNode("div",eR,[e.createElementVNode("div",{class:"media-management-view__action-menu",onKeydown:e.withKeys(e.withModifiers(Ot,["stop"]),["escape"])},[e.createElementVNode("button",{type:"button",class:"media-management-view__action-menu-trigger","data-testid":`btn-actions-menu-${ne.uuid}`,"aria-label":`Actions for ${e.unref(Ee)(ne)}`,"aria-haspopup":"menu","aria-expanded":T.value===ne.uuid?"true":"false",onClick:Fe=>zt(ne.uuid)}," ... ",8,aR),T.value===ne.uuid?(e.openBlock(),e.createElementBlock("div",{key:0,class:"media-management-view__action-menu-panel",role:"menu","data-testid":`media-item-actions-menu-${ne.uuid}`},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(oa(ne),Fe=>(e.openBlock(),e.createElementBlock("button",{key:Fe.id,type:"button",class:"media-management-view__action-menu-item",role:"menuitem","data-testid":Fe.testId,onClick:It=>jt(Fe)},e.toDisplayString(Fe.label),9,oR))),128))],8,nR)):e.createCommentVNode("",!0)],40,tR)])],!0)],10,OA))),128))])),e.unref(de).selectedCount.value>0&&O.value?e.renderSlot(X.$slots,"bulk-actions",e.normalizeProps(e.mergeProps({key:6},Tt.value)),()=>[e.createElementVNode("footer",iR,[e.createElementVNode("span",rR,e.toDisplayString(le(e.unref(de).selectedCount.value)),1),r.value.allowCreatePost===!0?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-management-view__btn-action","data-testid":"btn-bulk-create-post",onClick:we[5]||(we[5]=ne=>Bt(e.unref(de).selectedItems.value,"bulk"))},e.toDisplayString(l.value.createPostButton),1)):e.createCommentVNode("",!0),r.value.allowCreateGallery===!0?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button",class:"media-management-view__btn-action","data-testid":"btn-bulk-create-gallery",onClick:we[6]||(we[6]=ne=>Vt(e.unref(de).selectedItems.value,"bulk"))},e.toDisplayString(l.value.createGalleryButton),1)):e.createCommentVNode("",!0),r.value.allowAddToAlbum===!0?(e.openBlock(),e.createElementBlock("button",{key:2,type:"button",class:"media-management-view__btn-action","data-testid":"btn-bulk-add-to-album",onClick:we[7]||(we[7]=ne=>Lt(e.unref(de).selectedItems.value,"bulk"))},e.toDisplayString(l.value.addToAlbumButton),1)):e.createCommentVNode("",!0),r.value.allowBulkDelete!==!1?(e.openBlock(),e.createElementBlock("button",{key:3,type:"button",class:"media-management-view__btn-delete","data-testid":"btn-bulk-delete",disabled:e.unref(Ne).isDeleting.value,onClick:se},e.toDisplayString(k.value),9,lR)):e.createCommentVNode("",!0)])],!0):e.createCommentVNode("",!0),z.value.length>0?(e.openBlock(),e.createElementBlock("footer",sR,[e.createElementVNode("span",dR,e.toDisplayString(U.value),1),Ae.value.length>0?(e.openBlock(),e.createElementBlock("div",cR,[we[11]||(we[11]=e.createElementVNode("label",{class:"media-management-view__page-size-label",for:"media-management-page-size-select"},"Show:",-1)),e.createElementVNode("select",{id:"media-management-page-size-select",class:"media-management-view__page-size-select","data-testid":"select-media-management-page-size",value:Ye.value,disabled:e.unref(D).loading.value||e.unref(D).loadingMore.value,onChange:st},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Ae.value,ne=>(e.openBlock(),e.createElementBlock("option",{key:ne.value,value:ne.value,"data-testid":`option-page-size-${ne.value}`},e.toDisplayString(ne.label),9,mR))),128))],40,uR)])):e.createCommentVNode("",!0),!X.paginated&&e.unref(D).hasMore.value?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button",class:"media-management-view__load-more","data-testid":"btn-media-management-load-more",disabled:e.unref(D).loadingMore.value,onClick:J},e.toDisplayString(e.unref(D).loadingMore.value?l.value.loadingMoreButton:l.value.loadMoreButton),9,pR)):e.createCommentVNode("",!0),X.paginated&&(e.unref(D).totalPages.value??0)>1?(e.openBlock(),e.createElementBlock("nav",fR,[e.createElementVNode("button",{type:"button",class:"media-management-view__page-bar-step","data-testid":"btn-media-management-page-prev",disabled:(e.unref(D).currentPage.value??1)<=1||e.unref(D).loading.value,"aria-label":"Previous page",onClick:we[8]||(we[8]=ne=>fe(-1))}," ‹ ",8,hR),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(oe.value,ne=>(e.openBlock(),e.createElementBlock("button",{key:ne.key,type:"button",class:e.normalizeClass(["media-management-view__page-bar-page",{"is-current":ne.kind==="page"&&ne.value===e.unref(D).currentPage.value}]),"data-testid":ne.kind==="page"?`btn-media-management-page-${ne.value}`:"media-management-page-ellipsis",disabled:ne.kind!=="page"||e.unref(D).loading.value,"aria-current":ne.kind==="page"&&ne.value===e.unref(D).currentPage.value?"page":void 0,"aria-label":ne.kind==="page"?`Page ${ne.value}`:void 0,onClick:Fe=>ne.kind==="page"?De(ne.value):void 0},e.toDisplayString(ne.kind==="page"?ne.value:"…"),11,vR))),128)),e.createElementVNode("button",{type:"button",class:"media-management-view__page-bar-step","data-testid":"btn-media-management-page-next",disabled:(e.unref(D).currentPage.value??1)>=(e.unref(D).totalPages.value??1)||e.unref(D).loading.value,"aria-label":"Next page",onClick:we[9]||(we[9]=ne=>fe(1))}," › ",8,gR)])):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)])):V.value==="trash"?(e.openBlock(),e.createElementBlock("section",bR,[e.unref(ce).isLoading.value?(e.openBlock(),e.createElementBlock("div",yR,e.toDisplayString(u.value),1)):e.unref(ce).items.value.length===0?(e.openBlock(),e.createElementBlock("div",wR,[e.renderSlot(X.$slots,"empty-trash",{},()=>[e.createElementVNode("div",kR,[e.createElementVNode("p",_R,e.toDisplayString(f.value),1),e.createElementVNode("p",ER,e.toDisplayString(h.value),1)])],!0)])):(e.openBlock(),e.createElementBlock("ul",SR,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(ce).items.value,ne=>(e.openBlock(),e.createElementBlock("li",{key:ne.uuid,class:"media-management-view__item is-trashed","data-testid":`trash-item-${ne.uuid}`},[e.createElementVNode("div",xR,[at(ne)&&!ht.value.has(ne.uuid)?(e.openBlock(),e.createElementBlock("img",{key:0,src:at(ne)??"",alt:ne.alt_text||ne.file_name,loading:"lazy",onError:Fe=>St(ne)},null,40,NR)):(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__item-placeholder","data-testid":`placeholder-trash-${ne.uuid}`},e.toDisplayString(Dt(ne)),9,VR))]),e.createElementVNode("div",TR,[e.createElementVNode("span",BR,e.toDisplayString(ne.file_name),1),ne.purge_after?(e.openBlock(),e.createElementBlock("span",IR,e.toDisplayString(W(ne.purge_after)),1)):e.createCommentVNode("",!0)]),e.renderSlot(X.$slots,"trash-action",e.mergeProps({ref_for:!0},Xt(ne)),()=>[R(ne)?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-management-view__btn-restore","data-testid":`btn-restore-${ne.uuid}`,disabled:e.unref(ce).isRestoring.value,onClick:Fe=>Ve(ne.uuid)},e.toDisplayString(y.value),9,MR)):(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__btn-restore is-unavailable","data-testid":`btn-restore-${ne.uuid}-unavailable`,"aria-disabled":!0},e.toDisplayString(w.value),9,$R))],!0)],8,CR))),128))]))])):e.createCommentVNode("",!0),r.value.allowPreview!==!1?(e.openBlock(),e.createBlock(Md,{key:3,open:K.value!==null,media:K.value,"can-go-previous":x.value!==null&&x.value>0,"can-go-next":x.value!==null&&x.value<z.value.length-1,selected:K.value!==null&&e.unref(de).isSelected(K.value.uuid),"close-label":l.value.previewCloseButton,"previous-label":l.value.previewPreviousButton,"next-label":l.value.previewNextButton,"select-label":l.value.previewSelectButton,"deselect-label":l.value.previewDeselectButton,onClose:lt,onPrevious:Ct,onNext:Se,onToggleSelect:we[10]||(we[10]=ne=>e.unref(de).toggle(ne.uuid))},null,8,["open","media","can-go-previous","can-go-next","selected","close-label","previous-label","next-label","select-label","deselect-label"])):e.createCommentVNode("",!0)]))}}),Pf=$e(FR,[["__scopeId","data-v-8c4b53f6"]]),DR={class:"media-library-workspace","data-testid":"media-library-workspace"},AR=e.defineComponent({__name:"MediaLibraryWorkspace",props:{httpClient:{},filters:{default:()=>({sort:"newest"})},initialView:{default:()=>({scope:"library"})},capabilities:{default:()=>({})},labels:{default:()=>({})},groupVariants:{type:Boolean,default:!0}},emits:["filters-change","create-post","create-gallery","add-to-album","edit","deleted","restored","restore-conflict","error"],setup(o,{emit:a}){const t=o,n=a;function i(s){return{...s,...s.kinds!==void 0?{kinds:[...s.kinds]}:{},...s.selected_uuids!==void 0?{selected_uuids:[...s.selected_uuids]}:{}}}const r=e.ref(i(t.filters));e.watch(()=>t.filters,s=>{r.value=i(s)},{deep:!0});function l(s){r.value=i(s),n("filters-change",r.value)}return(s,d)=>(e.openBlock(),e.createElementBlock("section",DR,[e.createVNode(Pf,{"http-client":t.httpClient,filters:r.value,"initial-view":t.initialView,"group-variants":t.groupVariants,capabilities:{showHeader:!1,showTrash:!1,allowAddToAlbum:t.capabilities.allowAddToAlbum,allowBulkDelete:t.capabilities.allowBulkDelete,allowCreateGallery:t.capabilities.allowCreateGallery,allowCreatePost:t.capabilities.allowCreatePost,showRawFileName:t.capabilities.showRawFileName,allowPreview:t.capabilities.allowPreview,allowImageEdit:t.capabilities.allowImageEdit,allowVideoEdit:t.capabilities.allowVideoEdit},labels:{title:t.labels.title??"Media"},onCreatePost:d[0]||(d[0]=c=>n("create-post",c)),onCreateGallery:d[1]||(d[1]=c=>n("create-gallery",c)),onAddToAlbum:d[2]||(d[2]=c=>n("add-to-album",c)),onEdit:d[3]||(d[3]=c=>n("edit",c)),onDeleted:d[4]||(d[4]=c=>n("deleted",c)),onRestored:d[5]||(d[5]=c=>n("restored",c)),onRestoreConflict:d[6]||(d[6]=c=>n("restore-conflict",c)),onError:d[7]||(d[7]=c=>n("error",c))},{"filter-bar":e.withCtx(()=>[e.createVNode(Rf,{filters:r.value,"scope-label":t.labels.scopeLabel??"","onUpdate:filters":l},null,8,["filters","scope-label"])]),"bulk-actions":e.withCtx(c=>[e.renderSlot(s.$slots,"bulk-actions",e.normalizeProps(e.guardReactiveProps(c)),void 0,!0)]),"item-actions":e.withCtx(c=>[e.renderSlot(s.$slots,"item-actions",e.normalizeProps(e.guardReactiveProps(c)),void 0,!0)]),"empty-library":e.withCtx(()=>[e.renderSlot(s.$slots,"empty-library",{},void 0,!0)]),_:3},8,["http-client","filters","initial-view","group-variants","capabilities","labels"])]))}}),Uf=$e(AR,[["__scopeId","data-v-28ba5859"]]),RR=["data-testid"],LR={class:"media-empty-state__illustration","aria-hidden":"true"},PR={class:"media-empty-state__copy"},UR={class:"media-empty-state__title"},OR={key:0,class:"media-empty-state__description"},zR={class:"media-empty-state__actions"},jR=e.defineComponent({__name:"MediaEmptyState",props:{title:{},description:{default:""},actionLabel:{default:""},testId:{default:"media-empty-state"}},emits:["action"],setup(o,{emit:a}){const t=o,n=a;return(i,r)=>(e.openBlock(),e.createElementBlock("section",{class:"media-empty-state","data-testid":t.testId},[e.createElementVNode("div",LR,[e.renderSlot(i.$slots,"illustration",{},()=>[r[1]||(r[1]=e.createElementVNode("span",{class:"media-empty-state__icon"},"□",-1))],!0)]),e.createElementVNode("div",PR,[e.createElementVNode("h3",UR,e.toDisplayString(t.title),1),t.description!==""?(e.openBlock(),e.createElementBlock("p",OR,e.toDisplayString(t.description),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",zR,[e.renderSlot(i.$slots,"actions",{},()=>[t.actionLabel!==""?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-empty-state__action","data-testid":"btn-media-empty-state-action",onClick:r[0]||(r[0]=l=>n("action"))},e.toDisplayString(t.actionLabel),1)):e.createCommentVNode("",!0)],!0)])],8,RR))}}),Of=$e(jR,[["__scopeId","data-v-7b8e2619"]]),WR={class:"media-trash-workspace","data-testid":"media-trash-workspace"},HR={class:"media-trash-workspace__header"},ZR={key:0,class:"media-trash-workspace__status"},GR={key:2,class:"media-trash-workspace__grid"},XR=["data-testid"],KR={class:"media-trash-workspace__select"},JR=["checked","data-testid","onChange"],qR=["src","alt"],YR={key:1,class:"media-trash-workspace__purge"},QR=e.defineComponent({__name:"MediaTrashWorkspace",props:{httpClient:{},labels:{default:()=>({})}},emits:["restored","purged","error"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>{var p,f,h,v,k,y;return{title:((p=t.labels)==null?void 0:p.title)??"Trash",emptyTitle:((f=t.labels)==null?void 0:f.emptyTitle)??"Your trash is empty",emptyDescription:((h=t.labels)==null?void 0:h.emptyDescription)??"Deleted files appear here before permanent removal.",restore:((v=t.labels)==null?void 0:v.restore)??"Restore",purge:((k=t.labels)==null?void 0:k.purge)??"Delete forever",emptyTrash:((y=t.labels)==null?void 0:y.emptyTrash)??"Empty trash"}}),r=Pd({httpClient:t.httpClient}),l=tl(r.items);function s(p){return p.thumbnail_url??p.preview_url??p.original_url??null}async function d(){const p=Array.from(l.selectedIds.value),f=[];try{for(const h of p)(await r.restore(h)).status==="restored"&&f.push(h);l.clear(),n("restored",f)}catch(h){n("error",h instanceof Error?h:new Error(String(h)))}}async function c(){const p=Array.from(l.selectedIds.value);await m(p)}async function u(){await m(r.items.value.map(p=>p.uuid))}async function m(p){const f=[];try{for(const h of p)(await r.purge(h)).status==="purging"&&f.push(h);l.clear(),n("purged",f)}catch(h){n("error",h instanceof Error?h:new Error(String(h)))}}return e.onMounted(()=>{r.fetch().catch(p=>{n("error",p instanceof Error?p:new Error(String(p)))})}),(p,f)=>(e.openBlock(),e.createElementBlock("section",WR,[e.createElementVNode("header",HR,[e.createElementVNode("h2",null,e.toDisplayString(i.value.title),1),e.unref(r).items.value.length>0?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button","data-testid":"btn-media-empty-trash",onClick:u},e.toDisplayString(i.value.emptyTrash),1)):e.createCommentVNode("",!0)]),e.unref(r).isLoading.value?(e.openBlock(),e.createElementBlock("p",ZR,"Loading...")):e.unref(r).items.value.length===0?(e.openBlock(),e.createBlock(Of,{key:1,title:i.value.emptyTitle,description:i.value.emptyDescription,"test-id":"media-empty-trash"},null,8,["title","description"])):(e.openBlock(),e.createElementBlock("ul",GR,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(r).items.value,h=>(e.openBlock(),e.createElementBlock("li",{key:h.uuid,class:e.normalizeClass(["media-trash-workspace__item",{"is-selected":e.unref(l).isSelected(h.uuid)}]),"data-testid":`media-trash-item-${h.uuid}`},[e.createElementVNode("label",KR,[e.createElementVNode("input",{type:"checkbox",checked:e.unref(l).isSelected(h.uuid),"data-testid":`checkbox-trash-${h.uuid}`,onChange:v=>e.unref(l).toggle(h.uuid)},null,40,JR),e.createElementVNode("span",null,e.toDisplayString(h.file_name),1)]),s(h)?(e.openBlock(),e.createElementBlock("img",{key:0,src:s(h)??"",alt:h.alt_text??h.file_name},null,8,qR)):e.createCommentVNode("",!0),h.purge_after?(e.openBlock(),e.createElementBlock("span",YR,e.toDisplayString(h.purge_after),1)):e.createCommentVNode("",!0)],10,XR))),128))])),e.createVNode(Rd,{"selected-count":e.unref(l).selectedCount.value,"cross-page-count":e.unref(l).crossPageCount.value,scope:"trash",labels:{restore:i.value.restore,purge:i.value.purge},onBulkRestore:d,onBulkPurge:c,onClear:e.unref(l).clear},null,8,["selected-count","cross-page-count","labels","onClear"])]))}}),zf=$e(QR,[["__scopeId","data-v-3b1b3c56"]]),eL=["data-density"],tL={class:"media-library-shell__toolbar"},aL={class:"media-library-shell__tabs","aria-label":"Media library sections"},nL=["aria-label"],oL=["data-testid","onClick"],iL={key:2,class:"media-library-shell__uploads","data-testid":"media-library-uploads","aria-live":"polite"},rL=["data-testid"],lL={class:"media-library-shell__upload-thumb"},sL=["src","alt"],dL={key:1,"aria-hidden":"true"},cL={class:"media-library-shell__upload-meta"},uL={class:"media-library-shell__upload-name"},mL={class:"media-library-shell__upload-status"},pL=["data-testid","onClick"],fL={class:"media-library-shell__workspace"},hL={key:0,class:"media-library-shell__breadcrumb","data-testid":"media-album-breadcrumb"},vL={class:"media-library-shell__breadcrumb-name"},gL=["aria-label"],bL={class:"media-album-grid__toolbar"},yL=["placeholder","aria-label"],wL={class:"media-album-grid__tiles",role:"list"},kL={class:"media-album-grid__new-tile-label"},_L=["data-testid","onClick"],EL={class:"media-album-grid__cover","aria-hidden":"true"},SL=["src"],CL={key:1,class:"media-album-grid__cover-initial"},xL={class:"media-album-grid__tile-meta"},NL={class:"media-album-grid__tile-name"},VL={class:"media-album-grid__tile-count"},TL={key:0,class:"media-album-grid__empty","data-testid":"media-album-grid-empty-search"},BL={key:1,class:"media-album-grid__empty","data-testid":"media-album-grid-empty"},ju="media-library:density",Wu="media-library:recent-albums",Hu=5,IL=e.defineComponent({__name:"MediaLibraryShell",props:{httpClient:{},albumHttpClient:{},albumBaseUrl:{},initialTab:{default:"library"},initialAlbumId:{default:null},initialFilters:{default:()=>({sort:"newest"})},capabilities:{default:()=>({})},labels:{default:()=>({})},currentRoute:{},routerPush:{},routerReplace:{}},emits:["tab-change","album-change","filters-change","selection-change","create-post","create-gallery","add-to-album","edit","deleted","restored","restore-conflict","error"],setup(o,{emit:a}){function t(){if(typeof window>"u")return"comfortable";try{return window.localStorage.getItem(ju)==="compact"?"compact":"comfortable"}catch{return"comfortable"}}function n(J){if(!(typeof window>"u"))try{window.localStorage.setItem(ju,J)}catch{}}function i(){if(typeof window>"u")return[];try{const J=window.localStorage.getItem(Wu);if(typeof J!="string"||J==="")return[];const oe=JSON.parse(J);return Array.isArray(oe)?oe.filter(De=>typeof De=="string"):[]}catch{return[]}}function r(J){if(!(typeof window>"u"))try{window.localStorage.setItem(Wu,JSON.stringify(J.slice(0,Hu)))}catch{}}const l=o,s=a,d=e.ref(l.initialTab),c=e.ref(l.initialAlbumId),u=e.ref({...l.initialFilters}),m=e.ref(null),p=e.ref(null),f=e.ref(!1),h=e.ref(null),v=e.ref(null),k=e.ref(t()),y=e.ref(i()),w=e.ref(!1),g=e.ref("");function b(){if(typeof document>"u")return!1;const J=document.activeElement;if(!(J instanceof HTMLElement))return!1;if(J.isContentEditable)return!0;const oe=J.tagName.toLowerCase();return oe==="input"||oe==="textarea"||oe==="select"}function R(J){J.key==="?"&&(J.metaKey||J.ctrlKey||J.altKey||b()||(J.preventDefault(),w.value=!0))}const V=e.computed(()=>d.value==="albums"&&c.value===null),I=e.computed(()=>d.value==="albums"&&c.value!==null&&c.value!=="unfiled"),x=e.computed(()=>{var J;return c.value===null||c.value==="unfiled"?"":((J=D.albumsById.value.get(c.value))==null?void 0:J.name)??""}),T=e.computed(()=>{const J=g.value.trim().toLowerCase(),oe=D.albums.value;return J===""?oe:oe.filter(De=>De.name.toLowerCase().includes(J))});function $(J){const oe=J.name.trim();return oe.length===0?"·":oe.charAt(0).toUpperCase()}function S(J){var fe,Ae,Ye;const oe=J.cover_media;if(oe==null)return null;const De=((fe=oe.urls)==null?void 0:fe.thumb)??((Ae=oe.urls)==null?void 0:Ae.preview)??((Ye=oe.urls)==null?void 0:Ye.original)??null;return typeof De=="string"&&De!==""?De:null}function B(J){return O.value.itemsCount(J.media_count)}const _=e.computed(()=>y.value.map(J=>{const oe=D.albumsById.value.get(J);return oe?{id:J,name:oe.name}:null}).filter(J=>J!==null));function A(J){const oe=[J,...y.value.filter(De=>De!==J)].slice(0,Hu);y.value=oe,r(oe)}const P=e.computed(()=>u.value.sort??"newest"),D=Vl(),z=Mf({httpClient:l.httpClient,onMediaUploaded:()=>{M.value+=1}}),M=e.ref(0);function Z(J){J.length!==0&&z.uploadFiles(J).catch(oe=>{s("error",oe instanceof Error?oe:new Error(String(oe)))})}const O=e.computed(()=>{var J,oe,De,fe,Ae,Ye,st,Bt,Vt,Lt,Pt,zt,Ot,jt,oa,Q,ge,me,se,Ve,Pe,et,gt;return{library:((J=l.labels)==null?void 0:J.library)??((oe=l.labels)==null?void 0:oe.libraryTab)??"Library",libraryTab:((De=l.labels)==null?void 0:De.libraryTab)??((fe=l.labels)==null?void 0:fe.library)??"Library",albums:((Ae=l.labels)==null?void 0:Ae.albums)??((Ye=l.labels)==null?void 0:Ye.albumsTab)??"Albums",albumsTab:((st=l.labels)==null?void 0:st.albumsTab)??((Bt=l.labels)==null?void 0:Bt.albums)??"Albums",trash:((Vt=l.labels)==null?void 0:Vt.trash)??((Lt=l.labels)==null?void 0:Lt.trashTab)??"Trash",trashTab:((Pt=l.labels)==null?void 0:Pt.trashTab)??((zt=l.labels)==null?void 0:zt.trash)??"Trash",allMedia:((Ot=l.labels)==null?void 0:Ot.allMedia)??"All media",unfiled:((jt=l.labels)==null?void 0:jt.unfiled)??"Unfiled",newAlbum:((oa=l.labels)==null?void 0:oa.newAlbum)??"New album",selectionScope:((Q=l.labels)==null?void 0:Q.selectionScope)??"Showing selected items",exitSelectionScope:((ge=l.labels)==null?void 0:ge.exitSelectionScope)??"Exit selection view",findAlbum:((me=l.labels)==null?void 0:me.findAlbum)??"Find album…",noAlbumsYet:((se=l.labels)==null?void 0:se.noAlbumsYet)??"No albums yet — albums are private buckets where you group photos and videos. Create your first one above to start organising your work.",noAlbumMatchesFound:((Ve=l.labels)==null?void 0:Ve.noAlbumMatchesFound)??"No albums match your search.",itemsCount:((Pe=l.labels)==null?void 0:Pe.itemsCount)??(Tt=>`${Tt} ${Tt===1?"item":"items"}`),newAlbumNamePrompt:((et=l.labels)==null?void 0:et.newAlbumNamePrompt)??"Name this album",recentSection:((gt=l.labels)==null?void 0:gt.recentSection)??"Recent albums"}}),K=e.computed(()=>h.value!==null?{scope:"library"}:c.value==="unfiled"?{scope:"unfiled"}:c.value!==null?{scope:"album",albumId:c.value}:{scope:"library"}),de=e.computed(()=>h.value!==null?{...u.value,selected_uuids:[...h.value],unfiled_only:!1}:u.value),Ne=e.computed(()=>{if(c.value===null||c.value==="unfiled")return null;const J=D.albumsById.value.get(c.value);return{uuid:c.value,name:(J==null?void 0:J.name)??"this album"}}),ce=e.computed(()=>d.value==="trash"?"trash":h.value!==null?"selection":Ne.value!==null?"album":"all"),le=e.computed(()=>d.value==="trash"?O.value.trash:h.value!==null?O.value.selectionScope:c.value==="unfiled"?O.value.unfiled:Ne.value!==null?Ne.value.name:O.value.allMedia);function W(J){var oe,De,fe;d.value!==J&&(d.value=J,s("tab-change",J),J==="trash"?(oe=l.routerPush)==null||oe.call(l,"/media/trash"):J==="albums"?(De=l.routerPush)==null||De.call(l,"/media/albums"):(fe=l.routerPush)==null||fe.call(l,"/media"))}function C(J){var oe;be(),c.value=J,d.value="albums",A(J),u.value={...u.value,unfiled_only:!1},s("album-change",J),(oe=l.routerPush)==null||oe.call(l,`/media/album/${encodeURIComponent(J)}`)}function U(){var J;be(),c.value=null,d.value="albums",u.value={...u.value,unfiled_only:!1},s("album-change",null),(J=l.routerPush)==null||J.call(l,"/media/albums")}async function j(J){if(c.value===null||c.value==="unfiled")return;const oe=c.value;try{await D.updateAlbum(oe,{meta:{cover_media_uuid:J.uuid}}),D.fetchAlbums({parent_id:null})}catch(De){s("error",De instanceof Error?De:new Error(String(De)))}}async function re(){if(typeof window>"u")return;const J=window.prompt(O.value.newAlbumNamePrompt);if(J===null)return;const oe=J.trim();if(oe!=="")try{const De=await D.createAlbum({name:oe});De!=null&&C(De.id)}catch(De){s("error",De instanceof Error?De:new Error(String(De)))}}function ue(){return d.value==="trash"?"/media/trash":c.value==="unfiled"?"/media/unfiled":c.value!==null?`/media/album/${encodeURIComponent(c.value)}`:"/media"}function Xe(J){var oe;J.length!==0&&(h.value===null&&(v.value=ue()),h.value=[...J],(oe=l.routerPush)==null||oe.call(l,{path:"/media",query:{view:"selection"}}))}function be(){h.value=null,v.value=null}function Ee(){var oe;const J=v.value;be(),J!==null&&((oe=l.routerPush)==null||oe.call(l,J))}function ye(J){var oe;u.value={...u.value,sort:J},s("filters-change",u.value),(oe=l.routerReplace)==null||oe.call(l,{query:u.value})}function xe(J){k.value=J,n(J)}function Ce(J){var oe;u.value={...u.value,created_after:J.starts_at,created_before:J.ends_at},s("filters-change",u.value),(oe=l.routerReplace)==null||oe.call(l,{query:u.value})}function Re(){var oe;const J={...u.value};delete J.created_after,delete J.created_before,u.value=J,s("filters-change",u.value),(oe=l.routerReplace)==null||oe.call(l,{query:u.value})}const ze=e.computed(()=>u.value.created_after!==void 0||u.value.created_before!==void 0);function rt(J){var oe;u.value={...J,...J.kinds!==void 0?{kinds:[...J.kinds]}:{},...J.selected_uuids!==void 0?{selected_uuids:[...J.selected_uuids]}:{}},s("filters-change",u.value),(oe=l.routerReplace)==null||oe.call(l,{query:u.value})}function at(){of({...l.albumHttpClient!==void 0?{httpClient:l.albumHttpClient}:{},...l.albumBaseUrl!==void 0?{albumBaseUrl:l.albumBaseUrl}:{}})}function Dt(J){J.mediaIds.length!==0&&(p.value=J,f.value=!0)}function ht(){f.value=!1,p.value=null,ut.value=null}async function St(J){const oe=p.value;if(oe===null)return;const De=ut.value;try{await D.attachMedia(J,oe.mediaIds),De!==null&&await Promise.all(oe.mediaIds.map(fe=>D.detachMedia(De,fe))),f.value=!1,p.value=null,ut.value=null,s("add-to-album",oe)}catch(fe){s("error",fe instanceof Error?fe:new Error(String(fe)))}}const ut=e.ref(null);function lt(J){J.mediaIds.length===0||Ne.value===null||(p.value=J,ut.value=Ne.value.uuid,f.value=!0)}async function Ct(J){if(J.mediaIds.length===0||Ne.value===null)return;const oe=Ne.value.uuid;try{await Promise.all(J.mediaIds.map(De=>D.detachMedia(oe,De)))}catch(De){s("error",De instanceof Error?De:new Error(String(De)))}}e.watch(()=>l.initialAlbumId,J=>{c.value=J});function Se(J){J===null||J==="unfiled"||D.albumsById.value.has(J)||D.fetchAlbum(J).catch(oe=>{s("error",oe instanceof Error?oe:new Error(String(oe)))})}return e.watch(()=>c.value,J=>Se(J)),at(),e.onMounted(()=>{Se(c.value),D.fetchAlbums({parent_id:null}).catch(J=>{s("error",J instanceof Error?J:new Error(String(J)))}),typeof window<"u"&&window.addEventListener("keydown",R)}),e.onUnmounted(()=>{typeof window<"u"&&window.removeEventListener("keydown",R)}),e.watch(()=>[l.albumHttpClient,l.albumBaseUrl],()=>at()),(J,oe)=>{var De;return e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["media-library-shell",{"is-density-compact":k.value==="compact"}]),"data-density":k.value,"data-testid":"media-library-shell"},[e.createElementVNode("header",tL,[e.createElementVNode("nav",aL,[e.createElementVNode("button",{type:"button",class:e.normalizeClass({"is-active":d.value==="library"}),"data-testid":"tab-media-library",onClick:oe[0]||(oe[0]=fe=>W("library"))},e.toDisplayString(O.value.library),3),e.createElementVNode("button",{type:"button",class:e.normalizeClass({"is-active":d.value==="albums"}),"data-testid":"tab-media-albums",onClick:oe[1]||(oe[1]=fe=>W("albums"))},e.toDisplayString(O.value.albums),3),e.createElementVNode("button",{type:"button",class:e.normalizeClass({"is-active":d.value==="trash"}),"data-testid":"tab-media-trash",onClick:oe[2]||(oe[2]=fe=>W("trash"))},e.toDisplayString(O.value.trash),3)]),e.createElementVNode("button",{type:"button",class:"media-library-shell__shortcut-trigger","data-testid":"btn-media-shortcuts","aria-label":"Show keyboard shortcuts",onClick:oe[3]||(oe[3]=fe=>w.value=!0)}," ? "),h.value!==null?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-library-shell__exit-selection","data-testid":"btn-media-exit-selection-scope",onClick:Ee},e.toDisplayString(O.value.exitSelectionScope),1)):e.createCommentVNode("",!0)]),d.value!=="trash"&&!V.value?(e.openBlock(),e.createBlock(Bf,{key:0,class:"media-library-shell__toolbar-row",sort:P.value,density:k.value,"has-date-filter":ze.value,"http-client":l.httpClient,"onUpdate:sort":ye,"onUpdate:density":xe,onJumpTo:Ce,onJumpToAll:Re,onUploadFiles:Z},null,8,["sort","density","has-date-filter","http-client"])):e.createCommentVNode("",!0),_.value.length>0&&d.value!=="trash"&&!V.value&&!I.value?(e.openBlock(),e.createElementBlock("nav",{key:1,class:"media-library-shell__recent-albums","data-testid":"media-library-recent-albums","aria-label":O.value.recentSection},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(_.value,fe=>(e.openBlock(),e.createElementBlock("button",{key:fe.id,type:"button",class:"media-library-shell__recent-chip","data-testid":`btn-media-recent-album-${fe.id}`,onClick:Ae=>C(fe.id)},e.toDisplayString(fe.name),9,oL))),128))],8,nL)):e.createCommentVNode("",!0),e.unref(z).uploads.value.length>0&&d.value!=="trash"?(e.openBlock(),e.createElementBlock("div",iL,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(z).uploads.value,fe=>(e.openBlock(),e.createElementBlock("article",{key:fe.cid,class:e.normalizeClass(["media-library-shell__upload-tile",`is-status-${fe.status}`]),"data-testid":`upload-tile-${fe.cid}`},[e.createElementVNode("div",lL,[fe.previewUrl?(e.openBlock(),e.createElementBlock("img",{key:0,src:fe.previewUrl,alt:fe.fileName},null,8,sL)):(e.openBlock(),e.createElementBlock("span",dL,"⤴"))]),e.createElementVNode("div",cL,[e.createElementVNode("span",uL,e.toDisplayString(fe.fileName),1),e.createElementVNode("span",mL,[fe.status==="uploading"||fe.status==="queued"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createTextVNode("Uploading…")],64)):fe.status==="success"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[e.createTextVNode("Uploaded")],64)):(e.openBlock(),e.createElementBlock(e.Fragment,{key:2},[e.createTextVNode(e.toDisplayString(fe.errorMessage??"Upload failed"),1)],64))])]),e.createElementVNode("button",{type:"button",class:"media-library-shell__upload-dismiss","data-testid":`btn-upload-dismiss-${fe.cid}`,onClick:Ae=>e.unref(z).dismiss(fe.cid)}," × ",8,pL)],10,rL))),128))])):e.createCommentVNode("",!0),e.createElementVNode("div",{class:e.normalizeClass(["media-library-shell__body",{"has-inspector-target":m.value!==null}])},[e.createElementVNode("main",fL,[I.value?(e.openBlock(),e.createElementBlock("header",hL,[e.createElementVNode("button",{type:"button",class:"media-library-shell__breadcrumb-back","data-testid":"btn-media-album-back",onClick:U}," ← "+e.toDisplayString(O.value.albums),1),oe[15]||(oe[15]=e.createElementVNode("span",{class:"media-library-shell__breadcrumb-sep","aria-hidden":"true"},"/",-1)),e.createElementVNode("span",vL,e.toDisplayString(x.value),1)])):e.createCommentVNode("",!0),d.value==="trash"?(e.openBlock(),e.createBlock(zf,{key:1,"http-client":l.httpClient,onError:oe[4]||(oe[4]=fe=>s("error",fe))},null,8,["http-client"])):V.value?(e.openBlock(),e.createElementBlock("section",{key:2,class:"media-album-grid","data-testid":"media-album-grid","aria-label":O.value.albums},[e.createElementVNode("header",bL,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":oe[5]||(oe[5]=fe=>g.value=fe),type:"search",class:"media-album-grid__search",placeholder:O.value.findAlbum,"data-testid":"input-media-album-filter","aria-label":O.value.findAlbum},null,8,yL),[[e.vModelText,g.value]])]),e.createElementVNode("div",wL,[e.createElementVNode("button",{type:"button",class:"media-album-grid__new-tile","data-testid":"btn-media-album-new-tile",role:"listitem",onClick:re},[oe[16]||(oe[16]=e.createElementVNode("span",{class:"media-album-grid__new-tile-glyph","aria-hidden":"true"},"+",-1)),e.createElementVNode("span",kL,e.toDisplayString(O.value.newAlbum),1)]),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(T.value,fe=>(e.openBlock(),e.createElementBlock("button",{key:fe.id,type:"button",class:"media-album-grid__tile","data-testid":`media-album-tile-${fe.id}`,role:"listitem",onClick:Ae=>C(fe.id)},[e.createElementVNode("div",EL,[S(fe)!==null?(e.openBlock(),e.createElementBlock("img",{key:0,class:"media-album-grid__cover-image",src:S(fe),alt:"",loading:"lazy"},null,8,SL)):(e.openBlock(),e.createElementBlock("span",CL,e.toDisplayString($(fe)),1))]),e.createElementVNode("div",xL,[e.createElementVNode("span",NL,e.toDisplayString(fe.name),1),e.createElementVNode("span",VL,e.toDisplayString(B(fe)),1)])],8,_L))),128))]),T.value.length===0&&g.value!==""?(e.openBlock(),e.createElementBlock("p",TL,e.toDisplayString(O.value.noAlbumMatchesFound),1)):T.value.length===0?(e.openBlock(),e.createElementBlock("p",BL,e.toDisplayString(O.value.noAlbumsYet),1)):e.createCommentVNode("",!0)],8,gL)):(e.openBlock(),e.createBlock(Uf,{key:`workspace-${M.value}`,"http-client":l.httpClient,filters:de.value,"initial-view":K.value,capabilities:l.capabilities,labels:{scopeLabel:le.value},onFiltersChange:rt,onCreatePost:oe[6]||(oe[6]=fe=>s("create-post",fe)),onCreateGallery:oe[7]||(oe[7]=fe=>s("create-gallery",fe)),onAddToAlbum:Dt,onEdit:oe[8]||(oe[8]=fe=>s("edit",fe)),onDeleted:oe[9]||(oe[9]=fe=>s("deleted",fe)),onRestored:oe[10]||(oe[10]=fe=>s("restored",fe)),onRestoreConflict:oe[11]||(oe[11]=fe=>s("restore-conflict",fe)),onError:oe[12]||(oe[12]=fe=>s("error",fe))},{"bulk-actions":e.withCtx(fe=>[e.createVNode(Rd,{"selected-count":fe.selectedCount,"cross-page-count":fe.crossPageCount,scope:ce.value,"source-album":Ne.value,capabilities:l.capabilities,onClear:fe.clearSelection,onBulkMoveToTrash:fe.onBulkDelete,onBulkAddToAlbum:Ae=>{var Ye;return(Ye=fe.onAddToAlbum)==null?void 0:Ye.call(fe)},onBulkMoveBetweenAlbums:Ae=>lt({mediaIds:fe.selectedItemIds,items:fe.selectedItems,source:"bulk"}),onBulkRemoveFromCurrentAlbum:Ae=>void Ct({mediaIds:fe.selectedItemIds,items:fe.selectedItems,source:"bulk"}),onBulkCreatePost:Ae=>{var Ye;return(Ye=fe.onCreatePost)==null?void 0:Ye.call(fe)},onBulkCreateGallery:Ae=>{var Ye;return(Ye=fe.onCreateGallery)==null?void 0:Ye.call(fe)},onInspect:Ae=>fe.crossPageCount>0?Xe(fe.selectedItemIds):m.value={kind:"multi",count:fe.selectedCount,items:fe.selectedItems}},null,8,["selected-count","cross-page-count","scope","source-album","capabilities","onClear","onBulkMoveToTrash","onBulkAddToAlbum","onBulkMoveBetweenAlbums","onBulkRemoveFromCurrentAlbum","onBulkCreatePost","onBulkCreateGallery","onInspect"])]),_:1},8,["http-client","filters","initial-view","capabilities","labels"]))]),e.createVNode(Tf,{open:f.value,"selected-count":((De=p.value)==null?void 0:De.mediaIds.length)??0,onCancel:ht,onConfirm:St,onError:oe[13]||(oe[13]=fe=>s("error",fe))},null,8,["open","selected-count"]),e.createVNode(Af,{class:"media-library-shell__inspector",target:m.value,"http-client":l.httpClient,capabilities:l.capabilities,"in-album-scope":c.value!==null&&c.value!=="unfiled",onSetAsAlbumCover:j},null,8,["target","http-client","capabilities","in-album-scope"])],2),e.createVNode(If,{open:w.value,onClose:oe[14]||(oe[14]=fe=>w.value=!1)},null,8,["open"])],10,eL)}}}),ML=$e(IL,[["__scopeId","data-v-384bd4f9"]]),$L={class:"album-nav-rail__search"},FL={class:"album-nav-rail__sr-only"},DL=["placeholder"],AL={class:"album-nav-rail__primary","aria-label":"Media scopes"},RL={class:"album-nav-rail__count"},LL={class:"album-nav-rail__count"},PL={key:0,class:"album-nav-rail__recent","data-testid":"album-rail-recent","aria-label":"Recent albums"},UL={class:"album-nav-rail__section-label"},OL=["data-testid","onClick"],zL={class:"album-nav-rail__tree"},jL={class:"album-nav-rail__utility"},WL={class:"album-nav-rail__count"},HL=e.defineComponent({__name:"AlbumNavRail",props:{activeAlbumId:{},collapsed:{type:Boolean,default:!1},allowDragDropTarget:{type:Boolean,default:!1},mediaCounts:{default:()=>({})},labels:{default:()=>({})},recentAlbums:{default:()=>[]}},emits:["change-album","create-album","drop-media","open-trash"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!1),r=e.ref(""),l=e.ref([]),s=e.ref(null),d=e.computed(()=>{var y,w,g,b,R,V;return{allMedia:((y=t.labels)==null?void 0:y.allMedia)??"All media",unfiled:((w=t.labels)==null?void 0:w.unfiled)??"Unfiled",newAlbum:((g=t.labels)==null?void 0:g.newAlbum)??"New album",findAlbum:((b=t.labels)==null?void 0:b.findAlbum)??"Find album...",trash:((R=t.labels)==null?void 0:R.trash)??"Trash",recentSection:((V=t.labels)==null?void 0:V.recentSection)??"Recent"}});function c(y){return typeof y=="number"&&Number.isFinite(y)?String(y):""}function u(y){n("change-album",y.id)}function m(y,w){i.value=!1,n("create-album",w?{name:y,parentId:w}:{name:y})}function p(y){var g;const w=((g=y.dataTransfer)==null?void 0:g.getData("application/x-mediables-media-ids"))??"";if(w.trim()==="")return l.value;try{const b=JSON.parse(w);return Array.isArray(b)?b.filter(R=>typeof R=="string"&&R.trim()!==""):[]}catch{return w.split(",").map(b=>b.trim()).filter(b=>b!=="")}}function f(y,w){t.allowDragDropTarget&&(y.preventDefault(),s.value=w)}function h(){s.value=null}function v(y,w){if(!t.allowDragDropTarget)return;y.preventDefault();const g=p(y);s.value=null,g.length!==0&&n("drop-media",{albumId:w==="all"||w==="unfiled"?null:w,mediaIds:g})}const k=e.computed(()=>({"is-collapsed":t.collapsed}));return(y,w)=>(e.openBlock(),e.createElementBlock("aside",{class:e.normalizeClass(["album-nav-rail",k.value]),"data-testid":"album-rail"},[e.createElementVNode("label",$L,[e.createElementVNode("span",FL,e.toDisplayString(d.value.findAlbum),1),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":w[0]||(w[0]=g=>r.value=g),type:"search",placeholder:d.value.findAlbum,"data-testid":"input-album-rail-search"},null,8,DL),[[e.vModelText,r.value]])]),e.createElementVNode("nav",AL,[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["album-nav-rail__row",{"is-active":t.activeAlbumId===null,"is-drop-target":s.value==="all"}]),"data-testid":"album-rail-row-all",onClick:w[1]||(w[1]=g=>n("change-album",null)),onDragover:w[2]||(w[2]=g=>f(g,"all")),onDragleave:h,onDrop:w[3]||(w[3]=g=>v(g,"all"))},[e.createElementVNode("span",null,e.toDisplayString(d.value.allMedia),1),e.createElementVNode("span",RL,e.toDisplayString(c(t.mediaCounts.all)),1)],34),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["album-nav-rail__row",{"is-active":t.activeAlbumId==="unfiled","is-drop-target":s.value==="unfiled"}]),"data-testid":"album-rail-row-unfiled",onClick:w[4]||(w[4]=g=>n("change-album","unfiled")),onDragover:w[5]||(w[5]=g=>f(g,"unfiled")),onDragleave:h,onDrop:w[6]||(w[6]=g=>v(g,"unfiled"))},[e.createElementVNode("span",null,e.toDisplayString(d.value.unfiled),1),e.createElementVNode("span",LL,e.toDisplayString(c(t.mediaCounts.unfiled)),1)],34)]),t.recentAlbums.length>0?(e.openBlock(),e.createElementBlock("section",PL,[e.createElementVNode("p",UL,e.toDisplayString(d.value.recentSection),1),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.recentAlbums,g=>(e.openBlock(),e.createElementBlock("button",{key:`recent-${g.id}`,type:"button",class:e.normalizeClass(["album-nav-rail__row album-nav-rail__row--recent",{"is-active":t.activeAlbumId===g.id}]),"data-testid":`album-rail-recent-${g.id}`,onClick:b=>n("change-album",g.id)},[e.createElementVNode("span",null,e.toDisplayString(g.name),1)],10,OL))),128))])):e.createCommentVNode("",!0),e.createElementVNode("div",zL,[e.createVNode(Tl,{"model-value":t.activeAlbumId==="unfiled"?null:t.activeAlbumId,mode:"rail",compact:!0,draggable:!1,onAlbumSelected:u},null,8,["model-value"])]),e.createElementVNode("button",{type:"button",class:"album-nav-rail__new","data-testid":"btn-album-rail-new",onClick:w[7]||(w[7]=g=>i.value=!0)}," + "+e.toDisplayString(d.value.newAlbum),1),e.createVNode(Id,{open:i.value,onCancel:w[8]||(w[8]=g=>i.value=!1),onCreate:m},null,8,["open"]),e.createElementVNode("div",jL,[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["album-nav-rail__row album-nav-rail__row--utility",{"is-drop-target":s.value==="trash"}]),"data-testid":"album-rail-row-trash",onClick:w[9]||(w[9]=g=>n("open-trash")),onDragover:w[10]||(w[10]=g=>f(g,"trash")),onDragleave:h,onDrop:w[11]||(w[11]=g=>v(g,"trash"))},[e.createElementVNode("span",null,e.toDisplayString(d.value.trash),1),e.createElementVNode("span",WL,e.toDisplayString(c(t.mediaCounts.trash)),1)],34)])],2))}}),ZL=$e(HL,[["__scopeId","data-v-0913c5b6"]]),GL={key:0,class:"media-selection-tray","data-testid":"media-selection-tray"},XL={class:"media-selection-tray__header"},KL={class:"media-selection-tray__title"},JL={class:"media-selection-tray__items"},qL={class:"media-selection-tray__item-preview"},YL=["src","alt"],QL={key:1,class:"media-selection-tray__file-icon"},eP={class:"media-selection-tray__item-copy"},tP=["aria-label","onClick"],aP=e.defineComponent({__name:"MediaSelectionTray",props:{items:{},selectedCountLabel:{default:"Selected items"},dismissLabel:{default:"Remove"}},emits:["remove"],setup(o,{emit:a}){const t=a;function n(r){var l;return r?r.thumbnail_url??((l=r.conversion_urls)==null?void 0:l.thumb)??r.preview_url??r.original_url??r.url??null:null}function i(r){return r!=null&&r.mime_type?r.mime_type.startsWith("image/"):!1}return(r,l)=>r.items.length>0?(e.openBlock(),e.createElementBlock("section",GL,[e.createElementVNode("header",XL,[e.createElementVNode("h3",KL,e.toDisplayString(r.selectedCountLabel),1)]),e.createElementVNode("div",JL,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.items,s=>{var d,c,u,m;return e.openBlock(),e.createElementBlock("article",{key:s.id,class:"media-selection-tray__item"},[e.createElementVNode("div",qL,[i(s.media)&&n(s.media)?(e.openBlock(),e.createElementBlock("img",{key:0,src:n(s.media),alt:((d=s.media)==null?void 0:d.alt_text)??((c=s.media)==null?void 0:c.file_name)??"Selected media",class:"media-selection-tray__thumb"},null,8,YL)):(e.openBlock(),e.createElementBlock("div",QL,[...l[0]||(l[0]=[e.createElementVNode("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.5"},[e.createElementVNode("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.createElementVNode("polyline",{points:"14 2 14 8 20 8"})],-1)])]))]),e.createElementVNode("div",eP,[e.createElementVNode("strong",null,e.toDisplayString(((u=s.media)==null?void 0:u.file_name)??s.id),1),e.createElementVNode("span",null,e.toDisplayString(s.status),1)]),e.createElementVNode("button",{type:"button",class:"media-selection-tray__remove","aria-label":`${r.dismissLabel} ${((m=s.media)==null?void 0:m.file_name)??s.id}`,onClick:p=>t("remove",s.id)},e.toDisplayString(r.dismissLabel),9,tP)])}),128))])])):e.createCommentVNode("",!0)}}),nP=$e(aP,[["__scopeId","data-v-f2a3d69d"]]);function Ud(o={}){const a=e.ref(!1),t=e.ref(!1),n=e.ref(null),i=e.ref(null),r=e.ref(0),l=e.ref(0),s=e.ref(null),d=e.ref(null),c=e.computed(()=>d.value!==null),u=w=>{if(r.value++,d.value=null,i.value=null,t.value=!1,w!=null&&typeof w=="object"&&!(w instanceof Blob)&&("image"in w||"state"in w||"sessionKey"in w)){const g=w;n.value=g.image??null,s.value=g.state??null,l.value=g.sessionKey??r.value}else n.value=w??null,s.value=null,l.value=r.value;a.value=!0},m=()=>{a.value=!1,n.value=null,i.value=null,d.value=null,t.value=!1,s.value=null},p=async w=>{try{return t.value=!0,i.value=w,o.onSave&&await o.onSave(w),m(),w}catch(g){const b=g;throw d.value=b,o.onError&&o.onError(b),b}finally{t.value=!1}},f=()=>{o.onCancel&&o.onCancel(),m()},h=w=>{d.value=w,o.onError&&o.onError(w)},v=()=>{d.value=null},k=()=>i.value,y=e.computed(()=>a.value&&i.value!==null&&!t.value);return{isOpen:a,isProcessing:t,uploadedImage:n,editedImage:i,sessionKey:l,initialState:s,error:d,hasError:c,hasUnsavedChanges:y,open:u,close:m,handleSave:p,handleCancel:f,handleError:h,clearError:v,getEditedImage:k}}let ds=null;function oP(o){return ds||(ds=Ud(o)),ds}function iP(o){return a=>new Promise((t,n)=>{Ud({...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 Od(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 Ys(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 zd(o){if(o){const t={};o.apiBaseUrl!==void 0&&(t.apiBaseUrl=o.apiBaseUrl),o.isAdmin!==void 0&&(t.isAdmin=o.isAdmin),$o(t)}return{name:"mediables",async upload(t,n){const r=await xa().uploadFile(t,{collection:(n==null?void 0:n.collection)||"default",customProperties:n==null?void 0:n.customProperties});if(!r)throw new Error("Upload failed: No media returned");return{media:r,uuid:r.uuid}},async attach(t,n){await xa().attachMedia(n.modelType,String(n.modelId),[t],n.collection||"images")},async attachMany(t,n){await xa().attachMedia(n.modelType,String(n.modelId),t,n.collection||"images")},async detach(t,n){await xa().detachMedia(n.modelType,String(n.modelId),t,n.collection||"images")},async reorder(t,n){await xa().reorderMedia(t.modelType,String(t.modelId),n,t.collection||"images")},async fetchModelMedia(t){return await xa().fetchModelMedia(t.modelType,String(t.modelId),t.collection||"images")},getUrl(t,n){return xa().getMediaUrl(t,n)},getThumbnailUrl(t){var n,i;return(n=t.conversion_urls)!=null&&n.thumb?t.conversion_urls.thumb:(i=t.conversion_urls)!=null&&i.thumbnail?t.conversion_urls.thumbnail:t.thumbnail_url?t.thumbnail_url:t.original_url||t.url||""},async delete(t){await xa().deleteMedia(t)},async update(t,n){const r=await xa().updateMedia(t,n);if(!r)throw new Error("Update failed: No media returned");return r},configure(t){const n={};t.apiBaseUrl!==void 0&&(n.apiBaseUrl=t.apiBaseUrl),t.isAdmin!==void 0&&(n.isAdmin=t.isAdmin),$o(n)}}}let Mr=null;function rP(){return Mr||(Mr=zd()),Mr}function lP(){Mr=null}const sP={apiBaseUrl:"/media-library-pro"};function wr(){var o;return typeof document>"u"?null:((o=document.querySelector('meta[name="csrf-token"]'))==null?void 0:o.getAttribute("content"))||null}function cs(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 jd(o){const a={...sP,...o};return{name:"spatie",async upload(n,i){const r=new FormData;r.append("file",n),i!=null&&i.collection&&r.append("collection",i.collection),i!=null&&i.customProperties&&r.append("custom_properties",JSON.stringify(i.customProperties));const l={Accept:"application/json",...a.headers},s=a.csrfToken||wr();s&&(l["X-CSRF-TOKEN"]=s);const d={method:"POST",headers:l,body:r,credentials:"include"};i!=null&&i.signal&&(d.signal=i.signal);const c=await fetch(`${a.apiBaseUrl}/uploads`,d);if(!c.ok){const p=await c.json().catch(()=>({message:"Upload failed"}));throw new Error(p.message||`HTTP ${c.status}`)}const u=await c.json(),m=cs(u);return i!=null&&i.onProgress&&i.onProgress(100),{media:m,uuid:u.uuid}},async attach(n,i){},async attachMany(n,i){},async detach(n,i){},async reorder(n,i){},async fetchModelMedia(n){const i={Accept:"application/json",...a.headers},r=a.csrfToken||wr();r&&(i["X-CSRF-TOKEN"]=r);const l=new URLSearchParams;l.append("model_type",n.modelType),l.append("model_id",String(n.modelId)),n.collection&&l.append("collection",n.collection);try{const s=await fetch(`${a.apiBaseUrl}/media?${l}`,{method:"GET",headers:i,credentials:"include"});if(!s.ok)throw new Error(`HTTP ${s.status}`);return(await s.json()).map(cs)}catch{return[]}},getUrl(n,i){var r;if(i){const l=(r=n.conversion_urls)==null?void 0:r[i];if(l)return l}return n.original_url||n.url||""},getThumbnailUrl(n){var i,r;return n.preview_url?n.preview_url:(i=n.conversion_urls)!=null&&i.preview?n.conversion_urls.preview:n.thumbnail_url?n.thumbnail_url:(r=n.conversion_urls)!=null&&r.thumb?n.conversion_urls.thumb:n.original_url||n.url||""},async delete(n){const i={Accept:"application/json",...a.headers},r=a.csrfToken||wr();r&&(i["X-CSRF-TOKEN"]=r);const l=await fetch(`${a.apiBaseUrl}/uploads/${n}`,{method:"DELETE",headers:i,credentials:"include"});if(!l.ok){const s=await l.json().catch(()=>({message:"Delete failed"}));throw new Error(s.message||`HTTP ${l.status}`)}},async update(n,i){const r={Accept:"application/json","Content-Type":"application/json",...a.headers},l=a.csrfToken||wr();l&&(r["X-CSRF-TOKEN"]=l);const s=await fetch(`${a.apiBaseUrl}/uploads/${n}`,{method:"PATCH",headers:r,body:JSON.stringify(i),credentials:"include"});if(!s.ok){const c=await s.json().catch(()=>({message:"Update failed"}));throw new Error(c.message||`HTTP ${s.status}`)}const d=await s.json();return cs(d)},configure(n){Object.assign(a,n)}}}let $r=null;function dP(){return $r||($r=jd()),$r}function cP(){$r=null}function jf(o,a){switch(o){case"mediables":return zd(a);case"spatie":return jd(a);default:throw new Error(`Unknown adapter: ${o}`)}}function Wf(o={}){const{enabled:a=!0,onReorder:t,onDragStart:n,onDragEnd:i,draggingClass:r="is-dragging",dropTargetClass:l="is-drop-target"}=o,s=e.ref({isDragging:!1,dragIndex:null,dropIndex:null,draggedItem:null}),d=e.ref(!1);let c=null;function u(w,g,b){a&&("dataTransfer"in w&&w.dataTransfer&&(w.dataTransfer.effectAllowed="move",w.dataTransfer.setData("text/plain",String(b))),c=w.target,c&&c.classList.add(r),s.value={isDragging:!0,dragIndex:b,dropIndex:b,draggedItem:g},d.value=!0,n==null||n(g,b))}function m(w,g){var b;if(!(!a||!s.value.isDragging)&&(w.preventDefault(),s.value.dropIndex!==g)){const R=document.querySelector(`.${l}`);R==null||R.classList.remove(l);const V=(b=w.target)==null?void 0:b.closest("[data-index]");V==null||V.classList.add(l),s.value.dropIndex=g}}function p(){if(!s.value.isDragging)return;const{dragIndex:w,dropIndex:g,draggedItem:b}=s.value;c&&c.classList.remove(r);const R=document.querySelector(`.${l}`);R==null||R.classList.remove(l),w!==null&&g!==null&&w!==g&&b&&(t==null||t({fromIndex:w,toIndex:g,item:b})),h(),i==null||i()}function f(){c&&c.classList.remove(r);const w=document.querySelector(`.${l}`);w==null||w.classList.remove(l),h(),i==null||i()}function h(){s.value={isDragging:!1,dragIndex:null,dropIndex:null,draggedItem:null},d.value=!1,c=null}function v(w,g,b){const R=[...w],[V]=R.splice(g,1);return R.splice(b,0,V),R.map((I,x)=>({...I,order:x}))}function k(w,g){return{draggable:a,"data-index":g,onDragstart:b=>u(b,w,g),onDragover:b=>m(b,g),onDragend:()=>p(),onDrop:b=>{b.preventDefault(),p()}}}function y(w){w.key==="Escape"&&s.value.isDragging&&f()}return e.onMounted(()=>{document.addEventListener("keydown",y)}),e.onUnmounted(()=>{document.removeEventListener("keydown",y),f()}),{dragState:s,isDragging:d,startDrag:u,handleDragOver:m,endDrag:p,cancelDrag:f,reorderItems:v,getDragProps:k}}function Bl(o={}){const{initialItems:a=[],modelType:t,modelId:n,collection:i="images",maxItems:r,maxFileSize:l,acceptedMimeTypes:s,sortable:d=!0,disabled:c=!1,rules:u={},adapterType:m="mediables",adapter:p,maxConcurrentUploads:f=3,onChange:h,onUpload:v,onUploadComplete:k,onUploadError:y,onRemove:w,onReorder:g,onError:b,onReadyToSubmitChange:R}=o,V={maxItems:r,maxFileSize:l,acceptedMimeTypes:s,...u},I=p||jf(m),x=e.ref([]),T=e.ref(!1),$=e.ref([]);function S(ye){if(ye.length===0)return[];const xe=ye[0];return"media"in xe&&"clientId"in xe?ye:Ys(ye)}x.value=S(a);const{acceptString:B,canAddFiles:_}=Fd({rules:V}),A=Dd({adapter:I,maxConcurrent:f,rules:V,collection:i,onUploadStart:ye=>{v==null||v(ye)},onUploadComplete:(ye,xe)=>{const Ce=x.value.findIndex(Re=>Re.clientId===ye.id);Ce!==-1&&(x.value[Ce]={...x.value[Ce],media:xe,name:xe.name||xe.file_name,upload:{...ye,status:"completed"}}),k==null||k(xe)},onUploadError:(ye,xe)=>{const Ce=x.value.findIndex(Re=>Re.clientId===ye.id);Ce!==-1&&(x.value[Ce]={...x.value[Ce],upload:{...ye,status:"error",error:xe.message},errors:[{field:"upload",message:xe.message,code:"UPLOAD_ERROR"}]}),y==null||y({file:ye.file,message:xe.message})},onQueueComplete:()=>{h==null||h(x.value)}}),{dragState:P,getDragProps:D,reorderItems:z}=Wf({enabled:d&&!c,onReorder:ye=>{x.value=z(x.value,ye.fromIndex,ye.toIndex),g==null||g(x.value),h==null||h(x.value)}}),M=e.computed(()=>A.isUploading.value),Z=e.computed(()=>!A.isUploading.value&&A.pendingCount.value===0),O=e.computed(()=>r?x.value.length>=r:!1),K=e.computed(()=>Od(x.value)),de=e.computed(()=>x.value.length),Ne=e.computed(()=>r?Math.max(0,r-x.value.length):1/0);e.watch(Z,ye=>{R==null||R(ye)});function ce(ye){x.value=S(ye),h==null||h(x.value)}async function le(ye){if(c)return;const xe=Array.from(ye);if(!_(xe.length,x.value.length)){const rt={field:"count",message:`Maximum ${r} files allowed`,code:"MAX_ITEMS"};$.value=[rt],b==null||b([rt]);return}const Ce=await A.addFiles(xe),Re=x.value.length,ze=Ce.map((rt,at)=>({...rt,order:Re+at}));x.value=[...x.value,...ze],h==null||h(x.value)}function W(ye){c||(ye.upload&&(ye.upload.status==="uploading"||ye.upload.status==="pending")&&A.cancelUpload(ye.clientId),x.value=x.value.filter(xe=>xe.clientId!==ye.clientId),x.value=x.value.map((xe,Ce)=>({...xe,order:Ce})),w==null||w(ye),h==null||h(x.value))}function C(ye){const xe=x.value.find(Ce=>Ce.clientId===ye);xe&&W(xe)}function U(){c||(A.clearAll(),x.value=[],h==null||h(x.value))}function j(ye,xe){c||!d||(x.value=z(x.value,ye,xe),g==null||g(x.value),h==null||h(x.value))}function re(ye,xe){if(c)return;const Ce=x.value.findIndex(Re=>Re.clientId===ye);Ce!==-1&&(x.value[Ce]={...x.value[Ce],...xe},h==null||h(x.value))}function ue(ye){A.cancelUpload(ye),C(ye)}async function Xe(ye){await A.retryUpload(ye)}async function be(){if(!t||!n)throw new Error("modelType and modelId are required for save()");const ye={modelType:t,modelId:n,collection:i},xe=x.value.filter(Ce=>Ce.media&&!Ce.markedForRemoval).map(Ce=>Ce.media.uuid);T.value=!0;try{await I.attachMany(xe,ye),await I.reorder(ye,xe)}finally{T.value=!1}}async function Ee(){if(!t||!n)throw new Error("modelType and modelId are required for load()");const ye={modelType:t,modelId:n,collection:i};T.value=!0;try{const xe=await I.fetchModelMedia(ye);x.value=Ys(xe),h==null||h(x.value)}finally{T.value=!1}}return e.onMounted(()=>{t&&n&&a.length===0&&Ee().catch(console.error)}),e.onUnmounted(()=>{A.clearAll()}),{items:x,setItems:ce,addFiles:le,removeItem:W,removeItemById:C,clearAll:U,reorderItems:j,updateItem:re,cancelUpload:ue,retryUpload:Xe,save:be,load:Ee,isLoading:T,isUploading:M,isReadyToSubmit:Z,isAtMaxItems:O,errors:$,dragState:P,getDragProps:D,adapter:I,formValues:K,acceptString:B,count:de,remainingSlots:Ne}}const uP=["aria-disabled"],mP=["accept","multiple","disabled"],pP={class:"media-dropzone__content"},fP={class:"media-dropzone__title"},hP={class:"media-dropzone__subtitle"},vP=["disabled"],gP={key:0,class:"media-dropzone__helper"},bP=e.defineComponent({__name:"MediaCollectionDropzone",props:{accept:{default:"*"},multiple:{type:Boolean,default:!0},disabled:{type:Boolean,default:!1},maxFileSize:{},maxItems:{},title:{default:"Drop files here"},subtitle:{default:"or click to browse"},buttonText:{default:"Select files"}},emits:["files"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!1),r=e.ref(null),l=e.computed(()=>({"media-dropzone":!0,"media-dropzone--drag-over":i.value,"media-dropzone--disabled":t.disabled})),s=e.computed(()=>{const v=[];return t.maxFileSize&&v.push(`Max size: ${Yr(t.maxFileSize)}`),t.maxItems&&t.maxItems>1&&v.push(`Max files: ${t.maxItems}`),v.join(" • ")});function d(v){v.preventDefault(),!t.disabled&&(i.value=!0)}function c(v){v.preventDefault(),i.value=!1}function u(v){v.preventDefault()}function m(v){var y;if(v.preventDefault(),i.value=!1,t.disabled)return;const k=(y=v.dataTransfer)==null?void 0:y.files;k&&k.length>0&&n("files",k)}function p(){var v;t.disabled||(v=r.value)==null||v.click()}function f(v){const k=v.target,y=k.files;y&&y.length>0&&n("files",y),k.value=""}function h(v){(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),p())}return(v,k)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(l.value),role:"button",tabindex:"0","aria-disabled":v.disabled,"aria-label":"Upload files",onClick:p,onKeydown:h,onDragenter:d,onDragleave:c,onDragover:u,onDrop:m},[e.createElementVNode("input",{ref_key:"fileInput",ref:r,type:"file",accept:v.accept,multiple:v.multiple,disabled:v.disabled,class:"media-dropzone__input",onChange:f},null,40,mP),e.createElementVNode("div",pP,[e.renderSlot(v.$slots,"icon",{},()=>[k[0]||(k[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",fP,[e.renderSlot(v.$slots,"title",{},()=>[e.createTextVNode(e.toDisplayString(v.title),1)],!0)]),e.createElementVNode("p",hP,[e.renderSlot(v.$slots,"subtitle",{},()=>[e.createTextVNode(e.toDisplayString(v.subtitle),1)],!0)]),e.createElementVNode("button",{type:"button",class:"media-dropzone__button",disabled:v.disabled,onClick:e.withModifiers(p,["stop"])},[e.renderSlot(v.$slots,"button",{},()=>[e.createTextVNode(e.toDisplayString(v.buttonText),1)],!0)],8,vP),s.value?(e.openBlock(),e.createElementBlock("p",gP,e.toDisplayString(s.value),1)):e.createCommentVNode("",!0)])],42,uP))}}),Wd=$e(bP,[["__scopeId","data-v-b1366c1e"]]),yP=["data-index"],wP={key:0,class:"media-item__drag-handle","aria-label":"Drag to reorder",role:"button",tabindex:"0"},kP={class:"media-item__thumbnail"},_P=["src","alt"],EP={key:1,class:"media-item__file-icon"},SP={key:2,class:"media-item__progress-overlay"},CP={class:"media-item__progress-text"},xP={key:3,class:"media-item__processing-overlay"},NP={key:4,class:"media-item__error-overlay"},VP={class:"media-item__info"},TP=["title"],BP={key:0,class:"media-item__size"},IP={key:1,class:"media-item__error-message"},MP={class:"media-item__actions"},$P=["disabled"],FP=["disabled"],DP=["disabled"],AP=["disabled"],RP=e.defineComponent({__name:"MediaCollectionItem",props:{item:{},adapter:{},disabled:{type:Boolean,default:!1},sortable:{type:Boolean,default:!1},showRemove:{type:Boolean,default:!0},showEdit:{type:Boolean,default:!1},index:{default:0}},emits:["remove","edit","retry","cancel"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!1),r=e.computed(()=>{var g;return(g=t.item.upload)!=null&&g.previewUrl?t.item.upload.previewUrl:t.item.media?t.adapter.getThumbnailUrl(t.item.media):null}),l=e.computed(()=>{var g,b,R;return((g=t.item.upload)==null?void 0:g.status)==="uploading"||((b=t.item.upload)==null?void 0:b.status)==="pending"||((R=t.item.upload)==null?void 0:R.status)==="queued"}),s=e.computed(()=>{var g;return((g=t.item.upload)==null?void 0:g.status)==="processing"}),d=e.computed(()=>{var g;return((g=t.item.upload)==null?void 0:g.status)==="error"||t.item.errors&&t.item.errors.length>0}),c=e.computed(()=>{var g;return(g=t.item.upload)!=null&&g.error?t.item.upload.error:t.item.errors&&t.item.errors.length>0?t.item.errors[0].message:null}),u=e.computed(()=>{var g;return((g=t.item.upload)==null?void 0:g.progress)||0}),m=e.computed(()=>{var g;return t.item.name||((g=t.item.media)==null?void 0:g.file_name)||"Unknown file"}),p=e.computed(()=>{var I,x;const g=((I=t.item.media)==null?void 0:I.size)||((x=t.item.upload)==null?void 0:x.file.size);if(!g)return"";const b=1024,R=["Bytes","KB","MB","GB"],V=Math.floor(Math.log(g)/Math.log(b));return parseFloat((g/Math.pow(b,V)).toFixed(2))+" "+R[V]}),f=e.computed(()=>{var b,R;const g=((b=t.item.media)==null?void 0:b.mime_type)||((R=t.item.upload)==null?void 0:R.file.type);return g==null?void 0:g.startsWith("image/")}),h=e.computed(()=>({"media-item":!0,"media-item--uploading":l.value,"media-item--processing":s.value,"media-item--error":d.value,"media-item--disabled":t.disabled,"media-item--sortable":t.sortable}));function v(){t.disabled||n("remove",t.item)}function k(){t.disabled||n("edit",t.item)}function y(){t.disabled||n("retry",t.item)}function w(){t.disabled||n("cancel",t.item)}return(g,b)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(h.value),"data-index":g.index,onMouseenter:b[0]||(b[0]=R=>i.value=!0),onMouseleave:b[1]||(b[1]=R=>i.value=!1)},[g.sortable&&!g.disabled?(e.openBlock(),e.createElementBlock("div",wP,[...b[2]||(b[2]=[e.createStaticVNode('<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" data-v-ff81c9ec><circle cx="9" cy="5" r="1" data-v-ff81c9ec></circle><circle cx="9" cy="12" r="1" data-v-ff81c9ec></circle><circle cx="9" cy="19" r="1" data-v-ff81c9ec></circle><circle cx="15" cy="5" r="1" data-v-ff81c9ec></circle><circle cx="15" cy="12" r="1" data-v-ff81c9ec></circle><circle cx="15" cy="19" r="1" data-v-ff81c9ec></circle></svg>',1)])])):e.createCommentVNode("",!0),e.createElementVNode("div",kP,[r.value&&f.value?(e.openBlock(),e.createElementBlock("img",{key:0,src:r.value,alt:m.value,class:"media-item__image"},null,8,_P)):(e.openBlock(),e.createElementBlock("div",EP,[...b[3]||(b[3]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.createElementVNode("polyline",{points:"14 2 14 8 20 8"})],-1)])])),l.value?(e.openBlock(),e.createElementBlock("div",SP,[e.createElementVNode("div",{class:"media-item__progress-bar",style:e.normalizeStyle({width:`${u.value}%`})},null,4),e.createElementVNode("span",CP,e.toDisplayString(u.value)+"%",1)])):e.createCommentVNode("",!0),s.value?(e.openBlock(),e.createElementBlock("div",xP,[...b[4]||(b[4]=[e.createElementVNode("div",{class:"media-item__spinner","aria-label":"Processing"},null,-1)])])):e.createCommentVNode("",!0),d.value?(e.openBlock(),e.createElementBlock("div",NP,[...b[5]||(b[5]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("circle",{cx:"12",cy:"12",r:"10"}),e.createElementVNode("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),e.createElementVNode("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})],-1)])])):e.createCommentVNode("",!0)]),e.createElementVNode("div",VP,[e.createElementVNode("span",{class:"media-item__name",title:m.value},e.toDisplayString(m.value),9,TP),p.value?(e.openBlock(),e.createElementBlock("span",BP,e.toDisplayString(p.value),1)):e.createCommentVNode("",!0),c.value?(e.openBlock(),e.createElementBlock("span",IP,e.toDisplayString(c.value),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",MP,[l.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-item__action media-item__action--cancel",disabled:g.disabled,"aria-label":"Cancel upload",onClick:w},[...b[6]||(b[6]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.createElementVNode("line",{x1:"6",y1:"6",x2:"18",y2:"18"})],-1)])],8,$P)):e.createCommentVNode("",!0),d.value?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button",class:"media-item__action media-item__action--retry",disabled:g.disabled,"aria-label":"Retry upload",onClick:y},[...b[7]||(b[7]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("polyline",{points:"23 4 23 10 17 10"}),e.createElementVNode("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})],-1)])],8,FP)):e.createCommentVNode("",!0),g.showEdit&&g.item.media&&!l.value?(e.openBlock(),e.createElementBlock("button",{key:2,type:"button",class:"media-item__action media-item__action--edit",disabled:g.disabled,"aria-label":"Edit",onClick:k},[...b[8]||(b[8]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),e.createElementVNode("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})],-1)])],8,DP)):e.createCommentVNode("",!0),g.showRemove?(e.openBlock(),e.createElementBlock("button",{key:3,type:"button",class:"media-item__action media-item__action--remove",disabled:g.disabled,"aria-label":"Remove",onClick:v},[...b[9]||(b[9]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("polyline",{points:"3 6 5 6 21 6"}),e.createElementVNode("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})],-1)])],8,AP)):e.createCommentVNode("",!0)])],42,yP))}}),Hd=$e(RP,[["__scopeId","data-v-ff81c9ec"]]),LP=["aria-label"],PP=["draggable","data-index","onDragstart","onDragover","onDragend","onDrop"],UP={key:0,class:"media-collection__footer"},OP={class:"media-collection__count"},zP={key:0},jP={key:0,class:"media-collection__uploading"},WP=["name","value"],HP=["name","value"],ZP=["name","value"],GP=["name","value"],XP={key:3,class:"media-collection__errors",role:"alert","aria-live":"polite"},KP=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:M=>{n("update:modelValue",M),n("change",M)},onUpload:M=>{n("upload",M)},onUploadComplete:M=>{n("upload-complete",M)},onUploadError:M=>{n("upload-error",M)},onRemove:M=>{n("remove",M)},onReorder:M=>{n("reorder",M)},onError:M=>{n("validation-error",M)},onReadyToSubmitChange:M=>{n("is-ready-to-submit-change",M)}},{items:r,setItems:l,addFiles:s,removeItem:d,reorderItems:c,cancelUpload:u,retryUpload:m,isLoading:p,isUploading:f,isAtMaxItems:h,errors:v,dragState:k,getDragProps:y,adapter:w,formValues:g,acceptString:b,count:R,remainingSlots:V}=Bl(i);e.provide("mediaAdapter",w),e.provide("mediaCollection",{items:r,addFiles:s,removeItem:d,reorderItems:c}),e.watch(()=>t.modelValue,M=>{M!==r.value&&l(M)},{deep:!0});const I=e.computed(()=>t.showUploadZone&&!t.disabled&&!t.readonly&&!h.value),x=e.computed(()=>({"media-collection":!0,"media-collection--disabled":t.disabled,"media-collection--readonly":t.readonly,"media-collection--loading":p.value,"media-collection--has-items":r.value.length>0,"media-collection--dragging":k.value.isDragging}));function T(M){s(M)}function $(M){d(M)}function S(M){m(M.clientId)}function B(M){u(M.clientId)}function _(M){}function A(M,Z,O){if(!t.sortable||t.disabled)return;const K=y(Z,O);K.onDragstart&&K.onDragstart(M)}function P(M,Z){if(!t.sortable||t.disabled)return;M.preventDefault();const O=r.value[Z],K=y(O,Z);K.onDragover&&K.onDragover(M)}function D(M,Z){const O=y(M,Z);O.onDragend&&O.onDragend()}function z(M,Z){M.preventDefault();const O=r.value[Z],K=y(O,Z);K.onDrop&&K.onDrop(M)}return(M,Z)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(x.value)},[e.renderSlot(M.$slots,"dropzone",{addFiles:e.unref(s)},()=>[I.value?(e.openBlock(),e.createBlock(Wd,{key:0,accept:e.unref(b),multiple:M.maxItems!==1,disabled:M.disabled,"max-file-size":M.maxFileSize,"max-items":e.unref(V),onFiles:T},null,8,["accept","multiple","disabled","max-file-size","max-items"])):e.createCommentVNode("",!0)],!0),e.unref(r).length>0?(e.openBlock(),e.createElementBlock("div",{key:0,class:"media-collection__list",role:"list","aria-label":`${e.unref(R)} media items`},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(r),(O,K)=>e.renderSlot(M.$slots,"item",{key:O.clientId,item:O,index:K,remove:()=>$(O)},()=>[e.createElementVNode("div",{class:e.normalizeClass(["media-collection__item-wrapper",{"media-collection__item-wrapper--drag-over":e.unref(k).dropIndex===K}]),draggable:M.sortable&&!M.disabled,"data-index":K,onDragstart:de=>A(de,O,K),onDragover:de=>P(de,K),onDragend:de=>D(O,K),onDrop:de=>z(de,K)},[e.createVNode(Hd,{item:O,adapter:e.unref(w),disabled:M.disabled,sortable:M.sortable,"show-remove":!M.readonly,"show-edit":!1,index:K,onRemove:$,onRetry:S,onCancel:B,onEdit:_},null,8,["item","adapter","disabled","sortable","show-remove","index"])],42,PP)],!0)),128))],8,LP)):I.value?e.createCommentVNode("",!0):e.renderSlot(M.$slots,"empty",{key:1},()=>[Z[0]||(Z[0]=e.createElementVNode("div",{class:"media-collection__empty"},[e.createElementVNode("p",null,"No files uploaded")],-1))],!0),e.renderSlot(M.$slots,"footer",{count:e.unref(R),isUploading:e.unref(f)},()=>[e.unref(r).length>0?(e.openBlock(),e.createElementBlock("div",UP,[e.createElementVNode("span",OP,[e.createTextVNode(e.toDisplayString(e.unref(R))+" "+e.toDisplayString(e.unref(R)===1?"file":"files")+" ",1),M.maxItems?(e.openBlock(),e.createElementBlock("span",zP," / "+e.toDisplayString(M.maxItems)+" max",1)):e.createCommentVNode("",!0)]),e.unref(f)?(e.openBlock(),e.createElementBlock("span",jP," Uploading... ")):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)],!0),M.generateFormFields?(e.openBlock(),e.createElementBlock(e.Fragment,{key:2},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(g),(O,K)=>(e.openBlock(),e.createElementBlock("input",{key:`${M.name}-${O.uuid}`,type:"hidden",name:`${M.name}[${K}][uuid]`,value:O.uuid},null,8,WP))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(g),(O,K)=>(e.openBlock(),e.createElementBlock("input",{key:`${M.name}-${O.uuid}-name`,type:"hidden",name:`${M.name}[${K}][name]`,value:O.name},null,8,HP))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(g),(O,K)=>(e.openBlock(),e.createElementBlock("input",{key:`${M.name}-${O.uuid}-order`,type:"hidden",name:`${M.name}[${K}][order]`,value:O.order},null,8,ZP))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(g),(O,K)=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:`${M.name}-${O.uuid}-props`},[O.custom_properties?(e.openBlock(),e.createElementBlock("input",{key:0,type:"hidden",name:`${M.name}[${K}][custom_properties]`,value:JSON.stringify(O.custom_properties)},null,8,GP)):e.createCommentVNode("",!0)],64))),128))],64)):e.createCommentVNode("",!0),e.unref(v).length>0?(e.openBlock(),e.createElementBlock("div",XP,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(v),O=>(e.openBlock(),e.createElementBlock("p",{key:O.code||O.message,class:"media-collection__error"},e.toDisplayString(O.message),1))),128))])):e.createCommentVNode("",!0)],2))}}),JP=$e(KP,[["__scopeId","data-v-10a5bfff"]]);function Zd(o={}){const{initialItem:a,onChange:t,onReplace:n,onUpload:i,onUploadComplete:r,onUploadError:l,onRemove:s,onError:d,onReadyToSubmitChange:c,...u}=o,p={...u,initialItems:a?[a]:[],maxItems:1,sortable:!1,onChange:I=>{t==null||t(I[0]||null)},onUpload:i,onUploadComplete:r,onUploadError:l,onRemove:s,onError:d,onReadyToSubmitChange:c},f=Bl(p),h=e.computed(()=>f.items.value[0]||null),v=e.computed(()=>h.value!==null),k=e.computed(()=>f.formValues.value[0]||null);function y(I){I===null?f.clearAll():f.setItems([I])}async function w(I){const x=h.value;x&&f.removeItem(x),await f.addFiles([I])}function g(){h.value&&f.removeItem(h.value)}async function b(I){const x=h.value;x&&f.removeItem(x),await f.addFiles([I]);const T=f.items.value[0];T&&(n==null||n(x,T))}function R(){var I;(I=h.value)!=null&&I.upload&&f.cancelUpload(h.value.clientId)}async function V(){var I,x;((x=(I=h.value)==null?void 0:I.upload)==null?void 0:x.status)==="error"&&await f.retryUpload(h.value.clientId)}return{item:h,setItem:y,addFile:w,removeItem:g,replaceItem:b,cancelUpload:R,retryUpload:V,save:f.save,load:f.load,isLoading:f.isLoading,isUploading:f.isUploading,isReadyToSubmit:f.isReadyToSubmit,hasItem:v,errors:f.errors,adapter:f.adapter,formValue:k,acceptString:f.acceptString}}const qP=["accept","disabled"],YP={class:"media-attachment__preview"},QP=["name","value"],eU=["name","value"],tU=["name","value"],aU=["name","value"],nU={key:4,class:"media-attachment__errors",role:"alert","aria-live":"polite"},oU=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:S=>{n("update:modelValue",S),n("change",S)},onUpload:S=>{n("upload",S)},onUploadComplete:S=>{n("upload-complete",S)},onUploadError:S=>{n("upload-error",S)},onRemove:S=>{n("remove",S)},onReplace:(S,B)=>{n("replace",B)},onError:S=>{n("validation-error",S)},onReadyToSubmitChange:S=>{n("is-ready-to-submit-change",S)}},{item:l,setItem:s,addFile:d,removeItem:c,replaceItem:u,cancelUpload:m,retryUpload:p,isLoading:f,hasItem:h,errors:v,adapter:k,formValue:y,acceptString:w}=Zd(r);e.provide("mediaAdapter",k),e.watch(()=>t.modelValue,S=>{S!==l.value&&s(S)},{deep:!0});const g=e.computed(()=>t.showUploadZone&&!t.disabled&&!t.readonly&&!h.value),b=e.computed(()=>({"media-attachment":!0,"media-attachment--disabled":t.disabled,"media-attachment--readonly":t.readonly,"media-attachment--loading":f.value,"media-attachment--has-item":h.value}));function R(S){S.length>0&&d(S[0])}function V(){var S;(S=i.value)==null||S.click()}function I(S){const B=S.target,_=B.files;_&&_.length>0&&u(_[0]),B.value=""}function x(S){c()}function T(S){p()}function $(S){m()}return(S,B)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(b.value)},[e.createElementVNode("input",{ref_key:"fileInputRef",ref:i,type:"file",accept:e.unref(w),disabled:S.disabled,class:"media-attachment__hidden-input",onChange:I},null,40,qP),g.value?e.renderSlot(S.$slots,"dropzone",{key:0,addFile:e.unref(d)},()=>[e.createVNode(Wd,{accept:e.unref(w),multiple:!1,disabled:S.disabled,"max-file-size":S.maxFileSize,onFiles:R},null,8,["accept","disabled","max-file-size"])],!0):e.unref(h)&&e.unref(l)?e.renderSlot(S.$slots,"preview",{key:1,item:e.unref(l),remove:e.unref(c),replace:V},()=>[e.createElementVNode("div",YP,[e.createVNode(Hd,{item:e.unref(l),adapter:e.unref(k),disabled:S.disabled,sortable:!1,"show-remove":!S.readonly,"show-edit":!1,onRemove:x,onRetry:T,onCancel:$},null,8,["item","adapter","disabled","show-remove"]),S.showReplaceButton&&!S.readonly&&!S.disabled&&e.unref(l).media?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-attachment__replace-button",onClick:V},[...B[0]||(B[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(S.$slots,"empty",{key:2},()=>[B[1]||(B[1]=e.createElementVNode("div",{class:"media-attachment__empty"},[e.createElementVNode("p",null,"No file selected")],-1))],!0),S.generateFormFields&&e.unref(y)?(e.openBlock(),e.createElementBlock(e.Fragment,{key:3},[e.createElementVNode("input",{type:"hidden",name:`${S.name}[uuid]`,value:e.unref(y).uuid},null,8,QP),e.createElementVNode("input",{type:"hidden",name:`${S.name}[name]`,value:e.unref(y).name},null,8,eU),e.createElementVNode("input",{type:"hidden",name:`${S.name}[order]`,value:e.unref(y).order},null,8,tU),e.unref(y).custom_properties?(e.openBlock(),e.createElementBlock("input",{key:0,type:"hidden",name:`${S.name}[custom_properties]`,value:JSON.stringify(e.unref(y).custom_properties)},null,8,aU)):e.createCommentVNode("",!0)],64)):e.createCommentVNode("",!0),e.unref(v).length>0?(e.openBlock(),e.createElementBlock("div",nU,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(v),_=>(e.openBlock(),e.createElementBlock("p",{key:_.code||_.message,class:"media-attachment__error"},e.toDisplayString(_.message),1))),128))])):e.createCommentVNode("",!0)],2))}}),iU=$e(oU,[["__scopeId","data-v-26911174"]]),Hf={dropzone:{title:"Drop files here",subtitle:"or click to browse",button:"Select files"},item:{remove:"Remove",replace:"Replace",edit:"Edit",download:"Download"},errors:{maxItems:"Maximum {max} files allowed",maxFileSize:"File exceeds maximum size of {max}",invalidType:"File type not allowed",uploadFailed:"Upload failed"},status:{uploading:"Uploading...",processing:"Processing...",completed:"Complete",error:"Error"}},rU=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:S=>{i("update:modelValue",S),i("change",S)},onUpload:S=>{i("upload",S)},onUploadComplete:S=>{i("upload-complete",S)},onUploadError:S=>{i("upload-error",S)},onRemove:S=>{i("remove",S)},onReorder:S=>{i("reorder",S)},onError:S=>{i("validation-error",S)},onReadyToSubmitChange:S=>{i("is-ready-to-submit-change",S)}},{items:l,setItems:s,addFiles:d,removeItem:c,reorderItems:u,updateItem:m,cancelUpload:p,retryUpload:f,isLoading:h,isUploading:v,isReadyToSubmit:k,isAtMaxItems:y,errors:w,dragState:g,getDragProps:b,adapter:R,formValues:V,acceptString:I}=Bl(r);e.provide("mediaAdapter",R),e.provide("mediaCollection",{items:l,addFiles:d,removeItem:c,reorderItems:u}),e.watch(()=>n.modelValue,S=>{S!==l.value&&s(S)},{deep:!0});const x=e.computed(()=>({...Hf,...n.labels})),T=e.computed(()=>({accept:I.value,multiple:n.maxItems!==1,disabled:n.disabled||n.readonly||y.value})),$=e.computed(()=>({items:l.value,isLoading:h.value,isUploading:v.value,isReadyToSubmit:k.value,isAtMaxItems:y.value,errors:w.value,addFiles:d,removeItem:c,reorderItems:u,clearAll:()=>{l.value.forEach(S=>c(S))},cancelUpload:p,retryUpload:f,labels:x.value,dropzoneProps:T.value}));return a({items:l,addFiles:d,removeItem:c,reorderItems:u,updateItem:m,cancelUpload:p,retryUpload:f,isLoading:h,isUploading:v,isReadyToSubmit:k,isAtMaxItems:y,errors:w,dragState:g,getDragProps:b,adapter:R,formValues:V,acceptString:I}),(S,B)=>e.renderSlot(S.$slots,"default",e.normalizeProps(e.guardReactiveProps($.value)))}}),lU=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:x=>{i("update:modelValue",x),i("change",x)},onUpload:x=>{i("upload",x)},onUploadComplete:x=>{i("upload-complete",x)},onUploadError:x=>{i("upload-error",x)},onRemove:x=>{i("remove",x)},onReplace:(x,T)=>{i("replace",T)},onError:x=>{i("validation-error",x)},onReadyToSubmitChange:x=>{i("is-ready-to-submit-change",x)}},{item:l,setItem:s,addFile:d,removeItem:c,replaceItem:u,cancelUpload:m,retryUpload:p,isLoading:f,isUploading:h,isReadyToSubmit:v,hasItem:k,errors:y,adapter:w,formValue:g,acceptString:b}=Zd(r);e.provide("mediaAdapter",w),e.watch(()=>n.modelValue,x=>{x!==l.value&&s(x)},{deep:!0});const R=e.computed(()=>({...Hf,...n.labels})),V=e.computed(()=>({accept:b.value,multiple:!1,disabled:n.disabled||n.readonly||k.value})),I=e.computed(()=>({item:l.value,hasItem:k.value,isLoading:f.value,isUploading:h.value,isReadyToSubmit:v.value,errors:y.value,addFile:d,removeItem:c,replaceItem:u,cancelUpload:m,retryUpload:p,labels:R.value,dropzoneProps:V.value}));return a({item:l,setItem:s,addFile:d,removeItem:c,replaceItem:u,cancelUpload:m,retryUpload:p,isLoading:f,isUploading:h,isReadyToSubmit:v,hasItem:k,errors:y,adapter:w,formValue:g,acceptString:b}),(x,T)=>e.renderSlot(x.$slots,"default",e.normalizeProps(e.guardReactiveProps(I.value)))}}),sU=["name","value"],dU=["name","value"],cU=["name","value"],uU=["name","value"],mU=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(()=>Od(t.value));function i(s,d){var u;const c=((u=n.value[s])==null?void 0:u.uuid)||"";return`${a.name}[${c}][${d}]`}function r(s,d){return`${a.name}[${s}][${d}]`}function l(s,d){return a.format==="spatie"?i(s,d):r(s,d)}return(s,d)=>(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.value,(c,u)=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:c.uuid},[e.createElementVNode("input",{type:"hidden",name:l(u,"uuid"),value:c.uuid},null,8,sU),e.createElementVNode("input",{type:"hidden",name:l(u,"name"),value:c.name},null,8,dU),e.createElementVNode("input",{type:"hidden",name:l(u,"order"),value:c.order},null,8,cU),c.custom_properties&&Object.keys(c.custom_properties).length>0?(e.openBlock(),e.createElementBlock("input",{key:0,type:"hidden",name:l(u,"custom_properties"),value:JSON.stringify(c.custom_properties)},null,8,uU)):e.createCommentVNode("",!0)],64))),128))}}),pU=["data-testid"],fU=["data-testid"],hU=["id"],vU=["value","maxlength","disabled","aria-labelledby","placeholder","data-testid","onInput"],gU=e.defineComponent({__name:"MediaAttachmentMetadataFields",props:{items:{},disabled:{type:Boolean,default:!1},label:{default:"Caption"},placeholder:{default:"Add an optional caption"},maxLength:{default:500},testIdPrefix:{default:"media-attachment-metadata"},getItemLabel:{type:Function,default:(o,a)=>`${o.type==="video"?"video":"photo"} ${a+1}`}},emits:["update:items"],setup(o,{emit:a}){const t=o,n=a;function i(r,l){const s=l.target;s instanceof HTMLInputElement&&n("update:items",t.items.map((d,c)=>c!==r?d:{...d,caption:s.value===""?null:s.value}))}return(r,l)=>r.items.length>0?(e.openBlock(),e.createElementBlock("div",{key:0,class:"media-attachment-metadata-fields","data-testid":r.testIdPrefix},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.items,(s,d)=>(e.openBlock(),e.createElementBlock("div",{key:s._key??s.id??`${s.url}:${d}`,class:"media-attachment-metadata-fields__row","data-testid":`${r.testIdPrefix}-${d}`},[e.createElementVNode("p",{id:`${r.testIdPrefix}-label-${d}`,class:"media-attachment-metadata-fields__label"},e.toDisplayString(r.label)+" for "+e.toDisplayString(r.getItemLabel(s,d)),9,hU),e.createElementVNode("input",{value:s.caption??"",type:"text",class:"media-attachment-metadata-fields__input",maxlength:r.maxLength,disabled:r.disabled,"aria-labelledby":`${r.testIdPrefix}-label-${d}`,placeholder:r.placeholder,"data-testid":`input-${r.testIdPrefix}-${d}`,onInput:c=>i(d,c)},null,40,vU)],8,fU))),128))],8,pU)):e.createCommentVNode("",!0)}}),bU=$e(gU,[["__scopeId","data-v-a153768a"]]);exports.AlbumBrowser=lf;exports.AlbumManager=Z5;exports.AlbumMediaGrid=oF;exports.AlbumNavRail=ZL;exports.AlbumTree=Tl;exports.ArrayBufferTarget=ld;exports.ExistingMediaSelector=kb;exports.ImageEditor=nm;exports.ImageEditorModal=om;exports.LiveStreamManager=s5;exports.ManagedMediaGallery=Yh;exports.MediaAlbumInlineCreate=Id;exports.MediaAlbumPickerModal=Tf;exports.MediaAlbumUnavailableState=sf;exports.MediaAttachment=iU;exports.MediaAttachmentMetadataFields=bU;exports.MediaBulkActionBar=Rd;exports.MediaCollection=JP;exports.MediaCollectionDropzone=Wd;exports.MediaCollectionItem=Hd;exports.MediaEmptyState=Of;exports.MediaFilterChips=Rf;exports.MediaInspectorPanel=Af;exports.MediaLibraryPicker=Vf;exports.MediaLibraryPickerModal=M6;exports.MediaLibraryShell=ML;exports.MediaLibraryToolbar=Bf;exports.MediaLibraryWorkspace=Uf;exports.MediaManagementView=Pf;exports.MediaPreviewSheet=Md;exports.MediaSelectionTray=nP;exports.MediaShortcutHelp=If;exports.MediaSourceSheet=hf;exports.MediaThumbnailCell=gf;exports.MediaTrashWorkspace=zf;exports.MediaUploadSheet=vf;exports.MediaUsageList=$f;exports.MediaVariantStrip=Ff;exports.MediaWorkspace=Xh;exports.ModelMediaManager=jg;exports.Muxer=Nm;exports.RequiresConfirmationError=Ld;exports.VideoEditor=Qp;exports.VideoEditorDialog=H4;exports.VideoEditorSimple=hI;exports.VideoExportPanel=XM;exports.VideoJobClient=Cl;exports.VideoPlayer=nf;exports.VideoTimeline=PI;exports.VideoToolsPanel=VM;exports.VideoUploader=D3;exports.VirtualMediaGrid=bf;exports._sfc_main=rU;exports._sfc_main$1=lU;exports._sfc_main$2=mU;exports.applyTemporaryMediaStoreConfig=Ku;exports.configureAlbumStore=of;exports.configureMediaStore=$o;exports.createAdapter=jf;exports.createEmptyEditorState=yh;exports.createImageEditor=iP;exports.createMediablesAdapter=zd;exports.createSpatieAdapter=jd;exports.deserializeEditorState=bh;exports.formatFileSize=Yr;exports.fromMediaArray=Ys;exports.getFileExtension=yf;exports.getImageDimensions=wf;exports.getMediablesAdapter=rP;exports.getSpatieAdapter=dP;exports.isImageFile=$d;exports.normalizeEditorState=Qs;exports.normalizeRecipeForServerRender=x4;exports.recipeHasServerRenderableEdits=C4;exports.recipeHasUnsupportedServerEdits=af;exports.resetMediablesAdapter=lP;exports.resetSpatieAdapter=cP;exports.restoreAlbumStoreConfig=b5;exports.restoreMediaStoreConfig=Xu;exports.serializeEditorState=Zu;exports.snapshotAlbumStoreConfig=g5;exports.snapshotMediaStoreConfig=Gu;exports.toFormValues=Od;exports.useAdminMediaStore=Ju;exports.useAlbumDragDrop=rf;exports.useAlbumStore=Nl;exports.useAlbums=Vl;exports.useGlobalImageEditor=oP;exports.useImageEditorModal=Ud;exports.useMediaAttachment=Zd;exports.useMediaCollection=Bl;exports.useMediaDeletion=Lf;exports.useMediaDragSort=Wf;exports.useMediaLibraryPickerController=Nf;exports.useMediaLibraryQuery=Ad;exports.useMediaLibrarySession=Ef;exports.useMediaLibraryStateMachine=Sf;exports.useMediaLibraryTelemetry=Cf;exports.useMediaLibraryUploads=Mf;exports.useMediaSelection=tl;exports.useMediaStore=xa;exports.useMediaTrash=Pd;exports.useMediaUploadQueue=Dd;exports.useMediaValidation=Fd;exports.validateFile=kf;
357
- //# sourceMappingURL=index-BFrh53TT.cjs.map