@xiboplayer/pwa 0.6.2 → 0.6.4

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 (53) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/{chunk-config-BjXWw-V8.js → chunk-config-DCe-ux-i.js} +2 -2
  3. package/dist/assets/chunk-config-DCe-ux-i.js.map +1 -0
  4. package/dist/assets/{index-FG4fTI4i.js → index-BPWLt2qA.js} +2 -2
  5. package/dist/assets/{index-FG4fTI4i.js.map → index-BPWLt2qA.js.map} +1 -1
  6. package/dist/assets/{index-D4fqdfS-.js → index-C62BLuTi.js} +2 -2
  7. package/dist/assets/{index-D4fqdfS-.js.map → index-C62BLuTi.js.map} +1 -1
  8. package/dist/assets/index-CDj_ep7K.js +2 -0
  9. package/dist/assets/index-CDj_ep7K.js.map +1 -0
  10. package/dist/assets/index-CtXCdqID.js +2 -0
  11. package/dist/assets/{index-DnB9w-Dv.js.map → index-CtXCdqID.js.map} +1 -1
  12. package/dist/assets/index-DBqUu6yb.js +13 -0
  13. package/dist/assets/index-DBqUu6yb.js.map +1 -0
  14. package/dist/assets/{index-so_tPJrr.js → index-DRSaAd9B.js} +2 -2
  15. package/dist/assets/{index-so_tPJrr.js.map → index-DRSaAd9B.js.map} +1 -1
  16. package/dist/assets/index-DU3hjIga.js +2 -0
  17. package/dist/assets/{index-IEsktHaW.js.map → index-DU3hjIga.js.map} +1 -1
  18. package/dist/assets/{index-C0mqgU51.js → index-DyruL5Od.js} +2 -2
  19. package/dist/assets/{index-C0mqgU51.js.map → index-DyruL5Od.js.map} +1 -1
  20. package/dist/assets/{index-D9EQ-6Wd.js → index-_oCyqKl9.js} +2 -2
  21. package/dist/assets/{index-D9EQ-6Wd.js.map → index-_oCyqKl9.js.map} +1 -1
  22. package/dist/assets/index-aoZD2owd.js +5 -0
  23. package/dist/assets/index-aoZD2owd.js.map +1 -0
  24. package/dist/assets/main-D42peItG.js +735 -0
  25. package/dist/assets/main-D42peItG.js.map +1 -0
  26. package/dist/assets/protocol-detector-u7TXbwOq.js +16 -0
  27. package/dist/assets/protocol-detector-u7TXbwOq.js.map +1 -0
  28. package/dist/assets/setup-CxBZtuWA.js +2 -0
  29. package/dist/assets/{setup-BXLaipeI.js.map → setup-CxBZtuWA.js.map} +1 -1
  30. package/dist/assets/sync-manager-Cm51QXsO.js +2 -0
  31. package/dist/assets/sync-manager-Cm51QXsO.js.map +1 -0
  32. package/dist/assets/{widget-html-D6xqg8Sp.js → widget-html-qp4CLuTC.js} +2 -2
  33. package/dist/assets/{widget-html-D6xqg8Sp.js.map → widget-html-qp4CLuTC.js.map} +1 -1
  34. package/dist/index.html +19 -9
  35. package/dist/setup.html +3 -3
  36. package/dist/sw-pwa.js +1 -1
  37. package/package.json +13 -13
  38. package/dist/assets/chunk-config-BjXWw-V8.js.map +0 -1
  39. package/dist/assets/index-BglkPErZ.js +0 -5
  40. package/dist/assets/index-BglkPErZ.js.map +0 -1
  41. package/dist/assets/index-BwkVsox3.js +0 -2
  42. package/dist/assets/index-BwkVsox3.js.map +0 -1
  43. package/dist/assets/index-CwIMcVP6.js +0 -13
  44. package/dist/assets/index-CwIMcVP6.js.map +0 -1
  45. package/dist/assets/index-DnB9w-Dv.js +0 -2
  46. package/dist/assets/index-IEsktHaW.js +0 -2
  47. package/dist/assets/main-DJYbit7N.js +0 -729
  48. package/dist/assets/main-DJYbit7N.js.map +0 -1
  49. package/dist/assets/setup-BXLaipeI.js +0 -2
  50. package/dist/assets/sync-manager-DMpg8tED.js +0 -2
  51. package/dist/assets/sync-manager-DMpg8tED.js.map +0 -1
  52. package/dist/assets/xmds-client-D6JI3K3_.js +0 -16
  53. package/dist/assets/xmds-client-D6JI3K3_.js.map +0 -1
@@ -0,0 +1,735 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-_oCyqKl9.js","./chunk-config-DCe-ux-i.js","./index-aoZD2owd.js","./index-BPWLt2qA.js","./widget-html-qp4CLuTC.js","./index-CDj_ep7K.js","./protocol-detector-u7TXbwOq.js","./index-CtXCdqID.js","./modulepreload-polyfill-B5Qt9EMX.js","./index-DyruL5Od.js","./index-DBqUu6yb.js","./index-C62BLuTi.js","./index-DRSaAd9B.js","./index-DU3hjIga.js","./sync-manager-Cm51QXsO.js"])))=>i.map(i=>d[i]);
2
+ var Ee=Object.defineProperty;var Re=(y,e,t)=>e in y?Ee(y,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):y[e]=t;var L=(y,e,t)=>Re(y,typeof e!="symbol"?e+"":e,t);import"./modulepreload-polyfill-B5Qt9EMX.js";import{createLogger as H,PLAYER_API as B,EventEmitter as Ae,fetchWithRetry as Oe,applyCmsLogLevel as Pe,config as Fe,registerLogSink as ce}from"./index-aoZD2owd.js";import{c as We,C as Ne,D as qe,L as se,B as de,S as Be}from"./widget-html-qp4CLuTC.js";const He="modulepreload",Ue=function(y,e){return new URL(y,e).href},ue={},F=function(e,t,i){let n=Promise.resolve();if(t&&t.length>0){const s=document.getElementsByTagName("link"),r=document.querySelector("meta[property=csp-nonce]"),a=(r==null?void 0:r.nonce)||(r==null?void 0:r.getAttribute("nonce"));n=Promise.allSettled(t.map(l=>{if(l=Ue(l,i),l in ue)return;ue[l]=!0;const c=l.endsWith(".css"),d=c?'[rel="stylesheet"]':"";if(!!i)for(let p=s.length-1;p>=0;p--){const w=s[p];if(w.href===l&&(!c||w.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${l}"]${d}`))return;const g=document.createElement("link");if(g.rel=c?"stylesheet":He,c||(g.as="script"),g.crossOrigin="",g.href=l,a&&g.setAttribute("nonce",a),document.head.appendChild(g),c)return new Promise((p,w)=>{g.addEventListener("load",p),g.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(s){const r=new Event("vite:preloadError",{cancelable:!0});if(r.payload=s,window.dispatchEvent(r),!r.defaultPrevented)throw s}return n.then(s=>{for(const r of s||[])r.status==="rejected"&&o(r.reason);return e().catch(o)})};let ze=()=>({emit(y,...e){for(let t=this.events[y]||[],i=0,n=t.length;i<n;i++)t[i](...e)},events:{},on(y,e){var t;return((t=this.events)[y]||(t[y]=[])).push(e),()=>{var i;this.events[y]=(i=this.events[y])==null?void 0:i.filter(n=>e!==n)}}});const ne=H("schedule:criteria"),je=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],he={weatherTemp:"temperature",weatherHumidity:"humidity",weatherWindSpeed:"windSpeed",weatherCondition:"condition",weatherCloudCover:"cloudCover"};function Ke(y,e,t={},i={}){switch(y){case"dayOfWeek":return je[e.getDay()];case"dayOfMonth":return String(e.getDate());case"month":return String(e.getMonth()+1);case"hour":return String(e.getHours());case"isoDay":return String(e.getDay()===0?7:e.getDay());default:if(he[y]){const n=he[y];return i[n]!==void 0?String(i[n]):(ne.debug(`Weather metric "${y}" requested but no weather data available`),null)}return t[y]!==void 0?String(t[y]):(ne.debug(`Unknown metric: ${y}`),null)}}function Ve(y,e,t,i){if(y===null)return!1;if(i==="number"){const s=parseFloat(y),r=parseFloat(t);if(isNaN(s)||isNaN(r))return!1;switch(e){case"equals":return s===r;case"notEquals":return s!==r;case"greaterThan":return s>r;case"greaterThanOrEquals":return s>=r;case"lessThan":return s<r;case"lessThanOrEquals":return s<=r;default:return!1}}const n=y.toLowerCase(),o=t.toLowerCase();switch(e){case"equals":return n===o;case"notEquals":return n!==o;case"contains":return n.includes(o);case"notContains":return!n.includes(o);case"startsWith":return n.startsWith(o);case"endsWith":return n.endsWith(o);case"in":return o.split(",").map(s=>s.trim().toLowerCase()).includes(n);case"greaterThan":return n>o;case"lessThan":return n<o;default:return ne.debug(`Unknown condition: ${e}`),!1}}function ae(y,e={}){if(!y||y.length===0)return!0;const t=e.now||new Date,i=e.displayProperties||{},n=e.weatherData||{};for(const o of y){const s=Ke(o.metric,t,i,n);if(!Ve(s,o.condition,o.value,o.type))return ne.debug(`Criteria failed: ${o.metric} ${o.condition} "${o.value}" (actual: "${s}")`),!1}return!0}function le(y,e=null){const i=new DOMParser().parseFromString(y,"text/xml").querySelector("layout");if(!i)return{duration:60,isDynamic:!1};const n=parseInt(i.getAttribute("duration")||"0",10);if(n>0)return{duration:n,isDynamic:!1};let o=0,s=!1;for(const a of i.querySelectorAll("region")){const l=a.getAttribute("type");if(l==="drawer")continue;const c=l==="canvas";let d=0;for(const h of a.querySelectorAll("media")){const g=parseInt(h.getAttribute("duration")||"0",10),p=parseInt(h.getAttribute("useDuration")||"1",10),w=h.getAttribute("fileId")||"",m=e==null?void 0:e.get(w);let v;m!==void 0?v=m:g>0&&p!==0?v=g:(v=60,s=!0),c?d=Math.max(d,v):d+=v}o=Math.max(o,d)}return{duration:o>0?o:60,isDynamic:s}}function Xe(y,e){if(y.length!==e.length)return!1;for(let t=0;t<y.length;t++)if(y[t]!==e[t])return!1;return!0}function Ge(y,e,t){if(!e||e===0)return!0;const i=t-36e5,n=y.filter(o=>o>i);if(n.length>=e)return!1;if(n.length>0){const o=36e5/e,s=Math.max(...n);if(t-s<o)return!1}return!0}function ge(y,e,t){const i=y.filter(o=>{if(!o.maxPlaysPerHour||o.maxPlaysPerHour===0)return!0;const s=e.get(o.file)||[];return Ge(s,o.maxPlaysPerHour,t)});if(i.length===0)return[];const n=Math.max(...i.map(o=>o.priority));return i.filter(o=>o.priority===n).map(o=>o.file)}function Je(y,e,t={}){const i=t.from||new Date,n=t.hours||2,o=new Date(i.getTime()+n*36e5);t.currentLayoutStartedAt;const s=t.defaultLayout||null,r=t.durations||null;if(!y||y.length===0)return[];const a=[];let l=new Date(i),c=e%y.length;const d=500;for(;l<o&&a.length<d;){const h=y[c];let g=r&&r.get(h.layoutId)||h.duration;const p=l.getTime()+g*1e3;a.push({layoutFile:h.layoutId,startTime:new Date(l),endTime:new Date(p),duration:g,isDefault:s?h.layoutId===s:!1}),l=new Date(p),c=(c+1)%y.length}return a}function Qe(y,e){for(y=Math.abs(Math.round(y)),e=Math.abs(Math.round(e));e;)[y,e]=[e,y%e];return y}function Ye(y,e){return y===0||e===0?0:Math.abs(Math.round(y)*Math.round(e))/Qe(y,e)}function Ze(y){return y.reduce((e,t)=>Ye(e,t),1)}function et(y,e,t={}){const{defaultLayout:i=null,defaultDuration:n=60}=t;if(y.length===0&&!i)return{queue:[],periodSeconds:0};const o=y.filter(h=>h.maxPlaysPerHour>0);let s;if(o.length>0){const h=o.map(g=>Math.round(3600/g.maxPlaysPerHour));s=Ze(h),s>7200&&(s=7200)}else s=y.reduce((g,p)=>g+(e.get(p.file)||n),0)+(i&&!y.some(g=>g.file===i)?e.get(i)||n:0)||n;const r=[],a=new Map;let l=0;const c=s*1e3,d=500;for(;l<c&&r.length<d;){const h=ge(y,a,l);if(h.length===0){if(i){const g=e.get(i)||n;r.push({layoutId:i,duration:g}),l+=g*1e3}else l+=6e4;continue}for(let g=0;g<h.length&&l<c&&r.length<d;g++){const p=h[g],w=e.get(p)||n;r.push({layoutId:p,duration:w}),a.has(p)||a.set(p,[]),a.get(p).push(l),l+=w*1e3;const m=ge(y,a,l);if(!Xe(h,m))break}}if(r.length===0&&i){const h=e.get(i)||n;r.push({layoutId:i,duration:h})}return{queue:r,periodSeconds:s}}const q=H("Schedule");class tt{constructor(e={}){this.schedule=null,this.playHistory=new Map,this.interruptScheduler=e.interruptScheduler||null,this.displayProperties=e.displayProperties||{},this.weatherData={},this.playerLocation=null,this._layoutMetadata=new Map,this._scheduleQueue=null,this._queuePosition=0,this._queueLayoutSet=null}setSchedule(e){this.schedule=e,this._invalidateQueue()}setWeatherData(e){this.weatherData=e||{}}getDataConnectors(){var e;return((e=this.schedule)==null?void 0:e.dataConnectors)||[]}getDependantsMap(){const e=new Map;if(!this.schedule)return e;const t=this.schedule.dependants||[],i=n=>{const o=parseInt(String(n.file||n.id).replace(".xlf",""),10),s=[...t,...n.dependants||[]];s.length>0&&e.set(o,s)};if(this.schedule.layouts)for(const n of this.schedule.layouts)i(n);if(this.schedule.campaigns)for(const n of this.schedule.campaigns)for(const o of n.layouts)i(o);return e}isRecurringScheduleActive(e,t){if(!e.recurrenceType)return!0;if(e.recurrenceRange){const i=new Date(e.recurrenceRange);if(t>i)return!1}switch(e.recurrenceType){case"Week":{if(e.recurrenceRepeatsOn){const i=this.getIsoDayOfWeek(t);if(!e.recurrenceRepeatsOn.split(",").map(o=>parseInt(o.trim())).includes(i))return!1}return!0}case"Day":{const i=e.recurrenceDetail||1;if(i>1&&e.fromdt){const n=new Date(e.fromdt),o=t.getTime()-n.getTime(),s=Math.floor(o/864e5);if(s<0||s%i!==0)return!1}return!0}case"Month":{if(e.recurrenceRepeatsOn){const n=e.recurrenceRepeatsOn.split(",").map(s=>parseInt(s.trim())),o=t.getDate();if(!n.includes(o))return!1}const i=e.recurrenceDetail||1;if(i>1&&e.fromdt){const n=new Date(e.fromdt),o=(t.getFullYear()-n.getFullYear())*12+t.getMonth()-n.getMonth();if(o<0||o%i!==0)return!1}return!0}default:return q.debug(`Unsupported recurrence type: ${e.recurrenceType}`),!0}}getIsoDayOfWeek(e){const t=e.getDay();return t===0?7:t}isTimeActive(e,t){const i=e.fromdt?new Date(e.fromdt):null,n=e.todt?new Date(e.todt):null;if(e.recurrenceType==="Week"||e.recurrenceType==="Day"||e.recurrenceType==="Month"){if(i&&n){const o=t.getHours()*3600+t.getMinutes()*60+t.getSeconds(),s=i.getHours()*3600+i.getMinutes()*60+i.getSeconds(),r=n.getHours()*3600+n.getMinutes()*60+n.getSeconds();return s<=r?o>=s&&o<=r:o>=s||o<=r}return!0}return!(i&&t<i||n&&t>n)}getCurrentLayouts(){return this._getLayoutsAt(new Date)}getLayoutsAtTime(e){return this._getLayoutsAt(e,{skipRateLimiting:!0,skipInterrupts:!0,quiet:!0})}getAllLayoutsAtTime(e){if(!this.schedule)return[];const t=e,i=[];if(this.schedule.layouts)for(const n of this.schedule.layouts)this.isRecurringScheduleActive(n,t)&&this.isTimeActive(n,t)&&(n.criteria&&n.criteria.length>0&&!ae(n.criteria,{now:t,displayProperties:this.displayProperties,weatherData:this.weatherData})||n.isGeoAware&&n.geoLocation&&!this.isWithinGeoFence(n.geoLocation)||i.push({file:n.file,priority:n.priority||0,maxPlaysPerHour:n.maxPlaysPerHour||0}));if(this.schedule.campaigns){for(const n of this.schedule.campaigns)if(this.isRecurringScheduleActive(n,t)&&this.isTimeActive(n,t))for(const o of n.layouts)i.push({file:o.file,priority:n.priority||0,maxPlaysPerHour:o.maxPlaysPerHour||0})}return i}detectConflicts(e={}){const t=e.from||new Date,i=e.hours||24,n=new Date(t.getTime()+i*36e5),o=6e4,s=[];let r=null;for(let a=t.getTime();a<n.getTime();a+=o){const l=new Date(a),c=this.getAllLayoutsAtTime(l);if(c.length===0){r&&(s.push(r),r=null);continue}const d=Math.max(...c.map(m=>m.priority)),h=c.filter(m=>m.priority<d);if(h.length===0){r&&(s.push(r),r=null);continue}const g=c.filter(m=>m.priority===d),p=g.map(m=>m.file).sort().join(","),w=h.map(m=>`${m.file}:${m.priority}`).sort().join(",");r&&r._winnerKey===p&&r._hiddenKey===w?r.endTime=new Date(a+o):(r&&s.push(r),r={startTime:new Date(a),endTime:new Date(a+o),winner:{file:g[0].file,priority:d},hidden:h.map(m=>({file:m.file,priority:m.priority})),_winnerKey:p,_hiddenKey:w})}r&&s.push(r);for(const a of s)delete a._winnerKey,delete a._hiddenKey;return s}_getLayoutsAt(e,t={}){if(!this.schedule)return[];const{skipRateLimiting:i=!1,skipInterrupts:n=!1,quiet:o=!1}=t,s=o?()=>{}:(...d)=>q.info(...d),r=[];if(this._maxActivePriority=0,this.schedule.campaigns)for(const d of this.schedule.campaigns)this.isRecurringScheduleActive(d,e)&&this.isTimeActive(d,e)&&(this._maxActivePriority=Math.max(this._maxActivePriority,d.priority||0),r.push({type:"campaign",priority:d.priority,layouts:d.layouts,campaignId:d.id}));if(this.schedule.layouts){for(const d of this.schedule.layouts)if(this.isRecurringScheduleActive(d,e)&&this.isTimeActive(d,e)){if(d.criteria&&d.criteria.length>0&&!ae(d.criteria,{now:e,displayProperties:this.displayProperties,weatherData:this.weatherData})){s("[Schedule] Layout",d.id,"filtered by criteria");continue}if(d.isGeoAware&&d.geoLocation&&!this.isWithinGeoFence(d.geoLocation)){s("[Schedule] Layout",d.id,"filtered by geofence");continue}if(this._maxActivePriority=Math.max(this._maxActivePriority,d.priority||0),!i&&!this.canPlayLayout(d.id,d.maxPlaysPerHour)){s("[Schedule] Layout",d.id,"filtered by maxPlaysPerHour (limit:",d.maxPlaysPerHour,")");continue}r.push({type:"layout",priority:d.priority||0,layouts:[d],layoutId:d.id})}}if(r.length===0)return this.schedule.default?[this.schedule.default]:[];let a=Math.max(...r.map(d=>d.priority));s("[Schedule] Max priority:",a,"from",r.length,"active items");let l=[];for(const d of r)d.priority===a?(s("[Schedule] Including priority",d.priority,"layouts:",d.layouts.map(h=>h.file)),l.push(...d.layouts)):s("[Schedule] Skipping priority",d.priority,"< max",a);this._layoutMetadata.clear();for(const d of l)this._layoutMetadata.set(d.file,{syncEvent:d.syncEvent||!1,shareOfVoice:d.shareOfVoice||0,scheduleid:d.scheduleid,priority:d.priority||0});if(!n&&this.interruptScheduler){const{normalLayouts:d,interruptLayouts:h}=this.interruptScheduler.separateLayouts(l);if(h.length>0){s("[Schedule] Found",h.length,"interrupt layouts with shareOfVoice");const p=this.interruptScheduler.processInterrupts(d,h).map(w=>w.file);return s("[Schedule] Final layouts (with interrupts):",p),p}}const c=l.map(d=>d.file);return s("[Schedule] Final layouts:",c),c}shouldCheckSchedule(e){return e?Date.now()-e>=6e4:!0}canPlayLayout(e,t){if(!t||t===0)return!0;const i=Date.now(),n=i-60*60*1e3,s=(this.playHistory.get(e)||[]).filter(r=>r>n);if(s.length>=t)return q.info(`Layout ${e} has reached max plays per hour (${s.length}/${t})`),!1;if(s.length>0){const r=36e5/t,a=Math.max(...s),l=i-a;if(l<r){const c=((r-l)/6e4).toFixed(1);return q.info(`Layout ${e} spacing: next play in ${c} min (${s.length}/${t} plays, ${Math.round(r/6e4)} min gap)`),!1}}return!0}recordPlay(e){this.playHistory.has(e)||this.playHistory.set(e,[]);const t=this.playHistory.get(e);t.push(Date.now());const i=Date.now()-60*60*1e3,n=t.filter(o=>o>i);this.playHistory.set(e,n),q.info(`Recorded play for layout ${e} (${n.length} plays in last hour)`)}getMaxActivePriority(){return this._maxActivePriority||0}isSyncEvent(e){const t=this._layoutMetadata.get(e);return(t==null?void 0:t.syncEvent)===!0}getLayoutMetadata(e){return this._layoutMetadata.get(e)||null}getScheduleQueue(e,t={}){var r;const i=this.getAllLayoutsAtTime(new Date),n=i.map(a=>`${a.file}:${a.priority}:${a.maxPlaysPerHour}`).sort().join("|");if(this._scheduleQueue&&this._queueLayoutSet===n)return this._scheduleQueue;const o=et(i,e,{defaultLayout:((r=this.schedule)==null?void 0:r.default)||null,defaultDuration:60,dynamicLayouts:t.dynamicLayouts||new Set}),s=this._queueLayoutSet;return this._scheduleQueue=o,this._queueLayoutSet=n,s!==n&&(this._queuePosition=0),o.queue.length>0&&(q.info(`[Schedule] Built queue: ${o.queue.length} entries, period ${o.periodSeconds}s (pos ${this._queuePosition})`),q.info(`[Schedule] Queue: ${o.queue.map(a=>`${a.layoutId}(${a.duration}s)`).join(" → ")}`)),o}popNextFromQueue(e,t={}){const{queue:i}=this.getScheduleQueue(e,t);if(i.length===0)return null;const n=i[this._queuePosition%i.length];return this._queuePosition=(this._queuePosition+1)%i.length,n}peekNextInQueue(e,t={}){const{queue:i}=this.getScheduleQueue(e,t);return i.length===0?null:i[this._queuePosition%i.length]}peekAfterNext(e,t={}){const{queue:i}=this.getScheduleQueue(e,t);return i.length<=1?null:i[(this._queuePosition+1)%i.length]}_invalidateQueue(){this._scheduleQueue=null}hasSyncEvents(){for(const e of this._layoutMetadata.values())if(e.syncEvent)return!0;return!1}getActiveActions(){var t;if(!((t=this.schedule)!=null&&t.actions))return[];const e=new Date;return this.schedule.actions.filter(i=>this.isTimeActive(i,e))}getCommands(){var e;return((e=this.schedule)==null?void 0:e.commands)||[]}findActionByTrigger(e){return this.getActiveActions().find(i=>i.triggerCode===e)||null}clearPlayHistory(){this.playHistory.clear(),q.info("Play history cleared")}setLocation(e,t){this.playerLocation={latitude:e,longitude:t},q.info(`Location set: ${e}, ${t}`)}setDisplayProperties(e){this.displayProperties=e||{}}isWithinGeoFence(e,t=500){if(!this.playerLocation)return q.debug("No player location, skipping geofence check"),!0;if(!e)return!0;const i=e.split(",").map(l=>parseFloat(l.trim()));if(i.length<2||isNaN(i[0])||isNaN(i[1]))return q.warn("Invalid geoLocation format:",e),!0;const n=i[0],o=i[1],s=i[2]||t,r=this.haversineDistance(this.playerLocation.latitude,this.playerLocation.longitude,n,o),a=r<=s;return q.info(`Geofence: ${r.toFixed(0)}m from (${n},${o}), radius ${s}m → ${a?"WITHIN":"OUTSIDE"}`),a}haversineDistance(e,t,i,n){const s=c=>c*Math.PI/180,r=s(i-e),a=s(n-t),l=Math.sin(r/2)**2+Math.cos(s(e))*Math.cos(s(i))*Math.sin(a/2)**2;return 6371e3*2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l))}}const yt=new tt,U=H("schedule:interrupts");class pt{constructor(){this.interruptCommittedDurations=new Map}isInterrupt(e){return!!(e.shareOfVoice&&e.shareOfVoice>0)}resetCommittedDurations(){this.interruptCommittedDurations.clear(),U.debug("Reset interrupt committed durations")}getCommittedDuration(e){return this.interruptCommittedDurations.get(e)||0}addCommittedDuration(e,t){const i=this.getCommittedDuration(e);this.interruptCommittedDurations.set(e,i+t)}isInterruptDurationSatisfied(e){if(!e.shareOfVoice)return!0;const t=e.id||e.file,i=e.shareOfVoice/100*3600;return this.getCommittedDuration(t)>=i}getRequiredSeconds(e){return e.shareOfVoice?e.shareOfVoice/100*3600:0}processInterrupts(e,t){if(!t||t.length===0)return U.debug("No interrupt layouts, returning normal layouts"),e;if(!e||e.length===0)return U.warn("No normal layouts available, interrupts will fill entire hour"),this.fillHourWithInterrupts(t);U.info(`Processing ${t.length} interrupt layouts with ${e.length} normal layouts`);for(const c of t){const d=c.id||c.file;this.interruptCommittedDurations.set(d,0)}const i=[];let n=0,o=0,s=!1;for(;!s;){if(o>=t.length){o=0;let d=!0;for(const h of t)if(!this.isInterruptDurationSatisfied(h)){d=!1;break}if(d){s=!0;break}}const c=t[o];if(!this.isInterruptDurationSatisfied(c)){const d=c.id||c.file;this.addCommittedDuration(d,c.duration),n+=c.duration,i.push(c)}o++}if(U.debug(`Resolved ${i.length} interrupt plays (${n}s total)`),n>=3600)return U.info("Interrupts fill entire hour (>= 3600s), no room for normal layouts"),i;const r=3600-n,a=this.fillTimeWithLayouts(e,r);U.debug(`Resolved ${a.length} normal plays (${r}s target)`);const l=this.interleaveLayouts(a,i);return U.info(`Final loop: ${l.length} layouts (${a.length} normal + ${i.length} interrupts)`),l}fillTimeWithLayouts(e,t){const i=[];let n=t,o=0;for(;n>0;){o>=e.length&&(o=0);const s=e[o];i.push(s),n-=s.duration,o++}return i}fillHourWithInterrupts(e){return this.fillTimeWithLayouts(e,3600)}interleaveLayouts(e,t){const i=[],n=Math.max(e.length,t.length),o=Math.ceil(1*n/e.length),s=Math.floor(1*n/t.length);U.debug(`Interleaving: pickCount=${n}, normalPick=${o}, interruptPick=${s}`);let r=0,a=0,l=0;for(let c=0;c<n;c++)c%o===0&&(r>=e.length&&(r=0),i.push(e[r]),l+=e[r].duration,r++),c%s===0&&a<t.length&&(i.push(t[a]),l+=t[a].duration,a++);for(;l<3600;)r>=e.length&&(r=0),i.push(e[r]),l+=e[r].duration,r++;return U.debug(`Interleaved ${i.length} layouts, total duration: ${l}s`),i}separateLayouts(e){const t=[],i=[];for(const n of e)this.isInterrupt(n)?i.push(n):t.push(n);return{normalLayouts:t,interruptLayouts:i}}}const J=H("schedule:overlays");class it{constructor(){this.overlays=[],this.displayProperties={},this.scheduleManager=null,J.debug("OverlayScheduler initialized")}setScheduleManager(e){this.scheduleManager=e}setDisplayProperties(e){this.displayProperties=e||{}}setOverlays(e){this.overlays=e||[],J.info(`Loaded ${this.overlays.length} overlay(s)`)}getCurrentOverlays(){if(!this.overlays||this.overlays.length===0)return[];const e=new Date,t=[];for(const i of this.overlays){if(!this.isTimeActive(i,e)){J.debug(`Overlay ${i.file} not in time window`);continue}if(i.isGeoAware&&i.geoLocation&&this.scheduleManager&&!this.scheduleManager.isWithinGeoFence(i.geoLocation)){J.debug(`Overlay ${i.file} filtered by geofence`);continue}if(i.criteria&&i.criteria.length>0&&!ae(i.criteria,{now:e,displayProperties:this.displayProperties})){J.debug(`Overlay ${i.file} filtered by criteria`);continue}t.push(i)}return t.sort((i,n)=>{const o=i.priority||0;return(n.priority||0)-o}),t.length>0&&J.info(`Active overlays: ${t.length}`),t}isTimeActive(e,t){const i=e.fromdt||e.fromDt?new Date(e.fromdt||e.fromDt):null,n=e.todt||e.toDt?new Date(e.todt||e.toDt):null;return!(i&&t<i||n&&t>n)}shouldCheckOverlays(e){return e?Date.now()-e>=6e4:!0}getOverlayByFile(e){return this.overlays.find(t=>t.file===e)||null}clear(){this.overlays=[],J.debug("Cleared all overlays")}processOverlays(e,t){return this.setOverlays(t),e}}new it;const Q=H("LayoutPool");class Z{constructor(e=2){this.layouts=new Map,this.maxSize=e,this.hotLayoutId=null}has(e){return this.layouts.has(e)}get(e){return this.layouts.get(e)}add(e,t){if(this.layouts.has(e)){const i=this.layouts.get(e);Object.assign(i,t),i.lastAccess=Date.now();return}this.layouts.size>=this.maxSize&&this.evictLRU(),t.status="warm",t.lastAccess=Date.now(),this.layouts.set(e,t),Q.info(`Added layout ${e} to pool (size: ${this.layouts.size}/${this.maxSize})`)}setHot(e){if(this.hotLayoutId!==null&&this.layouts.has(this.hotLayoutId)&&(this.layouts.get(this.hotLayoutId).status="warm"),this.layouts.has(e)){const t=this.layouts.get(e);t.status="hot",t.lastAccess=Date.now()}this.hotLayoutId=e}evict(e){const t=this.layouts.get(e);if(t){if(Q.info(`Evicting layout ${e} from pool`),t.regions)for(const[i,n]of t.regions)n.timer&&(clearTimeout(n.timer),n.timer=null);if(t.container&&Z.releaseMediaElements(t.container),t.blobUrls&&t.blobUrls.size>0&&(t.blobUrls.forEach(i=>{URL.revokeObjectURL(i)}),Q.info(`Revoked ${t.blobUrls.size} blob URLs for layout ${e}`)),t.mediaUrlCache)for(const[i,n]of t.mediaUrlCache)n&&typeof n=="string"&&n.startsWith("blob:")&&URL.revokeObjectURL(n);t.container&&t.container.parentNode&&t.container.remove(),this.layouts.delete(e),this.hotLayoutId===e&&(this.hotLayoutId=null)}}static releaseMediaElements(e){let t=0,i=0;e.querySelectorAll("video").forEach(n=>{n._hlsInstance&&(n._hlsInstance.destroy(),n._hlsInstance=null,i++),n._mediaStream&&(n._mediaStream.getTracks().forEach(o=>o.stop()),n._mediaStream=null,n.srcObject=null),n.pause(),n.removeAttribute("src"),n.load(),t++}),e.querySelectorAll("audio").forEach(n=>{n.pause(),n.removeAttribute("src"),n.load()}),t>0&&Q.info(`Released ${t} video(s)${i?` (${i} HLS)`:""}`)}evictLRU(){let e=null,t=1/0;for(const[i,n]of this.layouts)n.status==="warm"&&n.lastAccess<t&&(e=i,t=n.lastAccess);e!==null&&this.evict(e)}clearWarm(){let e=0;const t=[];for(const[i,n]of this.layouts)n.status==="warm"&&t.push(i);for(const i of t)this.evict(i),e++;return e>0&&Q.info(`Cleared ${e} warm layout(s) from pool`),e}clearWarmNotIn(e){let t=0;const i=[];for(const[n,o]of this.layouts)o.status==="warm"&&!e.has(n)&&i.push(n);for(const n of i)this.evict(n),t++;return t>0&&Q.info(`Cleared ${t} warm layout(s) no longer in schedule`),t}clear(){const e=Array.from(this.layouts.keys());for(const t of e)this.evict(t);this.hotLayoutId=null}get size(){return this.layouts.size}}const ie={fadeIn(y,e){const t=[{opacity:0},{opacity:1}],i={duration:e,easing:"linear",fill:"forwards"};return y.animate(t,i)},fadeOut(y,e){const t=[{opacity:1},{opacity:0}],i={duration:e,easing:"linear",fill:"forwards"};return y.animate(t,i)},getFlyKeyframes(y,e,t,i){const n={N:{x:0,y:i?-t:t},NE:{x:i?e:-e,y:i?-t:t},E:{x:i?e:-e,y:0},SE:{x:i?e:-e,y:i?t:-t},S:{x:0,y:i?t:-t},SW:{x:i?-e:e,y:i?t:-t},W:{x:i?-e:e,y:0},NW:{x:i?-e:e,y:i?-t:t}},o=n[y]||n.N;return i?{from:{transform:`translate(${o.x}px, ${o.y}px)`,opacity:0},to:{transform:"translate(0, 0)",opacity:1}}:{from:{transform:"translate(0, 0)",opacity:1},to:{transform:`translate(${o.x}px, ${o.y}px)`,opacity:0}}},flyIn(y,e,t,i,n){const o=this.getFlyKeyframes(t,i,n,!0),s={duration:e,easing:"ease-out",fill:"forwards"};return y.animate([o.from,o.to],s)},flyOut(y,e,t,i,n){const o=this.getFlyKeyframes(t,i,n,!1),s={duration:e,easing:"ease-in",fill:"forwards"};return y.animate([o.from,o.to],s)},apply(y,e,t,i,n){if(!e||!e.type)return null;const o=e.type.toLowerCase(),s=e.duration||1e3,r=e.direction||"N";switch(o){case"fade":return t?this.fadeIn(y,s):this.fadeOut(y,s);case"fadein":return t?this.fadeIn(y,s):null;case"fadeout":return t?null:this.fadeOut(y,s);case"fly":return t?this.flyIn(y,s,r,i,n):this.flyOut(y,s,r,i,n);case"flyin":return t?this.flyIn(y,s,r,i,n):null;case"flyout":return t?null:this.flyOut(y,s,r,i,n);default:return null}}};class nt{constructor(e,t,i={}){this.config=e,this.container=t,this.options=i,this.log=H("RendererLite",i.logLevel),this.emitter=ze(),this.currentLayout=null,this.currentLayoutId=null,this._preloadingLayoutId=null,this.regions=new Map,this.layoutTimer=null,this.layoutEndEmitted=!1,this._paused=!1,this._layoutTimerStartedAt=null,this._layoutTimerDurationMs=null,this.widgetTimers=new Map,this.layoutBlobUrls=new Map,this.audioOverlays=new Map,this.scaleFactor=1,this.offsetX=0,this.offsetY=0,this.overlayContainer=null,this.activeOverlays=new Map,this._keydownHandler=null,this._keyboardActions=[],this._subPlaylistCycleIndex=new Map,this.layoutPool=new Z(2),this.preloadTimer=null,this._preloadRetryTimer=null,this.setupContainer(),this.emitter.on("interactiveTrigger",n=>this._handleInteractiveTrigger(n)),this.emitter.on("widgetExpire",n=>this._handleWidgetExpire(n)),this.emitter.on("widgetExtendDuration",n=>this._handleWidgetExtendDuration(n)),this.emitter.on("widgetSetDuration",n=>this._handleWidgetSetDuration(n)),this.log.info("Initialized")}setupContainer(){if(this.container.style.position="relative",this.container.style.width="100%",this.container.style.height="100vh",this.container.style.overflow="hidden",typeof ResizeObserver<"u"){let e=null;this.resizeObserver=new ResizeObserver(()=>{e&&clearTimeout(e),e=setTimeout(()=>this.rescaleRegions(),150)}),this.resizeObserver.observe(this.container)}this.overlayContainer=document.createElement("div"),this.overlayContainer.id="overlay-container",this.overlayContainer.style.position="absolute",this.overlayContainer.style.top="0",this.overlayContainer.style.left="0",this.overlayContainer.style.width="100%",this.overlayContainer.style.height="100%",this.overlayContainer.style.zIndex="1000",this.overlayContainer.style.pointerEvents="none",this.container.appendChild(this.overlayContainer)}calculateScale(e){const t=this.container.clientWidth,i=this.container.clientHeight;if(!t||!i)return;const n=t/e.width,o=i/e.height;this.scaleFactor=Math.min(n,o),this.offsetX=(t-e.width*this.scaleFactor)/2,this.offsetY=(i-e.height*this.scaleFactor)/2,this.log.info(`Scale: ${this.scaleFactor.toFixed(3)} (${e.width}x${e.height} → ${t}x${i}, offset ${Math.round(this.offsetX)},${Math.round(this.offsetY)})`)}applyRegionScale(e,t){const i=this.scaleFactor;e.style.left=`${t.left*i+this.offsetX}px`,e.style.top=`${t.top*i+this.offsetY}px`,e.style.width=`${t.width*i}px`,e.style.height=`${t.height*i}px`}rescaleRegions(){if(this.currentLayout){this.calculateScale(this.currentLayout);for(const[e,t]of this.regions)this.applyRegionScale(t.element,t.config),t.width=t.config.width*this.scaleFactor,t.height=t.config.height*this.scaleFactor;for(const[e,t]of this.activeOverlays){this.calculateScale(t.layout);for(const[i,n]of t.regions)this.applyRegionScale(n.element,n.config),n.width=n.config.width*this.scaleFactor,n.height=n.config.height*this.scaleFactor}}}on(e,t){return this.emitter.on(e,t)}emit(e,...t){this.emitter.emit(e,...t)}parseActions(e){const t=[];for(const i of e.children)i.tagName==="action"&&t.push({id:i.getAttribute("id")||"",actionType:i.getAttribute("actionType")||"",triggerType:i.getAttribute("triggerType")||"",triggerCode:i.getAttribute("triggerCode")||"",source:i.getAttribute("source")||"",sourceId:i.getAttribute("sourceId")||"",target:i.getAttribute("target")||"",targetId:i.getAttribute("targetId")||"",widgetId:i.getAttribute("widgetId")||"",layoutCode:i.getAttribute("layoutCode")||"",commandCode:i.getAttribute("commandCode")||""});return t}parseXlf(e){const n=new DOMParser().parseFromString(e,"text/xml").querySelector("layout");if(!n)throw new Error("Invalid XLF: no <layout> element");const o=n.getAttribute("duration"),s={schemaVersion:parseInt(n.getAttribute("schemaVersion")||"1"),width:parseInt(n.getAttribute("width")||"1920"),height:parseInt(n.getAttribute("height")||"1080"),duration:o?parseInt(o):0,bgcolor:n.getAttribute("backgroundColor")||n.getAttribute("bgcolor")||"#000000",background:n.getAttribute("background")||null,enableStat:n.getAttribute("enableStat")!=="0",actions:this.parseActions(n),regions:[]};s.schemaVersion>1&&this.log.debug(`XLF schema version: ${s.schemaVersion}`),o?this.log.info(`Layout duration from XLF: ${s.duration}s`):this.log.info("Layout duration NOT in XLF, will calculate from widgets");const r=n.querySelectorAll(":scope > region, :scope > drawer");for(const a of r){const l=a.tagName==="drawer",c=a.getAttribute("type")||null,d={id:a.getAttribute("id"),width:parseInt(a.getAttribute("width")||"0"),height:parseInt(a.getAttribute("height")||"0"),top:parseInt(a.getAttribute("top")||"0"),left:parseInt(a.getAttribute("left")||"0"),zindex:parseInt(a.getAttribute("zindex")||(l?"2000":"0")),enableStat:a.getAttribute("enableStat")!=="0",actions:this.parseActions(a),exitTransition:null,transitionType:null,transitionDuration:null,transitionDirection:null,loop:!0,isDrawer:l,isCanvas:c==="canvas",widgets:[]},h=Array.from(a.children).find(g=>g.tagName==="options");if(h){const g=h.querySelector("exitTransType");if(g&&g.textContent){const m=h.querySelector("exitTransDuration"),v=h.querySelector("exitTransDirection");d.exitTransition={type:g.textContent,duration:parseInt(m&&m.textContent||"1000"),direction:v&&v.textContent||"N"}}const p=h.querySelector("loop");p&&(d.loop=p.textContent!=="0");const w=h.querySelector("transitionType");if(w&&w.textContent){d.transitionType=w.textContent;const m=h.querySelector("transitionDuration"),v=h.querySelector("transitionDirection");d.transitionDuration=parseInt(m&&m.textContent||"1000"),d.transitionDirection=v&&v.textContent||"N"}}for(const g of a.children){if(g.tagName!=="media")continue;const p=this.parseWidget(g);d.widgets.push(p)}!d.isCanvas&&d.widgets.some(g=>g.type==="global")&&(d.isCanvas=!0),s.regions.push(d),l&&this.log.info(`Parsed drawer: id=${d.id} with ${d.widgets.length} widgets`),d.isCanvas&&this.log.info(`Parsed canvas region: id=${d.id} with ${d.widgets.length} widgets (all render simultaneously)`)}if(s.duration===0){const{duration:a}=le(e);s.duration=a,this.log.info(`Calculated layout duration: ${s.duration}s (not specified in XLF)`)}return s}parseWidget(e){const t=e.getAttribute("type"),i=parseInt(e.getAttribute("duration")||"10"),n=parseInt(e.getAttribute("useDuration")||"1"),o=e.getAttribute("id"),s=e.getAttribute("fileId"),r={},a=e.querySelector("options");if(a)for(const b of a.children)r[b.tagName]=b.textContent;const l=e.querySelector("raw"),c=l?l.textContent:"",d={in:null,out:null};r.transIn&&(d.in={type:r.transIn,duration:parseInt(r.transInDuration||"1000"),direction:r.transInDirection||"N"}),r.transOut&&(d.out={type:r.transOut,duration:parseInt(r.transOutDuration||"1000"),direction:r.transOutDirection||"N"});const h=this.parseActions(e),g=[];for(const b of e.children)if(b.tagName.toLowerCase()==="audio"){const C=b.querySelector("uri");C?g.push({mediaId:C.getAttribute("mediaId")||null,uri:C.textContent||"",volume:parseInt(C.getAttribute("volume")||"100"),loop:C.getAttribute("loop")==="1"}):g.push({mediaId:b.getAttribute("mediaId")||null,uri:b.getAttribute("uri")||"",volume:parseInt(b.getAttribute("volume")||"100"),loop:b.getAttribute("loop")==="1"})}const p=[],w=Array.from(e.children).find(b=>b.tagName==="commands");if(w)for(const b of w.children)b.tagName==="command"&&p.push({commandCode:b.getAttribute("commandCode")||"",commandString:b.getAttribute("commandString")||""});const m=e.getAttribute("parentWidgetId")||null,v=parseInt(e.getAttribute("displayOrder")||"0"),_=e.getAttribute("cyclePlayback")==="1",$=parseInt(e.getAttribute("playCount")||"0"),T=e.getAttribute("isRandom")==="1",x=e.getAttribute("fromDt")||e.getAttribute("fromdt")||null,I=e.getAttribute("toDt")||e.getAttribute("todt")||null,S=e.getAttribute("render")||null;return{type:t,duration:i,useDuration:n,id:o,fileId:s,render:S,fromDt:x,toDt:I,enableStat:e.getAttribute("enableStat")!=="0",webhookUrl:r.webhookUrl||null,options:r,raw:c,transitions:d,actions:h,audioNodes:g,commands:p,parentWidgetId:m,displayOrder:v,cyclePlayback:_,playCount:$,isRandom:T}}trackBlobUrl(e){const t=this._preloadingLayoutId||this.currentLayoutId||0;t||this.log.warn("trackBlobUrl called without currentLayoutId, tracking under key 0"),this.layoutBlobUrls.has(t)||this.layoutBlobUrls.set(t,new Set),this.layoutBlobUrls.get(t).add(e)}revokeBlobUrlsForLayout(e){const t=this.layoutBlobUrls.get(e);t&&(t.forEach(i=>{URL.revokeObjectURL(i)}),this.layoutBlobUrls.delete(e),this.log.info(`Revoked ${t.size} blob URLs for layout ${e}`))}updateLayoutDuration(){if(!this.currentLayout)return;let e=0;for(const t of this.currentLayout.regions){if(t.isDrawer)continue;let i=0;for(const n of t.widgets)n.duration>0&&(i+=n.duration);e=Math.max(e,i)}if(e>0&&e!==this.currentLayout.duration){const t=this.currentLayout.duration;if(this.currentLayout.duration=e,this.log.info(`Layout duration updated: ${t}s → ${e}s (based on video metadata)`),this.emit("layoutDurationUpdated",this.currentLayoutId,e),this.layoutTimer){clearTimeout(this.layoutTimer);const i=Date.now()-(this._layoutTimerStartedAt||Date.now()),n=Math.max(1e3,this.currentLayout.duration*1e3-i);this.layoutTimer=setTimeout(()=>{this.log.info(`Layout ${this.currentLayoutId} duration expired (${this.currentLayout.duration}s)`),this.currentLayoutId&&(this.layoutEndEmitted=!0,this.emit("layoutEnd",this.currentLayoutId))},n),this.log.info(`Layout timer adjusted to ${(n/1e3).toFixed(1)}s remaining (elapsed ${(i/1e3).toFixed(1)}s of ${this.currentLayout.duration}s)`)}else this.log.info(`Layout duration updated to ${e}s (timer not yet started, will use new value)`);this._scheduleNextLayoutPreload(this.currentLayout)}}attachActionListeners(e){var n;const t=[];let i=0;for(const o of e.actions||[])o.triggerType==="touch"?(this.attachTouchAction(this.container,o,null,null),i++):(n=o.triggerType)!=null&&n.startsWith("keyboard:")&&t.push(o);for(const o of e.regions){const s=this.regions.get(o.id);if(s){for(const r of o.actions||[])r.triggerType==="touch"?(this.attachTouchAction(s.element,r,o.id,null),i++):r.triggerType.startsWith("keyboard:")&&t.push(r);for(const r of o.widgets){if(!r.actions||r.actions.length===0)continue;const a=s.widgetElements.get(r.id);if(a)for(const l of r.actions)l.triggerType==="touch"?(this.attachTouchAction(a,l,o.id,r.id),i++):l.triggerType.startsWith("keyboard:")&&t.push(l)}}}this.setupKeyboardListener(t),(i>0||t.length>0)&&this.log.info(`Actions attached: ${i} touch, ${t.length} keyboard`)}attachTouchAction(e,t,i,n){e.style.cursor="pointer";const o=s=>{s.stopPropagation();const r=n?`widget ${n}`:`region ${i}`;this.log.info(`Touch action fired on ${r}: ${t.actionType}`),this.emit("action-trigger",{actionType:t.actionType,triggerType:"touch",triggerCode:t.triggerCode,layoutCode:t.layoutCode,targetId:t.targetId,commandCode:t.commandCode,source:{regionId:i,widgetId:n}})};e.addEventListener("click",o),e._actionHandlers||(e._actionHandlers=[]),e._actionHandlers.push(o)}setupKeyboardListener(e){this.removeKeyboardListener(),this._keyboardActions=e,e.length!==0&&(this._keydownHandler=t=>{const i=t.key;for(const n of this._keyboardActions){const o=n.triggerType.substring(9);if(i===o){this.log.info(`Keyboard action (key: ${i}): ${n.actionType}`),this.emit("action-trigger",{actionType:n.actionType,triggerType:n.triggerType,triggerCode:n.triggerCode,layoutCode:n.layoutCode,targetId:n.targetId,commandCode:n.commandCode,source:{key:i}});break}}},document.addEventListener("keydown",this._keydownHandler))}removeKeyboardListener(){this._keydownHandler&&(document.removeEventListener("keydown",this._keydownHandler),this._keydownHandler=null),this._keyboardActions=[]}removeActionListeners(){for(const[,e]of this.regions){this._cleanElementActionHandlers(e.element);for(const[,t]of e.widgetElements)this._cleanElementActionHandlers(t)}this.removeKeyboardListener()}_cleanElementActionHandlers(e){if(e._actionHandlers){for(const t of e._actionHandlers)e.removeEventListener("click",t);delete e._actionHandlers,e.style.cursor=""}}_findRegionByWidgetId(e){for(const[t,i]of this.regions){const n=i.widgets.findIndex(o=>o.id===e);if(n!==-1)return{regionId:t,region:i,widget:i.widgets[n],widgetIndex:n,regionMap:this.regions}}for(const t of this.activeOverlays.values())if(t.regions)for(const[i,n]of t.regions){const o=n.widgets.findIndex(s=>s.id===e);if(o!==-1)return{regionId:i,region:n,widget:n.widgets[o],widgetIndex:o,regionMap:t.regions}}return null}_advanceRegion(e,t){const i=t.get(e);if(!i)return;i.currentIndex=(i.currentIndex+1)%i.widgets.length;const n=t===this.regions;this._startRegionCycle(i,e,n?(o,s)=>this.renderWidget(o,s):(o,s)=>this.renderWidget(o,s),n?(o,s)=>this.stopWidget(o,s):(o,s)=>this.stopWidget(o,s),n?()=>this.checkLayoutComplete():void 0)}_handleInteractiveTrigger({targetId:e,triggerCode:t}){this.log.info(`XIC interactiveTrigger: target=${e} code=${t}`),this._findRegionByWidgetId(e)?this.navigateToWidget(e):this.log.warn(`XIC interactiveTrigger: widget ${e} not found`)}_handleWidgetExpire({widgetId:e}){const t=this._findRegionByWidgetId(e);if(!t){this.log.warn(`XIC widgetExpire: widget ${e} not found`);return}const{regionId:i,region:n,widgetIndex:o,regionMap:s}=t;this.log.info(`XIC widgetExpire: widget=${e} region=${i}`),n.timer&&(clearTimeout(n.timer),n.timer=null),this.stopWidget(i,o),this._advanceRegion(i,s)}_handleWidgetExtendDuration({widgetId:e,duration:t}){const i=this._findRegionByWidgetId(e);if(!i){this.log.warn(`XIC widgetExtendDuration: widget ${e} not found`);return}const{regionId:n,region:o}=i;this.log.info(`XIC widgetExtendDuration: widget=${e} +${t}s`),o.timer&&(clearTimeout(o.timer),o.timer=null),o.timer=setTimeout(()=>{this.stopWidget(n,o.currentIndex),this._advanceRegion(n,i.regionMap)},t*1e3)}_handleWidgetSetDuration({widgetId:e,duration:t}){const i=this._findRegionByWidgetId(e);if(!i){this.log.warn(`XIC widgetSetDuration: widget ${e} not found`);return}const{regionId:n,region:o}=i;this.log.info(`XIC widgetSetDuration: widget=${e} ${t}s`),o.timer&&(clearTimeout(o.timer),o.timer=null),o.timer=setTimeout(()=>{this.stopWidget(n,o.currentIndex),this._advanceRegion(n,i.regionMap)},t*1e3)}navigateToWidget(e){for(const[t,i]of this.regions){const n=i.widgets.findIndex(o=>o.id===e);if(n!==-1){if(this.log.info(`Navigating to widget ${e} in region ${t} (index ${n})`),i.isDrawer&&i.element.style.display==="none"&&(i.element.style.display="",this.log.info(`Drawer region ${t} revealed`)),i.timer&&(clearTimeout(i.timer),i.timer=null),this.stopWidget(t,i.currentIndex),i.currentIndex=n,this.renderWidget(t,n),i.widgets.length>1){const s=i.widgets[n].duration*1e3;i.timer=setTimeout(()=>{this.stopWidget(t,n);const r=(n+1)%i.widgets.length;i.currentIndex=r,i.isDrawer&&r===0?(i.element.style.display="none",this.log.info(`Drawer region ${t} hidden (cycle complete)`)):i.isDrawer?this.navigateToWidget(i.widgets[r].id):this.startRegion(t)},s)}else if(i.isDrawer){const s=i.widgets[n].duration*1e3;i.timer=setTimeout(()=>{this.stopWidget(t,n),i.element.style.display="none",this.log.info(`Drawer region ${t} hidden (single widget done)`)},s)}return}}this.log.warn(`Target widget ${e} not found in any region`)}nextWidget(e){const t=e?this.regions.get(e):this.regions.values().next().value;if(!t||t.widgets.length<=1)return;const i=(t.currentIndex+1)%t.widgets.length,n=t.widgets[i];this.log.info(`nextWidget → index ${i} (widget ${n.id})`),this.navigateToWidget(n.id)}previousWidget(e){const t=e?this.regions.get(e):this.regions.values().next().value;if(!t||t.widgets.length<=1)return;const i=(t.currentIndex-1+t.widgets.length)%t.widgets.length,n=t.widgets[i];this.log.info(`previousWidget → index ${i} (widget ${n.id})`),this.navigateToWidget(n.id)}_mediaFileUrl(e){return`${window.location.origin}${B}/media/file/${e}`}_positionWidgetElement(e){Object.assign(e.style,{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",visibility:"hidden",opacity:"0"})}_applyBackgroundImage(e,t){Object.assign(e.style,{backgroundImage:`url(${t})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"})}_clearRegionTimers(e){for(const[,t]of e)t.timer&&(clearTimeout(t.timer),t.timer=null)}async renderLayout(e,t){var i;try{if(this.log.info(`Rendering layout ${t}`),this.currentLayoutId===t){this.log.info(`Replaying layout ${t} - reusing elements (no recreation!)`),this._clearRegionTimers(this.regions);for(const[,s]of this.regions)s.currentIndex=0;this.layoutTimer&&(clearTimeout(this.layoutTimer),this.layoutTimer=null),this.layoutEndEmitted=!1,this.emit("layoutStart",t,this.currentLayout);for(const[s,r]of this.regions)r.isDrawer||this.startRegion(s);this.startLayoutTimerWhenReady(t,this.currentLayout),this.log.info(`Layout ${t} restarted (reused elements)`),this._scheduleNextLayoutPreload(this.currentLayout);return}if(this.layoutPool.has(t)){this.log.info(`Layout ${t} found in preload pool - instant swap!`),await this._swapToPreloadedLayout(t);return}this.log.info(`Switching to new layout ${t}`),this.stopCurrentLayout();const o=this.parseXlf(e);if(this.currentLayout=o,this.currentLayoutId=t,this.calculateScale(o),this.container.style.backgroundColor=o.bgcolor,this.container.style.backgroundImage="",o.background){const s=((i=this.options.fileIdToSaveAs)==null?void 0:i.get(String(o.background)))||o.background;this._applyBackgroundImage(this.container,this._mediaFileUrl(s)),this.log.info(`Background image set: ${o.background} → ${s}`)}for(const s of o.regions)await this.createRegion(s);this.log.info("Pre-creating widget elements for instant transitions...");for(const[s,r]of this.regions)for(let a=0;a<r.widgets.length;a++){const l=r.widgets[a];l.layoutId=this.currentLayoutId,l.regionId=s;try{const c=await this.createWidgetElement(l,r);this._positionWidgetElement(c),r.element.appendChild(c),r.widgetElements.set(l.id,c)}catch(c){this.log.error(`Failed to pre-create widget ${l.id}:`,c)}}this.log.info("All widget elements pre-created"),this.attachActionListeners(o),this.emit("layoutStart",t,o);for(const[s,r]of this.regions)r.isDrawer||this.startRegion(s);this.startLayoutTimerWhenReady(t,o),this._scheduleNextLayoutPreload(o),this.log.info(`Layout ${t} started`)}catch(n){throw this.log.error("Error rendering layout:",n),this.emit("error",{type:"layoutError",error:n,layoutId:t}),n}}async createRegion(e){const t=document.createElement("div");t.id=`region_${e.id}`,t.className="renderer-lite-region",t.style.position="absolute",t.style.zIndex=e.zindex,t.style.overflow="hidden",e.isDrawer&&(t.style.display="none"),this.applyRegionScale(t,e),this.container.appendChild(t);let i=e.widgets.filter(o=>this._isWidgetActive(o));i.some(o=>o.cyclePlayback)&&(i=this._applyCyclePlayback(i));const n=this.scaleFactor;this.regions.set(e.id,{element:t,config:e,widgets:i,currentIndex:0,timer:null,width:e.width*n,height:e.height*n,complete:!1,isDrawer:e.isDrawer||!1,isCanvas:e.isCanvas||!1,widgetElements:new Map})}startRegion(e){const t=this.regions.get(e);this._startRegionCycle(t,e,(i,n)=>this.renderWidget(i,n),(i,n)=>this.stopWidget(i,n),()=>{this.log.info(`Region ${e} completed one full cycle`),this.checkLayoutComplete()})}async createWidgetElement(e,t){if(e.render==="html"&&e.type!=="pdf")return await this.renderGenericWidget(e,t);switch(e.type){case"image":return await this.renderImage(e,t);case"video":return await this.renderVideo(e,t);case"audio":return await this.renderAudio(e,t);case"text":case"ticker":return await this.renderTextWidget(e,t);case"pdf":return await this.renderPdf(e,t);case"webpage":return await this.renderWebpage(e,t);case"localvideo":return await this.renderVideo(e,t);case"videoin":return await this.renderVideoIn(e,t);case"powerpoint":case"flash":return this.log.warn(`Widget type '${e.type}' is not supported on web players (widget ${e.id})`),this._renderUnsupportedPlaceholder(e,t);default:return await this.renderGenericWidget(e,t)}}findMediaElement(e,t){return e.tagName===t?e:e.querySelector(t.toLowerCase())}updateMediaElement(e,t){const i=this.findMediaElement(e,"VIDEO")||this.findMediaElement(e,"AUDIO");if(i){if(i.tagName==="VIDEO"&&i._mediaConstraints&&!i._mediaStream){navigator.mediaDevices.getUserMedia(i._mediaConstraints).then(n=>{i.srcObject=n,i._mediaStream=n,this.log.info(`Webcam stream re-acquired for widget ${t.id}`)}).catch(n=>{this.log.warn("Failed to re-acquire webcam stream:",n.message)});return}this._restartMediaElement(i),this.log.info(`${i.tagName==="VIDEO"?"Video":"Audio"} restarted: ${t.fileId||t.id}`)}}_restartMediaElement(e){e.currentTime=0;const t=()=>{e.removeEventListener("seeked",t),e.play().catch(()=>{})};e.addEventListener("seeked",t),e.currentTime===0&&e.readyState>=2&&(e.removeEventListener("seeked",t),e.play().catch(()=>{}))}waitForWidgetReady(e,t){const n=this.findMediaElement(e,"VIDEO");if(n)return!n.paused&&n.readyState>=3?Promise.resolve():new Promise(r=>{const a=setTimeout(()=>{this.log.warn(`Video ready timeout (10000ms) for widget ${t.id}`),r()},1e4),l=()=>{n.removeEventListener("playing",l),clearTimeout(a),this.log.info(`Video widget ${t.id} ready (playing)`),r()};n.addEventListener("playing",l)});const o=this.findMediaElement(e,"AUDIO");if(o)return!o.paused&&o.readyState>=3?Promise.resolve():new Promise(r=>{const a=setTimeout(()=>{this.log.warn(`Audio ready timeout (10000ms) for widget ${t.id}`),r()},1e4),l=()=>{o.removeEventListener("playing",l),clearTimeout(a),this.log.info(`Audio widget ${t.id} ready (playing)`),r()};o.addEventListener("playing",l)});const s=this.findMediaElement(e,"IMG");return s?s.complete&&s.naturalWidth>0?Promise.resolve():new Promise(r=>{const a=()=>{s.removeEventListener("load",a),clearTimeout(l),r()},l=setTimeout(()=>{s.removeEventListener("load",a),this.log.warn(`Image ready timeout for widget ${t.id}`),r()},1e4);s.addEventListener("load",a)}):Promise.resolve()}async startLayoutTimerWhenReady(e,t){if(!t||t.duration<=0)return;const i=[];for(const[o,s]of this.regions){if(s.widgets.length===0)continue;const r=s.widgets[s.currentIndex||0],a=s.widgetElements.get(r.id);a&&i.push(this.waitForWidgetReady(a,r))}if(i.length>0&&(this.log.info(`Waiting for ${i.length} widget(s) to be ready before starting layout timer...`),await Promise.all(i),this.log.info("All widgets ready — starting layout timer")),this.currentLayoutId!==e){this.log.warn(`Layout changed while waiting for widgets — skipping timer for ${e}`);return}const n=t.duration*1e3;this.log.info(`Layout ${e} will end after ${t.duration}s`),this._layoutTimerStartedAt=Date.now(),this._layoutTimerDurationMs=n,this.layoutTimer=setTimeout(()=>{this.log.info(`Layout ${e} duration expired (${t.duration}s)`),this.currentLayoutId&&(this.layoutEndEmitted=!0,this.emit("layoutEnd",this.currentLayoutId))},n)}async _showWidget(e,t){var o,s;const i=e.widgets[t];if(!i)return null;let n=e.widgetElements.get(i.id);if(n||(this.log.warn(`Widget ${i.id} not pre-created, creating now`),n=await this.createWidgetElement(i,e),n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%",n.style.height="100%",e.widgetElements.set(i.id,n),e.element.appendChild(n)),!e.isCanvas)for(const[r,a]of e.widgetElements)r!==i.id&&((o=a.getAnimations)==null||o.call(a).forEach(l=>l.cancel()),a.style.visibility="hidden",a.style.opacity="0");return this.updateMediaElement(n,i),(s=n.getAnimations)==null||s.call(n).forEach(r=>r.cancel()),n.style.visibility="visible",i.transitions.in?ie.apply(n,i.transitions.in,!0,e.width,e.height):n.style.opacity="1",this._startAudioOverlays(i),i}_startAudioOverlays(e){if(!e.audioNodes||e.audioNodes.length===0)return;this._stopAudioOverlays(e.id);const t=[];for(const i of e.audioNodes){if(!i.uri)continue;const n=document.createElement("audio");n.autoplay=!0,n.loop=i.loop,n.volume=Math.max(0,Math.min(1,i.volume/100)),n.src=i.uri?this._mediaFileUrl(i.uri):"",n.style.display="none",this.container.appendChild(n);const o=n.play();o&&o.catch&&o.catch(()=>{}),t.push(n),this.log.info(`Audio overlay started for widget ${e.id}: ${i.uri} (loop=${i.loop}, vol=${i.volume})`)}t.length>0&&this.audioOverlays.set(e.id,t)}_stopAudioOverlays(e){const t=this.audioOverlays.get(e);if(t){for(const i of t)i.pause(),i.removeAttribute("src"),i.load(),i.parentNode&&i.parentNode.removeChild(i);this.audioOverlays.delete(e),this.log.info(`Audio overlays stopped for widget ${e}`)}}_hideWidget(e,t){const i=e.widgets[t];if(!i)return{widget:null,animPromise:null};const n=e.widgetElements.get(i.id);if(!n)return{widget:null,animPromise:null};let o=null;if(i.transitions.out){const a=ie.apply(n,i.transitions.out,!1,e.width,e.height);a&&(o=new Promise(l=>{a.onfinish=l}))}const s=n.querySelector("video");if(s&&i.options.loop!=="1"&&s.pause(),s!=null&&s._mediaStream&&(s._mediaStream.getTracks().forEach(a=>a.stop()),s._mediaStream=null,s.srcObject=null),s!=null&&s._hlsInstance&&(s._hlsInstance.destroy(),s._hlsInstance=null),s!=null&&s._eventCleanup){for(const[a,l]of s._eventCleanup)s.removeEventListener(a,l);s._eventCleanup=null}const r=n.querySelector("audio");if(r&&i.options.loop!=="1"&&r.pause(),r!=null&&r._eventCleanup){for(const[a,l]of r._eventCleanup)r.removeEventListener(a,l);r._eventCleanup=null}return this._stopAudioOverlays(i.id),n._pdfCleanup&&n._pdfCleanup(),{widget:i,animPromise:o}}_isWidgetActive(e){const t=new Date;if(e.fromDt){const i=new Date(e.fromDt);if(t<i)return!1}if(e.toDt){const i=new Date(e.toDt);if(t>i)return!1}return!0}_parseDurationComments(e,t){const i=t.duration,n=e.match(/<!--\s*DURATION=(\d+)\s*-->/);if(n){const s=parseInt(n[1],10);if(s>0){this.log.info(`Widget ${t.id}: DURATION comment overrides duration ${t.duration}→${s}s`),t.duration=s,t.duration!==i&&this.updateLayoutDuration();return}}const o=e.match(/<!--\s*NUMITEMS=(\d+)\s*-->/);if(o){const s=parseInt(o[1],10);if(s>0&&t.duration>0){const r=s*t.duration;this.log.info(`Widget ${t.id}: NUMITEMS=${s} × ${t.duration}s = ${r}s`),t.duration=r}}t.duration!==i&&this.updateLayoutDuration()}_applyCyclePlayback(e){this._subPlaylistCycleIndex||(this._subPlaylistCycleIndex=new Map);const t=new Map,i=[];for(const n of e)n.parentWidgetId&&n.cyclePlayback?(t.has(n.parentWidgetId)||t.set(n.parentWidgetId,[]),t.get(n.parentWidgetId).push(n)):i.push({type:"direct",widget:n});for(const[n,o]of t){o.sort((r,a)=>r.displayOrder-a.displayOrder);let s;if(o.some(r=>r.isRandom)){const r=Math.floor(Math.random()*o.length);s=o[r]}else{const r=this._subPlaylistCycleIndex.get(n)||{widgetIdx:0,playsDone:0};s=o[r.widgetIdx%o.length];const a=s.playCount||1;r.playsDone++,r.playsDone>=a&&(r.widgetIdx++,r.playsDone=0),this._subPlaylistCycleIndex.set(n,r)}this.log.info(`Sub-playlist cycle: group ${n} selected widget ${s.id} (${o.length} in group)`),i.push({type:"direct",widget:s})}return i.map(n=>n.widget)}_startRegionCycle(e,t,i,n,o){if(!e||e.widgets.length===0)return;if(e.isCanvas){this._startCanvasRegion(e,t,i,o);return}if(e.widgets.length===1){i(t,0);return}const s=()=>{const r=e.currentIndex,a=e.widgets[r];i(t,r);const l=a.duration*1e3;this.log.info(`Region ${t} widget ${a.id} (${a.type}) playing for ${a.duration}s (useDuration=${a.useDuration}, index ${r}/${e.widgets.length})`),e.timer=setTimeout(()=>{this._handleWidgetCycleEnd(a,e,t,r,i,n,o,s)},l)};s()}_startCanvasRegion(e,t,i,n){for(let s=0;s<e.widgets.length;s++)i(t,s);const o=Math.max(...e.widgets.map(s=>s.duration))*1e3;o>0?e.timer=setTimeout(()=>{e.complete||(e.complete=!0,n==null||n())},o):(e.complete=!0,n==null||n())}_handleWidgetCycleEnd(e,t,i,n,o,s,r,a){var c;e.webhookUrl&&this.emit("widgetAction",{type:"durationEnd",widgetId:e.id,layoutId:this.currentLayoutId,regionId:i,url:e.webhookUrl}),s(i,n);const l=(t.currentIndex+1)%t.widgets.length;if(l===0&&!t.complete&&(t.complete=!0,r==null||r()),l===0&&((c=t.config)==null?void 0:c.loop)===!1&&t.widgets.length===1){o(i,0);return}this.layoutEndEmitted||(t.currentIndex=l,a())}async renderWidget(e,t){var n;const i=this.regions.get(e);if(i)try{const o=await this._showWidget(i,t);if(o&&(this.log.info(`Showing widget ${o.type} (${o.id}) in region ${e}`),this.emit("widgetStart",{widgetId:o.id,regionId:e,layoutId:this.currentLayoutId,mediaId:parseInt(o.fileId||o.id)||null,type:o.type,duration:o.duration,enableStat:o.enableStat}),o.commands&&o.commands.length>0))for(const s of o.commands)this.emit("widgetCommand",{commandCode:s.commandCode,commandString:s.commandString,widgetId:o.id,regionId:e,layoutId:this.currentLayoutId})}catch(o){this.log.error("Error rendering widget:",o),this.emit("error",{type:"widgetError",error:o,widgetId:(n=i.widgets[t])==null?void 0:n.id,regionId:e})}}async stopWidget(e,t){const i=this.regions.get(e);if(!i)return;const{widget:n,animPromise:o}=this._hideWidget(i,t);o&&await o,n&&this.emit("widgetEnd",{widgetId:n.id,regionId:e,layoutId:this.currentLayoutId,mediaId:parseInt(n.fileId||n.id)||null,type:n.type,enableStat:n.enableStat})}async renderImage(e,t){const i=document.createElement("img");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%";const n=e.options.scaleType,o={stretch:"fill",center:"contain",fit:"cover"};i.style.objectFit=o[n]||"contain";const s={left:"left",center:"center",right:"right"},r={top:"top",middle:"center",bottom:"bottom"},a=s[e.options.alignId]||"center",l=r[e.options.valignId]||"center";i.style.objectPosition=`${a} ${l}`,i.style.opacity="0";const c=e.options.uri?this._mediaFileUrl(e.options.uri):"";return i.src=c,i}async renderVideo(e,t){const i=document.createElement("video");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%";const n=e.options.scaleType,o={stretch:"fill",center:"none",fit:"contain"};i.style.objectFit=o[n]||"contain",i.style.opacity="1",i.autoplay=!0,i.preload="auto",i.muted=e.options.mute==="1",i.loop=!1,i.controls=!1,i.playsInline=!0;const s=e.options.uri||"",r=e.fileId||e.id,a=()=>{e.options.loop==="1"?(i.currentTime=0,this.log.info(`Video ${s} ended - reset to start, waiting for widget cycle to replay`)):this.log.info(`Video ${s} ended - paused on last frame`)};i.addEventListener("ended",a);let l=s?this._mediaFileUrl(s):"";if(l.includes(".m3u8"))if(i.canPlayType("application/vnd.apple.mpegurl"))this.log.info(`HLS stream (native): ${r}`),i.src=l;else try{const{default:m}=await F(async()=>{const{default:v}=await import("hls.js");return{default:v}},[],import.meta.url);if(m.isSupported()){const v=new m({enableWorker:!0,lowLatencyMode:!0});v.loadSource(l),v.attachMedia(i),i._hlsInstance=v,v.on(m.Events.ERROR,(_,$)=>{$.fatal&&(this.log.error(`HLS fatal error: ${$.type}`,$.details),v.destroy(),i._hlsInstance=null)}),this.log.info(`HLS stream (hls.js): ${r}`)}else this.log.warn(`HLS not supported on this browser for ${r}`),i.src=l}catch(m){this.log.warn(`hls.js not available, falling back to native: ${m.message}`),i.src=l}else i.src=l;const d=this.currentLayoutId,h=()=>{const m=i.duration;this.log.info(`Video ${s} duration detected: ${m}s`),(e.duration===0||e.useDuration===0)&&(e.duration=m,this.log.info(`Updated widget ${e.id} duration to ${m}s (useDuration=0)`),this.currentLayoutId===d?this.updateLayoutDuration():this.log.info(`Video ${s} duration set but layout timer not updated (preloaded for layout ${d}, current is ${this.currentLayoutId})`))};i.addEventListener("loadedmetadata",h);const g=()=>{this.log.info("Video loaded and ready:",s)};i.addEventListener("loadeddata",g);const p=()=>{const m=i.error,v=m==null?void 0:m.code,_=(m==null?void 0:m.message)||"Unknown error";this.log.warn(`Video error: ${s}, code: ${v}, time: ${i.currentTime.toFixed(1)}s, message: ${_}`),this.emit("videoError",{storedAs:s,fileId:r,errorCode:v,errorMessage:_,currentTime:i.currentTime})};i.addEventListener("error",p);const w=()=>{this.log.info("Video playing:",s)};return i.addEventListener("playing",w),i._eventCleanup=[["ended",a],["loadedmetadata",h],["loadeddata",g],["error",p],["playing",w]],this.log.info("Video element created:",s,i.src),i}async renderVideoIn(e,t){const i=document.createElement("video");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%",i.style.objectFit=e.options.showFullScreen==="1"?"cover":"contain",i.autoplay=!0,i.playsInline=!0,i.controls=!1,i.muted=e.options.mute!=="0",e.options.mirror==="1"&&(i.style.transform="scaleX(-1)");const n={width:{ideal:t.width},height:{ideal:t.height}},o=e.options.sourceId||e.options.deviceId;o?n.deviceId={exact:o}:n.facingMode=e.options.facingMode||"environment";const s={video:n,audio:e.options.captureAudio==="1"};i._mediaConstraints=s;try{const r=await navigator.mediaDevices.getUserMedia(s);i.srcObject=r,i._mediaStream=r,this.log.info(`Webcam stream acquired for widget ${e.id} (tracks: ${r.getTracks().length})`)}catch(r){return this.log.warn(`getUserMedia failed for widget ${e.id}: ${r.message}`),this._renderUnsupportedPlaceholder({...e,type:"Camera unavailable"},t)}return i}async renderAudio(e,t){const i=document.createElement("div");i.className="renderer-lite-widget audio-widget",i.style.width="100%",i.style.height="100%",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.background="linear-gradient(135deg, #667eea 0%, #764ba2 100%)",i.style.opacity="0";const n=document.createElement("audio");n.autoplay=!0,n.loop=e.options.loop==="1",n.volume=parseFloat(e.options.volume||"100")/100;const o=e.options.uri||"";e.fileId||e.id,n.src=o?this._mediaFileUrl(o):"";const s=()=>{e.options.loop==="1"?(n.currentTime=0,this.log.info(`Audio ${o} ended - reset to start, waiting for widget cycle to replay`)):this.log.info(`Audio ${o} ended - playback complete`)};n.addEventListener("ended",s);const r=this.currentLayoutId,a=()=>{const g=Math.floor(n.duration);this.log.info(`Audio ${o} duration detected: ${g}s`),(e.duration===0||e.useDuration===0)&&(e.duration=g,this.log.info(`Updated widget ${e.id} duration to ${g}s (useDuration=0)`),this.currentLayoutId===r?this.updateLayoutDuration():this.log.info(`Audio ${o} duration set but layout timer not updated (preloaded for layout ${r}, current is ${this.currentLayoutId})`))};n.addEventListener("loadedmetadata",a);const l=()=>{const g=n.error;this.log.warn(`Audio error (non-fatal): ${o}, code: ${g==null?void 0:g.code}, message: ${(g==null?void 0:g.message)||"Unknown"}`)};n.addEventListener("error",l),n._eventCleanup=[["ended",s],["loadedmetadata",a],["error",l]];const c=document.createElement("div");c.innerHTML="♪",c.style.fontSize="120px",c.style.color="white",c.style.marginBottom="20px";const d=document.createElement("div");d.style.color="white",d.style.fontSize="24px",d.textContent="Playing Audio";const h=document.createElement("div");return h.style.color="rgba(255,255,255,0.7)",h.style.fontSize="16px",h.style.marginTop="10px",h.textContent=e.options.uri,i.appendChild(n),i.appendChild(c),i.appendChild(d),i.appendChild(h),i}async renderTextWidget(e,t){const i=document.createElement("iframe");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.opacity="0";let n=e.raw;if(this.options.getWidgetHtml){const r=await this.options.getWidgetHtml(e);if(r&&typeof r=="object"&&r.url){if(i.src=r.url,r.fallback){const a=this;i.addEventListener("load",function(){var l;try{if(!((l=i.contentDocument)!=null&&l.querySelector("base"))){a.log.warn("Cache URL failed (hard reload?), using original CMS URLs");const c=new Blob([r.fallback],{type:"text/html"}),d=URL.createObjectURL(c);a.trackBlobUrl(d),i.src=d}}catch{}},{once:!0})}return r.fallback&&this._parseDurationComments(r.fallback,e),i}n=r}n&&this._parseDurationComments(n,e);const o=new Blob([n],{type:"text/html"}),s=URL.createObjectURL(o);return i.src=s,this.trackBlobUrl(s),i}async renderPdf(e,t){const i=document.createElement("div");if(i.className="renderer-lite-widget pdf-widget",i.style.width="100%",i.style.height="100%",i.style.backgroundColor="#525659",i.style.opacity="0",i.style.position="relative",typeof window.pdfjsLib>"u")try{const o=await F(()=>import("./pdf-BnPRJEQ6.js"),[],import.meta.url);window.pdfjsLib=o;const s=window.location.pathname.replace(/\/[^/]*$/,"/");window.pdfjsLib.GlobalWorkerOptions.workerSrc=`${window.location.origin}${s}pdf.worker.min.mjs`}catch(o){return this.log.error("PDF.js not available:",o),i.innerHTML='<div style="color:white;padding:20px;text-align:center;">PDF viewer unavailable</div>',i.style.opacity="1",i}let n=e.options.uri?this._mediaFileUrl(e.options.uri):"";try{const s=await window.pdfjsLib.getDocument(n).promise,r=s.numPages,a=e.duration||60,l=a*1e3/r;this.log.info(`[pdf] PDF loaded: ${r} pages, ${a}s duration, ${(l/1e3).toFixed(1)}s/page`);const c=await s.getPage(1),d=c.getViewport({scale:1}),h=Math.min(t.width/d.width,t.height/d.height);c.cleanup();const g=document.createElement("canvas");g.className="pdf-page",g.width=Math.floor(d.width*h),g.height=Math.floor(d.height*h),g.style.cssText="display:block;margin:auto;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);";const p=g.getContext("2d");i.appendChild(g);const w=document.createElement("div");w.style.cssText="position:absolute;bottom:10px;right:10px;background:rgba(0,0,0,0.7);color:white;padding:8px 12px;border-radius:4px;font:14px system-ui;z-index:1;",i.appendChild(w);let m=1,v=null,_=null,$=!1;const T=async()=>{if($)return;w.textContent=`Page ${m} / ${r}`;const x=await s.getPage(m),I=x.getViewport({scale:h});p.clearRect(0,0,g.width,g.height),_=x.render({canvasContext:p,viewport:I});try{await _.promise}catch(S){if($)return;throw S}_=null,x.cleanup(),r>1&&!$&&(v=setTimeout(()=>{m=m>=r?1:m+1,T()},l))};await T(),i._pdfCleanup=()=>{$=!0,v&&clearTimeout(v),v=null,_&&(_.cancel(),_=null),g.width=0,g.height=0,s.destroy()}}catch(o){this.log.error("PDF render failed:",o),i.innerHTML='<div style="color:white;padding:20px;text-align:center;">Failed to load PDF</div>'}return i.style.opacity="1",i}async renderWebpage(e,t){if(parseInt(e.options.modeId||"1")===0)return await this.renderGenericWidget(e,t);const n=document.createElement("iframe");n.className="renderer-lite-widget",n.style.width="100%",n.style.height="100%",n.style.border="none",n.style.opacity="0";const o=decodeURIComponent(e.options.uri||"");return n.src=o,n}async renderGenericWidget(e,t){const i=document.createElement("iframe");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.opacity="0";let n=e.raw;if(this.options.getWidgetHtml){const o=await this.options.getWidgetHtml(e);if(o&&typeof o=="object"&&o.url){if(i.src=o.url,o.fallback){const s=this;i.addEventListener("load",function(){var r;try{if(!((r=i.contentDocument)!=null&&r.querySelector("base"))){s.log.warn("Cache URL failed (hard reload?), using original CMS URLs");const a=new Blob([o.fallback],{type:"text/html"}),l=URL.createObjectURL(a);s.trackBlobUrl(l),i.src=l}}catch{}},{once:!0})}return o.fallback&&this._parseDurationComments(o.fallback,e),i}n=o}if(n){this._parseDurationComments(n,e);const o=new Blob([n],{type:"text/html"}),s=URL.createObjectURL(o);i.src=s,this.trackBlobUrl(s)}else this.log.warn(`No HTML for widget ${e.id}`),i.srcdoc='<div style="padding:20px;">Widget content unavailable</div>';return i}_renderUnsupportedPlaceholder(e,t){const i=document.createElement("div");return i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.backgroundColor="#111",i.style.color="#666",i.style.fontSize="14px",i.textContent=`Unsupported: ${e.type}`,i}_scheduleNextLayoutPreload(e){this.preloadTimer&&(clearTimeout(this.preloadTimer),this.preloadTimer=null),this._preloadRetryTimer&&(clearTimeout(this._preloadRetryTimer),this._preloadRetryTimer=null);const t=e.duration||60,i=t*1e3*.75,n=t*1e3*.9;this.log.info(`Scheduling next layout preload in ${(i/1e3).toFixed(1)}s (75% of ${t}s)`),this.preloadTimer=setTimeout(()=>{this.preloadTimer=null,this.emit("request-next-layout-preload")},i),this._preloadRetryTimer=setTimeout(()=>{this._preloadRetryTimer=null,this.emit("request-next-layout-preload")},n)}hasPreloadedLayout(e){return this.layoutPool.has(e)}async preloadLayout(e,t){var i;if(this.layoutPool.has(t))return this.log.info(`Layout ${t} already in preload pool, skipping`),!0;if(this.currentLayoutId===t)return this.log.info(`Layout ${t} is current, skipping preload`),!0;try{this.log.info(`Preloading layout ${t} into pool...`);const n=this.parseXlf(e);this.calculateScale(n);const o=document.createElement("div");if(o.id=`preload_layout_${t}`,o.className="renderer-lite-preload-wrapper",o.style.position="absolute",o.style.top="0",o.style.left="0",o.style.width="100%",o.style.height="100%",o.style.visibility="hidden",o.style.zIndex="-1",o.style.backgroundColor=n.bgcolor,n.background){const h=((i=this.options.fileIdToSaveAs)==null?void 0:i.get(String(n.background)))||n.background;this._applyBackgroundImage(o,this._mediaFileUrl(h))}const s=this.currentLayoutId,r=new Map,a=this.scaleFactor;for(const h of n.regions){const g=document.createElement("div");g.id=`preload_region_${t}_${h.id}`,g.className="renderer-lite-region",g.style.position="absolute",g.style.zIndex=h.zindex,g.style.overflow="hidden",this.applyRegionScale(g,h),o.appendChild(g);const p={element:g,config:h,widgets:h.widgets,currentIndex:0,timer:null,width:h.width*a,height:h.height*a,complete:!1,widgetElements:new Map};r.set(h.id,p)}const l=new Set,c=this.layoutBlobUrls;this.layoutBlobUrls=new Map,this.layoutBlobUrls.set(t,l),this._preloadingLayoutId=t;for(const[h,g]of r)for(let p=0;p<g.widgets.length;p++){const w=g.widgets[p];w.layoutId=t,w.regionId=h;try{const m=await this.createWidgetElement(w,g);this._positionWidgetElement(m),g.element.appendChild(m),g.widgetElements.set(w.id,m)}catch(m){this.log.error(`Preload: Failed to create widget ${w.id}:`,m)}}return this.currentLayoutId=s,o.querySelectorAll("video").forEach(h=>h.pause()),(this.layoutBlobUrls.get(t)||new Set).forEach(h=>l.add(h)),this.layoutBlobUrls=c,this.container.appendChild(o),this.layoutPool.add(t,{container:o,layout:n,regions:r,blobUrls:l}),this.log.info(`Layout ${t} preloaded into pool (${r.size} regions)`),!0}catch(n){return this.log.error(`Preload failed for layout ${t}:`,n),!1}}async _swapToPreloadedLayout(e){var n;const t=this.layoutPool.get(e);if(!t){this.log.error(`Cannot swap: layout ${e} not in pool`);return}this.removeActionListeners(),this.layoutTimer&&(clearTimeout(this.layoutTimer),this.layoutTimer=null),this.preloadTimer&&(clearTimeout(this.preloadTimer),this.preloadTimer=null),this._preloadRetryTimer&&(clearTimeout(this._preloadRetryTimer),this._preloadRetryTimer=null);const i=this.currentLayoutId;if(i&&this.layoutPool.has(i))this.layoutPool.evict(i);else{this._clearRegionTimers(this.regions);for(const[,o]of this.regions)if(Z.releaseMediaElements(o.element),(n=o.config)!=null&&n.exitTransition){const s=ie.apply(o.element,o.config.exitTransition,!1,o.width,o.height);if(s){const r=o.element;s.onfinish=()=>r.remove()}else o.element.remove()}else o.element.remove();i&&this.revokeBlobUrlsForLayout(i)}if(i&&!this.layoutEndEmitted&&this.emit("layoutEnd",i),this.regions.clear(),t.container.style.visibility="visible",t.container.style.zIndex="0",this.layoutPool.setHot(e),this.currentLayout=t.layout,this.currentLayoutId=e,this.regions=t.regions,this.layoutEndEmitted=!1,this.container.style.backgroundColor=t.layout.bgcolor,t.container.style.backgroundImage)for(const o of["backgroundImage","backgroundSize","backgroundPosition","backgroundRepeat"])this.container.style[o]=t.container.style[o];else this.container.style.backgroundImage="";this.calculateScale(t.layout),this.attachActionListeners(t.layout),this.emit("layoutStart",e,t.layout);for(const[o,s]of this.regions)s.currentIndex=0,s.complete=!1,this.startRegion(o);this.updateLayoutDuration(),this.startLayoutTimerWhenReady(e,t.layout),this.preloadTimer||this._scheduleNextLayoutPreload(t.layout),this.log.info(`Swapped to preloaded layout ${e} (instant transition)`)}checkLayoutComplete(){let e=!0;for(const[t,i]of this.regions)if(i.widgets.length>1&&!i.complete){e=!1;break}e&&this.currentLayoutId&&this.log.info("All multi-widget regions completed one cycle")}stopCurrentLayout(){var e;if(this.currentLayout){if(this.log.info(`Stopping layout ${this.currentLayoutId}`),this.removeActionListeners(),this.layoutTimer&&(clearTimeout(this.layoutTimer),this.layoutTimer=null),this.preloadTimer&&(clearTimeout(this.preloadTimer),this.preloadTimer=null),this._preloadRetryTimer&&(clearTimeout(this._preloadRetryTimer),this._preloadRetryTimer=null),this.currentLayoutId&&this.layoutPool.has(this.currentLayoutId))this.layoutPool.evict(this.currentLayoutId);else{this.currentLayoutId&&this.revokeBlobUrlsForLayout(this.currentLayoutId),this._clearRegionTimers(this.regions);for(const[t,i]of this.regions)if(i.widgets.length>0&&this.stopWidget(t,i.currentIndex),Z.releaseMediaElements(i.element),(e=i.config)!=null&&e.exitTransition){const n=ie.apply(i.element,i.config.exitTransition,!1,i.width,i.height);if(n){const o=i.element;n.onfinish=()=>o.remove()}else i.element.remove()}else i.element.remove()}this.regions.clear(),this.currentLayoutId&&!this.layoutEndEmitted&&this.emit("layoutEnd",this.currentLayoutId),this.layoutEndEmitted=!1,this.currentLayout=null,this.currentLayoutId=null}}async renderOverlay(e,t,i=0){try{if(this.log.info(`Rendering overlay ${t} (priority ${i})`),this.activeOverlays.has(t)){this.log.warn(`Overlay ${t} already active, skipping`);return}const n=this.parseXlf(e),o=document.createElement("div");o.id=`overlay_${t}`,o.className="renderer-lite-overlay",o.style.position="absolute",o.style.top="0",o.style.left="0",o.style.width="100%",o.style.height="100%",o.style.zIndex=String(1e3+i),o.style.pointerEvents="auto",o.style.backgroundColor=n.bgcolor,this.calculateScale(n);const s=new Map,r=this.scaleFactor;for(const a of n.regions){const l=document.createElement("div");l.id=`overlay_${t}_region_${a.id}`,l.className="renderer-lite-region overlay-region",l.style.position="absolute",l.style.zIndex=String(a.zindex),l.style.overflow="hidden",this.applyRegionScale(l,a),o.appendChild(l),s.set(a.id,{element:l,config:a,widgets:a.widgets,currentIndex:0,timer:null,width:a.width*r,height:a.height*r,complete:!1,isCanvas:a.isCanvas||!1,widgetElements:new Map})}for(const[a,l]of s)for(const c of l.widgets){c.layoutId=t,c.regionId=a;try{const d=await this.createWidgetElement(c,l);this._positionWidgetElement(d),l.element.appendChild(d),l.widgetElements.set(c.id,d)}catch(d){this.log.error(`Failed to pre-create overlay widget ${c.id}:`,d)}}this.overlayContainer.appendChild(o),this.activeOverlays.set(t,{container:o,layout:n,regions:s,timer:null,priority:i}),this.emit("overlayStart",t,n);for(const[a,l]of s)this.startOverlayRegion(t,a);if(n.duration>0){const a=n.duration*1e3,l=this.activeOverlays.get(t);l&&(l.timer=setTimeout(()=>{this.log.info(`Overlay ${t} duration expired (${n.duration}s)`),this.emit("overlayEnd",t)},a))}this.log.info(`Overlay ${t} started`)}catch(n){throw this.log.error("Error rendering overlay:",n),this.emit("error",{type:"overlayError",error:n,layoutId:t}),n}}startOverlayRegion(e,t){const i=this.activeOverlays.get(e);if(!i)return;const n=i.regions.get(t);this._startRegionCycle(n,t,(o,s)=>this.renderOverlayWidget(e,o,s),(o,s)=>this.stopOverlayWidget(e,o,s),()=>this.log.info(`Overlay ${e} region ${t} completed one full cycle`))}async renderOverlayWidget(e,t,i){var s;const n=this.activeOverlays.get(e);if(!n)return;const o=n.regions.get(t);if(o)try{const r=await this._showWidget(o,i);r&&(this.log.info(`Showing overlay widget ${r.type} (${r.id}) in overlay ${e} region ${t}`),this.emit("overlayWidgetStart",{overlayId:e,widgetId:r.id,regionId:t,type:r.type,duration:r.duration}))}catch(r){this.log.error("Error rendering overlay widget:",r),this.emit("error",{type:"overlayWidgetError",error:r,widgetId:(s=o.widgets[i])==null?void 0:s.id,regionId:t,overlayId:e})}}async stopOverlayWidget(e,t,i){const n=this.activeOverlays.get(e);if(!n)return;const o=n.regions.get(t);if(!o)return;const{widget:s,animPromise:r}=this._hideWidget(o,i);r&&await r,s&&this.emit("overlayWidgetEnd",{overlayId:e,widgetId:s.id,regionId:t,type:s.type})}stopOverlay(e){const t=this.activeOverlays.get(e);if(!t){this.log.warn(`Overlay ${e} not active`);return}this.log.info(`Stopping overlay ${e}`),t.timer&&(clearTimeout(t.timer),t.timer=null);for(const[i,n]of t.regions)n.timer&&(clearTimeout(n.timer),n.timer=null),n.widgets.length>0&&this.stopOverlayWidget(e,i,n.currentIndex);t.container&&t.container.remove(),this.revokeBlobUrlsForLayout(e),this.activeOverlays.delete(e),this.emit("overlayEnd",e),this.log.info(`Overlay ${e} stopped`)}stopAllOverlays(){const e=Array.from(this.activeOverlays.keys());for(const t of e)this.stopOverlay(t);this.log.info("All overlays stopped")}getActiveOverlays(){return Array.from(this.activeOverlays.keys())}pause(){if(!this._paused){this._paused=!0;for(const[,e]of this.regions)e.timer&&(clearTimeout(e.timer),e.timer=null);this._forEachMedia(e=>e.pause()),this.emit("paused"),this.log.info("Playback paused (layout timer continues)")}}isPaused(){return this._paused}resume(){if(this._paused){this._paused=!1,this._forEachMedia(e=>e.play().catch(()=>{}));for(const[e]of this.regions)this.startRegion(e);this.emit("resumed"),this.log.info("Playback resumed")}}_forEachMedia(e){var t;for(const[,i]of this.regions)(t=i.element)==null||t.querySelectorAll("video, audio").forEach(e)}cleanup(){this.stopAllOverlays(),this.stopCurrentLayout();for(const e of this.audioOverlays.keys())this._stopAudioOverlays(e);this.layoutPool.clear(),this.preloadTimer&&(clearTimeout(this.preloadTimer),this.preloadTimer=null),this._preloadRetryTimer&&(clearTimeout(this._preloadRetryTimer),this._preloadRetryTimer=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.container.innerHTML="",this.log.info("Cleaned up")}}const V=H("Layout");class mt{constructor(e){this.xmds=e}async translateXLF(e,t){const n=new DOMParser().parseFromString(t,"text/xml"),o=n.querySelector("layout");if(!o)throw new Error("Invalid XLF: no <layout> element");const s=parseInt(o.getAttribute("width")||"1920"),r=parseInt(o.getAttribute("height")||"1080"),a=o.getAttribute("bgcolor")||"#000000",l=[];for(const c of n.querySelectorAll("region"))l.push(await this.translateRegion(e,c));return this.generateHTML(s,r,a,l)}async translateRegion(e,t){const i=t.getAttribute("id"),n=parseInt(t.getAttribute("width")),o=parseInt(t.getAttribute("height")),s=parseInt(t.getAttribute("top")),r=parseInt(t.getAttribute("left")),a=parseInt(t.getAttribute("zindex")||"0"),l=[];for(const c of t.querySelectorAll("media"))l.push(await this.translateMedia(e,i,c));return{id:i,width:n,height:o,top:s,left:r,zindex:a,media:l}}async translateMedia(e,t,i){const n=i.getAttribute("type"),o=parseInt(i.getAttribute("duration")||"10"),s=i.getAttribute("id"),r=i.querySelector("options"),a=i.querySelector("raw"),l={};if(r)for(const $ of r.children)l[$.tagName]=$.textContent;const c={in:null,out:null},d=i.querySelector("options > transIn"),h=i.querySelector("options > transOut"),g=i.querySelector("options > transInDuration"),p=i.querySelector("options > transOutDuration"),w=i.querySelector("options > transInDirection"),m=i.querySelector("options > transOutDirection");d&&d.textContent&&(c.in={type:d.textContent,duration:parseInt((g==null?void 0:g.textContent)||"1000"),direction:(w==null?void 0:w.textContent)||"N"}),h&&h.textContent&&(c.out={type:h.textContent,duration:parseInt((p==null?void 0:p.textContent)||"1000"),direction:(m==null?void 0:m.textContent)||"N"});let v=a?a.textContent:"";if(["clock","clock-digital","clock-analogue","calendar","weather","currencies","stocks","twitter","global","embedded","text","ticker"].some($=>n.includes($))){let $=3,T=null;for(let x=1;x<=$;x++)try{V.info(`Fetching resource for ${n} widget (layout=${e}, region=${t}, media=${s}) - attempt ${x}/${$}`),v=await this.xmds.getResource(e,t,s),V.info(`Got resource HTML (${v.length} chars)`);const I=await We(e,t,s,v);l.widgetCacheKey=I;break}catch(I){if(T=I,V.warn(`Failed to get resource (attempt ${x}/${$}):`,I.message),x<$){const S=x*2e3;V.info(`Retrying in ${S}ms...`),await new Promise(b=>setTimeout(b,S))}}if(!v&&T){V.warn("All retries failed, checking for cached widget HTML...");try{const x=await fetch(`/store${B}/widgets/${e}/${t}/${s}`);x.ok?(v=await x.text(),l.widgetCacheKey=`${B}/widgets/${e}/${t}/${s}`,V.info(`Using stored widget HTML (${v.length} chars) - CMS update pending`)):(V.error(`No stored version available for widget ${s}`),v='<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#999;font-size:18px;">Content updating...</div>')}catch(x){V.error("Store fallback failed:",x),v='<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#999;font-size:18px;">Content updating...</div>'}}}return{type:n,duration:o,id:s,options:l,raw:v,transitions:c}}generateHTML(e,t,i,n){const o=n.map(r=>this.generateRegionHTML(r)).join(`
3
+ `),s=n.map(r=>this.generateRegionJS(r)).join(`,
4
+ `);return`<!DOCTYPE html>
5
+ <html>
6
+ <head>
7
+ <meta charset="utf-8">
8
+ <meta name="viewport" content="width=${e}, height=${t}">
9
+ <style>
10
+ * { margin: 0; padding: 0; box-sizing: border-box; }
11
+ html, body { width: 100%; height: 100%; overflow: hidden; }
12
+ body { background-color: ${i}; }
13
+ .region {
14
+ position: absolute;
15
+ overflow: hidden;
16
+ }
17
+ .media {
18
+ width: 100%;
19
+ height: 100%;
20
+ object-fit: contain;
21
+ }
22
+ iframe {
23
+ border: none;
24
+ width: 100%;
25
+ height: 100%;
26
+ }
27
+ </style>
28
+ </head>
29
+ <body>
30
+ ${o}
31
+ <script>
32
+ // Transition utilities
33
+ window.Transitions = {
34
+ fadeIn(element, duration) {
35
+ const keyframes = [
36
+ { opacity: 0 },
37
+ { opacity: 1 }
38
+ ];
39
+ const timing = {
40
+ duration: duration,
41
+ easing: 'linear',
42
+ fill: 'forwards'
43
+ };
44
+ return element.animate(keyframes, timing);
45
+ },
46
+
47
+ fadeOut(element, duration) {
48
+ const keyframes = [
49
+ { opacity: 1 },
50
+ { opacity: 0 }
51
+ ];
52
+ const timing = {
53
+ duration: duration,
54
+ easing: 'linear',
55
+ fill: 'forwards'
56
+ };
57
+ return element.animate(keyframes, timing);
58
+ },
59
+
60
+ getFlyKeyframes(direction, width, height, isIn) {
61
+ const dirMap = {
62
+ 'N': { x: 0, y: isIn ? -height : height },
63
+ 'NE': { x: isIn ? width : -width, y: isIn ? -height : height },
64
+ 'E': { x: isIn ? width : -width, y: 0 },
65
+ 'SE': { x: isIn ? width : -width, y: isIn ? height : -height },
66
+ 'S': { x: 0, y: isIn ? height : -height },
67
+ 'SW': { x: isIn ? -width : width, y: isIn ? height : -height },
68
+ 'W': { x: isIn ? -width : width, y: 0 },
69
+ 'NW': { x: isIn ? -width : width, y: isIn ? -height : height }
70
+ };
71
+
72
+ const offset = dirMap[direction] || dirMap['N'];
73
+
74
+ if (isIn) {
75
+ return [
76
+ { transform: \`translate(\${offset.x}px, \${offset.y}px)\`, opacity: 0 },
77
+ { transform: 'translate(0, 0)', opacity: 1 }
78
+ ];
79
+ } else {
80
+ return [
81
+ { transform: 'translate(0, 0)', opacity: 1 },
82
+ { transform: \`translate(\${offset.x}px, \${offset.y}px)\`, opacity: 0 }
83
+ ];
84
+ }
85
+ },
86
+
87
+ flyIn(element, duration, direction, regionWidth, regionHeight) {
88
+ const keyframes = this.getFlyKeyframes(direction, regionWidth, regionHeight, true);
89
+ const timing = {
90
+ duration: duration,
91
+ easing: 'ease-out',
92
+ fill: 'forwards'
93
+ };
94
+ return element.animate(keyframes, timing);
95
+ },
96
+
97
+ flyOut(element, duration, direction, regionWidth, regionHeight) {
98
+ const keyframes = this.getFlyKeyframes(direction, regionWidth, regionHeight, false);
99
+ const timing = {
100
+ duration: duration,
101
+ easing: 'ease-in',
102
+ fill: 'forwards'
103
+ };
104
+ return element.animate(keyframes, timing);
105
+ },
106
+
107
+ apply(element, transitionConfig, isIn, regionWidth, regionHeight) {
108
+ if (!transitionConfig || !transitionConfig.type) {
109
+ return null;
110
+ }
111
+
112
+ const type = transitionConfig.type.toLowerCase();
113
+ const duration = transitionConfig.duration || 1000;
114
+ const direction = transitionConfig.direction || 'N';
115
+
116
+ switch (type) {
117
+ case 'fade':
118
+ return isIn ? this.fadeIn(element, duration) : this.fadeOut(element, duration);
119
+ case 'fadein':
120
+ return isIn ? this.fadeIn(element, duration) : null;
121
+ case 'fadeout':
122
+ return isIn ? null : this.fadeOut(element, duration);
123
+ case 'fly':
124
+ return isIn
125
+ ? this.flyIn(element, duration, direction, regionWidth, regionHeight)
126
+ : this.flyOut(element, duration, direction, regionWidth, regionHeight);
127
+ case 'flyin':
128
+ return isIn ? this.flyIn(element, duration, direction, regionWidth, regionHeight) : null;
129
+ case 'flyout':
130
+ return isIn ? null : this.flyOut(element, duration, direction, regionWidth, regionHeight);
131
+ default:
132
+ return null;
133
+ }
134
+ }
135
+ };
136
+
137
+ const regions = {
138
+ ${s}
139
+ };
140
+
141
+ // Auto-start all regions
142
+ Object.keys(regions).forEach(id => {
143
+ playRegion(id);
144
+ });
145
+
146
+ // Track active timers per region so layout teardown can cancel them
147
+ const regionTimers = {};
148
+
149
+ function playRegion(id) {
150
+ const region = regions[id];
151
+ if (!region || region.media.length === 0) return;
152
+
153
+ regionTimers[id] = [];
154
+
155
+ // If only one media item, just show it and don't cycle (arexibo behavior)
156
+ if (region.media.length === 1) {
157
+ const media = region.media[0];
158
+ if (media.start) media.start();
159
+ return; // Don't schedule stop/restart
160
+ }
161
+
162
+ // Multiple media items - cycle normally
163
+ let currentIndex = 0;
164
+
165
+ function playNext() {
166
+ const media = region.media[currentIndex];
167
+ if (media.start) media.start();
168
+
169
+ const duration = media.duration || 10;
170
+ const timerId = setTimeout(() => {
171
+ if (media.stop) media.stop();
172
+ currentIndex = (currentIndex + 1) % region.media.length;
173
+ playNext();
174
+ }, duration * 1000);
175
+ regionTimers[id].push(timerId);
176
+ }
177
+
178
+ playNext();
179
+ }
180
+
181
+ // Cleanup function — called before layout teardown
182
+ window._stopAllRegions = function() {
183
+ Object.values(regionTimers).forEach(timers => timers.forEach(t => clearTimeout(t)));
184
+ };
185
+ <\/script>
186
+ </body>
187
+ </html>`}generateRegionHTML(e){return` <div id="region_${e.id}" class="region" style="
188
+ left: ${e.left}px;
189
+ top: ${e.top}px;
190
+ width: ${e.width}px;
191
+ height: ${e.height}px;
192
+ z-index: ${e.zindex};
193
+ "></div>`}generateRegionJS(e){const t=e.media.map(i=>this.generateMediaJS(i,e.id)).join(`,
194
+ `);return` '${e.id}': {
195
+ media: [
196
+ ${t}
197
+ ]
198
+ }`}_generateIframeWidgetJS(e,t,i,n,o){const s=`widget_${e}_${t}`,r=`() => {
199
+ const region = document.getElementById('region_${e}');
200
+ let iframe = document.getElementById('${s}');
201
+ if (!iframe) {
202
+ iframe = document.createElement('iframe');
203
+ iframe.id = '${s}';
204
+ iframe.src = '${i}';
205
+ iframe.style.width = '100%';
206
+ iframe.style.height = '100%';
207
+ iframe.style.border = 'none';
208
+ iframe.scrolling = 'no';
209
+ iframe.style.opacity = '0';
210
+ region.innerHTML = '';
211
+ region.appendChild(iframe);
212
+
213
+ // Apply transition after iframe loads
214
+ iframe.onload = () => {
215
+ const transIn = ${n};
216
+ if (transIn && window.Transitions) {
217
+ const regionRect = region.getBoundingClientRect();
218
+ window.Transitions.apply(iframe, transIn, true, regionRect.width, regionRect.height);
219
+ } else {
220
+ iframe.style.opacity = '1';
221
+ }
222
+ };
223
+ } else {
224
+ iframe.style.display = 'block';
225
+ iframe.style.opacity = '1';
226
+ }
227
+ }`,a=`() => {
228
+ const region = document.getElementById('region_${e}');
229
+ const iframe = document.getElementById('${s}');
230
+ if (iframe) {
231
+ const transOut = ${o};
232
+ if (transOut && window.Transitions) {
233
+ const regionRect = region.getBoundingClientRect();
234
+ const animation = window.Transitions.apply(iframe, transOut, false, regionRect.width, regionRect.height);
235
+ if (animation) {
236
+ animation.onfinish = () => {
237
+ iframe.style.display = 'none';
238
+ };
239
+ return;
240
+ }
241
+ }
242
+ iframe.style.display = 'none';
243
+ }
244
+ }`;return{startFn:r,stopFn:a}}generateMediaJS(e,t){var a,l;const i=e.duration||10,n=(a=e.transitions)!=null&&a.in?JSON.stringify(e.transitions.in):"null",o=(l=e.transitions)!=null&&l.out?JSON.stringify(e.transitions.out):"null";let s="null",r="null";switch(e.type){case"image":const c=`${window.location.origin}${B}/media/${e.options.uri}`;s=`() => {
245
+ const region = document.getElementById('region_${t}');
246
+ const img = document.createElement('img');
247
+ img.className = 'media';
248
+ img.src = '${c}';
249
+ img.style.opacity = '0';
250
+ region.innerHTML = '';
251
+ region.appendChild(img);
252
+
253
+ // Apply transition
254
+ const transIn = ${n};
255
+ if (transIn && window.Transitions) {
256
+ const regionRect = region.getBoundingClientRect();
257
+ window.Transitions.apply(img, transIn, true, regionRect.width, regionRect.height);
258
+ } else {
259
+ img.style.opacity = '1';
260
+ }
261
+ }`;break;case"video":const d=`${window.location.origin}${B}/media/${e.options.uri}`,h=e.options.uri;s=`() => {
262
+ const region = document.getElementById('region_${t}');
263
+ const video = document.createElement('video');
264
+ video.className = 'media';
265
+ video.src = '${d}';
266
+ video.dataset.filename = '${h}';
267
+ video.autoplay = true;
268
+ video.muted = ${e.options.mute==="1"?"true":"false"};
269
+ video.loop = false;
270
+ video.style.width = '100%';
271
+ video.style.height = '100%';
272
+ video.style.objectFit = 'contain';
273
+ video.style.opacity = '0';
274
+
275
+ // Retry loading if cache completes while video is playing
276
+ const retryOnCache = (event) => {
277
+ if (event.detail.filename === '${h}' && video.error) {
278
+ console.log('[Video] Cache complete, reloading:', '${h}');
279
+ video.load();
280
+ video.play();
281
+ }
282
+ };
283
+ video._retryOnCache = retryOnCache;
284
+ window.addEventListener('media-cached', retryOnCache);
285
+
286
+ region.innerHTML = '';
287
+ region.appendChild(video);
288
+
289
+ // Apply transition
290
+ const transIn = ${n};
291
+ if (transIn && window.Transitions) {
292
+ const regionRect = region.getBoundingClientRect();
293
+ window.Transitions.apply(video, transIn, true, regionRect.width, regionRect.height);
294
+ } else {
295
+ video.style.opacity = '1';
296
+ }
297
+
298
+ console.log('[Video] Playing:', '${e.options.uri}');
299
+ }`,r=`() => {
300
+ const region = document.getElementById('region_${t}');
301
+ const video = document.querySelector('#region_${t} video');
302
+ if (video) {
303
+ // Remove global media-cached listener to prevent leak
304
+ if (video._retryOnCache) {
305
+ window.removeEventListener('media-cached', video._retryOnCache);
306
+ video._retryOnCache = null;
307
+ }
308
+ const transOut = ${o};
309
+ if (transOut && window.Transitions) {
310
+ const regionRect = region.getBoundingClientRect();
311
+ const animation = window.Transitions.apply(video, transOut, false, regionRect.width, regionRect.height);
312
+ if (animation) {
313
+ animation.onfinish = () => {
314
+ video.pause();
315
+ video.remove();
316
+ };
317
+ return;
318
+ }
319
+ }
320
+ video.pause();
321
+ video.remove();
322
+ }
323
+ }`;break;case"text":case"ticker":if(e.options.widgetCacheKey){const x=`${window.location.origin}${e.options.widgetCacheKey}`,I=this._generateIframeWidgetJS(t,e.id,x,n,o);s=I.startFn,r=I.stopFn;break}case"audio":const g=`${window.location.origin}${B}/media/${e.options.uri}`,p=`audio_${t}_${e.id}`,w=e.options.loop==="1",m=(parseInt(e.options.volume||"100")/100).toFixed(2);s=`() => {
324
+ const region = document.getElementById('region_${t}');
325
+
326
+ // Create audio element
327
+ const audio = document.createElement('audio');
328
+ audio.id = '${p}';
329
+ audio.className = 'media';
330
+ audio.src = '${g}';
331
+ audio.autoplay = true;
332
+ audio.loop = ${w};
333
+ audio.volume = ${m};
334
+
335
+ // Create visual feedback container
336
+ const visualContainer = document.createElement('div');
337
+ visualContainer.className = 'audio-visual';
338
+ visualContainer.style.cssText = \`
339
+ width: 100%;
340
+ height: 100%;
341
+ display: flex;
342
+ flex-direction: column;
343
+ align-items: center;
344
+ justify-content: center;
345
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
346
+ opacity: 0;
347
+ \`;
348
+
349
+ // Audio icon
350
+ const icon = document.createElement('div');
351
+ icon.innerHTML = '♪';
352
+ icon.style.cssText = \`
353
+ font-size: 120px;
354
+ color: white;
355
+ margin-bottom: 20px;
356
+ animation: pulse 2s ease-in-out infinite;
357
+ \`;
358
+
359
+ // Audio info
360
+ const info = document.createElement('div');
361
+ info.style.cssText = \`
362
+ color: white;
363
+ font-size: 24px;
364
+ text-align: center;
365
+ padding: 0 20px;
366
+ \`;
367
+ info.textContent = 'Playing Audio';
368
+
369
+ // Filename
370
+ const filename = document.createElement('div');
371
+ filename.style.cssText = \`
372
+ color: rgba(255,255,255,0.7);
373
+ font-size: 16px;
374
+ margin-top: 10px;
375
+ \`;
376
+ filename.textContent = '${e.options.uri}';
377
+
378
+ visualContainer.appendChild(icon);
379
+ visualContainer.appendChild(info);
380
+ visualContainer.appendChild(filename);
381
+
382
+ region.innerHTML = '';
383
+ region.appendChild(audio);
384
+ region.appendChild(visualContainer);
385
+
386
+ // Add pulse animation
387
+ const style = document.createElement('style');
388
+ style.textContent = \`
389
+ @keyframes pulse {
390
+ 0%, 100% { transform: scale(1); opacity: 1; }
391
+ 50% { transform: scale(1.1); opacity: 0.8; }
392
+ }
393
+ \`;
394
+ document.head.appendChild(style);
395
+
396
+ // Apply transition
397
+ const transIn = ${n};
398
+ if (transIn && window.Transitions) {
399
+ const regionRect = region.getBoundingClientRect();
400
+ window.Transitions.apply(visualContainer, transIn, true, regionRect.width, regionRect.height);
401
+ } else {
402
+ visualContainer.style.opacity = '1';
403
+ }
404
+
405
+ console.log('[Audio] Playing:', '${g}', 'Volume:', ${m}, 'Loop:', ${w});
406
+ }`,r=`() => {
407
+ const audio = document.getElementById('${p}');
408
+ if (audio) {
409
+ audio.pause();
410
+ audio.remove();
411
+ }
412
+ const region = document.getElementById('region_${t}');
413
+ if (region) {
414
+ const visualContainer = region.querySelector('.audio-visual');
415
+ if (visualContainer) {
416
+ const transOut = ${o};
417
+ if (transOut && window.Transitions) {
418
+ const regionRect = region.getBoundingClientRect();
419
+ const animation = window.Transitions.apply(visualContainer, transOut, false, regionRect.width, regionRect.height);
420
+ if (animation) {
421
+ animation.onfinish = () => visualContainer.remove();
422
+ return;
423
+ }
424
+ }
425
+ visualContainer.remove();
426
+ }
427
+ }
428
+ }`;break;case"pdf":const v=`${window.location.origin}${B}/media/${e.options.uri}`,_=`pdf_${t}_${e.id}`,$=i;s=`async () => {
429
+ const container = document.createElement('div');
430
+ container.className = 'media pdf-container';
431
+ container.id = '${_}';
432
+ container.style.width = '100%';
433
+ container.style.height = '100%';
434
+ container.style.overflow = 'hidden';
435
+ container.style.backgroundColor = '#525659';
436
+ container.style.opacity = '0';
437
+ container.style.position = 'relative';
438
+
439
+ const region = document.getElementById('region_${t}');
440
+ region.innerHTML = '';
441
+ region.appendChild(container);
442
+
443
+ // Load PDF.js if not already loaded
444
+ if (typeof pdfjsLib === 'undefined') {
445
+ try {
446
+ const pdfjsModule = await import('pdfjs-dist');
447
+ window.pdfjsLib = pdfjsModule;
448
+ pdfjsLib.GlobalWorkerOptions.workerSrc = '${window.location.origin}/player/pdf.worker.min.mjs';
449
+ } catch (error) {
450
+ console.error('[PDF] Failed to load PDF.js:', error);
451
+ container.innerHTML = '<div style="color:white;padding:20px;text-align:center;">PDF viewer unavailable</div>';
452
+ return;
453
+ }
454
+ }
455
+
456
+ // Render PDF with multi-page support
457
+ try {
458
+ const loadingTask = pdfjsLib.getDocument('${v}');
459
+ const pdf = await loadingTask.promise;
460
+ const totalPages = pdf.numPages;
461
+
462
+ // Calculate time per page (distribute total duration across all pages)
463
+ const timePerPage = (${$} * 1000) / totalPages; // milliseconds per page
464
+
465
+ console.log(\`[PDF] Loading: \${totalPages} pages, \${timePerPage}ms per page\`);
466
+
467
+ const containerWidth = container.offsetWidth || ${width};
468
+ const containerHeight = container.offsetHeight || ${height};
469
+
470
+ // Create page indicator
471
+ const pageIndicator = document.createElement('div');
472
+ pageIndicator.className = 'pdf-page-indicator';
473
+ pageIndicator.style.cssText = \`
474
+ position: absolute;
475
+ bottom: 10px;
476
+ right: 10px;
477
+ background: rgba(0,0,0,0.7);
478
+ color: white;
479
+ padding: 8px 12px;
480
+ border-radius: 4px;
481
+ font-size: 14px;
482
+ z-index: 10;
483
+ \`;
484
+ container.appendChild(pageIndicator);
485
+
486
+ let currentPage = 1;
487
+ let pageTimers = [];
488
+
489
+ // Function to render a single page
490
+ async function renderPage(pageNum) {
491
+ const page = await pdf.getPage(pageNum);
492
+ const viewport = page.getViewport({ scale: 1 });
493
+
494
+ // Calculate scale to fit page within container
495
+ const scaleX = containerWidth / viewport.width;
496
+ const scaleY = containerHeight / viewport.height;
497
+ const scale = Math.min(scaleX, scaleY);
498
+
499
+ const scaledViewport = page.getViewport({ scale });
500
+
501
+ const canvas = document.createElement('canvas');
502
+ canvas.className = 'pdf-page';
503
+ const context = canvas.getContext('2d');
504
+ canvas.width = scaledViewport.width;
505
+ canvas.height = scaledViewport.height;
506
+
507
+ // Center canvas in container
508
+ canvas.style.cssText = \`
509
+ display: block;
510
+ margin: auto;
511
+ margin-top: \${Math.max(0, (containerHeight - scaledViewport.height) / 2)}px;
512
+ position: absolute;
513
+ top: 0;
514
+ left: 50%;
515
+ transform: translateX(-50%);
516
+ opacity: 0;
517
+ transition: opacity 0.5s ease-in-out;
518
+ \`;
519
+
520
+ container.appendChild(canvas);
521
+
522
+ await page.render({
523
+ canvasContext: context,
524
+ viewport: scaledViewport
525
+ }).promise;
526
+
527
+ // Fade in new page
528
+ setTimeout(() => canvas.style.opacity = '1', 50);
529
+
530
+ return canvas;
531
+ }
532
+
533
+ // Function to cycle through pages
534
+ async function cyclePage() {
535
+ // Update page indicator
536
+ pageIndicator.textContent = \`Page \${currentPage} / \${totalPages}\`;
537
+
538
+ // Remove old pages
539
+ const oldPages = container.querySelectorAll('.pdf-page');
540
+ oldPages.forEach(oldPage => {
541
+ if (oldPage !== container.lastChild) {
542
+ oldPage.style.opacity = '0';
543
+ setTimeout(() => oldPage.remove(), 500);
544
+ }
545
+ });
546
+
547
+ // Render current page
548
+ await renderPage(currentPage);
549
+
550
+ console.log(\`[PDF] Showing page \${currentPage}/\${totalPages}\`);
551
+
552
+ // Schedule next page
553
+ if (totalPages > 1) {
554
+ const timer = setTimeout(() => {
555
+ currentPage = currentPage >= totalPages ? 1 : currentPage + 1;
556
+ cyclePage();
557
+ }, timePerPage);
558
+ pageTimers.push(timer);
559
+ }
560
+ }
561
+
562
+ // Store live timer array on element for cleanup (not JSON — stays current)
563
+ container._pageTimers = pageTimers;
564
+
565
+ // Start cycling
566
+ await cyclePage();
567
+
568
+ // Apply transition to container
569
+ const transIn = ${n};
570
+ if (transIn && window.Transitions) {
571
+ const regionRect = region.getBoundingClientRect();
572
+ window.Transitions.apply(container, transIn, true, regionRect.width, regionRect.height);
573
+ } else {
574
+ container.style.opacity = '1';
575
+ }
576
+
577
+ } catch (error) {
578
+ console.error('[PDF] Render failed:', error);
579
+ container.innerHTML = '<div style="color:white;padding:20px;text-align:center;">Failed to load PDF</div>';
580
+ container.style.opacity = '1';
581
+ }
582
+ }`,r=`() => {
583
+ const region = document.getElementById('region_${t}');
584
+ const container = document.getElementById('${_}');
585
+ if (container) {
586
+ // Clear page cycling timers (live array, always current)
587
+ if (container._pageTimers) {
588
+ container._pageTimers.forEach(t => clearTimeout(t));
589
+ container._pageTimers.length = 0;
590
+ }
591
+
592
+ const transOut = ${o};
593
+ if (transOut && window.Transitions) {
594
+ const regionRect = region.getBoundingClientRect();
595
+ const animation = window.Transitions.apply(container, transOut, false, regionRect.width, regionRect.height);
596
+ if (animation) {
597
+ animation.onfinish = () => {
598
+ container.remove();
599
+ };
600
+ return;
601
+ }
602
+ }
603
+ container.remove();
604
+ }
605
+ }`;break;case"webpage":const T=decodeURIComponent(e.options.uri||"");s=`() => {
606
+ const region = document.getElementById('region_${t}');
607
+ const iframe = document.createElement('iframe');
608
+ iframe.src = '${T}';
609
+ iframe.style.opacity = '0';
610
+ region.innerHTML = '';
611
+ region.appendChild(iframe);
612
+
613
+ // Apply transition after iframe loads
614
+ iframe.onload = () => {
615
+ const transIn = ${n};
616
+ if (transIn && window.Transitions) {
617
+ const regionRect = region.getBoundingClientRect();
618
+ window.Transitions.apply(iframe, transIn, true, regionRect.width, regionRect.height);
619
+ } else {
620
+ iframe.style.opacity = '1';
621
+ }
622
+ };
623
+ }`;break;default:if(e.options.widgetCacheKey){const x=`${window.location.origin}${e.options.widgetCacheKey}`,I=this._generateIframeWidgetJS(t,e.id,x,n,o);s=I.startFn,r=I.stopFn}else V.warn(`Unsupported media type: ${e.type}`),s=`() => console.log('Unsupported media type: ${e.type}')`}return` {
624
+ start: ${s},
625
+ stop: ${r},
626
+ duration: ${i}
627
+ }`}}const N=H("DataConnector");class ot extends Ae{constructor(){super(),this.connectors=new Map}setConnectors(e){if(this.stopPolling(),this.connectors.clear(),!e||e.length===0){N.debug("No data connectors configured");return}for(const t of e){if(!t.dataKey||!t.url){N.warn("Skipping data connector with missing dataKey or url:",t);continue}this.connectors.set(t.dataKey,{config:t,data:null,timer:null,lastFetch:null}),N.info(`Registered data connector: ${t.dataKey} (interval: ${t.updateInterval}s)`)}N.info(`${this.connectors.size} data connector(s) configured`)}startPolling(){for(const[e,t]of this.connectors.entries()){const{config:i}=t,n=(i.updateInterval||300)*1e3;this.fetchData(t).catch(o=>{N.error(`Initial fetch failed for ${e}:`,o)}),t.timer=setInterval(()=>{this.fetchData(t).catch(o=>{N.error(`Polling fetch failed for ${e}:`,o)})},n),N.debug(`Started polling for ${e} every ${i.updateInterval}s`)}}stopPolling(){for(const[e,t]of this.connectors.entries())t.timer&&(clearInterval(t.timer),t.timer=null,N.debug(`Stopped polling for ${e}`))}getData(e){const t=this.connectors.get(e);return t?t.data:(N.debug(`No data connector found for key: ${e}`),null)}getAvailableKeys(){const e=[];for(const[t,i]of this.connectors.entries())i.data!==null&&e.push(t);return e}async fetchData(e){const{config:t}=e,{dataKey:i,url:n}=t;N.debug(`Fetching data for ${i}: ${n}`);try{const o=await Oe(n,{method:"GET",headers:{Accept:"application/json"}},{maxRetries:2,baseDelayMs:2e3});if(!o.ok){N.warn(`Data connector ${i} returned ${o.status}: ${o.statusText}`);return}const s=o.headers.get("Content-Type")||"";let r;s.includes("application/json")?r=await o.json():r=await o.text();const a=e.data;e.data=r,e.lastFetch=Date.now(),N.debug(`Data updated for ${i} (fetched at ${new Date(e.lastFetch).toISOString()})`),this.emit("data-updated",i,r),JSON.stringify(a)!==JSON.stringify(r)&&this.emit("data-changed",i,r)}catch(o){N.error(`Failed to fetch data for ${i}:`,o),this.emit("fetch-error",i,o)}}cleanup(){this.stopPolling(),this.connectors.clear(),this.removeAllListeners(),N.debug("DataConnectorManager cleaned up")}}const f=H("PlayerCore"),fe="xibo-offline-cache",st=1,Y="cache";function z(y){return parseInt(String(y).replace(".xlf",""),10)}function ye(y){const e=y?`${fe}-${y}`:fe;return new Promise((t,i)=>{const n=indexedDB.open(e,st);n.onupgradeneeded=()=>{const o=n.result;o.objectStoreNames.contains(Y)||o.createObjectStore(Y)},n.onsuccess=()=>t(n.result),n.onerror=()=>i(n.error)})}class rt extends Ae{constructor(e){super(),this.config=e.config,this.xmds=e.xmds,this.cache=e.cache,this.schedule=e.schedule,this.renderer=e.renderer,this.XmrWrapper=e.xmrWrapper,this.statsCollector=e.statsCollector,this.displaySettings=e.displaySettings,this._cmsId=e.cmsId||null,this.dataConnectorManager=new ot,this.xmr=null,this.currentLayoutId=null,this.collecting=!1,this.collectionInterval=null,this.pendingLayouts=new Map,this._layoutMediaStatus=new Map,this.offlineMode=!1,this._normalCollectInterval=null,this._offlineRetrySeconds=0,this._lastCheckRf=null,this._lastCheckSchedule=null,this._lastTimelineFingerprint=null,this._lastTimeline=null,this._layoutOverride=null,this._lastRequiredFiles=[],this._executedCommands=new Set,this.displayCommands=null,this._faultReportingInterval=null,this._faultReportingSeconds=60,this._layoutBlacklist=new Map,this._blacklistThreshold=3,this._lastLayoutChangeTime=null,this._statusCode=2,this._dynamicLayouts=new Set,this.syncConfig=null,this.syncManager=null,this._layoutDurations=new Map,this.cacheAnalyzer=this.cache?new Ne(this.cache):null,this._offlineCache={schedule:null,settings:null,requiredFiles:null},this._offlineDbReady=this._initOfflineCache()}get _queueOptions(){return{dynamicLayouts:this._dynamicLayouts}}_scheduleAutoRevert(e,t,i){t>0&&setTimeout(()=>{var n;((n=this._layoutOverride)==null?void 0:n.layoutId)===e&&(f.info(`${i} duration expired (${t}s), reverting to schedule`),this.revertToSchedule())},t*1e3)}async _initOfflineCache(){try{const e=await ye(this._cmsId),i=e.transaction(Y,"readonly").objectStore(Y),[n,o,s,r]=await Promise.all([new Promise(a=>{const l=i.get("schedule");l.onsuccess=()=>a(l.result??null),l.onerror=()=>a(null)}),new Promise(a=>{const l=i.get("settings");l.onsuccess=()=>a(l.result??null),l.onerror=()=>a(null)}),new Promise(a=>{const l=i.get("requiredFiles");l.onsuccess=()=>a(l.result??null),l.onerror=()=>a(null)}),new Promise(a=>{const l=i.get("durations");l.onsuccess=()=>a(l.result??null),l.onerror=()=>a(null)})]);if(Array.isArray(r)&&r.length>0){for(const[a,l]of r)this._layoutDurations.set(a,l);f.info(`[Timeline] Restored ${r.length} cached durations from IDB`)}this._offlineCache={schedule:n,settings:o,requiredFiles:s},e.close(),f.info("Offline cache loaded from IndexedDB",n?"(has schedule)":"(empty)")}catch(e){f.warn("Failed to load offline cache from IndexedDB:",e)}}async _offlineSave(e,t){this._offlineCache[e]=t;try{const i=await ye(this._cmsId),n=i.transaction(Y,"readwrite");n.objectStore(Y).put(t,e),await new Promise((o,s)=>{n.oncomplete=o,n.onerror=()=>s(n.error)}),i.close()}catch(i){f.warn("Failed to save offline cache:",e,i)}}hasCachedData(){return this._offlineCache.schedule!==null}isOffline(){return typeof navigator<"u"&&navigator.onLine===!1}isInOfflineMode(){return this.offlineMode}collectOffline(){if(f.warn("Offline mode — using cached schedule"),this.offlineMode||(this.offlineMode=!0,this.emit("offline-mode",!0)),this.collectionInterval&&(this._normalCollectInterval?this._offlineRetrySeconds=Math.min(this._offlineRetrySeconds*2,this._normalCollectInterval):(this._normalCollectInterval=this._currentCollectInterval,this._offlineRetrySeconds=30),this._setCollectionTimer(this._offlineRetrySeconds),f.info(`Offline: retry in ${this._offlineRetrySeconds}s`)),!this.collectionInterval){const i=this._offlineCache.settings;i!=null&&i.settings&&(this.setupCollectionInterval(i.settings),this._normalCollectInterval=this._currentCollectInterval,this._offlineRetrySeconds=30,this._setCollectionTimer(this._offlineRetrySeconds),f.info(`Offline: retry in ${this._offlineRetrySeconds}s`))}const e=this._offlineCache.schedule;e&&(this.schedule.setSchedule(e),this.emit("schedule-received",e));const t=this.schedule.getCurrentLayouts();f.info("Offline layouts:",t),this.emit("layouts-scheduled",t),this._evaluateAndSwitchLayout(t,"Offline"),this.emit("collection-complete")}async _evaluateAndSwitchLayout(e,t){const i=t?`${t}: `:"",{queue:n}=this.schedule.getScheduleQueue(this._layoutDurations,this._queueOptions);if(n.length>0)if(this.currentLayoutId)n.some(s=>z(s.layoutId)===this.currentLayoutId)?(f.info(`Layout ${this.currentLayoutId} playing — queue updated in background, playback continues`),this.emit("layout-already-playing",this.currentLayoutId)):(f.info(`Layout ${this.currentLayoutId} no longer in queue — expiring`),this.currentLayoutId=null,this.emit("layout-expire-current"));else{const o=this.getNextLayout();o&&(f.info(`${i}switching to layout ${o.layoutId}`),this.emit("layout-prepare-request",o.layoutId))}else f.info(`${t?`${t}: n`:"N"}o layouts${t?" in cached schedule":" scheduled, falling back to default"}`),this.emit("no-layouts-scheduled");await this._buildLayoutDurations(),this.logUpcomingTimeline()}async collectNow(){return this._lastCheckRf=null,this._lastCheckSchedule=null,this.collect()}async collect(){var e,t,i,n,o,s,r;if(this.collecting){f.debug("Collection already in progress, skipping");return}this.collecting=!0;try{if(await this._offlineDbReady,f.info("Starting collection cycle..."),this.emit("collection-start"),this.isOffline()){if(this.hasCachedData())return this.collectOffline();throw new Error("Offline with no cached data — cannot start playback")}this.config.ensureXmrKeyPair&&await this.config.ensureXmrKeyPair(),f.debug("Collection step: registerDisplay");const a=await this.xmds.registerDisplay();if(f.info(`Display registered: ${a.code}${(e=a.tags)!=null&&e.length?`, tags: ${a.tags.join(", ")}`:""}`),f.debug("Register result:",JSON.stringify(a)),this._offlineSave("settings",a),this.offlineMode&&(this.offlineMode=!1,f.info("Back online — resuming normal collection"),this.emit("offline-mode",!1),this._normalCollectInterval&&(this._setCollectionTimer(this._normalCollectInterval),this._normalCollectInterval=null,this._offlineRetrySeconds=0)),this.displaySettings&&a.settings){const h=this.displaySettings.applySettings(a.settings);h.changed.includes("collectInterval")&&this.updateCollectionInterval(h.settings.collectInterval),a.settings.logLevel&&Pe(a.settings.logLevel)&&(f.info("Log level updated from CMS:",a.settings.logLevel),this.emit("log-level-changed",a.settings.logLevel))}if((t=this.schedule)!=null&&t.setDisplayProperties&&a.settings&&this.schedule.setDisplayProperties(a.settings),a.syncConfig&&(this.syncConfig=a.syncConfig,f.info("Sync group:",a.syncConfig.isLead?"LEAD":`follower → ${a.syncConfig.syncGroup}`,`(switchDelay: ${a.syncConfig.syncSwitchDelay}ms, videoPauseDelay: ${a.syncConfig.syncVideoPauseDelay}ms)`),this.emit("sync-config",a.syncConfig)),this._applyTagConfig(a.tags),a.commands&&a.commands.length>0){this.displayCommands={};for(const h of a.commands)this.displayCommands[h.commandCode]=h;f.debug("Display commands:",Object.keys(this.displayCommands).join(", "))}this.emit("register-complete",a),f.debug("Collection step: initializeXmr"),await this.initializeXmr(a);const l=a.checkRf||"",c=a.checkSchedule||"";if(!this._lastCheckRf||this._lastCheckRf!==l){this.resetBlacklist(),f.debug("Collection step: requiredFiles");const h=await this.xmds.requiredFiles(),g=h.files||h,p=h.purge||[];if(f.info("Required files:",g.length,p.length>0?`(+ ${p.length} purge)`:""),this._lastCheckRf=l,this.emit("files-received",g),this._offlineSave("requiredFiles",h),p.length>0&&this.emit("purge-request",p),!this._lastCheckSchedule||this._lastCheckSchedule!==c){f.debug("Collection step: schedule");const _=await this.xmds.schedule();f.info("Schedule received"),this._lastCheckSchedule=c,f.debug("Collection step: processing schedule"),this.emit("schedule-received",_),this.schedule.setSchedule(_),this._executedCommands.clear(),this.updateDataConnectors(),this._offlineSave("schedule",_),this.logUpcomingTimeline()}f.debug("Collection step: download-request + mediaInventory");const w=this.schedule.getCurrentLayouts(),{queue:m}=this.schedule.getScheduleQueue(this._layoutDurations,this._queueOptions),v=[...new Set(m.map(_=>z(_.layoutId)))];if(this._lastRequiredFiles=g,(i=this.displaySettings)!=null&&i.isInDownloadWindow&&!this.displaySettings.isInDownloadWindow()){const _=(o=(n=this.displaySettings).getNextDownloadWindow)==null?void 0:o.call(n);f.info(`Outside download window, skipping downloads${_?` (next: ${_.toLocaleTimeString()})`:""}`)}else this.emit("download-request",{layoutOrder:v,files:g,layoutDependants:Object.fromEntries(this.schedule.getDependantsMap())});this.cacheAnalyzer&&this.cacheAnalyzer.analyze(g).then(_=>{this.emit("cache-analysis",_)}).catch(_=>f.warn("Cache analysis failed:",_)),this.submitMediaInventory(g)}else if(l&&f.info("RequiredFiles CRC unchanged, skipping download check"),this._lastCheckSchedule!==c){const h=await this.xmds.schedule();f.info("Schedule received (RF unchanged but schedule changed)"),this._lastCheckSchedule=c,this.emit("schedule-received",h),this.schedule.setSchedule(h),this._executedCommands.clear(),this.updateDataConnectors(),this._offlineSave("schedule",h)}else c&&f.info("Schedule CRC unchanged, skipping");await this._fetchWeatherData(),f.debug("Collection step: evaluateSchedule");const d=this.schedule.getCurrentLayouts();f.info("Current layouts:",d),this.emit("layouts-scheduled",d),this._evaluateAndSwitchLayout(d,""),this._processScheduledCommands(),(((s=a.settings)==null?void 0:s.statsEnabled)==="On"||((r=a.settings)==null?void 0:r.statsEnabled)==="1")&&(this.statsCollector?(f.info("Stats enabled, submitting proof of play"),this.emit("submit-stats-request")):f.warn("Stats enabled but no StatsCollector provided")),this.emit("submit-logs-request"),this.emit("submit-faults-request"),!this.collectionInterval&&a.settings&&this.setupCollectionInterval(a.settings),this._faultReportingInterval||this._startFaultReportingAgent(),this.logUpcomingTimeline(),this.emit("collection-complete")}catch(a){if(this.hasCachedData())return f.warn("Collection failed, falling back to cached data:",(a==null?void 0:a.message)||a),this.emit("collection-error",a),this.collectOffline();throw f.error("Collection error:",a),this.emit("collection-error",a),a}finally{this.collecting=!1}}async initializeXmr(e){var n,o,s,r;const t=((n=e.settings)==null?void 0:n.xmrWebSocketAddress)||((o=e.settings)==null?void 0:o.xmrNetworkAddress);if(!t){f.warn("XMR not configured: no xmrWebSocketAddress or xmrNetworkAddress in CMS settings"),this.emit("xmr-misconfigured",{reason:"missing",message:"XMR address not configured in CMS. Go to CMS Admin → Settings → Configuration → XMR and set the WebSocket address."});return}if(t.startsWith("tcp://")){f.warn(`XMR address uses tcp:// protocol which is not supported by PWA players: ${t}`),f.warn("Configure XMR_WS_ADDRESS in CMS Admin → Settings → Configuration → XMR (e.g. wss://your-domain/xmr)"),this.emit("xmr-misconfigured",{reason:"wrong-protocol",url:t,message:"XMR uses tcp:// protocol (not supported by PWA). Set XMR WebSocket Address to wss://your-domain/xmr in CMS Settings."});return}if(/example\.(org|com|net)/i.test(t)){f.warn(`XMR address contains placeholder domain: ${t}`),f.warn("Configure the real XMR address in CMS Admin → Settings → Configuration → XMR"),this.emit("xmr-misconfigured",{reason:"placeholder",url:t,message:`XMR address is still the default placeholder (${t}). Update it in CMS Settings.`});return}const i=((s=e.settings)==null?void 0:s.xmrCmsKey)||((r=e.settings)==null?void 0:r.serverKey)||this.config.serverKey;f.debug("XMR CMS Key:",i?"present":"missing"),this.xmr?this.xmr.isConnected()?f.debug("XMR already connected"):(f.info("XMR disconnected, attempting to reconnect..."),this.xmr.reconnectAttempts=0,await this.xmr.start(t,i),this.emit("xmr-reconnected",t)):(f.info("Initializing XMR WebSocket:",t),this.xmr=new this.XmrWrapper(this.config,this),await this.xmr.start(t,i),this.emit("xmr-connected",t))}setupCollectionInterval(e){const t=this.displaySettings?this.displaySettings.getCollectInterval():parseInt(e.collectInterval||"300",10);this._setCollectionTimer(t),this.emit("collection-interval-set",t)}updateCollectionInterval(e){this.collectionInterval&&(this._setCollectionTimer(e),this.emit("collection-interval-updated",e))}_startFaultReportingAgent(){this._faultReportingInterval&&clearInterval(this._faultReportingInterval),f.info(`Fault reporting agent started (interval: ${this._faultReportingSeconds}s)`),this._faultReportingInterval=setInterval(()=>{this.emit("submit-faults-request")},this._faultReportingSeconds*1e3)}_setCollectionTimer(e){this.collectionInterval&&clearInterval(this.collectionInterval),this._currentCollectInterval=e,f.info(`Collection interval: ${e}s`),this.collectionInterval=setInterval(()=>{f.debug("Running scheduled collection cycle..."),this.collect().catch(t=>{f.error("Collection error:",t),this.emit("collection-error",t)})},e*1e3)}async requestLayoutChange(e){f.info(`Layout change requested: ${e}`),this.currentLayoutId=null,this.emit("layout-change-requested",e)}setCurrentLayout(e){this.currentLayoutId=e,this._lastLayoutChangeTime=new Date().toISOString(),this._statusCode=1,this.pendingLayouts.delete(e),this._layoutMediaStatus.delete(`${e}.xlf`),this.emit("layout-current",e),this._lastTimelineFingerprint=null,this.logUpcomingTimeline()}setPendingLayout(e,t){this.pendingLayouts.set(e,t),this.emit("layout-pending",e,t)}clearCurrentLayout(){this.currentLayoutId=null,this.emit("layout-cleared")}getNextLayout(){var i;const e=this.schedule.popNextFromQueue(this._layoutDurations,this._queueOptions);if(!e){const n=(i=this.schedule.schedule)==null?void 0:i.default;return n?{layoutId:z(n),layoutFile:n}:null}const t=z(e.layoutId);if(this.isLayoutBlacklisted(t)){const{queue:n}=this.schedule.getScheduleQueue(this._layoutDurations,this._queueOptions);for(let o=0;o<n.length-1;o++){const s=this.schedule.popNextFromQueue(this._layoutDurations,this._queueOptions);if(s){const r=z(s.layoutId);if(!this.isLayoutBlacklisted(r))return{layoutId:r,layoutFile:s.layoutId}}}f.warn("All queued layouts are blacklisted, using current entry as fallback")}return{layoutId:t,layoutFile:e.layoutId}}peekNextLayout(){const e=this.schedule.peekNextInQueue(this._layoutDurations,this._queueOptions);if(!e)return null;const t=z(e.layoutId);if(t===this.currentLayoutId){const i=this.schedule.peekAfterNext(this._layoutDurations,this._queueOptions);if(!i)return null;const n=z(i.layoutId);return n===this.currentLayoutId||this.isLayoutBlacklisted(n)?null:{layoutId:n,layoutFile:i.layoutId}}return this.isLayoutBlacklisted(t)?null:{layoutId:t,layoutFile:e.layoutId}}advanceToNextLayout(){if(this._layoutOverride){f.info("Layout override active, not advancing schedule");return}const e=this.getNextLayout();if(!e){if(this.currentLayoutId){f.info(`No layouts in queue, replaying ${this.currentLayoutId} to avoid blank screen`);const r=this.currentLayoutId;this.currentLayoutId=null,this.emit("layout-prepare-request",r)}else f.info("No layouts scheduled during advance"),this.emit("no-layouts-scheduled");return}const{layoutId:t,layoutFile:i}=e,n=this._layoutDurations.get(i)||"?";if(this._lastTimeline&&this._lastTimeline.length>0){const r=this._lastTimeline.slice(0,2).map(a=>{const l=a.startTime.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit"});return`${a.layoutFile}(${a.duration}s@${l})`});f.debug(`[Timeline] Layout transition: entering ${i} (${n}s), overlay top: [${r.join(", ")}]`),this._lastTimeline[0].layoutFile!==i&&f.warn(`[Timeline] Mismatch: entering ${i} but overlay expects ${this._lastTimeline[0].layoutFile}`)}else f.debug(`[Timeline] Layout transition: entering ${i} (${n}s), no timeline data`);if(this.syncManager&&this.schedule.isSyncEvent(i))if(this.isSyncLead()){f.info(`[Sync] Lead requesting coordinated layout change: ${t}`),this.syncManager.requestLayoutChange(t).catch(r=>{f.error("[Sync] Layout change failed:",r),this.emit("layout-prepare-request",t)});return}else{f.info("[Sync] Follower waiting for lead signal (not advancing independently)");return}t===this.currentLayoutId&&(f.info(`Next layout ${t} is same as current, triggering replay`),this.currentLayoutId=null);const{queue:o}=this.schedule.getScheduleQueue(this._layoutDurations,this._queueOptions),s=this.schedule._queuePosition;f.info(`Advancing to layout ${t} (queue pos ${s}/${o.length})`),this.emit("layout-prepare-request",t)}advanceToPreviousLayout(){if(this._layoutOverride){f.info("Layout override active, not going back");return}const{queue:e}=this.schedule.getScheduleQueue(this._layoutDurations,this._queueOptions);if(e.length<=1){f.info("Single or empty queue, nothing to go back to");return}this.schedule._queuePosition=(this.schedule._queuePosition-2+e.length)%e.length;const t=e[this.schedule._queuePosition];this.schedule._queuePosition=(this.schedule._queuePosition+1)%e.length;const i=z(t.layoutId);if(i===this.currentLayoutId){f.info("Previous layout is same as current, nothing to go back to");return}f.info(`Going back to layout ${i}`),this.emit("layout-prepare-request",i)}notifyMediaReady(e,t="media"){f.debug(`File ${e} ready (${t})`);for(const[i,n]of this.pendingLayouts.entries()){const o=t==="layout"&&i===parseInt(e),s=t==="media"&&n.includes(e);(o||s)&&(f.debug(`${t} ${e} was needed by pending layout ${i}, checking if ready...`),this.emit("check-pending-layout",i,n))}}async notifyLayoutStatus(e){var t,i,n,o;try{const s={currentLayoutId:e,deviceName:((t=this.config)==null?void 0:t.displayName)||"",displayName:((i=this.config)==null?void 0:i.displayName)||"",lastCommandSuccess:this._lastCommandSuccess??!0,code:this._statusCode,lastLayoutChangeTime:this._lastLayoutChangeTime||new Date().toISOString()};(n=this.config)!=null&&n.latitude&&(s.latitude=this.config.latitude),(o=this.config)!=null&&o.longitude&&(s.longitude=this.config.longitude),await this.xmds.notifyStatus(s),this.emit("status-notified",e)}catch(s){f.warn("Failed to notify status:",s),this.emit("status-notify-failed",e,s)}}reportGeoLocation(e){var n;const t=parseFloat(e==null?void 0:e.latitude),i=parseFloat(e==null?void 0:e.longitude);if(isNaN(t)||isNaN(i)){f.warn("reportGeoLocation: invalid coordinates",e);return}f.info(`Geo location from CMS: ${t.toFixed(4)}, ${i.toFixed(4)}`),(n=this.schedule)!=null&&n.setLocation&&this.schedule.setLocation(t,i),this.emit("location-updated",{latitude:t,longitude:i,source:"cms"}),this.checkSchedule()}async requestGeoLocation(){var n;if(this._geoCache&&Date.now()-this._geoCache.ts<18e5)return this._geoCache.location;if(!this._browserGeoFailed){const o=await this._tryBrowserGeolocation();if(o)return this._cacheGeo(this._applyLocation(o.latitude,o.longitude,"browser"));this._browserGeoFailed=!0}const t=(n=this.config)==null?void 0:n.googleGeoApiKey;if(t){const o=await this._tryGoogleGeolocation(t);if(o)return this._cacheGeo(this._applyLocation(o.latitude,o.longitude,"google-api"))}const i=await this._tryIpGeolocation();return i?this._cacheGeo(this._applyLocation(i.latitude,i.longitude,"ip-geolocation")):(f.warn("All geolocation methods failed"),null)}_cacheGeo(e){return this._geoCache={location:e,ts:Date.now()},e}_applyTagConfig(e){if(!Array.isArray(e)||e.length===0)return;const t={geoApiKey:"googleGeoApiKey"};for(const i of e){const n=i.indexOf("|");if(n===-1)continue;const o=i.substring(0,n),s=i.substring(n+1),r=t[o];r&&s&&this.config&&(f.info(`Config from CMS tag: ${o} → ${r}`),this.config[r]=s)}}_applyLocation(e,t,i){var n;return f.info(`Geolocation (${i}): ${e.toFixed(4)}, ${t.toFixed(4)}`),(n=this.schedule)!=null&&n.setLocation&&this.schedule.setLocation(e,t),this.emit("location-updated",{latitude:e,longitude:t,source:i}),this.checkSchedule(),{latitude:e,longitude:t}}async _tryBrowserGeolocation(){if(typeof navigator>"u"||!navigator.geolocation)return null;try{const e=await new Promise((t,i)=>{navigator.geolocation.getCurrentPosition(t,i,{timeout:1e4,maximumAge:3e5,enableHighAccuracy:!1})});return{latitude:e.coords.latitude,longitude:e.coords.longitude}}catch(e){return f.warn("Browser geolocation failed:",(e==null?void 0:e.message)||e),null}}async _tryGoogleGeolocation(e){var t,i;try{const n=await fetch(`https://www.googleapis.com/geolocation/v1/geolocate?key=${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({considerIp:!0}),signal:AbortSignal.timeout(5e3)});if(!n.ok)return f.warn(`Google Geolocation API returned ${n.status}`),null;const o=await n.json();return((t=o.location)==null?void 0:t.lat)!=null&&((i=o.location)==null?void 0:i.lng)!=null?{latitude:o.location.lat,longitude:o.location.lng}:null}catch(n){return f.warn("Google Geolocation API failed:",(n==null?void 0:n.message)||n),null}}async _tryIpGeolocation(){const e=[{url:"https://ipapi.co/json/",parse:t=>t.latitude!=null&&t.longitude!=null?{latitude:t.latitude,longitude:t.longitude}:null},{url:"https://freeipapi.com/api/json",parse:t=>t.latitude!=null&&t.longitude!=null?{latitude:t.latitude,longitude:t.longitude}:null}];for(const t of e)try{const i=await fetch(t.url,{signal:AbortSignal.timeout(5e3)});if(!i.ok)continue;const n=await i.json(),o=t.parse(n);if(o)return o}catch(i){f.warn(`IP geolocation (${t.url}) failed:`,(i==null?void 0:i.message)||i)}return null}checkSchedule(){const e=this.schedule.getCurrentLayouts();this.emit("layouts-scheduled",e),this._evaluateAndSwitchLayout(e,"")}async captureScreenshot(){f.info("Screenshot requested"),this.emit("screenshot-request")}async changeLayout(e,t){f.info("Layout change requested via XMR:",e);const i=parseInt(e,10),n=(t==null?void 0:t.duration)||0,o=(t==null?void 0:t.changeMode)||"replace";this._layoutOverride={layoutId:i,type:"change",duration:n,changeMode:o},this.currentLayoutId=null,this.emit("layout-prepare-request",i),this._scheduleAutoRevert(i,n,"Layout override")}async overlayLayout(e,t){f.info("Overlay layout requested via XMR:",e);const i=parseInt(e,10),n=(t==null?void 0:t.duration)||0;this._layoutOverride={layoutId:i,type:"overlay",duration:n},this.emit("overlay-layout-request",i),this._scheduleAutoRevert(i,n,"Overlay")}async revertToSchedule(){f.info("Reverting to scheduled content"),this._layoutOverride=null,this.currentLayoutId=null,this.emit("revert-to-schedule");const e=this.schedule.getCurrentLayouts();if(e.length>0){const t=e[0],i=z(t);this.emit("layout-prepare-request",i)}else this.emit("no-layouts-scheduled")}async purgeAll(){return f.info("Purge all cache requested via XMR"),this._lastCheckRf=null,this._lastCheckSchedule=null,this.emit("purge-all-request"),this.collectNow()}async executeCommand(e,t){if(f.info("Execute command requested:",e),!t||!t[e]){f.warn("Unknown command code:",e),this._lastCommandSuccess=!1,this.emit("command-result",{code:e,success:!1,reason:"Unknown command"});return}const i=t[e],n=i.commandString||i.value||"";if(n.startsWith("http|")){const o=n.split("|"),s=o[1],r=o[2]||"application/json";try{const a=await fetch(s,{method:"POST",headers:{"Content-Type":r}}),l=a.ok;this._lastCommandSuccess=l,f.info(`HTTP command ${e} result: ${a.status}`),this.emit("command-result",{code:e,success:l,status:a.status})}catch(a){this._lastCommandSuccess=!1,f.error(`HTTP command ${e} failed:`,a),this.emit("command-result",{code:e,success:!1,reason:a.message})}}else f.info("Delegating non-HTTP command to platform layer:",e),this.emit("execute-native-command",{code:e,commandString:n})}triggerWebhook(e){f.info("Webhook trigger from XMR:",e),this.handleTrigger(e)}refreshDataConnectors(){f.info("Data connector refresh requested via XMR"),this.dataConnectorManager.refreshAll(),this.emit("data-connectors-refreshed")}async submitMediaInventory(e){if(!(!e||e.length===0))try{const t=Math.floor(Date.now()/1e3),n=`<files>${e.filter(o=>["media","layout","resource","dependency","widget"].includes(o.type)).map(o=>{const s=o.complete!==void 0?o.complete?"1":"0":"1",r=o.fileType?` fileType="${o.fileType}"`:"";return`<file type="${o.type}" id="${o.id}" complete="${s}" md5="${o.md5||""}" lastChecked="${t}"${r}/>`}).join("")}</files>`;await this.xmds.mediaInventory(n),f.info(`Media inventory submitted: ${e.length} files`),this.emit("media-inventory-submitted",e.length)}catch(t){f.warn("MediaInventory submission failed:",t)}}async blackList(e,t,i){try{await this.xmds.blackList(e,t,i),this.emit("media-blacklisted",{mediaId:e,type:t,reason:i})}catch(n){f.warn("BlackList failed:",n)}}reportLayoutFailure(e,t){const i=Number(e),n=this._layoutBlacklist.get(i)||{failures:0,blacklisted:!1,reason:""};n.failures++,n.reason=t,this._statusCode=3,!n.blacklisted&&n.failures>=this._blacklistThreshold?(n.blacklisted=!0,f.warn(`Layout ${i} blacklisted after ${n.failures} consecutive failures: ${t}`),this.emit("layout-blacklisted",{layoutId:i,reason:t,failures:n.failures}),this.blackList(i,"layout",t)):n.blacklisted||f.info(`Layout ${i} failure ${n.failures}/${this._blacklistThreshold}: ${t}`),this._layoutBlacklist.set(i,n)}reportLayoutSuccess(e){const t=Number(e);if(this._layoutBlacklist.has(t)){const i=this._layoutBlacklist.get(t);this._layoutBlacklist.delete(t),i.blacklisted&&(f.info(`Layout ${t} removed from blacklist (rendered successfully)`),this.emit("layout-unblacklisted",{layoutId:t}))}}isLayoutBlacklisted(e){const t=this._layoutBlacklist.get(Number(e));return(t==null?void 0:t.blacklisted)===!0}getBlacklistedLayouts(){const e=[];for(const[t,i]of this._layoutBlacklist)i.blacklisted&&e.push(t);return e}resetBlacklist(){this._layoutBlacklist.size>0&&(f.info(`Blacklist reset (${this._layoutBlacklist.size} entries cleared)`),this._layoutBlacklist.clear(),this.emit("blacklist-reset"))}isLayoutOverridden(){return this._layoutOverride!==null}handleTrigger(e){const t=this.schedule.findActionByTrigger(e);if(!t){f.debug("No scheduled action matches trigger:",e);return}switch(f.info(`Action triggered: ${t.actionType} (trigger: ${e})`),t.actionType){case"navLayout":case"navigateToLayout":t.layoutCode&&this.changeLayout(t.layoutCode);break;case"navWidget":case"navigateToWidget":this.emit("navigate-to-widget",t);break;case"command":this.emit("execute-command",t.commandCode);break;default:f.warn("Unknown action type:",t.actionType)}}updateDataConnectors(){const e=this.schedule.getDataConnectors();e.length>0&&f.info(`Configuring ${e.length} data connector(s)`),this.dataConnectorManager.setConnectors(e),e.length>0&&(this.dataConnectorManager.startPolling(),this.emit("data-connectors-started",e.length))}_processScheduledCommands(){var i;if(!((i=this.schedule)!=null&&i.getCommands))return;const e=this.schedule.getCommands();if(e.length===0)return;const t=new Date;for(const n of e){if(!n.code||!n.date)continue;const o=`${n.code}|${n.date}`;if(this._executedCommands.has(o))continue;const s=new Date(n.date);if(isNaN(s.getTime())){f.warn("Scheduled command has invalid date:",n.date);continue}t>=s&&(f.info(`Executing scheduled command: ${n.code} (scheduled: ${n.date})`),this._executedCommands.add(o),n.code==="collectNow"?setTimeout(()=>this.collectNow().catch(r=>f.error("collectNow command failed:",r)),0):this.emit("scheduled-command",n))}}async _fetchWeatherData(){var e,t;if(!(!((e=this.xmds)!=null&&e.getWeather)||!((t=this.schedule)!=null&&t.setWeatherData)))try{const i=await this.xmds.getWeather(),n=typeof i=="string"?JSON.parse(i):i;this.schedule.setWeatherData(n),f.info("Weather data updated:",Object.keys(n).join(", "))}catch(i){f.warn("GetWeather failed (non-critical):",(i==null?void 0:i.message)||i)}}getDataConnectorManager(){return this.dataConnectorManager}setSyncManager(e){this.syncManager=e,f.info("SyncManager attached:",e.isLead?"LEAD":"FOLLOWER")}isInSyncGroup(){return this.syncConfig!==null}isSyncLead(){var e;return((e=this.syncConfig)==null?void 0:e.isLead)===!0}getSyncConfig(){return this.syncConfig}async _buildLayoutDurations(){var o,s;if(!((o=this.cache)!=null&&o.getFile))return;const e=this.schedule.getCurrentLayouts(),t=(s=this.schedule.schedule)==null?void 0:s.default,i=[...new Set([...e,...t?[t]:[]])];let n=0;for(const r of i){const a=z(r);try{const l=await this.cache.get("layout",a);if(l){const{duration:c,isDynamic:d}=le(l);this._layoutDurations.has(r)||this._layoutDurations.set(r,c),this._layoutDurations.has(String(a))||this._layoutDurations.set(String(a),c),d&&this._dynamicLayouts.add(r),n++}}catch(l){f.debug(`Could not parse duration for layout ${a}:`,l.message)}}n>0&&(f.info(`[Timeline] Parsed durations for ${n} layouts`),this._offlineSave("durations",[...this._layoutDurations.entries()]))}logUpcomingTimeline(){var l;if(!this.schedule.getLayoutsAtTime)return;const e=[...this._layoutDurations.entries()].sort(([c],[d])=>c.localeCompare(d)).map(([c,d])=>`${c}:${d}`).join("|"),t=[...this._layoutMediaStatus.entries()].sort(([c],[d])=>c.localeCompare(d)).map(([c,d])=>`${c}:${d.ready}:${d.missingKey}`).join("|"),i=[...this.pendingLayouts.keys()].sort().join(","),n=this.schedule._queuePosition||0,o=`${this._lastCheckSchedule}|${e}|${this.currentLayoutId}|${n}|${t}|${i}`;if(o===this._lastTimelineFingerprint&&this._lastTimeline){this.emit("timeline-updated",this._lastTimeline);return}const{queue:s}=this.schedule.getScheduleQueue(this._layoutDurations,this._queueOptions),r=Je(s,this.schedule._queuePosition,{currentLayoutStartedAt:this._lastLayoutChangeTime?new Date(this._lastLayoutChangeTime):null,defaultLayout:((l=this.schedule.schedule)==null?void 0:l.default)||null,durations:this._layoutDurations});if(r.length===0)return;for(const c of r){const d=parseInt(c.layoutFile.replace(".xlf",""),10),h=this.pendingLayouts.get(d);if(h&&h.length>0)c.missingMedia=h.map(String);else{const g=this._layoutMediaStatus.get(c.layoutFile);g&&!g.ready&&g.missing.length>0&&(c.missingMedia=g.missing.map(String))}}this._lastTimelineFingerprint=o,this._lastTimeline=r;const a=r.slice(0,20).map(c=>{const d=c.startTime.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit"}),h=c.endTime.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit"}),g=c.missingMedia?` [MISSING: ${c.missingMedia.length} files]`:"";return` ${d}-${h} Layout ${c.layoutFile} (${c.duration}s)${c.isDefault?" [default]":""}${g}`});for(const c of r)c.missingMedia&&f.warn(`[Timeline] Layout ${c.layoutFile}: ${c.missingMedia.length} files missing`);f.info(`[Timeline] Next ${r.length} plays:
628
+ ${a.join(`
629
+ `)}`),this.emit("timeline-updated",r)}setLayoutMediaStatus(e,t,i=[]){const n=this._layoutMediaStatus.get(e),o=i.slice().sort().join(",");n&&n.ready===t&&n.missingKey===o||(this._layoutMediaStatus.set(e,{ready:t,missing:i,missingKey:o}),this._lastTimelineFingerprint=null)}recordLayoutDuration(e,t){const i=this._layoutDurations.get(e);i!==t&&(i&&t<=60&&i>60||(this._layoutDurations.set(e,t),f.debug(`[Timeline] Duration corrected: layout ${e} ${i||"?"}s → ${t}s`),this._timelineRecalcTimer&&clearTimeout(this._timelineRecalcTimer),this._timelineRecalcTimer=setTimeout(()=>{this._timelineRecalcTimer=null,this.logUpcomingTimeline(),this._offlineSave("durations",[...this._layoutDurations.entries()])},500)))}cleanup(){this.collectionInterval&&(clearInterval(this.collectionInterval),this.collectionInterval=null),this._faultReportingInterval&&(clearInterval(this._faultReportingInterval),this._faultReportingInterval=null),this._timelineRecalcTimer&&(clearTimeout(this._timelineRecalcTimer),this._timelineRecalcTimer=null),this.xmr&&(this.xmr.stop(),this.xmr=null),this.syncManager&&(this.syncManager.stop(),this.syncManager=null),this.dataConnectorManager.cleanup(),this.emit("cleanup-complete"),this.removeAllListeners()}getCurrentLayoutId(){return this.currentLayoutId}isCollecting(){return this.collecting}getPendingLayouts(){return Array.from(this.pendingLayouts.keys())}}class pe{constructor(e){L(this,"overlay",null);L(this,"config");L(this,"updateTimer",null);L(this,"_visible",!1);L(this,"_getProgress",null);this.config={updateInterval:1e3,autoHide:!0,...e},this.config.enabled&&(this.createOverlay(),this.overlay.style.display="none")}createOverlay(){this.overlay=document.createElement("div"),this.overlay.id="download-overlay",this.overlay.style.cssText=`
630
+ position: fixed;
631
+ top: 1.5vh;
632
+ left: 1.5vw;
633
+ background: rgba(0, 0, 0, 0.88);
634
+ color: #fff;
635
+ font-family: system-ui, -apple-system, sans-serif;
636
+ font-size: 1.4vw;
637
+ padding: 1vh 1.2vw;
638
+ border-radius: 0.4vw;
639
+ border: 1px solid rgba(255, 255, 255, 0.25);
640
+ z-index: 999999;
641
+ max-width: 35vw;
642
+ box-shadow: 0 0.3vh 1.2vw rgba(0, 0, 0, 0.5);
643
+ `,document.body.appendChild(this.overlay)}setProgressCallback(e){this._getProgress=e}updateOverlay(){if(!this.overlay)return;const e=this._getProgress?this._getProgress():{},t=this.renderStatus(e);!!t?(this.overlay.innerHTML=t,this.overlay.style.display="block"):this._visible?(this.overlay.innerHTML='<div style="color: #6c6; font-size: 1.4vw;">✓ All downloads complete</div>',this.overlay.style.display="block"):(this.stopUpdating(),this.overlay.style.display="none")}renderStatus(e){const t=e||{};if(Object.keys(t).length===0)return this.config.autoHide?"":'<div style="color: #6c6;">✓ No downloads</div>';let n=`<div style="font-weight: 600; margin-bottom: 0.8vh; font-size: 1.4vw;">Downloads: ${Object.keys(t).length} active</div>`;for(const[o,s]of Object.entries(t)){const r=this.extractFilename(o),a=Math.round(s.percent||0),l=this.formatBytes(s.downloaded||0),c=this.formatBytes(s.total||0);n+=`
644
+ <div style="margin-bottom: 0.6vh; padding-bottom: 0.6vh; border-bottom: 1px solid rgba(255,255,255,0.1);">
645
+ <div style="font-size: 1.2vw; margin-bottom: 0.2vh;">${r}</div>
646
+ <div style="background: rgba(255,255,255,0.1); height: 0.4vh; border-radius: 0.2vw; overflow: hidden;">
647
+ <div style="width: ${a}%; height: 100%; background: #4a9eff; transition: width 0.3s;"></div>
648
+ </div>
649
+ <div style="color: #999; font-size: 1.1vw; margin-top: 0.2vh;">
650
+ ${a}% · ${l} / ${c}
651
+ </div>
652
+ </div>
653
+ `}return n}extractFilename(e){return e||"unknown"}formatBytes(e){if(e<1024)return`${e} B`;const t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;const i=t/1024;return i<1024?`${i.toFixed(1)} MB`:`${(i/1024).toFixed(1)} GB`}toggle(){this.overlay&&(this._visible=!this._visible,this._visible?(this.overlay.style.display="block",this.updateOverlay(),this.startUpdating()):(this.overlay.style.display="none",this.stopUpdating()))}startUpdating(){this.updateTimer||(this.updateTimer=window.setInterval(()=>{this.updateOverlay()},this.config.updateInterval),this.updateOverlay())}stopUpdating(){this.updateTimer&&(clearInterval(this.updateTimer),this.updateTimer=null)}destroy(){this.stopUpdating(),this.overlay&&(this.overlay.remove(),this.overlay=null)}setEnabled(e){this.config.enabled=e,e&&!this.overlay?this.createOverlay():!e&&this.overlay&&this.destroy()}}function at(){const e=new URLSearchParams(window.location.search).get("showDownloads");if(e!==null)return{enabled:e!=="0"&&e!=="false"};const t=localStorage.getItem("xibo_show_download_overlay");return t!==null?{enabled:t==="true"}:{enabled:!1}}class me{constructor(e=!1,t){L(this,"overlay",null);L(this,"visible");L(this,"timeline",[]);L(this,"currentLayoutId",null);L(this,"layoutStartedAt",null);L(this,"currentDuration",null);L(this,"currentIsDefault",!1);L(this,"previousLayout",null);L(this,"offline",!1);L(this,"onLayoutClick",null);L(this,"refreshTimer",null);this.visible=e,this.onLayoutClick=t||null,this.createOverlay(),this.visible||(this.overlay.style.display="none"),this.refreshTimer=setInterval(()=>this.render(),5e3)}createOverlay(){this.overlay=document.createElement("div"),this.overlay.id="timeline-overlay",this.overlay.style.cssText=`
654
+ position: fixed;
655
+ bottom: 1.5vh;
656
+ left: 1.5vw;
657
+ background: rgba(0, 0, 0, 0.88);
658
+ color: #fff;
659
+ font-family: system-ui, -apple-system, sans-serif;
660
+ font-size: 1.4vw;
661
+ padding: 1vh 1.2vw;
662
+ border-radius: 0.4vw;
663
+ border: 1px solid rgba(255, 255, 255, 0.25);
664
+ z-index: 999999;
665
+ max-width: 35vw;
666
+ box-shadow: 0 0.3vh 1.2vw rgba(0, 0, 0, 0.5);
667
+ pointer-events: auto;
668
+ `,this.overlay.addEventListener("click",e=>{const t=e.target.closest("[data-layout-id]");if(!t||!this.onLayoutClick)return;const i=parseInt(t.dataset.layoutId,10);isNaN(i)||i===this.currentLayoutId||this.onLayoutClick(i)}),document.body.appendChild(this.overlay)}toggle(){this.visible=!this.visible,this.overlay&&(this.overlay.style.display=this.visible?"block":"none"),this.visible&&this.render(),localStorage.setItem("xibo_show_timeline_overlay",String(this.visible))}setOffline(e){this.offline=e,this.render()}update(e,t){if(t!==null&&t!==this.currentLayoutId&&(this.currentLayoutId!==null&&this.currentDuration!==null&&this.layoutStartedAt!==null&&(this.previousLayout={id:this.currentLayoutId,duration:this.currentDuration,startedAt:this.layoutStartedAt}),this.currentLayoutId=t,this.layoutStartedAt=Date.now(),this.currentDuration=null,this.currentIsDefault=!1),e!==null&&(this.timeline=e),this.currentDuration===null&&this.currentLayoutId!==null&&this.timeline.length>0){const i=this.timeline.find(n=>parseInt(n.layoutFile.replace(".xlf",""),10)===this.currentLayoutId);i&&(this.currentDuration=i.duration,this.currentIsDefault=i.isDefault)}this.render()}render(){if(!this.overlay||!this.visible)return;if(this.timeline.length===0&&!this.previousLayout&&!this.currentLayoutId){this.overlay.innerHTML='<div style="color: #999;">Timeline — no upcoming layouts</div>';return}const e=Date.now(),t=this.onLayoutClick!==null;let i=!1;const n=[];for(const d of this.timeline){const h=parseInt(d.layoutFile.replace(".xlf",""),10);if(!i&&h===this.currentLayoutId){i=!0;continue}n.push(d)}const o=(this.previousLayout?1:0)+(this.currentLayoutId?1:0)+n.length,s=this.offline?' <span style="color: #ff4444; font-size: 1.1vw;">OFFLINE</span>':"";let r=`<div style="font-weight: 600; margin-bottom: 0.8vh; font-size: 1.4vw; color: #ccc;">Timeline (${o} scheduled)${s}</div>`;const a=8;let l=0;if(this.previousLayout&&l<a){const d=this.previousLayout,g=this.formatDuration(d.duration).padStart(7).replace(/ /g,"&nbsp;"),p=`#${d.id}`.padEnd(6).replace(/ /g,"&nbsp;"),w=new Date(d.startedAt),m=new Date(d.startedAt+d.duration*1e3),v=`${this.formatTime(w)}–${this.formatTime(m)} `,_=t?"cursor: pointer;":"",$=t?`onmouseover="this.style.background='rgba(255,255,255,0.1)'" onmouseout="this.style.background='none'"`:"";r+=`<div data-layout-id="${d.id}" style="border-left: 0.25vw solid #555; padding-left: 0.6vw; color: #666; text-decoration: line-through; ${_} margin-bottom: 0.3vh; font-family: monospace; font-size: 1.3vw; line-height: 1.5; white-space: nowrap;" ${$}>`,r+=`${v}${p}${g}`,r+="</div>",l++}if(this.currentLayoutId!==null&&l<a){let d,h="";if(this.currentDuration!==null&&this.layoutStartedAt!==null){const w=(e-this.layoutStartedAt)/1e3,m=Math.max(0,Math.round(this.currentDuration-w));d=this.formatDuration(m);const v=new Date(this.layoutStartedAt),_=new Date(this.layoutStartedAt+this.currentDuration*1e3);h=`${this.formatTime(v)}–${this.formatTime(_)} `}else d="---";const g=d.padStart(7).replace(/ /g,"&nbsp;"),p=`#${this.currentLayoutId}`.padEnd(6).replace(/ /g,"&nbsp;");r+=`<div data-layout-id="${this.currentLayoutId}" style="border-left: 0.25vw solid #4a9eff; padding-left: 0.6vw; color: #fff; font-weight: 600; margin-bottom: 0.3vh; font-family: monospace; font-size: 1.3vw; line-height: 1.5; white-space: nowrap;">`,r+=`${h}${p}${g}`,this.currentIsDefault&&(r+=' <span style="color: #888;">[def]</span>'),r+="</div>",l++}let c=this.layoutStartedAt!==null&&this.currentDuration!==null?this.layoutStartedAt+this.currentDuration*1e3:e;for(const d of n){if(l>=a)break;const h=parseInt(d.layoutFile.replace(".xlf",""),10),g=d.missingMedia&&d.missingMedia.length>0,p=this.formatDuration(d.duration),w=c+d.duration*1e3,m=this.formatTime(new Date(c)),v=this.formatTime(new Date(w));let _,$;g?(_="border-left: 0.25vw solid #ff4444; padding-left: 0.6vw;",$="color: #ff6666;"):(_="padding-left: 0.85vw;",$="color: #aaa;"),r+=`<div data-layout-id="${h}" style="${_} ${$} ${t?"cursor: pointer;":""} margin-bottom: 0.3vh; font-family: monospace; font-size: 1.3vw; line-height: 1.5; white-space: nowrap;" ${t?`onmouseover="this.style.background='rgba(255,255,255,0.1)'" onmouseout="this.style.background='none'"`:""}>`;const I=`#${h}`.padEnd(6).replace(/ /g,"&nbsp;"),S=p.padStart(7).replace(/ /g,"&nbsp;");if(r+=`${m}–${v} ${I}${S}`,d.isDefault&&(r+=' <span style="color: #888;">[def]</span>'),g){const b=d.missingMedia.join(", ");r+=` <span style="color: #ff4444; font-size: 1.1vw;" title="Missing: ${b}">⚠ ${d.missingMedia.length}</span>`}if(d.hidden&&d.hidden.length>0){const b=d.hidden.map(C=>`#${C.file.replace(".xlf","")} (p${C.priority})`).join(", ");r+=` <span style="color: #8899aa; font-size: 1.1vw;" title="Also scheduled: ${b}">+${d.hidden.length}</span>`}r+="</div>",c=w,l++}o>a&&(r+=`<div style="padding-left: 0.85vw; color: #888; font-size: 1.1vw; margin-top: 0.3vh;">+${o-a} more</div>`),this.overlay.innerHTML=r}formatTime(e){return e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit"})}formatDuration(e){const t=Math.floor(e/60),i=Math.round(e%60);return t>0?`${t}m ${i.toString().padStart(2,"0")}s`:`${i}s`}destroy(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null),this.overlay&&(this.overlay.remove(),this.overlay=null)}}function lt(){const e=new URLSearchParams(window.location.search).get("showTimeline");if(e!==null)return e!=="0"&&e!=="false";const t=localStorage.getItem("xibo_show_timeline_overlay");return t!==null?t==="true":!1}const we=H("SetupOverlay");class ct{constructor(){L(this,"backdrop",null);L(this,"gateCard",null);L(this,"iframe",null);L(this,"cancelBtn",null);L(this,"visible",!1)}show(){this.visible||(this.visible=!0,this.backdrop||this.create(),this.showGate(),this.backdrop.style.display="flex",we.info("[SetupOverlay] Opened"))}hide(){this.visible&&(this.visible=!1,this.backdrop&&(this.backdrop.style.display="none"),this.iframe&&(this.iframe.src="about:blank",this.iframe.style.display="none"),we.info("[SetupOverlay] Closed"))}toggle(){this.visible?this.hide():this.show()}isVisible(){return this.visible}showGate(){var i,n;this.gateCard&&(this.gateCard.style.display="block"),this.iframe&&(this.iframe.style.display="none"),this.cancelBtn&&(this.cancelBtn.style.display="none");const e=(i=this.gateCard)==null?void 0:i.querySelector("#gate-key");e&&(e.value="",requestAnimationFrame(()=>e.focus()));const t=(n=this.gateCard)==null?void 0:n.querySelector("#gate-error");t&&(t.style.display="none")}showSetup(){this.gateCard&&(this.gateCard.style.display="none"),this.cancelBtn&&(this.cancelBtn.style.display="block"),this.iframe&&(this.iframe.style.display="block",this.iframe.src="./setup.html?unlocked=1")}create(){this.backdrop=document.createElement("div"),this.backdrop.id="setup-overlay-backdrop",this.backdrop.style.cssText=`
669
+ position: fixed;
670
+ inset: 0;
671
+ background: rgba(0, 0, 0, 0.85);
672
+ z-index: 1000000;
673
+ display: none;
674
+ align-items: center;
675
+ justify-content: center;
676
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
677
+ `,this.cancelBtn=document.createElement("button"),this.cancelBtn.textContent="Cancel",this.cancelBtn.style.cssText=`
678
+ position: absolute;
679
+ top: 12px;
680
+ right: 16px;
681
+ background: transparent;
682
+ border: 1px solid rgba(255, 255, 255, 0.3);
683
+ color: #aaa;
684
+ font-size: 14px;
685
+ padding: 6px 18px;
686
+ border-radius: 6px;
687
+ cursor: pointer;
688
+ z-index: 1000001;
689
+ display: none;
690
+ transition: background 0.2s, color 0.2s;
691
+ `,this.cancelBtn.addEventListener("mouseenter",()=>{this.cancelBtn.style.background="rgba(255,255,255,0.1)",this.cancelBtn.style.color="#fff"}),this.cancelBtn.addEventListener("mouseleave",()=>{this.cancelBtn.style.background="transparent",this.cancelBtn.style.color="#aaa"}),this.cancelBtn.addEventListener("click",()=>this.hide()),this.gateCard=document.createElement("div"),this.gateCard.style.cssText=`
692
+ background: #2A2A2A;
693
+ border-radius: 16px;
694
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
695
+ padding: 48px;
696
+ max-width: 480px;
697
+ width: 90vw;
698
+ color: #E0E0E0;
699
+ `,this.gateCard.innerHTML=`
700
+ <div style="text-align: center; margin-bottom: 32px;">
701
+ <div style="font-size: 36px; font-weight: 700; color: #fff; letter-spacing: -0.5px;">
702
+ <span style="color: #0097D8;">xibo</span> player
703
+ </div>
704
+ <div style="font-size: 14px; color: #888; margin-top: 4px;">PWA Digital Signage</div>
705
+ </div>
706
+ <div style="font-size: 18px; font-weight: 600; color: #fff; margin-bottom: 8px; text-align: center;">
707
+ Reconfigure Display
708
+ </div>
709
+ <div style="font-size: 13px; color: #888; margin-bottom: 20px; text-align: center; line-height: 1.5;">
710
+ Enter the current CMS Key to change settings.
711
+ </div>
712
+ <form id="gate-form">
713
+ <div style="margin-bottom: 20px;">
714
+ <label style="display: block; margin-bottom: 6px; color: #AAA; font-size: 13px; font-weight: 500; text-transform: uppercase; letter-spacing: 0.5px;">
715
+ CMS Key
716
+ </label>
717
+ <input type="password" id="gate-key" placeholder="Current CMS key" required
718
+ style="width: 100%; padding: 12px 14px; background: #1D1D1D; border: 2px solid #3A3A3A; border-radius: 8px; font-size: 15px; color: #E0E0E0; transition: border-color 0.2s; box-sizing: border-box;">
719
+ </div>
720
+ <button type="submit" style="width: 100%; padding: 14px; background: #0097D8; color: white; border: none; border-radius: 8px; font-size: 15px; font-weight: 600; cursor: pointer; transition: background 0.2s, transform 0.1s;">
721
+ Unlock
722
+ </button>
723
+ </form>
724
+ <div id="gate-error" style="margin-top: 16px; padding: 12px 14px; background: rgba(244, 67, 54, 0.15); border: 1px solid rgba(244, 67, 54, 0.3); border-radius: 8px; color: #EF9A9A; font-size: 14px; display: none;"></div>
725
+ <button id="gate-cancel" style="width: 100%; padding: 14px; background: transparent; border: 1px solid #3A3A3A; color: #AAA; border-radius: 8px; font-size: 15px; font-weight: 600; cursor: pointer; margin-top: 8px; transition: background 0.2s;">
726
+ Cancel
727
+ </button>
728
+ `,this.iframe=document.createElement("iframe"),this.iframe.style.cssText=`
729
+ width: 100%;
730
+ height: 100%;
731
+ border: none;
732
+ background: #1D1D1D;
733
+ display: none;
734
+ `,this.iframe.addEventListener("load",()=>{var o,s;try{if((((s=(o=this.iframe.contentWindow)==null?void 0:o.location)==null?void 0:s.href)||"").includes("index.html")){this.hide(),window.location.reload();return}const a=this.iframe.contentDocument;if(!a)return;a.addEventListener("keydown",l=>{l.key==="Escape"&&(l.preventDefault(),this.hide())})}catch{}}),this.backdrop.appendChild(this.cancelBtn),this.backdrop.appendChild(this.gateCard),this.backdrop.appendChild(this.iframe),document.body.appendChild(this.backdrop);const e=this.gateCard.querySelector("#gate-form"),t=this.gateCard.querySelector("#gate-key"),i=this.gateCard.querySelector("#gate-error"),n=this.gateCard.querySelector("#gate-cancel");t.addEventListener("focus",()=>{t.style.borderColor="#0097D8"}),t.addEventListener("blur",()=>{t.style.borderColor="#3A3A3A"}),e.addEventListener("submit",o=>{o.preventDefault(),t.value.trim()===Fe.cmsKey?this.showSetup():(i.textContent="Incorrect CMS key",i.style.display="block",t.focus(),t.select())}),n.addEventListener("click",()=>this.hide()),this.backdrop.addEventListener("keydown",o=>{o.key==="Escape"&&(o.preventDefault(),this.hide()),o.stopPropagation()})}}const u=H("PWA"),j=B.slice(1),re=new URL("./",window.location.href).pathname.replace(/\/$/,"");let ve,X,D,be,Se,$e,Le,W,G,_e,Ce,Ie,xe,Te,ke;const K={};class dt{constructor(){L(this,"renderer");L(this,"core");L(this,"xmds");L(this,"downloadOverlay",null);L(this,"timelineOverlay",null);L(this,"setupOverlay",null);L(this,"statsCollector",null);L(this,"logReporter",null);L(this,"displaySettings",null);L(this,"currentScheduleId",-1);L(this,"scheduledLayoutIds",new Set);L(this,"preparingLayoutId",null);L(this,"_pendingRetryLayoutId",null);L(this,"_screenshotInterval",null);L(this,"_screenshotMethod",null);L(this,"_screenshotInFlight",!1);L(this,"_html2canvasMod",null);L(this,"_wakeLock",null);L(this,"syncManager",null);L(this,"_currentLayoutEnableStat",!0);L(this,"_probeTimer",null);L(this,"_mediaStatusTimer",null);L(this,"_pendingFollowerStats",null);L(this,"_pendingFollowerLogs",null);L(this,"_iframeObserver",null);L(this,"_swIcHandler",null);L(this,"_chunkConfig",null);L(this,"_fileIdToSaveAs",new Map);L(this,"protocolDetector",null)}async init(){if(u.info("Initializing player with RendererLite + PlayerCore..."),await this.loadCoreModules(),"serviceWorker"in navigator)try{const s=await navigator.serviceWorker.register(`${re}/sw-pwa.js?v=${Date.now()}`,{scope:`${re}/`,type:"module",updateViaCache:"none"});u.info("Service Worker registered for offline mode:",s.scope),navigator.storage&&navigator.storage.persist&&(await navigator.storage.persist()?u.info("Persistent storage granted - cache won't be evicted"):u.warn("Persistent storage denied - cache may be evicted"))}catch(s){u.warn("Service Worker registration failed:",s)}u.info("Initializing cache clients..."),W=new Be;const{calculateChunkConfig:e}=await F(async()=>{const{calculateChunkConfig:s}=await import("./index-_oCyqKl9.js");return{calculateChunkConfig:s}},__vite__mapDeps([0,1,2]),import.meta.url);this._chunkConfig=e(u),G=new qe({concurrency:this._chunkConfig.concurrency,chunkSize:this._chunkConfig.chunkSize,chunksPerFile:2}),u.info("Cache clients ready — StoreClient + DownloadManager");const t=document.getElementById("player-container");if(!t)throw new Error("No #player-container found");this.renderer=new nt({cmsUrl:D.cmsUrl,hardwareKey:D.hardwareKey},t,{fileIdToSaveAs:this._fileIdToSaveAs,getWidgetHtml:async s=>{const r=`${B}/widgets/${s.layoutId}/${s.regionId}/${s.id}`;u.debug(`Looking for widget HTML at: ${r}`,s);try{if(await W.has(`${j}/widgets`,`${s.layoutId}/${s.regionId}/${s.id}`))return u.debug("Widget HTML found in store, using mirror URL for iframe"),{url:r,fallback:s.raw||""};u.warn(`No widget HTML found in store: ${r}`)}catch(a){u.error(`Failed to check widget HTML for ${s.id}:`,a)}return u.warn(`Using widget.raw fallback for ${s.id}`),s.raw||""}}),this.core=new rt({config:D,xmds:this.xmds,cache:W,schedule:X,renderer:this.renderer,xmrWrapper:Le,statsCollector:this.statsCollector,displaySettings:this.displaySettings,cmsId:D.activeCmsId}),this.setupCoreEventHandlers(),this.setupRendererEventHandlers(),this.setupInteractiveControl(),this.setupDataConnectorNotify(),this.setupRemoteControls(),this.core.on("register-complete",s=>{var l,c;const r=parseFloat((l=s==null?void 0:s.settings)==null?void 0:l.latitude),a=parseFloat((c=s==null?void 0:s.settings)==null?void 0:c.longitude);r&&a&&!isNaN(r)&&!isNaN(a)?(u.info(`Display location from CMS: ${r.toFixed(4)}, ${a.toFixed(4)}`),X!=null&&X.setLocation&&X.setLocation(r,a)):this.core.requestGeoLocation&&(u.info("No CMS coordinates, requesting browser geolocation..."),this.core.requestGeoLocation())}),this.updateConfigDisplay(),window.addEventListener("online",()=>{u.info("Browser reports online — triggering immediate collection"),this.updateStatus("Back online, syncing..."),this.removeOfflineIndicator(),this.core.collectNow().catch(s=>{u.error("Failed to collect after coming online:",s)})}),window.addEventListener("offline",()=>{u.warn("Browser reports offline — continuing playback with cached data"),this.updateStatus("Offline mode — using cached content"),this.showOfflineIndicator()});const n=(this.getControls().keyboard||{}).debugOverlays===!0,o=at();o.enabled&&n&&(this.downloadOverlay=new pe(o),this.downloadOverlay.setProgressCallback(()=>G.getProgress()),u.info("Download overlay enabled (hover bottom-right corner)")),lt()&&n&&(this.timelineOverlay=new me(!0,s=>this.skipToLayout(s))),this.setupCertWarnings(),await this.requestWakeLock(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.requestWakeLock()}),await this.core.collect(),u.info("Player initialized successfully")}async requestWakeLock(){if(!("wakeLock"in navigator)){u.debug("Wake Lock API not supported");return}try{this._wakeLock=await navigator.wakeLock.request("screen"),u.info("Screen Wake Lock acquired — display will stay on"),this._wakeLock.addEventListener("release",()=>{u.debug("Screen Wake Lock released"),this._wakeLock=null})}catch(e){u.warn("Wake Lock request failed:",e==null?void 0:e.message)}}setupCertWarnings(){const e=new Set;window.addEventListener("cert-warning",t=>{const{host:i,error:n}=t.detail;if(e.has(i))return;e.add(i),u.warn(`Invalid SSL certificate accepted for stream: ${i} (${n})`);let o=document.getElementById("overlay"),s=!1;if(!o){o=document.createElement("div"),o.id="overlay";const l=document.createElement("div");l.id="config-info",o.appendChild(l);const c=document.createElement("div");c.id="status",o.appendChild(c),document.body.appendChild(o),s=!0}let r=document.getElementById("cert-warnings");if(!r){r=document.createElement("span"),r.id="cert-warnings",r.style.cssText="color: #ffaa33; flex: 0 0 auto;";const l=document.getElementById("status");o.insertBefore(r,l)}const a=[...e].join(", ");r.textContent=`⚠ SSL: ${a}`,s&&this.updateConfigDisplay()})}async loadCoreModules(){var e,t,i;try{const[n,o,s,r,a,l,c,d,h,g]=await Promise.all([F(()=>import("./index-BPWLt2qA.js"),__vite__mapDeps([3,4,2]),import.meta.url),F(()=>import("./index-CDj_ep7K.js"),__vite__mapDeps([5,6,2]),import.meta.url),F(()=>import("./index-CtXCdqID.js"),__vite__mapDeps([7,8,2,4]),import.meta.url),F(()=>import("./index-aoZD2owd.js"),[],import.meta.url),F(()=>import("./index-DyruL5Od.js"),__vite__mapDeps([9,2]),import.meta.url),F(()=>import("./index-DBqUu6yb.js"),__vite__mapDeps([10,2]),import.meta.url),F(()=>import("./index-C62BLuTi.js"),__vite__mapDeps([11,2]),import.meta.url),F(()=>import("./index-DRSaAd9B.js"),__vite__mapDeps([12,2,8,4]),import.meta.url),F(()=>import("./index-DU3hjIga.js"),__vite__mapDeps([13,8,2,4]),import.meta.url),F(()=>import("./sync-manager-Cm51QXsO.js"),__vite__mapDeps([14,2]),import.meta.url)]);if(ve=n.cacheWidgetHtml,ke=g.SyncManager,X=s.scheduleManager,D=r.config,be=o.RestClient,Se=o.XmdsClient,$e=o.ProtocolDetector,Le=a.XmrWrapper,_e=l.StatsCollector,Ce=l.formatStats,Ie=l.LogReporter,xe=l.formatLogs,Te=c.DisplaySettings,K.core=d.VERSION||"?",K.cache=n.VERSION||"?",K.renderer=h.VERSION||"?",K.schedule=s.VERSION||"?",K.xmds=o.VERSION||"?",K.xmr=a.VERSION||"?",K.utils=r.VERSION||"?",K.stats=l.VERSION||"?",K.settings=c.VERSION||"?",(e=window.electronAPI)!=null&&e.getSystemInfo)try{const M=await window.electronAPI.getSystemInfo();M.macAddress&&(D.macAddress=M.macAddress)}catch{}const p=D.transport!=="auto"?D.transport:void 0,m=new URLSearchParams(window.location.search).get("transport")||(re.includes("pwa-xmds")?"xmds":null)||p||"auto";this.protocolDetector=new $e(D.cmsUrl,be,Se);const v=m==="auto"?void 0:m,{client:_}=await this.protocolDetector.detect(D,v);this.xmds=_;const $=D.activeCmsId;this.statsCollector=new _e($),await this.statsCollector.init(),u.info(`Stats collector initialized${$?` (CMS: ${$})`:""}`),this.logReporter=new Ie($),await this.logReporter.init(),u.info(`Log reporter initialized${$?` (CMS: ${$})`:""}`),ce(({level:M,name:R,args:k})=>{if(!this.logReporter)return;const E=k.map(P=>typeof P=="string"?P:JSON.stringify(P)).join(" ");this.logReporter.log(M,`[${R}] ${E}`,"PLAYER").catch(()=>{})});const T=D.debug;if(T!=null&&T.consoleLogs){const M=(T.consoleLogsInterval||10)*1e3;let R=[],k=null;const E=()=>{if(R.length===0)return;const P=R;R=[],k=null,fetch("/debug/log",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)}).catch(()=>{})};ce(({level:P,name:ee,args:te})=>{const Me=te.map(oe=>typeof oe=="string"?oe:JSON.stringify(oe)).join(" ");R.push({level:P,name:ee,message:Me,ts:new Date().toISOString()}),k||(k=setTimeout(E,M))}),u.info(`Console log forwarding to proxy enabled (flush every ${M/1e3}s)`)}this.displaySettings=new Te,u.info("Display settings manager initialized");const x="2026-03-05T23:20:54.887Z",I="0.6.4";u.info(`v${I} built ${x}`);const S=Object.entries(K).map(([M,R])=>`${M}=${R}`).join(" ");u.info(`SDK: ${S}`);const b=!!window.electronAPI,C=b?((t=navigator.userAgent.match(/Electron\/([\d.]+)/))==null?void 0:t[1])||"?":null,O=((i=navigator.userAgent.match(/Chrome\/([\d.]+)/))==null?void 0:i[1])||"?",A=b?`Electron ${C} / Chrome ${O}`:`Chrome ${O}`;u.info(`Env: PWA v${I} | ${A} | ${navigator.platform} | ${screen.width}x${screen.height}`),u.info("Core modules loaded")}catch(n){throw u.error("Failed to load core modules:",n),n}}setupCoreEventHandlers(){this.core.on("collection-start",()=>{this.updateStatus("Collecting data from CMS...")}),this.core.on("register-complete",e=>{var i;const t=((i=this.displaySettings)==null?void 0:i.getDisplayName())||e.displayName||D.hardwareKey;this.updateStatus(`Registered: ${t}`),this.displaySettings&&(document.title=`Xibo Player - ${this.displaySettings.getDisplayName()}`)}),this.core.on("sync-config",e=>{if(this.syncManager&&this.syncManager.stop(),e.syncPublisherPort&&e.syncGroup!=="lead"){const t=e.isLead?"localhost":e.syncGroup;e.relayUrl=`ws://${t}:${e.syncPublisherPort}/sync`}this.syncManager=new ke({displayId:D.hardwareKey,syncConfig:e,onLayoutChange:async t=>{var i;u.info(`[Sync] Loading layout ${t} (waiting for show signal)`),await this.prepareAndRenderLayout(parseInt(t,10)),(i=this.syncManager)==null||i.reportReady(t)},onLayoutShow:t=>{u.info(`[Sync] Show signal for layout ${t}`)},onVideoStart:(t,i)=>{var n,o;u.info(`[Sync] Video start: layout ${t} region ${i}`),(o=(n=this.renderer).resumeRegionMedia)==null||o.call(n,i)},onStatsReport:async(t,i,n)=>{u.info(`[Sync] Submitting stats for follower ${t}`);try{await this.xmds.submitStats(i,t)&&n()}catch(o){u.warn(`[Sync] Stats submission failed for follower ${t}:`,o)}},onLogsReport:async(t,i,n)=>{u.info(`[Sync] Submitting logs for follower ${t}`);try{await this.xmds.submitLog(i,t)&&n()}catch(o){u.warn(`[Sync] Log submission failed for follower ${t}:`,o)}},onStatsAck:async t=>{u.info("[Sync] Lead confirmed stats submission"),this._pendingFollowerStats&&this.statsCollector&&(await this.statsCollector.clearSubmittedStats(this._pendingFollowerStats),this._pendingFollowerStats=null)},onLogsAck:async t=>{u.info("[Sync] Lead confirmed logs submission"),this._pendingFollowerLogs&&this.logReporter&&(await this.logReporter.clearSubmittedLogs(this._pendingFollowerLogs),this._pendingFollowerLogs=null)}}),this.core.setSyncManager(this.syncManager),this.syncManager.start(),u.info(`[Sync] SyncManager started as ${e.isLead?"LEAD":"FOLLOWER"}`)}),this.core.on("files-received",e=>{this.updateStatus(`Downloading ${e.length} files...`)}),this.core.on("offline-mode",e=>{e?(this.updateStatus("Offline mode — using cached content"),this.showOfflineIndicator()):(this.updateStatus("Back online"),this.removeOfflineIndicator())}),this.core.on("purge-request",async e=>{try{const t=await W.remove(e);u.info(`Purge complete: ${t.deleted}/${t.total} files deleted`)}catch(t){u.warn("Purge failed:",t)}}),this.core.on("download-request",async e=>{var t,i;(t=this.downloadOverlay)==null||t.startUpdating();try{const n=((i=this.xmds)==null?void 0:i._token)||null;n&&await fetch("/auth-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:n})}),await this.enqueueDownloads(e),u.info("Download enqueue complete")}catch(n){u.error("Download request failed:",n),this.updateStatus("Download failed: "+n,"error")}}),this.core.on("schedule-received",e=>{var t;if(this.updateStatus("Processing schedule..."),e.layouts&&e.layouts.length>0?this.currentScheduleId=parseInt(e.layouts[0].scheduleid)||-1:e.campaigns&&e.campaigns.length>0&&(this.currentScheduleId=parseInt(e.campaigns[0].scheduleid)||-1),(t=this.renderer)!=null&&t.layoutPool){const i=new Set;if(e.layouts)for(const o of e.layouts){const s=parseInt(String(o.file||o.id||o).replace(".xlf",""),10);s&&i.add(s)}if(e.campaigns){for(const o of e.campaigns)if(o.layouts)for(const s of o.layouts){const r=parseInt(String(s.file||s.id||s).replace(".xlf",""),10);r&&i.add(r)}}const n=this.renderer.layoutPool.clearWarmNotIn(i);n>0&&u.info(`Cleared ${n} preloaded layout(s) no longer in schedule`),this.scheduledLayoutIds=i}u.debug("Current scheduleId for stats:",this.currentScheduleId)}),this.core.on("layout-prepare-request",async e=>{await this.prepareAndRenderLayout(e)}),this.core.on("layout-expire-current",()=>{u.info("Schedule changed — expiring current layout"),this.renderer.stopCurrentLayout()}),this.core.on("no-layouts-scheduled",()=>{this.updateStatus("No layouts scheduled")}),this.core.on("collection-complete",()=>{const e=this.core.getCurrentLayoutId();e?this.updateStatus(`Playing layout ${e}`):this.preparingLayoutId&&this.updateStatus(`Downloading layout ${this.preparingLayoutId}...`)}),this.core.on("collection-error",async e=>{var t;if(this.updateStatus(`Collection error: ${e}`,"error"),(t=this.logReporter)==null||t.reportFault("COLLECTION_FAILED",`Collection cycle failed: ${(e==null?void 0:e.message)||e}`),this.submitFault("COLLECTION_FAILED",`Collection cycle failed: ${(e==null?void 0:e.message)||e}`),this.protocolDetector&&this.protocolDetector.getProtocol()!==null)try{const{client:i,protocol:n,changed:o}=await this.protocolDetector.reprobe(D);o&&i&&(u.info(`Protocol switched to ${n} after connection error`),this.xmds=i,this.core.xmds=i)}catch(i){u.warn("Protocol re-probe failed:",i)}}),this.core.on("xmr-connected",e=>{u.info("XMR connected:",e)}),this.core.on("xmr-misconfigured",e=>{u.warn(`XMR misconfigured (${e.reason}): ${e.message}`)}),this.core.on("log-level-changed",()=>{u.info("Log level changed")}),this.core.on("overlay-layout-request",async e=>{u.info("Overlay layout requested:",e),await this.prepareAndRenderLayout(e)}),this.core.on("revert-to-schedule",()=>{u.info("Reverting to scheduled content"),this.updateStatus("Reverting to schedule...")}),this.core.on("purge-all-request",async()=>{u.info("Purging all cached content..."),this.updateStatus("Purging cache...");try{const e=await W.list();if(e.length>0){const i=await W.remove(e);u.info(`Purged ${i.deleted} files from ContentStore`)}const t=await caches.keys();t.length>0&&(await Promise.all(t.map(i=>caches.delete(i))),u.info(`Purged ${t.length} legacy caches`))}catch(e){u.error("Cache purge failed:",e)}}),this.core.on("command-result",e=>{var t;u.info("Command result:",e),e.success||((t=this.logReporter)==null||t.reportFault("COMMAND_FAILED",`Command ${e.code} failed: ${e.reason||"unknown"}`),this.submitFault("COMMAND_FAILED",`Command ${e.code} failed: ${e.reason||"unknown"}`))}),this.core.on("scheduled-command",e=>{u.info(`Scheduled command: ${e.code}`),this.core.executeCommand(e.code)}),this.core.on("execute-native-command",async e=>{var i;let t;if((i=window.electronAPI)!=null&&i.executeShellCommand)t=await window.electronAPI.executeShellCommand({commandString:e.commandString});else try{t=await(await fetch("/shell-command",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commandString:e.commandString})})).json()}catch(n){t={success:!1,reason:n.message}}this.core.emit("command-result",{code:e.code,...t})}),this.displaySettings&&(this.displaySettings.on("interval-changed",e=>{u.info(`Collection interval changed to ${e}s`)}),this.displaySettings.on("settings-applied",(e,t)=>{t.length>0&&u.info("Settings updated from CMS:",t.join(", ")),this._screenshotInterval||this.startScreenshotInterval()})),this.core.on("submit-stats-request",async()=>{await this.submitStats()}),this.core.on("submit-logs-request",async()=>{await this.submitLogs()}),this.core.on("screenshot-request",async()=>{await this.captureAndSubmitScreenshot()}),this.core.on("check-pending-layout",async e=>{await this.prepareAndRenderLayout(e)}),this.core.on("navigate-to-widget",e=>{e.targetId?this.renderer.navigateToWidget(e.targetId):u.warn("navigate-to-widget action has no targetId:",e)}),this.core.on("timeline-updated",e=>{var t;(t=this.timelineOverlay)==null||t.update(e,this.core.getCurrentLayoutId())})}setupInteractiveControl(){var e;this._swIcHandler=t=>{var l,c;if(((l=t.data)==null?void 0:l.type)!=="INTERACTIVE_CONTROL")return;const{method:i,path:n,search:o,body:s}=t.data,r=(c=t.ports)==null?void 0:c[0];if(!r)return;const a=this.handleInteractiveControl(i,n,o,s);r.postMessage(a)},(e=navigator.serviceWorker)==null||e.addEventListener("message",this._swIcHandler)}setupDataConnectorNotify(){this.core.getDataConnectorManager().on("data-changed",t=>{var o;const i=document.querySelectorAll("iframe"),n={ctrl:"rtNotifyData",data:{dataKey:t}};for(const s of i)try{(o=s.contentWindow)==null||o.postMessage(n,"*")}catch{}})}setupRemoteControls(){window.addEventListener("blur",()=>{setTimeout(()=>window.focus(),200)});const e=a=>{const l=()=>{var c;try{const d=a.contentDocument||((c=a.contentWindow)==null?void 0:c.document);if(!d||a.__keyForwarderAttached)return;a.__keyForwarderAttached=!0,d.addEventListener("keydown",h=>{const g=new KeyboardEvent("keydown",{key:h.key,code:h.code,keyCode:h.keyCode,ctrlKey:h.ctrlKey,shiftKey:h.shiftKey,altKey:h.altKey,metaKey:h.metaKey,bubbles:!0,cancelable:!0});document.dispatchEvent(g)||h.preventDefault()})}catch{}};a.addEventListener("load",l),l()};Array.from(document.querySelectorAll("iframe")).forEach(a=>e(a)),this._iframeObserver=new MutationObserver(a=>{for(const l of a)for(const c of l.addedNodes)c instanceof HTMLIFrameElement&&e(c),c instanceof HTMLElement&&c.querySelectorAll("iframe").forEach(d=>e(d))}),this._iframeObserver.observe(document.body,{childList:!0,subtree:!0});const t=this.getControls(),{keyboard:i={}}=t,n=i.debugOverlays===!0,o=i.setupKey===!0,s=i.playbackControl===!0,r=i.videoControls===!0;document.addEventListener("keydown",a=>{if(a.key==="q"&&(a.ctrlKey||a.metaKey)){a.preventDefault(),u.info("[Remote] Quit requested (Ctrl+Q)"),fetch("/quit",{method:"POST"}).catch(()=>{});return}switch(a.key){case"t":case"T":if(!n)break;this.timelineOverlay||(this.timelineOverlay=new me(!0,l=>this.skipToLayout(l))),this.timelineOverlay.toggle();break;case"d":case"D":if(!n)break;this.downloadOverlay||(this.downloadOverlay=new pe({enabled:!0,autoHide:!1}),this.downloadOverlay.setProgressCallback(()=>G.getProgress())),this.downloadOverlay.toggle();break;case"v":case"V":{if(!r)break;const l=[...document.querySelectorAll("video")];document.querySelectorAll("iframe").forEach(d=>{try{l.push(...d.contentDocument.querySelectorAll("video"))}catch{}});const c=l.length>0&&!l[0].controls;l.forEach(d=>d.controls=c);break}case"ArrowRight":case"PageDown":if(!s)break;u.info("[Remote] Next layout (keyboard)"),this.core.advanceToNextLayout(),a.preventDefault();break;case"ArrowLeft":case"PageUp":if(!s)break;u.info("[Remote] Previous layout (keyboard)"),this.core.advanceToPreviousLayout(),a.preventDefault();break;case" ":if(!s)break;u.info("[Remote] Toggle pause (keyboard)"),this.renderer.isPaused()?this.renderer.resume():this.renderer.pause(),a.preventDefault();break;case"r":case"R":if(!s)break;this.core.isLayoutOverridden()&&(u.info("[Remote] Revert to schedule (keyboard)"),this.core.revertToSchedule());break;case"s":case"S":if(!o)break;this.setupOverlay||(this.setupOverlay=new ct),this.setupOverlay.toggle(),a.preventDefault();break}}),s&&"mediaSession"in navigator&&(navigator.mediaSession.setActionHandler("nexttrack",()=>{u.info("[Remote] Next layout (MediaSession)"),this.core.advanceToNextLayout()}),navigator.mediaSession.setActionHandler("previoustrack",()=>{u.info("[Remote] Previous layout (MediaSession)"),this.core.advanceToPreviousLayout()}),navigator.mediaSession.setActionHandler("pause",()=>{u.info("[Remote] Pause (MediaSession)"),this.renderer.pause()}),navigator.mediaSession.setActionHandler("play",()=>{u.info("[Remote] Resume (MediaSession)"),this.renderer.resume()})),u.info("Remote controls initialized (keyboard + MediaSession)")}getControls(){return D.controls}skipToLayout(e){u.info(`Skipping to layout ${e} (timeline click)`),this.core.changeLayout(e)}parseBody(e){try{return e?JSON.parse(e):{}}catch{return{}}}handleInteractiveControl(e,t,i,n){var o;switch(u.debug("IC request:",e,t,i),t){case"/info":return{status:200,body:JSON.stringify({hardwareKey:D.hardwareKey,displayName:D.displayName,playerType:"pwa",currentLayoutId:this.core.getCurrentLayoutId()})};case"/trigger":{const s=this.parseBody(n);return this.renderer.emit("interactiveTrigger",{targetId:s.id,triggerCode:s.trigger}),s.trigger&&this.core.handleTrigger(s.trigger),{status:200,body:"OK"}}case"/duration/expire":{const s=this.parseBody(n);return u.info("IC: Widget duration expire requested for",s.id),this.renderer.emit("widgetExpire",{widgetId:s.id}),{status:200,body:"OK"}}case"/duration/extend":{const s=this.parseBody(n);return u.info("IC: Widget duration extend by",s.duration,"for",s.id),this.renderer.emit("widgetExtendDuration",{widgetId:s.id,duration:parseInt(s.duration)}),{status:200,body:"OK"}}case"/duration/set":{const s=this.parseBody(n);return u.info("IC: Widget duration set to",s.duration,"for",s.id),this.renderer.emit("widgetSetDuration",{widgetId:s.id,duration:parseInt(s.duration)}),{status:200,body:"OK"}}case"/fault":{const s=this.parseBody(n);return(o=this.logReporter)==null||o.reportFault(s.code||"WIDGET_FAULT",s.reason||"Widget reported fault"),this.submitFault(s.code||"WIDGET_FAULT",s.reason||"Widget reported fault",{layoutId:s.layoutId,regionId:s.regionId,widgetId:s.widgetId}),{status:200,body:"OK"}}case"/realtime":{const r=new URLSearchParams(i).get("dataKey");if(u.debug("IC: Realtime data request for key:",r),!r)return{status:400,body:JSON.stringify({error:"Missing dataKey parameter"})};const l=this.core.getDataConnectorManager().getData(r);return l===null?{status:404,body:JSON.stringify({error:`No data available for key: ${r}`})}:{status:200,body:typeof l=="string"?l:JSON.stringify(l)}}case"/criteria":return{status:200,body:JSON.stringify({displayId:D.displayId,hardwareKey:D.hardwareKey,displayName:D.displayName,width:window.innerWidth,height:window.innerHeight,latitude:D.latitude||null,longitude:D.longitude||null,playerType:"pwa"})};default:return{status:404,body:JSON.stringify({error:"Unknown IC route"})}}}notifyFileCached(e,t){if(u.debug(`Download complete: ${t}/${e}`),t==="layout")this.core.notifyMediaReady(parseInt(e),t);else if(t==="media"){const i=this._fileIdToSaveAs.get(e)||e;this.core.notifyMediaReady(i,t)}this._probeTimer&&clearTimeout(this._probeTimer),this._probeTimer=setTimeout(()=>{this._probeTimer=null,this.probeLayoutDurations().catch(()=>{})},3e3),this._mediaStatusTimer&&clearTimeout(this._mediaStatusTimer),this._mediaStatusTimer=setTimeout(()=>{this._mediaStatusTimer=null,this.checkTimelineMediaStatus().catch(()=>{})},2e3)}async enqueueDownloads(e){const{extractMediaIdsFromXlf:t}=await F(async()=>{const{extractMediaIdsFromXlf:S}=await import("./index-_oCyqKl9.js");return{extractMediaIdsFromXlf:S}},__vite__mapDeps([0,1,2]),import.meta.url),{layoutOrder:i,files:n,layoutDependants:o}=e,s=G.queue,r=S=>(S.path||"").split("?")[0].replace(/^\/+/,"")||`${S.type||"media"}/${S.id}`;for(const S of n)S.saveAs&&this._fileIdToSaveAs.set(String(S.id),S.saveAs);const a=new Map,l=[],c=new Map,d=new Map;for(const S of n)if(S.type==="layout")a.set(parseInt(S.id),S);else if(S.type==="static")l.push(S);else{const b=`${S.type}:${S.id}`;c.set(b,S);const C=String(S.id);d.has(C)||d.set(C,[]),d.get(C).push(b)}u.info(`Download: ${i.length} layouts, ${c.size} media, ${l.length} resources`);const h=new Map,p=[...i,...[...a.keys()].filter(S=>!i.includes(S))].map(async S=>{const b=a.get(S);if(!(b!=null&&b.path))return;let C;try{const O=await fetch(b.path);O.ok&&(C=await O.text(),u.info(`Fetched XLF ${S} (${C.length} bytes)`),this.notifyFileCached(String(S),"layout"))}catch{}C&&h.set(S,t(C,u))});await Promise.allSettled(p),u.info(`Parsed ${h.size} XLFs`);const w=async(S,b)=>{if(!b.path||b.path==="null"||b.path==="undefined")return!1;const C=r(b);try{if((await fetch(`/store/${C}`,{method:"HEAD"})).ok)return!1}catch{}if(G.getTask(C))return!1;try{const A=await fetch(`/store/missing-chunks/${C}`);if(A.ok){const{missing:M,numChunks:R}=await A.json();if(R>0&&M.length<R){const k=new Set;for(let E=0;E<R;E++)M.includes(E)||k.add(E);b.skipChunks=k,u.info(`Resuming ${C}: ${k.size}/${R} chunks cached, ${M.length} to download`)}}}catch{}const O=S.addFile(b);return O.state!=="pending"?!1:(O.wait().then(A=>{const M=parseInt(b.size)||A.size;u.info("Download complete:",C,`(${M} bytes)`),M>this._chunkConfig.chunkSize&&fetch("/store/mark-complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storeKey:C})}).catch(R=>u.warn("mark-complete failed:",C,R.message)),this.notifyFileCached(String(b.id),b.type),s.removeCompleted(C)}).catch(A=>{u.error("Download failed:",b.id,A),s.removeCompleted(r(b))}),!0)},m=new se(s);for(const S of l)await w(m,S);const v=await m.build();v.length>0&&(v.push(de),s.enqueueOrderedTasks(v));const _=new Set,$=[...h.keys()].filter(S=>!i.includes(S)),T=new Map;for(const[S,b]of c)b.saveAs&&T.set(b.saveAs,S);const x=new Map;if(o)for(const[S,b]of Object.entries(o))x.set(parseInt(S,10),b);for(const S of i){const b=h.get(S);if(!b)continue;const C=new Set(b);for(const k of $){const E=h.get(k);if(E)for(const P of E)C.add(P)}const O=x.get(S)||[];for(const k of O){const E=T.get(k);E&&C.add(E)}const A=[];for(const k of C){if(c.has(k)&&!_.has(k)){A.push(c.get(k)),_.add(k);continue}const E=d.get(String(k))||[];for(const P of E)_.has(P)||(A.push(c.get(P)),_.add(P))}if(A.length===0)continue;u.info(`Layout ${S}: ${A.length} media`),A.sort((k,E)=>(k.size||0)-(E.size||0));const M=new se(s);for(const k of A)await w(M,k);const R=await M.build();R.length>0&&(R.push(de),s.enqueueOrderedTasks(R))}const I=[...c.keys()].filter(S=>!_.has(S));if(I.length>0){u.info(`${I.length} media not in any XLF`);const S=new se(s);for(const C of I){const O=c.get(C);O&&await w(S,O)}const b=await S.build();b.length>0&&s.enqueueOrderedTasks(b)}u.info("Downloads active:",s.running,", queued:",s.queue.length)}setupRendererEventHandlers(){this.renderer.on("layoutStart",(e,t)=>{var i;u.info("Layout started:",e),this.updateStatus(`Playing layout ${e}`),this.core.setCurrentLayout(e),(t==null?void 0:t.duration)>0&&this.core.recordLayoutDuration(String(e),t.duration),this._currentLayoutEnableStat=(t==null?void 0:t.enableStat)!==!1,(i=this.timelineOverlay)==null||i.update(null,e),this.statsCollector&&this._currentLayoutEnableStat&&this.statsCollector.startLayout(e,this.currentScheduleId).catch(n=>{u.error("Failed to start layout stat:",n)})}),this.renderer.on("layoutEnd",e=>{u.info("Layout ended:",e),X==null||X.recordPlay(e.toString()),this.statsCollector&&this._currentLayoutEnableStat&&this.statsCollector.endLayout(e,this.currentScheduleId).catch(i=>{u.error("Failed to end layout stat:",i)}),this.core.notifyLayoutStatus(e),this.core.clearCurrentLayout();const t=this.core.getPendingLayouts();if(t.length>0){u.info(`Layout ${t[0]} pending download, skipping advance`);return}u.info("Layout cycle completed, advancing to next layout..."),this.core.advanceToNextLayout()}),this.renderer.on("widgetStart",e=>{const{widgetId:t,layoutId:i,mediaId:n}=e;u.debug("Widget started:",e.type,t,"media:",n),this.statsCollector&&n&&e.enableStat!==!1&&this.statsCollector.startWidget(n,i,this.currentScheduleId).catch(o=>{u.error("Failed to start widget stat:",o)})}),this.renderer.on("widgetEnd",e=>{const{widgetId:t,layoutId:i,mediaId:n}=e;u.debug("Widget ended:",e.type,t,"media:",n),this.statsCollector&&n&&e.enableStat!==!1&&this.statsCollector.endWidget(n,i,this.currentScheduleId).catch(o=>{u.error("Failed to end widget stat:",o)})}),this.renderer.on("widgetCommand",e=>{u.info("Widget command:",e.commandCode);const t={[e.commandCode]:{commandString:e.commandString}};this.core.executeCommand(e.commandCode,t)}),this.renderer.on("error",e=>{var t;u.error("Renderer error:",e),this.updateStatus(`Error: ${e.type}`,"error"),(t=this.logReporter)==null||t.reportFault(e.type||"RENDERER_ERROR",`Renderer error: ${e.message||e.type} (layout ${e.layoutId||"unknown"})`),this.submitFault(e.type||"RENDERER_ERROR",`Renderer error: ${e.message||e.type}`,{layoutId:e.layoutId,regionId:e.regionId,widgetId:e.widgetId})}),this.renderer.on("action-trigger",e=>{var r,a;const{actionType:t,triggerCode:i,layoutCode:n,targetId:o,commandCode:s}=e;switch(u.info("Action trigger:",t,e),t){case"navLayout":case"navigateToLayout":i?this.core.handleTrigger(i):n&&this.core.changeLayout(n);break;case"navWidget":case"navigateToWidget":i?this.core.handleTrigger(i):o&&this.renderer.navigateToWidget(o);break;case"previousWidget":this.renderer.previousWidget((r=e.source)==null?void 0:r.regionId);break;case"nextWidget":this.renderer.nextWidget((a=e.source)==null?void 0:a.regionId);break;case"command":s&&this.core.executeCommand(s);break;default:u.warn("Unknown action type:",t)}this.statsCollector&&this.statsCollector.recordEvent("touch",this.core.getCurrentLayoutId(),e.targetId||null,this.currentScheduleId)}),this.renderer.on("widgetAction",e=>{e.type==="durationEnd"&&e.url&&(u.info(`Widget ${e.widgetId} duration ended, calling webhook: ${e.url}`),this.statsCollector&&this.statsCollector.recordEvent("webhook",e.layoutId,e.widgetId,this.currentScheduleId),fetch(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({widgetId:e.widgetId,layoutId:e.layoutId,regionId:e.regionId,event:"durationEnd",timestamp:new Date().toISOString()})}).catch(t=>u.warn("Webhook failed (non-critical):",t)))}),this.renderer.on("layoutDurationUpdated",(e,t)=>{this.core.recordLayoutDuration(String(e),t)}),this.renderer.on("request-next-layout-preload",async()=>{try{const e=this.core.peekNextLayout();if(!e){u.debug("No next layout to preload (single layout schedule or same layout)");return}const t=e.layoutId;if(this.renderer.layoutPool.has(t)){u.debug(`Layout ${t} already in preload pool`);return}u.info(`Preloading next layout ${t}...`);const i=await W.get(`${j}/layouts`,t);if(!i){u.debug(`Layout ${t} XLF not cached, skipping preload`);return}const n=await i.text(),{allMedia:o}=this.getMediaIds(n);if(!await this.checkAllMediaCached(o)){u.debug(`Media not fully cached for layout ${t}, skipping preload`);return}await this.fetchWidgetHtml(n,t),await this.renderer.preloadLayout(n,t)?u.info(`Layout ${t} preloaded successfully`):u.warn(`Layout ${t} preload failed (will fall back to normal render)`)}catch(e){u.warn("Layout preload failed (non-blocking):",e)}}),this.renderer.on("videoError",async({storedAs:e})=>{if(!e)return;const t=`${B.slice(1)}/media/file/${e}`;try{const i=await fetch(`/store/missing-chunks/${t}`),{missing:n}=await i.json();if(n.length===0){u.warn(`Video error for ${e} but no missing chunks — possible decode error`);return}u.warn(`Video ${e}: ${n.length} missing chunks (${n.join(", ")}), re-downloading`),await fetch("/store/unmark-complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storeKey:t})}),this.core.collectNow().catch(o=>{u.error(`Failed to trigger re-download for ${e}:`,o.message)})}catch(i){u.error(`Failed to check/re-download ${e}:`,i.message)}})}async prepareAndRenderLayout(e){var t;if(this.core.getCurrentLayoutId()===e){u.debug(`Layout ${e} already playing, skipping duplicate prepare`);return}if(this.preparingLayoutId===e){u.debug(`Layout ${e} preparation in progress, will retry after it completes`),this._pendingRetryLayoutId=e;return}this.preparingLayoutId=e;try{const i=await W.get(`${j}/layouts`,e);if(!i){u.info("Layout not in cache yet, marking as pending:",e),this.core.setPendingLayout(e,[String(e)]),this.updateStatus(`Downloading layout ${e}...`);return}const n=await i.text(),{allMedia:o}=this.getMediaIds(n);if(!await this.checkAllMediaCached(o)){G.prioritizeLayoutFiles(o.map(String)),u.info(`Waiting for media to finish downloading for layout ${e}`),this.updateStatus(`Preparing layout ${e}...`),this.core.setPendingLayout(e,o);return}this.renderer.hasPreloadedLayout(e)||await this.fetchWidgetHtml(n,e),await this.renderer.renderLayout(n,e),this.updateStatus(`Playing layout ${e}`)}catch(i){u.error("Failed to prepare layout:",e,i),this.updateStatus(`Failed to load layout ${e}`,"error"),(t=this.logReporter)==null||t.reportFault("LAYOUT_LOAD_FAILED",`Failed to prepare layout ${e}: ${(i==null?void 0:i.message)||i}`),this.submitFault("LAYOUT_LOAD_FAILED",`Failed to prepare layout ${e}: ${(i==null?void 0:i.message)||i}`,{layoutId:e})}finally{this.preparingLayoutId=null;const i=this._pendingRetryLayoutId;this._pendingRetryLayoutId=null,i!=null&&this.core.getCurrentLayoutId()!==i&&(u.debug(`Retrying preparation for layout ${i} after 500ms`),setTimeout(()=>this.prepareAndRenderLayout(i),500))}}getMediaIds(e){var r;const i=new DOMParser().parseFromString(e,"text/xml"),n=[],o=[];i.querySelectorAll("media[fileId]").forEach(a=>{const l=a.getAttribute("fileId");if(l){const c=this._fileIdToSaveAs.get(l)||l;n.push(c),a.getAttribute("type")==="video"&&o.push(c)}});const s=(r=i.querySelector("layout"))==null?void 0:r.getAttribute("background");if(s){const a=this._fileIdToSaveAs.get(s)||s;n.includes(a)||n.push(a)}return{allMedia:n,videoMedia:o}}async checkAllMediaCached(e){for(const t of e)try{if(!await W.has(j,`media/file/${t}`))return u.debug(`Media ${t} not yet cached`),!1;u.debug(`Media ${t} cached`)}catch{u.warn(`Unable to verify media ${t}, assuming cached (offline mode)`)}return!0}async fetchWidgetHtml(e,t){const n=new DOMParser().parseFromString(e,"text/xml"),o=[];for(const s of n.querySelectorAll("region")){const r=s.getAttribute("id");for(const a of s.querySelectorAll("media")){const l=a.getAttribute("type"),c=a.getAttribute("id");a.getAttribute("render")==="html"&&o.push((async()=>{try{const h=`${t}/${r}/${c}`;let g=null;const p=await W.get(`${j}/widgets`,h);p&&(g=await p.text(),u.debug(`Found cached widget HTML for ${l} ${c}`)),g||(g=await this.xmds.getResource(t,r,c),u.debug(`Retrieved widget HTML for ${l} ${c} from CMS`)),await ve(t,r,c,g);const w=await W.get(`${j}/widgets`,h);w&&(g=await w.text());const m=a.querySelector("raw");if(m)m.textContent=g;else{const v=n.createElement("raw");v.textContent=g,a.appendChild(v)}}catch(h){u.warn(`Failed to get widget HTML for ${l} ${c}:`,h)}})())}}o.length>0&&(u.info(`Fetching ${o.length} widget HTML resources in parallel...`),await Promise.all(o),u.debug("All widget HTML fetched"))}async checkTimelineMediaStatus(){if(this.scheduledLayoutIds.size!==0){for(const e of this.scheduledLayoutIds){const t=`${e}.xlf`;try{const i=await W.get(`${j}/layouts`,e);if(!i)continue;const n=await i.text(),{allMedia:o}=this.getMediaIds(n);if(o.length===0){this.core.setLayoutMediaStatus(t,!0);continue}const s=[];for(const r of o)try{await W.has(j,`media/file/${r}`)||s.push(r)}catch{}this.core.setLayoutMediaStatus(t,s.length===0,s)}catch{}}this.core.logUpcomingTimeline()}}async probeLayoutDurations(){if(this.scheduledLayoutIds.size!==0)for(const e of this.scheduledLayoutIds)try{const t=await W.get(`${j}/layouts`,e);if(!t)continue;const i=await t.text(),{videoMedia:n}=this.getMediaIds(i);if(n.length===0)continue;const s=new DOMParser().parseFromString(i,"text/xml"),r=new Map;for(const l of s.querySelectorAll('media[type="video"]')){if(l.getAttribute("useDuration")==="1")continue;const d=l.getAttribute("fileId");if(!d)continue;const h=this._fileIdToSaveAs.get(d)||d;if(!await W.has(j,`media/file/${h}`))continue;const p=await this.probeVideoDuration(`${window.location.origin}${B}/media/file/${h}`);p>0&&r.set(d,p)}if(r.size===0)continue;const{duration:a}=le(i,r);a>0&&this.core.recordLayoutDuration(String(e),a)}catch(t){u.debug(`Duration probe failed for layout ${e}:`,t)}}probeVideoDuration(e){return new Promise(t=>{const i=document.createElement("video");i.preload="metadata",i.muted=!0;const n=()=>{i.removeAttribute("src"),i.load()};i.addEventListener("loadedmetadata",()=>{const o=i.duration;n(),t(o)},{once:!0}),i.addEventListener("error",()=>{n(),t(0)},{once:!0}),setTimeout(()=>{n(),t(0)},5e3),i.src=e})}updateConfigDisplay(){const e=document.getElementById("config-info");if(e){const t="0.6.4",i="2026-03-05T23:20:54.887Z".replace("T"," ").replace(/\.\d+Z$/,""),n=i?`v${t} (${i})`:`v${t}`;e.textContent=`${n} | CMS: ${D.cmsUrl} | Display: ${D.displayName||"Unknown"} | HW: ${D.hardwareKey}`}}async submitStats(){var e;if(!this.statsCollector){u.warn("Stats collector not initialized");return}if(this._pendingFollowerStats!==null){u.debug("Stats delegation in-flight, skipping");return}try{const i=(((e=this.displaySettings)==null?void 0:e.getSetting("aggregationLevel"))||"Individual")==="Aggregate"?await this.statsCollector.getAggregatedStatsForSubmission(50):await this.statsCollector.getStatsForSubmission(50);if(i.length===0){u.debug("No stats to submit");return}const n=Ce(i);if(this.syncManager&&!this.syncManager.isLead&&this._syncLeadAlive()){u.info(`[Sync] Delegating ${i.length} stats to lead`),this._pendingFollowerStats=i,this.syncManager.reportStats(n);return}this.syncManager&&!this.syncManager.isLead&&u.warn("[Sync] Lead not alive, submitting stats directly"),u.info(`Submitting ${i.length} proof of play stats...`),await this.xmds.submitStats(n)?(u.info("Stats submitted successfully"),await this.statsCollector.clearSubmittedStats(i),u.debug(`Cleared ${i.length} submitted stats from database`)):u.warn("Stats submission failed (CMS returned false)")}catch(t){u.error("Failed to submit stats:",t)}}async submitLogs(){if(this.logReporter){if(this._pendingFollowerLogs!==null){u.debug("Logs delegation in-flight, skipping");return}try{const e=await this.logReporter.getLogsForSubmission();if(e.length===0){u.debug("No logs to submit");return}const t=xe(e);if(this.syncManager&&!this.syncManager.isLead&&this._syncLeadAlive()){u.info(`[Sync] Delegating ${e.length} logs to lead`),this._pendingFollowerLogs=e,this.syncManager.reportLogs(t);return}this.syncManager&&!this.syncManager.isLead&&u.warn("[Sync] Lead not alive, submitting logs directly"),u.info(`Submitting ${e.length} logs to CMS...`),await this.xmds.submitLog(t)?(u.info("Logs submitted successfully"),await this.logReporter.clearSubmittedLogs(e)):u.warn("Log submission failed (CMS returned false)")}catch(e){u.error("Failed to submit logs:",e)}}}submitFault(e,t,i){if(!this.xmds)return;const n=JSON.stringify([{code:e,reason:t,date:new Date().toISOString().replace("T"," ").substring(0,19),...i}]);this.xmds.reportFaults(n).catch(o=>{u.debug("reportFaults failed (non-critical):",o)})}async captureAndSubmitScreenshot(){var e;if(this._screenshotInFlight){u.debug("Screenshot capture already in progress, skipping");return}this._screenshotInFlight=!0;try{let t;if(this._screenshotMethod==="electron"||this._screenshotMethod===null&&((e=window.electronAPI)!=null&&e.captureScreenshot)){const n=await window.electronAPI.captureScreenshot();if(n)this._screenshotMethod="electron",t=n;else{u.debug("Electron screenshot not ready yet, will retry next interval");return}}else this._screenshotMethod="html2canvas",t=await this.captureHtml2Canvas();await this.xmds.submitScreenShot(t)?u.info(`Screenshot submitted (${this._screenshotMethod})`):u.warn("Screenshot submission failed")}catch(t){u.error("Failed to capture screenshot:",t)}finally{this._screenshotInFlight=!1}}async captureHtml2Canvas(){const e=document.createElement("canvas");e.width=window.innerWidth,e.height=window.innerHeight;const t=e.getContext("2d");t.fillStyle="#000",t.fillRect(0,0,e.width,e.height);const i=document.getElementById("player-container");if(!i)return e.toDataURL("image/jpeg",.8).split(",")[1];const n=i.getBoundingClientRect(),o=getComputedStyle(i),s=o.backgroundColor;s&&s!=="transparent"&&s!=="rgba(0, 0, 0, 0)"&&(t.fillStyle=s,t.fillRect(n.left,n.top,n.width,n.height));const r=o.backgroundImage;if(r&&r!=="none"){const c=r.match(/url\(["']?(.*?)["']?\)/);if(c)try{const d=new Image;d.crossOrigin="anonymous",await new Promise(h=>{d.onload=()=>h(),d.onerror=()=>h(),setTimeout(()=>h(),2e3),d.src=c[1]}),d.naturalWidth&&t.drawImage(d,n.left,n.top,n.width,n.height)}catch{}}this._html2canvasMod||(this._html2canvasMod=(await F(async()=>{const{default:c}=await import("./html2canvas.esm-CBrSDip1.js");return{default:c}},[],import.meta.url)).default);const a=i.querySelectorAll("img, video, iframe, canvas");let l=0;for(const c of a){const d=c;if(d.style.visibility==="hidden"||d.style.display==="none")continue;const h=c.getBoundingClientRect();if(!(h.width===0||h.height===0))try{if(c instanceof HTMLImageElement){if(!c.complete||!c.naturalWidth)continue;if(getComputedStyle(c).objectFit==="contain"&&c.naturalWidth&&c.naturalHeight){const p=this.containedRect(c.naturalWidth,c.naturalHeight,h);t.drawImage(c,p.x,p.y,p.w,p.h)}else t.drawImage(c,h.left,h.top,h.width,h.height);l++}else if(c instanceof HTMLVideoElement){if(c.readyState<2)continue;if(getComputedStyle(c).objectFit==="contain"&&c.videoWidth&&c.videoHeight){const p=this.containedRect(c.videoWidth,c.videoHeight,h);t.drawImage(c,p.x,p.y,p.w,p.h)}else t.drawImage(c,h.left,h.top,h.width,h.height);l++}else if(c instanceof HTMLCanvasElement)t.drawImage(c,h.left,h.top,h.width,h.height),l++;else if(c instanceof HTMLIFrameElement){const g=c.contentDocument;if(!(g!=null&&g.body))continue;const p=document.createElement("div");p.style.cssText=`position:fixed;left:-9999px;top:0;width:${h.width}px;height:${h.height}px;overflow:hidden;`;const w=[];for(const $ of g.querySelectorAll("style"))p.appendChild($.cloneNode(!0));for(const $ of g.querySelectorAll('link[rel="stylesheet"]')){const T=document.createElement("link");T.rel="stylesheet",T.href=new URL($.getAttribute("href")||"",g.baseURI).href,p.appendChild(T),w.push(new Promise(x=>{T.onload=()=>x(),T.onerror=()=>x()}))}p.appendChild(g.body.cloneNode(!0)),document.body.appendChild(p);const m=g.querySelectorAll("img"),v=new Map;m.forEach(($,T)=>{$.naturalWidth&&$.naturalHeight&&v.set(String(T),{nw:$.naturalWidth,nh:$.naturalHeight})}),w.length>0&&await Promise.race([Promise.all(w),new Promise($=>setTimeout($,500))]);const _=await this._html2canvasMod(p,{useCORS:!0,allowTaint:!0,logging:!1,backgroundColor:null,width:h.width,height:h.height,onclone:$=>{const T=$.createElement("style");T.textContent="*, *::before, *::after { animation: none !important; transition: none !important; opacity: 1 !important; }",$.head.appendChild(T),$.querySelectorAll("img").forEach((I,S)=>{var ee,te;const b=(ee=$.defaultView)==null?void 0:ee.getComputedStyle(I);if(!b||b.objectFit!=="contain")return;const C=v.get(String(S));if(!C)return;const O=I.clientWidth||parseFloat(b.width)||0,A=I.clientHeight||parseFloat(b.height)||0;if(!O||!A)return;const M=C.nw/C.nh,R=O/A;let k,E;M>R?(k=O,E=O/M):(E=A,k=A*M);const P=$.createElement("div");P.style.cssText=`width:${O}px;height:${A}px;display:flex;align-items:center;justify-content:center;overflow:hidden;`,I.style.objectFit="fill",I.style.width=`${k}px`,I.style.height=`${E}px`,(te=I.parentNode)==null||te.insertBefore(P,I),P.appendChild(I)})}});document.body.removeChild(p),t.drawImage(_,h.left,h.top,h.width,h.height),l++}}catch(g){u.warn("Screenshot: failed to draw element",c.tagName,g)}}return u.debug(`Screenshot: composed ${l}/${a.length} elements`),e.toDataURL("image/jpeg",.8).split(",")[1]}containedRect(e,t,i){const n=e/t,o=i.width/i.height;let s,r;return n>o?(s=i.width,r=i.width/n):(r=i.height,s=i.height*n),{x:i.left+(i.width-s)/2,y:i.top+(i.height-r)/2,w:s,h:r}}startScreenshotInterval(){var i;const e=((i=this.displaySettings)==null?void 0:i.getSetting("screenshotInterval"))||0;if(!e||e<=0)return;this._html2canvasMod||F(()=>import("./html2canvas.esm-CBrSDip1.js"),[],import.meta.url).then(n=>{this._html2canvasMod=n.default});const t=e*1e3;u.info(`Starting periodic screenshots every ${e}s`),this._screenshotInterval=setInterval(()=>{this.captureAndSubmitScreenshot()},t)}updateStatus(e,t="info"){const i=document.getElementById("status");i&&(i.textContent=e,i.className=`status status-${t}`),t==="error"?u.error("Status:",e):u.info("Status:",e)}showOfflineIndicator(){var e;(e=this.timelineOverlay)==null||e.setOffline(!0)}removeOfflineIndicator(){var e;(e=this.timelineOverlay)==null||e.setOffline(!1)}_syncLeadAlive(){if(!this.syncManager)return!1;for(const[,e]of this.syncManager.followers)if(e.role==="lead"&&Date.now()-e.lastSeen<15e3)return!0;return!1}cleanup(){this.core.cleanup(),this.renderer.cleanup(),this._screenshotInterval&&(clearInterval(this._screenshotInterval),this._screenshotInterval=null),this._wakeLock&&(this._wakeLock.release(),this._wakeLock=null),this.downloadOverlay&&this.downloadOverlay.destroy(),this.timelineOverlay&&this.timelineOverlay.destroy(),this._iframeObserver&&(this._iframeObserver.disconnect(),this._iframeObserver=null),navigator.serviceWorker&&this._swIcHandler&&(navigator.serviceWorker.removeEventListener("message",this._swIcHandler),this._swIcHandler=null),G==null||G.clear(),this._probeTimer&&(clearTimeout(this._probeTimer),this._probeTimer=null),this._mediaStatusTimer&&(clearTimeout(this._mediaStatusTimer),this._mediaStatusTimer=null)}}function De(){const y=new dt;y.init().catch(e=>{u.error("Failed to initialize:",e),u.warn("Redirecting to setup screen..."),window.location.href="./setup.html"}),window.addEventListener("beforeunload",()=>{y.cleanup()})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",De):De();export{ot as D,pt as I,Z as L,it as O,rt as P,nt as R,tt as S,mt as a,et as b,Je as c,le as p,yt as s};
735
+ //# sourceMappingURL=main-D42peItG.js.map