@forcecalendar/interface 1.0.13 → 1.0.14

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.
@@ -1,4 +1,4 @@
1
- (function(v,k){typeof exports=="object"&&typeof module<"u"?k(exports):typeof define=="function"&&define.amd?define(["exports"],k):(v=typeof globalThis<"u"?globalThis:v||self,k(v.ForceCalendarInterface={}))})(this,function(v){"use strict";var se=Object.defineProperty;var ie=(v,k,A)=>k in v?se(v,k,{enumerable:!0,configurable:!0,writable:!0,value:A}):v[k]=A;var I=(v,k,A)=>ie(v,typeof k!="symbol"?k+"":k,A);class k extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}),this._listeners=[],this._state=null,this._props=new Map,this._initialized=!1}connectedCallback(){this._initialized||(this.initialize(),this._initialized=!0),this.mount()}disconnectedCallback(){this.unmount(),this.cleanup()}initialize(){}mount(){this.render()}unmount(){}cleanup(){this._listeners.forEach(({element:e,event:t,handler:s})=>{e.removeEventListener(t,s)}),this._listeners=[]}setState(e){const t=this._state;this._state={...this._state,...e},this.stateChanged(t,this._state),this.render()}getState(){return this._state}stateChanged(e,t){}setProp(e,t){const s=this._props.get(e);this._props.set(e,t),this.propChanged(e,s,t)}getProp(e){return this._props.get(e)}propChanged(e,t,s){}addListener(e,t,s){if(!e||!t||!s){console.warn("addListener called with invalid parameters",{element:e,event:t,handler:s});return}const i=s.bind(this);e.addEventListener(t,i),this._listeners.push({element:e,event:t,handler:i})}emit(e,t={}){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}getStyles(){return""}getBaseStyles(){return`
1
+ (function(v,k){typeof exports=="object"&&typeof module<"u"?k(exports):typeof define=="function"&&define.amd?define(["exports"],k):(v=typeof globalThis<"u"?globalThis:v||self,k(v.ForceCalendarInterface={}))})(this,function(v){"use strict";var ie=Object.defineProperty;var re=(v,k,A)=>k in v?ie(v,k,{enumerable:!0,configurable:!0,writable:!0,value:A}):v[k]=A;var L=(v,k,A)=>re(v,typeof k!="symbol"?k+"":k,A);class k extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}),this._listeners=[],this._state=null,this._props=new Map,this._initialized=!1}connectedCallback(){this._initialized||(this.initialize(),this._initialized=!0),this.mount()}disconnectedCallback(){this.unmount(),this.cleanup()}initialize(){}mount(){this.render()}unmount(){}cleanup(){this._listeners.forEach(({element:e,event:t,handler:s})=>{e.removeEventListener(t,s)}),this._listeners=[]}setState(e){const t=this._state;this._state={...this._state,...e},this.stateChanged(t,this._state),this.render()}getState(){return this._state}stateChanged(e,t){}setProp(e,t){const s=this._props.get(e);this._props.set(e,t),this.propChanged(e,s,t)}getProp(e){return this._props.get(e)}propChanged(e,t,s){}addListener(e,t,s){if(!e||!t||!s){console.warn("addListener called with invalid parameters",{element:e,event:t,handler:s});return}const i=s.bind(this);e.addEventListener(t,i),this._listeners.push({element:e,event:t,handler:i})}emit(e,t={}){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}getStyles(){return""}getBaseStyles(){return`
2
2
  :host {
3
3
  display: block;
4
4
  box-sizing: border-box;
@@ -12,7 +12,7 @@
12
12
  ${this.getBaseStyles()}
13
13
  ${this.getStyles()}
14
14
  </style>
15
- `,t=this.template();this.shadowRoot.innerHTML=e+t,this.afterRender()}template(){return""}afterRender(){}$(e){return this.shadowRoot.querySelector(e)}$$(e){return this.shadowRoot.querySelectorAll(e)}static get observedAttributes(){return[]}attributeChangedCallback(e,t,s){this.setProp(e,s),this._initialized&&this.render()}}class A{constructor(){this.timezones={UTC:{offset:0,dst:null},GMT:{offset:0,dst:null},"Africa/Abidjan":{offset:0,dst:null},"Africa/Accra":{offset:0,dst:null},"Africa/Addis_Ababa":{offset:180,dst:null},"Africa/Algiers":{offset:60,dst:null},"Africa/Cairo":{offset:120,dst:null},"Africa/Casablanca":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Africa/Johannesburg":{offset:120,dst:null},"Africa/Lagos":{offset:60,dst:null},"Africa/Nairobi":{offset:180,dst:null},"America/Anchorage":{offset:-540,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Argentina/Buenos_Aires":{offset:-180,dst:null},"America/Bogota":{offset:-300,dst:null},"America/Caracas":{offset:-240,dst:null},"America/Chicago":{offset:-360,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Denver":{offset:-420,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Detroit":{offset:-300,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Halifax":{offset:-240,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Los_Angeles":{offset:-480,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Mexico_City":{offset:-360,dst:{start:{month:4,week:1,day:0},end:{month:10,week:-1,day:0},offset:60}},"America/New_York":{offset:-300,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Phoenix":{offset:-420,dst:null},"America/Regina":{offset:-360,dst:null},"America/Santiago":{offset:-180,dst:{start:{month:9,week:1,day:0},end:{month:4,week:1,day:0},offset:60}},"America/Sao_Paulo":{offset:-180,dst:{start:{month:10,week:3,day:0},end:{month:2,week:3,day:0},offset:60}},"America/St_Johns":{offset:-210,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Toronto":{offset:-300,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Vancouver":{offset:-480,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"Asia/Baghdad":{offset:180,dst:null},"Asia/Bangkok":{offset:420,dst:null},"Asia/Dubai":{offset:240,dst:null},"Asia/Hong_Kong":{offset:480,dst:null},"Asia/Jakarta":{offset:420,dst:null},"Asia/Jerusalem":{offset:120,dst:{start:{month:3,week:-1,day:5},end:{month:10,week:-1,day:0},offset:60}},"Asia/Karachi":{offset:300,dst:null},"Asia/Kolkata":{offset:330,dst:null},"Asia/Kuala_Lumpur":{offset:480,dst:null},"Asia/Manila":{offset:480,dst:null},"Asia/Seoul":{offset:540,dst:null},"Asia/Shanghai":{offset:480,dst:null},"Asia/Singapore":{offset:480,dst:null},"Asia/Taipei":{offset:480,dst:null},"Asia/Tehran":{offset:210,dst:{start:{month:3,week:4,day:0},end:{month:9,week:4,day:0},offset:60}},"Asia/Tokyo":{offset:540,dst:null},"Atlantic/Azores":{offset:-60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Atlantic/Bermuda":{offset:-240,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"Atlantic/Reykjavik":{offset:0,dst:null},"Australia/Adelaide":{offset:570,dst:{start:{month:10,week:1,day:0},end:{month:4,week:1,day:0},offset:60}},"Australia/Brisbane":{offset:600,dst:null},"Australia/Darwin":{offset:570,dst:null},"Australia/Hobart":{offset:600,dst:{start:{month:10,week:1,day:0},end:{month:4,week:1,day:0},offset:60}},"Australia/Melbourne":{offset:600,dst:{start:{month:10,week:1,day:0},end:{month:4,week:1,day:0},offset:60}},"Australia/Perth":{offset:480,dst:null},"Australia/Sydney":{offset:600,dst:{start:{month:10,week:1,day:0},end:{month:4,week:1,day:0},offset:60}},"Europe/Amsterdam":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Athens":{offset:120,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Berlin":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Brussels":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Budapest":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Copenhagen":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Dublin":{offset:0,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Helsinki":{offset:120,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Istanbul":{offset:180,dst:null},"Europe/Kiev":{offset:120,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Lisbon":{offset:0,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/London":{offset:0,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Madrid":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Moscow":{offset:180,dst:null},"Europe/Oslo":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Paris":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Prague":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Rome":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Stockholm":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Vienna":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Warsaw":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Zurich":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Indian/Maldives":{offset:300,dst:null},"Indian/Mauritius":{offset:240,dst:null},"Pacific/Auckland":{offset:720,dst:{start:{month:9,week:-1,day:0},end:{month:4,week:1,day:0},offset:60}},"Pacific/Fiji":{offset:720,dst:{start:{month:11,week:1,day:0},end:{month:1,week:3,day:0},offset:60}},"Pacific/Guam":{offset:600,dst:null},"Pacific/Honolulu":{offset:-600,dst:null},"Pacific/Midway":{offset:-660,dst:null},"Pacific/Noumea":{offset:660,dst:null},"Pacific/Pago_Pago":{offset:-660,dst:null},"Pacific/Port_Moresby":{offset:600,dst:null},"Pacific/Tahiti":{offset:-600,dst:null}},this.aliases={EST:"America/New_York",EDT:"America/New_York",CST:"America/Chicago",CDT:"America/Chicago",MST:"America/Denver",MDT:"America/Denver",PST:"America/Los_Angeles",PDT:"America/Los_Angeles",AKST:"America/Anchorage",AKDT:"America/Anchorage",HST:"Pacific/Honolulu",AST:"America/Halifax",ADT:"America/Halifax",NST:"America/St_Johns",NDT:"America/St_Johns",BST:"Europe/London",IST:"Asia/Kolkata",WET:"Europe/Lisbon",WEST:"Europe/Lisbon",CET:"Europe/Paris",CEST:"Europe/Paris",EET:"Europe/Athens",EEST:"Europe/Athens",MSK:"Europe/Moscow",JST:"Asia/Tokyo",KST:"Asia/Seoul",CST_CN:"Asia/Shanghai",HKT:"Asia/Hong_Kong",SGT:"Asia/Singapore",AEST:"Australia/Sydney",AEDT:"Australia/Sydney",ACST:"Australia/Adelaide",ACDT:"Australia/Adelaide",AWST:"Australia/Perth",NZST:"Pacific/Auckland",NZDT:"Pacific/Auckland","US/Eastern":"America/New_York","US/Central":"America/Chicago","US/Mountain":"America/Denver","US/Pacific":"America/Los_Angeles","US/Alaska":"America/Anchorage","US/Hawaii":"Pacific/Honolulu","Canada/Eastern":"America/Toronto","Canada/Central":"America/Regina","Canada/Mountain":"America/Denver","Canada/Pacific":"America/Vancouver","Canada/Atlantic":"America/Halifax","Canada/Newfoundland":"America/St_Johns","Mexico/General":"America/Mexico_City","Brazil/East":"America/Sao_Paulo","Chile/Continental":"America/Santiago",GB:"Europe/London","GB-Eire":"Europe/London",Eire:"Europe/Dublin",Israel:"Asia/Jerusalem",Japan:"Asia/Tokyo",Singapore:"Asia/Singapore",Hongkong:"Asia/Hong_Kong",ROK:"Asia/Seoul",PRC:"Asia/Shanghai","Australia/NSW":"Australia/Sydney","Australia/Victoria":"Australia/Melbourne","Australia/Queensland":"Australia/Brisbane","Australia/South":"Australia/Adelaide","Australia/Tasmania":"Australia/Hobart","Australia/West":"Australia/Perth","Australia/North":"Australia/Darwin",NZ:"Pacific/Auckland"}}getTimezone(e){return this.aliases[e]&&(e=this.aliases[e]),this.timezones[e]||null}getAllTimezones(){return Object.keys(this.timezones)}isValidTimezone(e){return this.aliases[e]!==void 0||this.timezones[e]!==void 0}resolveAlias(e){return this.aliases[e]||e}getTimezonesByOffset(e){return Object.entries(this.timezones).filter(([t,s])=>s.offset===e).map(([t,s])=>t)}getCommonTimezones(){return{Americas:["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Toronto","America/Mexico_City","America/Sao_Paulo"],Europe:["Europe/London","Europe/Paris","Europe/Berlin","Europe/Moscow","Europe/Rome","Europe/Madrid","Europe/Amsterdam"],Asia:["Asia/Tokyo","Asia/Shanghai","Asia/Hong_Kong","Asia/Singapore","Asia/Kolkata","Asia/Dubai","Asia/Seoul"],"Australia/Pacific":["Australia/Sydney","Australia/Melbourne","Australia/Brisbane","Australia/Perth","Pacific/Auckland","Pacific/Honolulu"],Africa:["Africa/Cairo","Africa/Lagos","Africa/Johannesburg","Africa/Nairobi"]}}}class ${constructor(){this.database=new A,this.offsetCache=new Map,this.dstCache=new Map,this.maxCacheSize=1e3,this.cacheHits=0,this.cacheMisses=0}convertTimezone(e,t,s){if(!e)return null;if(t===s)return new Date(e);const i=this.getTimezoneOffset(e,t),a=(this.getTimezoneOffset(e,s)-i)*60*1e3;return new Date(e.getTime()+a)}toUTC(e,t){if(!e)return null;if(t==="UTC")return new Date(e);const s=this.getTimezoneOffset(e,t);return new Date(e.getTime()+s*60*1e3)}fromUTC(e,t){if(!e)return null;if(t==="UTC")return new Date(e);const s=this.getTimezoneOffset(e,t);return new Date(e.getTime()-s*60*1e3)}getTimezoneOffset(e,t){t=this.database.resolveAlias(t);const s=`${t}_${e.getFullYear()}_${e.getMonth()}_${e.getDate()}`;if(this.offsetCache.has(s))return this.cacheHits++,this._manageCacheSize(),this.offsetCache.get(s);if(this.cacheMisses++,typeof Intl<"u"&&Intl.DateTimeFormat)try{const n=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(e),c=(new Date(n.find(l=>l.type==="year").value,n.find(l=>l.type==="month").value-1,n.find(l=>l.type==="day").value,n.find(l=>l.type==="hour").value,n.find(l=>l.type==="minute").value,n.find(l=>l.type==="second").value).getTime()-e.getTime())/(1e3*60);return this.offsetCache.set(s,-c),this._manageCacheSize(),-c}catch{}const i=this.database.getTimezone(t);if(!i)throw new Error(`Unknown timezone: ${t}`);let r=i.offset;return i.dst&&this.isDST(e,t,i.dst)&&(r+=i.dst.offset),this.offsetCache.set(s,r),this._manageCacheSize(),r}isDST(e,t,s=null){if(!s){const n=this.database.getTimezone(t);if(!n||!n.dst)return!1;s=n.dst}const i=e.getFullYear(),r=this.getNthWeekdayOfMonth(i,s.start.month,s.start.week,s.start.day),a=this.getNthWeekdayOfMonth(i,s.end.month,s.end.week,s.end.day);return r>a?e>=r||e<a:e>=r&&e<a}getNthWeekdayOfMonth(e,t,s,i){const r=new Date(e,t,1),a=r.getDay();let n=i-a;if(n<0&&(n+=7),s>0)r.setDate(1+n+(s-1)*7);else{const o=new Date(e,t+1,0).getDate();r.setDate(o);let l=r.getDay()-i;l<0&&(l+=7),r.setDate(o-l+(s+1)*7)}return r}getCommonTimezones(){const e=new Date;return[{value:"America/New_York",label:"Eastern Time (New York)",region:"Americas"},{value:"America/Chicago",label:"Central Time (Chicago)",region:"Americas"},{value:"America/Denver",label:"Mountain Time (Denver)",region:"Americas"},{value:"America/Phoenix",label:"Mountain Time - Arizona (Phoenix)",region:"Americas"},{value:"America/Los_Angeles",label:"Pacific Time (Los Angeles)",region:"Americas"},{value:"America/Anchorage",label:"Alaska Time (Anchorage)",region:"Americas"},{value:"Pacific/Honolulu",label:"Hawaii Time (Honolulu)",region:"Pacific"},{value:"America/Toronto",label:"Eastern Time (Toronto)",region:"Americas"},{value:"America/Vancouver",label:"Pacific Time (Vancouver)",region:"Americas"},{value:"America/Mexico_City",label:"Central Time (Mexico City)",region:"Americas"},{value:"America/Sao_Paulo",label:"Brasilia Time (São Paulo)",region:"Americas"},{value:"Europe/London",label:"GMT/BST (London)",region:"Europe"},{value:"Europe/Paris",label:"Central European Time (Paris)",region:"Europe"},{value:"Europe/Berlin",label:"Central European Time (Berlin)",region:"Europe"},{value:"Europe/Moscow",label:"Moscow Time",region:"Europe"},{value:"Asia/Dubai",label:"Gulf Time (Dubai)",region:"Asia"},{value:"Asia/Kolkata",label:"India Time (Mumbai)",region:"Asia"},{value:"Asia/Shanghai",label:"China Time (Shanghai)",region:"Asia"},{value:"Asia/Tokyo",label:"Japan Time (Tokyo)",region:"Asia"},{value:"Asia/Seoul",label:"Korea Time (Seoul)",region:"Asia"},{value:"Asia/Singapore",label:"Singapore Time",region:"Asia"},{value:"Australia/Sydney",label:"Australian Eastern Time (Sydney)",region:"Oceania"},{value:"Australia/Melbourne",label:"Australian Eastern Time (Melbourne)",region:"Oceania"},{value:"Pacific/Auckland",label:"New Zealand Time (Auckland)",region:"Oceania"},{value:"UTC",label:"UTC",region:"UTC"}].map(s=>{const i=this.getTimezoneOffset(e,s.value),r=-i/60,a=Math.floor(Math.abs(r)),n=Math.round(Math.abs(r%1)*60),c=`UTC${r>=0?"+":"-"}${a.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`;return{...s,offset:c,offsetMinutes:-i}}).sort((s,i)=>s.offsetMinutes-i.offsetMinutes)}formatInTimezone(e,t,s={}){if(!e)return"";const r={...{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0,timeZone:t},...s};try{return new Intl.DateTimeFormat("en-US",r).format(e)}catch{return this.fromUTC(this.toUTC(e,"UTC"),t).toLocaleString("en-US",s)}}getSystemTimezone(){if(typeof Intl<"u"&&Intl.DateTimeFormat)try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}const t=-new Date().getTimezoneOffset()/60;for(const[s,i]of Object.entries(this.database.timezones))if(i.offset/60===t)return s;return"UTC"}parseTimezone(e){if(!e)return"UTC";if(this.database.timezones.hasOwnProperty(e))return e;const t=e.toUpperCase();if(this.database.abbreviations&&this.database.abbreviations.hasOwnProperty(t))return this.database.abbreviations[t];const s=e.match(/^([+-])(\d{2}):?(\d{2})$/);if(s){const i=s[1]==="+"?1:-1,r=parseInt(s[2],10),a=parseInt(s[3],10),n=i*(r+a/60);for(const[o,c]of Object.entries(this.database.timezones))if(c.offset/60===n)return o}return"UTC"}getTimezoneDifference(e,t,s=new Date){const i=this.getTimezoneOffset(s,e);return(this.getTimezoneOffset(s,t)-i)/60}clearCache(){this.offsetCache.clear(),this.dstCache.clear(),this.cacheHits=0,this.cacheMisses=0}isValidTimezone(e){return this.database.isValidTimezone(e)}getCacheStats(){const e=this.cacheHits+this.cacheMisses>0?(this.cacheHits/(this.cacheHits+this.cacheMisses)*100).toFixed(2):0;return{offsetCacheSize:this.offsetCache.size,dstCacheSize:this.dstCache.size,maxCacheSize:this.maxCacheSize,cacheHits:this.cacheHits,cacheMisses:this.cacheMisses,hitRate:`${e}%`}}_manageCacheSize(){if(this.offsetCache.size>this.maxCacheSize){const e=Math.floor(this.offsetCache.size/2),t=Array.from(this.offsetCache.keys());for(let s=0;s<e;s++)this.offsetCache.delete(t[s])}if(this.dstCache.size>this.maxCacheSize/2){const e=Math.floor(this.dstCache.size/2),t=Array.from(this.dstCache.keys());for(let s=0;s<e;s++)this.dstCache.delete(t[s])}}}class C{static normalize(e){const t={...e};return t.start&&!(t.start instanceof Date)&&(t.start=new Date(t.start)),t.end&&!(t.end instanceof Date)&&(t.end=new Date(t.end)),t.end||(t.end=t.start?new Date(t.start):null),t.allDay&&t.start&&(t.start.setHours(0,0,0,0),t.end&&t.end.setHours(23,59,59,999)),t.id=String(t.id||"").trim(),t.title=String(t.title||"").trim(),t.description=String(t.description||"").trim(),t.location=String(t.location||"").trim(),t.attendees=Array.isArray(t.attendees)?t.attendees:[],t.reminders=Array.isArray(t.reminders)?t.reminders:[],e.category&&!e.categories?t.categories=[e.category]:t.categories?t.categories=Array.isArray(t.categories)?t.categories:[]:t.categories=[],t.attachments=Array.isArray(t.attachments)?t.attachments:[],["confirmed","tentative","cancelled"].includes(t.status)||(t.status="confirmed"),["public","private","confidential"].includes(t.visibility)||(t.visibility="public"),t.color&&!t.backgroundColor&&(t.backgroundColor=t.color),t.color&&!t.borderColor&&(t.borderColor=t.color),t}static validate(e){if(!e.id)throw new Error("Event must have an id");if(!e.title)throw new Error("Event must have a title");if(!e.start)throw new Error("Event must have a start date");if(!(e.start instanceof Date)||isNaN(e.start.getTime()))throw new Error("Invalid start date");if(e.end&&(!(e.end instanceof Date)||isNaN(e.end.getTime())))throw new Error("Invalid end date");if(e.end&&e.start&&e.end<e.start)throw new Error("Event end time cannot be before start time");if(e.recurring&&!e.recurrenceRule)throw new Error("Recurring events must have a recurrence rule");if(e.attendees&&e.attendees.length>0&&e.attendees.forEach((t,s)=>{if(!t.email||!t.name)throw new Error(`Attendee at index ${s} must have email and name`);if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.email))throw new Error(`Invalid email for attendee: ${t.email}`)}),e.reminders&&e.reminders.length>0&&e.reminders.forEach((t,s)=>{if(!t.method||t.minutesBefore==null)throw new Error(`Reminder at index ${s} must have method and minutesBefore`);if(t.minutesBefore<0)throw new Error("Reminder minutesBefore must be non-negative")}),e.timeZone)try{new Intl.DateTimeFormat("en-US",{timeZone:e.timeZone})}catch{throw new Error(`Invalid timezone: ${e.timeZone}`)}}constructor({id:e,title:t,start:s,end:i,allDay:r=!1,description:a="",location:n="",color:o=null,backgroundColor:c=null,borderColor:l=null,textColor:d=null,recurring:h=!1,recurrenceRule:g=null,timeZone:b=null,endTimeZone:f=null,status:T="confirmed",visibility:D="public",organizer:S=null,attendees:q=[],reminders:K=[],category:G,categories:Q,attachments:J=[],conferenceData:X=null,metadata:ee={},...te}){const m=C.normalize({id:e,title:t,start:s,end:i,allDay:r,description:a,location:n,color:o,backgroundColor:c,borderColor:l,textColor:d,recurring:h,recurrenceRule:g,timeZone:b,endTimeZone:f,status:T,visibility:D,organizer:S,attendees:q,reminders:K,category:G,categories:Q,attachments:J,conferenceData:X,metadata:ee,...te});C.validate(m),this.id=m.id,this.title=m.title,this._timezoneManager=new $,this.timeZone=m.timeZone||this._timezoneManager.getSystemTimezone(),this.endTimeZone=m.endTimeZone||this.timeZone,this.start=m.start,this.end=m.end,this.startUTC=this._timezoneManager.toUTC(this.start,this.timeZone),this.endUTC=this._timezoneManager.toUTC(this.end,this.endTimeZone),this.allDay=m.allDay,this.description=m.description,this.location=m.location,this.color=m.color,this.backgroundColor=m.backgroundColor,this.borderColor=m.borderColor,this.textColor=m.textColor,this.recurring=m.recurring,this.recurrenceRule=m.recurrenceRule,this._originalTimeZone=m.timeZone||null,this.status=m.status,this.visibility=m.visibility,this.organizer=m.organizer,this.attendees=[...m.attendees],this.reminders=[...m.reminders],this.categories=m.categories?[...m.categories]:[],this.attachments=[...m.attachments],this.conferenceData=m.conferenceData,this.metadata={...m.metadata},this._cache={},this._validateAttendees(),this._validateReminders()}get duration(){return this._cache.duration||(this._cache.duration=this.endUTC.getTime()-this.startUTC.getTime()),this._cache.duration}getStartInTimezone(e){return e===this.timeZone?new Date(this.start):this._timezoneManager.fromUTC(this.startUTC,e)}getEndInTimezone(e){return e===this.endTimeZone?new Date(this.end):this._timezoneManager.fromUTC(this.endUTC,e)}updateTimes(e,t,s){if(s||this.timeZone,this.start=e instanceof Date?e:new Date(e),this.end=t instanceof Date?t:new Date(t),s&&(this.timeZone=s,this.endTimeZone=s),this.startUTC=this._timezoneManager.toUTC(this.start,this.timeZone),this.endUTC=this._timezoneManager.toUTC(this.end,this.endTimeZone),this._cache={},this.endUTC<this.startUTC)throw new Error("Event end time cannot be before start time")}get durationMinutes(){return Math.floor(this.duration/(1e3*60))}get durationHours(){return this.duration/(1e3*60*60)}get isMultiDay(){if(!this._cache.hasOwnProperty("isMultiDay")){const e=this.start.toDateString(),t=this.end.toDateString();this._cache.isMultiDay=e!==t}return this._cache.isMultiDay}isRecurring(){return this.recurring&&this.recurrenceRule!==null}occursOn(e){e instanceof Date||(e=new Date(e));const t=e.toDateString(),s=this.start.toDateString(),i=this.end.toDateString();if(this.allDay)return e>=new Date(s)&&e<=new Date(i);if(this.isMultiDay){const r=new Date(t),a=new Date(t);return a.setHours(23,59,59,999),this.start<=a&&this.end>=r}else return s===t}overlaps(e){if(e instanceof C)return!(this.end<=e.start||this.start>=e.end);if(e&&e.start&&e.end)return!(this.end<=e.start||this.start>=e.end);throw new Error("Parameter must be an Event instance or have start/end properties")}contains(e){return e instanceof Date||(e=new Date(e)),e>=this.start&&e<=this.end}clone(e={}){return new C({id:this.id,title:this.title,start:new Date(this.start),end:new Date(this.end),allDay:this.allDay,description:this.description,location:this.location,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,textColor:this.textColor,recurring:this.recurring,recurrenceRule:this.recurrenceRule,timeZone:this.timeZone,status:this.status,visibility:this.visibility,organizer:this.organizer?{...this.organizer}:null,attendees:this.attendees.map(t=>({...t})),reminders:this.reminders.map(t=>({...t})),categories:[...this.categories],attachments:this.attachments.map(t=>({...t})),conferenceData:this.conferenceData?{...this.conferenceData}:null,metadata:{...this.metadata},...e})}toObject(){return{id:this.id,title:this.title,start:this.start.toISOString(),end:this.end.toISOString(),allDay:this.allDay,description:this.description,location:this.location,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,textColor:this.textColor,recurring:this.recurring,recurrenceRule:this.recurrenceRule,timeZone:this.timeZone,status:this.status,visibility:this.visibility,organizer:this.organizer,attendees:this.attendees,reminders:this.reminders,categories:this.categories,attachments:this.attachments,conferenceData:this.conferenceData,metadata:{...this.metadata}}}static fromObject(e){return new C(e)}equals(e){return e instanceof C?this.id===e.id&&this.title===e.title&&this.start.getTime()===e.start.getTime()&&this.end.getTime()===e.end.getTime()&&this.allDay===e.allDay&&this.description===e.description&&this.location===e.location&&this.recurring===e.recurring&&this.recurrenceRule===e.recurrenceRule&&this.status===e.status:!1}addAttendee(e){if(!e||!e.email)throw new Error("Attendee must have an email");return this.hasAttendee(e.email)?!1:(e.id||(e.id=`attendee_${Date.now()}_${Math.random().toString(36).substr(2,9)}`),e.responseStatus=e.responseStatus||"needs-action",e.role=e.role||"required",this.attendees.push(e),!0)}removeAttendee(e){const t=this.attendees.findIndex(s=>s.email===e||s.id===e);return t!==-1?(this.attendees.splice(t,1),!0):!1}updateAttendeeResponse(e,t){const s=this.getAttendee(e);return s?(s.responseStatus=t,s.responseTime=new Date,!0):!1}getAttendee(e){return this.attendees.find(t=>t.email===e)||null}hasAttendee(e){return this.attendees.some(t=>t.email===e)}getAttendeesByStatus(e){return this.attendees.filter(t=>t.responseStatus===e)}getAttendeeCounts(){return this.attendees.reduce((e,t)=>{const s=t.responseStatus||"needs-action";return e[s]=(e[s]||0)+1,e},{})}addReminder(e){if(!e||typeof e.minutesBefore!="number")throw new Error("Reminder must have minutesBefore property");return e.id||(e.id=`reminder_${Date.now()}_${Math.random().toString(36).substr(2,9)}`),e.method=e.method||"popup",e.enabled=e.enabled!==!1,this.reminders.some(s=>s.method===e.method&&s.minutesBefore===e.minutesBefore)?!1:(this.reminders.push(e),!0)}removeReminder(e){const t=this.reminders.findIndex(s=>s.id===e);return t!==-1?(this.reminders.splice(t,1),!0):!1}getActiveReminders(){return this.reminders.filter(e=>e.enabled!==!1)}getReminderTriggerTimes(){return this.getActiveReminders().map(e=>{const t=new Date(this.start);return t.setMinutes(t.getMinutes()-e.minutesBefore),t})}addCategory(e){if(!e||typeof e!="string")throw new Error("Category must be a non-empty string");const t=e.trim().toLowerCase();return this.hasCategory(t)?!1:(this.categories.push(t),!0)}removeCategory(e){const t=e.trim().toLowerCase(),s=this.categories.findIndex(i=>i.toLowerCase()===t);return s!==-1?(this.categories.splice(s,1),!0):!1}get category(){return this.categories&&this.categories.length>0?this.categories[0]:null}hasCategory(e){const t=e.trim().toLowerCase();return this.categories.some(s=>s.toLowerCase()===t)}hasAnyCategory(e){return e.some(t=>this.hasCategory(t))}hasAllCategories(e){return e.every(t=>this.hasCategory(t))}_validateAttendees(){for(const e of this.attendees){if(!e.email)throw new Error("All attendees must have an email address");if(e.name||(e.name=e.email),!this._isValidEmail(e.email))throw new Error(`Invalid attendee email: ${e.email}`)}}_validateReminders(){for(const e of this.reminders){if(typeof e.minutesBefore!="number"||e.minutesBefore<0)throw new Error("Reminder minutesBefore must be a positive number");if(!["email","popup","sms"].includes(e.method))throw new Error(`Invalid reminder method: ${e.method}`)}}_isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}get isCancelled(){return this.status==="cancelled"}get isTentative(){return this.status==="tentative"}get isConfirmed(){return this.status==="confirmed"}get isPrivate(){return this.visibility==="private"}get isPublic(){return this.visibility==="public"}get hasAttendees(){return this.attendees.length>0}get hasReminders(){return this.reminders.length>0}get isMeeting(){return this.hasAttendees||this.conferenceData!==null}get isVirtual(){return this.conferenceData!==null}}let u=class M{static startOfDay(e){const t=new Date(e);return t.setHours(0,0,0,0),t}static endOfDay(e){const t=new Date(e);return t.setHours(23,59,59,999),t}static startOfWeek(e,t=0){const s=new Date(e),i=s.getDay(),r=(i<t?7:0)+i-t;return s.setTime(s.getTime()-r*24*60*60*1e3),s.setHours(0,0,0,0),s}static endOfWeek(e,t=0){const s=M.startOfWeek(e,t);return s.setTime(s.getTime()+6*24*60*60*1e3),s.setHours(23,59,59,999),s}static startOfMonth(e){return new Date(e.getFullYear(),e.getMonth(),1,0,0,0,0)}static endOfMonth(e){return new Date(e.getFullYear(),e.getMonth()+1,0,23,59,59,999)}static startOfYear(e){return new Date(e.getFullYear(),0,1,0,0,0,0)}static endOfYear(e){return new Date(e.getFullYear(),11,31,23,59,59,999)}static addDays(e,t){const s=new Date(e);return s.setTime(s.getTime()+t*24*60*60*1e3),s}static addWeeks(e,t){return M.addDays(e,t*7)}static addMonths(e,t){const s=new Date(e),i=s.getDate();return s.setMonth(s.getMonth()+t),s.getDate()!==i&&s.setDate(0),s}static addYears(e,t){const s=new Date(e);return s.setFullYear(s.getFullYear()+t),s}static getUTCDateString(e){const t=e.getUTCFullYear(),s=String(e.getUTCMonth()+1).padStart(2,"0"),i=String(e.getUTCDate()).padStart(2,"0");return`${t}-${s}-${i}`}static getLocalDateString(e){const t=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${s}-${i}`}static isToday(e){const t=new Date;return e.toDateString()===t.toDateString()}static isPast(e){return e<new Date}static isFuture(e){return e>new Date}static isSameDay(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}static isSameWeek(e,t,s=0){const i=M.startOfWeek(e,s),r=M.startOfWeek(t,s);return i.toDateString()===r.toDateString()}static isSameMonth(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()}static isSameYear(e,t){return e.getFullYear()===t.getFullYear()}static differenceInDays(e,t){const s=e.getTime()-t.getTime();return Math.floor(s/(1e3*60*60*24))}static differenceInWeeks(e,t){return Math.floor(M.differenceInDays(e,t)/7)}static differenceInMonths(e,t){const s=e.getFullYear()-t.getFullYear(),i=e.getMonth()-t.getMonth();return s*12+i}static getWeekNumber(e){const t=new Date(e.getFullYear(),0,1),s=(e-t)/864e5;return Math.ceil((s+t.getDay()+1)/7)}static getDayOfWeek(e,t=0){return(e.getDay()-t+7)%7}static getDaysInMonth(e){return new Date(e.getFullYear(),e.getMonth()+1,0).getDate()}static format(e,t="en-US",s={}){return new Intl.DateTimeFormat(t,s).format(e)}static getMonthName(e,t="en-US",s="long"){return M.format(e,t,{month:s})}static getDayName(e,t="en-US",s="long"){return M.format(e,t,{weekday:s})}static formatTime(e,t="en-US",s=!1){return M.format(e,t,{hour:"numeric",minute:"2-digit",hour12:!s})}static parseTime(e){const[t,s]=e.split(":").map(Number);return{hours:t,minutes:s}}static setTime(e,t){const s=new Date(e),{hours:i,minutes:r}=M.parseTime(t);return s.setHours(i,r,0,0),s}static isLeapYear(e){return e%4===0&&e%100!==0||e%400===0}static getDateRange(e,t){const s=[],i=new Date(e),r=t.getTime();for(;i.getTime()<=r;)s.push(new Date(i)),i.setTime(i.getTime()+24*60*60*1e3);return s}static clone(e){return new Date(e)}static isValidDate(e){return e instanceof Date&&!isNaN(e.getTime())}static toTimeZone(e,t){const i=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(e),r={};return i.forEach(a=>{a.type!=="literal"&&(r[a.type]=a.value)}),new Date(`${r.year}-${r.month}-${r.day}T${r.hour}:${r.minute}:${r.second}`)}static getTimezoneOffset(e,t){const s=new Date(e.toLocaleString("en-US",{timeZone:"UTC"})),i=new Date(e.toLocaleString("en-US",{timeZone:t}));return(s.getTime()-i.getTime())/6e4}static isDST(e,t){const s=new Date(e.getFullYear(),0,1),i=new Date(e.getFullYear(),6,1),r=M.getTimezoneOffset(s,t),a=M.getTimezoneOffset(i,t),n=M.getTimezoneOffset(e,t);return Math.max(r,a)===n}static addHoursWithDST(e,t,s){const i=new Date(e),r=M.getTimezoneOffset(e,s);i.setTime(i.getTime()+t*60*60*1e3);const a=M.getTimezoneOffset(i,s);if(r!==a){const n=(a-r)*6e4;i.setTime(i.getTime()+n)}return i}static createInTimeZone(e,t,s,i=0,r=0,a=0,n){const o=`${e}-${String(t+1).padStart(2,"0")}-${String(s).padStart(2,"0")}`,c=`${String(i).padStart(2,"0")}:${String(r).padStart(2,"0")}:${String(a).padStart(2,"0")}`,l=new Date(`${o}T${c}`),d=M.getTimezoneOffset(l,n),h=l.getTime()+d*6e4;return new Date(h)}};class B{static parse(e){if(typeof e=="object")return this.validateRule(e);const t={freq:null,interval:1,count:null,until:null,byDay:[],byWeekNo:[],byMonth:[],byMonthDay:[],byYearDay:[],bySetPos:[],byHour:[],byMinute:[],bySecond:[],wkst:"MO",exceptions:[],tzid:null},s=e.toUpperCase().split(";");for(const i of s){const[r,a]=i.split("=");switch(r){case"FREQ":t.freq=this.parseFrequency(a);break;case"INTERVAL":t.interval=parseInt(a,10),t.interval<1&&(t.interval=1);break;case"COUNT":t.count=parseInt(a,10);break;case"UNTIL":t.until=this.parseDateTime(a);break;case"BYDAY":t.byDay=this.parseByDay(a);break;case"BYWEEKNO":t.byWeekNo=this.parseIntList(a);break;case"BYMONTH":t.byMonth=this.parseIntList(a);break;case"BYMONTHDAY":t.byMonthDay=this.parseIntList(a);break;case"BYYEARDAY":t.byYearDay=this.parseIntList(a);break;case"BYSETPOS":t.bySetPos=this.parseIntList(a);break;case"BYHOUR":t.byHour=this.parseIntList(a);break;case"BYMINUTE":t.byMinute=this.parseIntList(a);break;case"BYSECOND":t.bySecond=this.parseIntList(a);break;case"WKST":t.wkst=a;break;case"EXDATE":t.exceptions=this.parseExceptionDates(a);break;case"TZID":t.tzid=a;break}}return this.validateRule(t)}static parseFrequency(e){return["SECONDLY","MINUTELY","HOURLY","DAILY","WEEKLY","MONTHLY","YEARLY"].includes(e)?e:"DAILY"}static parseByDay(e){const t=e.split(","),s=["SU","MO","TU","WE","TH","FR","SA"],i=[];for(const r of t){const n=r.trim().toUpperCase().match(/^([+-]?\d*)([A-Z]{2})$/);if(n){const[o,c,l]=n;s.includes(l)&&i.push(c?`${c}${l}`:l)}}return i}static parseIntList(e){return e.split(",").map(t=>parseInt(t.trim(),10)).filter(t=>!isNaN(t))}static parseDateTime(e){if(e.length===8){const t=parseInt(e.substr(0,4),10),s=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10);return new Date(t,s,i)}if(e.length===15&&e[8]==="T"){const t=parseInt(e.substr(0,4),10),s=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10),r=parseInt(e.substr(9,2),10),a=parseInt(e.substr(11,2),10),n=parseInt(e.substr(13,2),10);return new Date(t,s,i,r,a,n)}if(e.length===16&&e[8]==="T"&&e[15]==="Z"){const t=parseInt(e.substr(0,4),10),s=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10),r=parseInt(e.substr(9,2),10),a=parseInt(e.substr(11,2),10),n=parseInt(e.substr(13,2),10);return new Date(Date.UTC(t,s,i,r,a,n))}return new Date(e)}static parseExceptionDates(e){return e.split(",").map(s=>this.parseDateTime(s.trim()))}static validateRule(e){if(e.freq||(e.freq="DAILY"),e.count&&e.until)throw new Error("RRULE cannot have both COUNT and UNTIL");e.interval<1&&(e.interval=1);const t=(s,i,r)=>s.filter(a=>a>=i&&a<=r);return e.byMonth=t(e.byMonth||[],1,12),e.byMonthDay=t(e.byMonthDay||[],-31,31).filter(s=>s!==0),e.byYearDay=t(e.byYearDay||[],-366,366).filter(s=>s!==0),e.byWeekNo=t(e.byWeekNo||[],-53,53).filter(s=>s!==0),e.byHour=t(e.byHour||[],0,23),e.byMinute=t(e.byMinute||[],0,59),e.bySecond=t(e.bySecond||[],0,59),e}static buildRRule(e){const t=[];if(t.push(`FREQ=${e.freq}`),e.interval&&e.interval>1&&t.push(`INTERVAL=${e.interval}`),e.count?t.push(`COUNT=${e.count}`):e.until&&t.push(`UNTIL=${this.formatDateTime(e.until)}`),e.byDay&&e.byDay.length>0){const s=e.byDay.map(i=>i.nth?`${i.nth}${i.weekday}`:i.weekday).join(",");t.push(`BYDAY=${s}`)}return e.byMonth&&e.byMonth.length>0&&t.push(`BYMONTH=${e.byMonth.join(",")}`),e.byMonthDay&&e.byMonthDay.length>0&&t.push(`BYMONTHDAY=${e.byMonthDay.join(",")}`),e.byYearDay&&e.byYearDay.length>0&&t.push(`BYYEARDAY=${e.byYearDay.join(",")}`),e.byWeekNo&&e.byWeekNo.length>0&&t.push(`BYWEEKNO=${e.byWeekNo.join(",")}`),e.bySetPos&&e.bySetPos.length>0&&t.push(`BYSETPOS=${e.bySetPos.join(",")}`),e.byHour&&e.byHour.length>0&&t.push(`BYHOUR=${e.byHour.join(",")}`),e.byMinute&&e.byMinute.length>0&&t.push(`BYMINUTE=${e.byMinute.join(",")}`),e.bySecond&&e.bySecond.length>0&&t.push(`BYSECOND=${e.bySecond.join(",")}`),e.wkst&&e.wkst!=="MO"&&t.push(`WKST=${e.wkst}`),t.join(";")}static formatDateTime(e){const t=e.getUTCFullYear(),s=String(e.getUTCMonth()+1).padStart(2,"0"),i=String(e.getUTCDate()).padStart(2,"0"),r=String(e.getUTCHours()).padStart(2,"0"),a=String(e.getUTCMinutes()).padStart(2,"0"),n=String(e.getUTCSeconds()).padStart(2,"0");return`${t}${s}${i}T${r}${a}${n}Z`}static getDescription(e){const t={SECONDLY:"second",MINUTELY:"minute",HOURLY:"hour",DAILY:"day",WEEKLY:"week",MONTHLY:"month",YEARLY:"year"},s={SU:"Sunday",MO:"Monday",TU:"Tuesday",WE:"Wednesday",TH:"Thursday",FR:"Friday",SA:"Saturday"},i={1:"first",2:"second",3:"third",4:"fourth",5:"fifth","-1":"last","-2":"second to last"};let r="Every";if(e.interval>1&&(r+=` ${e.interval}`),r+=` ${t[e.freq]}`,e.interval>1&&(r+="s"),e.byDay&&e.byDay.length>0){if(e.freq==="WEEKLY"){const a=e.byDay.map(n=>s[n.weekday]).join(", ");r+=` on ${a}`}else if(e.freq==="MONTHLY"||e.freq==="YEARLY"){const a=e.byDay.map(n=>n.nth?`the ${i[n.nth]||n.nth} ${s[n.weekday]}`:s[n.weekday]).join(", ");r+=` on ${a}`}}if(e.byMonthDay&&e.byMonthDay.length>0){const a=e.byMonthDay.map(n=>n<0?`${Math.abs(n)} day(s) from the end`:`day ${n}`).join(", ");r+=` on ${a}`}if(e.byMonth&&e.byMonth.length>0){const a=["January","February","March","April","May","June","July","August","September","October","November","December"],n=e.byMonth.map(o=>a[o-1]).join(", ");r+=` in ${n}`}return e.count?r+=`, ${e.count} time${e.count>1?"s":""}`:e.until&&(r+=`, until ${e.until.toLocaleDateString()}`),r}}class U{static expandEvent(e,t,s,i=365,r=null){if(!e.recurring||!e.recurrenceRule)return[{start:e.start,end:e.end,timezone:e.timeZone}];const a=this.parseRule(e.recurrenceRule),n=[],o=e.end-e.start,c=r||e.timeZone||"UTC",l=new $;let d=new Date(e.start),h=0;a.until&&a.until<s&&(s=a.until);let g=l.getTimezoneOffset(d,c);for(;d<=s&&h<i;){if(d>=t){const b=new Date(d),f=new Date(d.getTime()+o),T=l.getTimezoneOffset(b,c);if(T!==g){const D=g-T;b.setMinutes(b.getMinutes()+D),f.setMinutes(f.getMinutes()+D)}g=T,this.isException(b,a,e.id)||n.push({start:b,end:f,recurringEventId:e.id,timezone:c,originalStart:e.start})}if(d=this.getNextOccurrence(d,a,c),h++,a.count&&h>=a.count)break}return n}static parseRule(e){return B.parse(e)}static getNextOccurrence(e,t,s="UTC"){const i=new Date(e);switch(t.freq){case"DAILY":i.setDate(i.getDate()+t.interval);break;case"WEEKLY":if(t.byDay&&t.byDay.length>0){let a=0;for(i.setDate(i.getDate()+1);!this.matchesByDay(i,t.byDay)&&a<8;)i.setDate(i.getDate()+1),a++;a>=8&&(console.warn("RecurrenceEngine: Invalid byDay rule, falling back to weekly interval"),i.setDate(i.getDate()+7*t.interval-8))}else i.setDate(i.getDate()+7*t.interval);break;case"MONTHLY":if(t.byMonthDay&&t.byMonthDay.length>0){const r=i.getMonth();i.setMonth(r+t.interval),i.setDate(t.byMonthDay[0])}else t.byDay&&t.byDay.length>0?(i.setMonth(i.getMonth()+t.interval),this.setToWeekdayOfMonth(i,t.byDay[0],t.bySetPos[0]||1)):i.setMonth(i.getMonth()+t.interval);break;case"YEARLY":t.byMonth&&t.byMonth.length>0?(i.setFullYear(i.getFullYear()+t.interval),i.setMonth(t.byMonth[0]-1)):i.setFullYear(i.getFullYear()+t.interval);break;default:i.setTime(i.getTime()+24*60*60*1e3)}return i}static matchesByDay(e,t){const s={SU:0,MO:1,TU:2,WE:3,TH:4,FR:5,SA:6},i=e.getDay();return t.some(r=>{const a=r.match(/^(-?\d+)?([A-Z]{2})$/);if(a){const n=a[2];return s[n]===i}return!1})}static setToWeekdayOfMonth(e,t,s=1){const i={SU:0,MO:1,TU:2,WE:3,TH:4,FR:5,SA:6},r=t.match(/^(-?\d+)?([A-Z]{2})$/),a=r?r[2]:t,n=i[a];for(e.setDate(1);e.getDay()!==n;)e.setDate(e.getDate()+1);if(s>1)e.setDate(e.getDate()+7*(s-1));else if(s===-1){const o=new Date(e);for(o.setMonth(o.getMonth()+1),o.setDate(0);o.getDay()!==n;)o.setDate(o.getDate()-1);e.setTime(o.getTime())}}static isException(e,t,s=null){if(!t.exceptions||t.exceptions.length===0)return!1;const i=e.toDateString(),r=e.getTime();return t.exceptions.some(a=>{if(typeof a=="object"&&a.date){const n=a.date instanceof Date?a.date:new Date(a.date);return a.matchTime?Math.abs(n.getTime()-r)<1e3:n.toDateString()===i}else return(a instanceof Date?a:new Date(a)).toDateString()===i})}static addExceptions(e,t,s={}){return e.exceptions||(e.exceptions=[]),(Array.isArray(t)?t:[t]).forEach(r=>{s.reason||s.matchTime?e.exceptions.push({date:r,reason:s.reason,matchTime:s.matchTime||!1}):e.exceptions.push(r)}),e}static parseDate(e){if(e.length===8){const t=parseInt(e.substr(0,4),10),s=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10);return new Date(t,s,i)}else if(e.length===15||e.length===16){const t=parseInt(e.substr(0,4),10),s=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10),r=parseInt(e.substr(9,2),10),a=parseInt(e.substr(11,2),10),n=parseInt(e.substr(13,2),10);return e.endsWith("Z")?new Date(Date.UTC(t,s,i,r,a,n)):new Date(t,s,i,r,a,n)}return new Date(e)}static getDescription(e){typeof e=="string"&&(e=this.parseRule(e));let t="";const s=e.interval||1;switch(e.freq){case"DAILY":t=s===1?"Daily":`Every ${s} days`;break;case"WEEKLY":if(t=s===1?"Weekly":`Every ${s} weeks`,e.byDay&&e.byDay.length>0){const i=e.byDay.map(r=>this.getDayName(r)).join(", ");t+=` on ${i}`}break;case"MONTHLY":t=s===1?"Monthly":`Every ${s} months`,e.byMonthDay&&e.byMonthDay.length>0&&(t+=` on day ${e.byMonthDay.join(", ")}`);break;case"YEARLY":t=s===1?"Yearly":`Every ${s} years`;break}return e.count?t+=`, ${e.count} times`:e.until&&(t+=`, until ${e.until.toLocaleDateString()}`),t}static getDayName(e){const t={SU:"Sunday",MO:"Monday",TU:"Tuesday",WE:"Wednesday",TH:"Thursday",FR:"Friday",SA:"Saturday"},s=e.match(/^(-?\d+)?([A-Z]{2})$/),i=s?s[2]:e,r=s&&s[1]?parseInt(s[1],10):null;let a=t[i]||e;return r&&(a=`${r===-1?"Last":["","1st","2nd","3rd","4th","5th"][r]||`${r}th`} ${a}`),a}}class z{constructor(e=100){this.capacity=e,this.cache=new Map,this.hits=0,this.misses=0,this.evictions=0}get(e){if(!this.cache.has(e)){this.misses++;return}const t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),this.hits++,t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){const s=this.cache.keys().next().value;this.cache.delete(s),this.evictions++}this.cache.set(e,t)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear(),this.hits=0,this.misses=0,this.evictions=0}getStats(){const e=this.hits+this.misses>0?(this.hits/(this.hits+this.misses)*100).toFixed(2):0;return{size:this.cache.size,capacity:this.capacity,hits:this.hits,misses:this.misses,evictions:this.evictions,hitRate:`${e}%`}}keys(){return Array.from(this.cache.keys())}get size(){return this.cache.size}}class P{constructor(e={}){this.config={checkInterval:3e4,memoryThreshold:.8,criticalThreshold:.95,minCacheSize:10,maxCacheSize:1e4,adaptiveScaling:!0,...e},this.caches=new Map,this.stats={adjustments:0,emergencyClears:0,lastMemoryUsage:0,lastCheckTime:null,cacheResizes:[]},this.monitoringInterval=null,this.config.adaptiveScaling&&this.startMonitoring()}registerCache(e,t,s={}){this.caches.set(e,{cache:t,priority:s.priority||1,currentCapacity:s.initialCapacity||100,minCapacity:s.minCapacity||this.config.minCacheSize,maxCapacity:s.maxCapacity||this.config.maxCacheSize,scaleFactor:s.scaleFactor||.5,lastAccess:Date.now()})}unregisterCache(e){this.caches.delete(e)}startMonitoring(){this.monitoringInterval||(this.monitoringInterval=setInterval(()=>{this.checkMemoryPressure()},this.config.checkInterval),this.checkMemoryPressure())}stopMonitoring(){this.monitoringInterval&&(clearInterval(this.monitoringInterval),this.monitoringInterval=null)}async checkMemoryPressure(){const e=await this.getMemoryUsage();this.stats.lastMemoryUsage=e,this.stats.lastCheckTime=new Date,e>this.config.criticalThreshold?this.emergencyClear():e>this.config.memoryThreshold?this.reduceCacheSizes(e):e<this.config.memoryThreshold-.2&&this.increaseCacheSizes()}async getMemoryUsage(){if(typeof performance<"u"&&performance.memory){const e=performance.memory;if(e.jsHeapSizeLimit&&e.usedJSHeapSize)return e.usedJSHeapSize/e.jsHeapSizeLimit}try{const t=(typeof globalThis<"u"?globalThis:{}).process;if(t&&typeof t=="object"){const s=t.memoryUsage;if(typeof s=="function"){const i=s.call(t);return i.heapUsed/i.heapTotal}}}catch{}return this.estimateMemoryUsage()}estimateMemoryUsage(){let e=0,t=0;for(const[s,i]of this.caches)i.cache.size!==void 0&&(e+=i.cache.size,t+=i.maxCapacity);return t>0?e/t:.5}reduceCacheSizes(e){const t=(e-this.config.memoryThreshold)/(this.config.criticalThreshold-this.config.memoryThreshold),s=Array.from(this.caches.entries()).sort((i,r)=>i[1].priority-r[1].priority);for(const[i,r]of s){const a=Math.floor(r.currentCapacity*r.scaleFactor*t),n=Math.max(r.minCapacity,r.currentCapacity-a);n<r.currentCapacity&&this.resizeCache(i,r,n)}this.stats.adjustments++}increaseCacheSizes(){for(const[e,t]of this.caches)if(Date.now()-t.lastAccess<6e4){const i=Math.floor(t.currentCapacity*.2),r=Math.min(t.maxCapacity,t.currentCapacity+i);r>t.currentCapacity&&this.resizeCache(e,t,r)}}resizeCache(e,t,s){const i=t.currentCapacity;t.currentCapacity=s,t.cache.capacity!==void 0&&(t.cache.capacity=s),t.cache.size>s&&this.evictExcessItems(t.cache,s),this.stats.cacheResizes.push({cache:e,timestamp:new Date,oldCapacity:i,newCapacity:s,reason:s<i?"pressure":"available"}),this.stats.cacheResizes.length>100&&this.stats.cacheResizes.shift()}evictExcessItems(e,t){if(e.size<=t)return;const s=e.size-t;if(e.keys){const i=Array.from(e.keys());for(let r=0;r<s;r++)e.delete(i[r])}else e.clear&&e.clear()}emergencyClear(){for(const[e,t]of this.caches)t.cache.clear&&t.cache.clear(),t.currentCapacity=t.minCapacity;this.stats.emergencyClears++,console.warn("AdaptiveMemoryManager: Emergency cache clear triggered")}touchCache(e){const t=this.caches.get(e);t&&(t.lastAccess=Date.now())}getStats(){const e={};for(const[t,s]of this.caches)e[t]={size:s.cache.size||0,capacity:s.currentCapacity,priority:s.priority,lastAccess:new Date(s.lastAccess)};return{...this.stats,memoryUsagePercent:`${(this.stats.lastMemoryUsage*100).toFixed(2)}%`,totalCaches:this.caches.size,cacheStats:e,monitoring:this.monitoringInterval!==null}}async checkNow(){await this.checkMemoryPressure()}setThresholds(e){e.memoryThreshold!==void 0&&(this.config.memoryThreshold=Math.max(.5,Math.min(.95,e.memoryThreshold))),e.criticalThreshold!==void 0&&(this.config.criticalThreshold=Math.max(this.config.memoryThreshold+.05,Math.min(1,e.criticalThreshold)))}destroy(){this.stopMonitoring(),this.caches.clear()}}class V{constructor(e={}){this.config={enableCache:!0,cacheCapacity:500,maxIndexDays:365,batchSize:100,enableMetrics:!0,cleanupInterval:36e5,maxIndexAge:30*24*60*60*1e3,enableAdaptiveMemory:!0,...e},this.eventCache=new z(this.config.cacheCapacity),this.queryCache=new z(Math.floor(this.config.cacheCapacity/2)),this.dateRangeCache=new z(Math.floor(this.config.cacheCapacity/4)),this.config.enableAdaptiveMemory&&(this.memoryManager=new P({checkInterval:3e4,memoryThreshold:.75,criticalThreshold:.9}),this.memoryManager.registerCache("events",this.eventCache,{priority:3,initialCapacity:this.config.cacheCapacity,minCapacity:50,maxCapacity:2e3}),this.memoryManager.registerCache("queries",this.queryCache,{priority:2,initialCapacity:Math.floor(this.config.cacheCapacity/2),minCapacity:25,maxCapacity:1e3}),this.memoryManager.registerCache("dateRanges",this.dateRangeCache,{priority:1,initialCapacity:Math.floor(this.config.cacheCapacity/4),minCapacity:10,maxCapacity:500})),this.lazyIndexes=new Map,this.pendingIndexes=new Map,this.batchQueue=[],this.batchTimer=null,this.batchCallbacks=[],this.metrics={operations:{},averageTimes:{},slowQueries:[]},this.cleanupTimer=null,this.config.cleanupInterval>0&&this.startCleanupTimer()}measure(e,t){if(!this.config.enableMetrics)return t();const s=performance.now();try{const i=t(),r=performance.now()-s;return this.recordMetric(e,r),i}catch(i){const r=performance.now()-s;throw this.recordMetric(e,r,!0),i}}async measureAsync(e,t){if(!this.config.enableMetrics)return await t();const s=performance.now();try{const i=await t(),r=performance.now()-s;return this.recordMetric(e,r),i}catch(i){const r=performance.now()-s;throw this.recordMetric(e,r,!0),i}}recordMetric(e,t,s=!1){this.metrics.operations[e]||(this.metrics.operations[e]={count:0,totalTime:0,errors:0,min:1/0,max:0});const i=this.metrics.operations[e];i.count++,i.totalTime+=t,i.min=Math.min(i.min,t),i.max=Math.max(i.max,t),s&&i.errors++,this.metrics.averageTimes[e]=i.totalTime/i.count,t>100&&(this.metrics.slowQueries.push({operation:e,duration:t,timestamp:new Date,isError:s}),this.metrics.slowQueries.length>100&&this.metrics.slowQueries.shift())}getMetrics(){const e={cacheStats:{event:this.eventCache.getStats(),query:this.queryCache.getStats(),dateRange:this.dateRangeCache.getStats()},operations:{},slowestOperations:[],recentSlowQueries:this.metrics.slowQueries.slice(-10),memoryManagement:this.memoryManager?this.memoryManager.getStats():null};for(const[t,s]of Object.entries(this.metrics.operations))e.operations[t]={count:s.count,avgTime:`${(s.totalTime/s.count).toFixed(2)}ms`,minTime:`${s.min.toFixed(2)}ms`,maxTime:`${s.max.toFixed(2)}ms`,totalTime:`${s.totalTime.toFixed(2)}ms`,errors:s.errors,errorRate:`${(s.errors/s.count*100).toFixed(2)}%`};return e.slowestOperations=Object.entries(this.metrics.averageTimes).sort((t,s)=>s[1]-t[1]).slice(0,5).map(([t,s])=>({operation:t,avgTime:`${s.toFixed(2)}ms`})),e}shouldUseLazyIndexing(e){return Math.ceil((e.end-e.start)/864e5)>this.config.maxIndexDays}createLazyIndexMarkers(e){const t={eventId:e.id,start:e.start,end:e.end,indexed:new Set,pending:!1},s=new Date(e.start.getFullYear(),e.start.getMonth(),1),i=new Date(e.end.getFullYear(),e.end.getMonth(),1);return t.indexed.add(this.getMonthKey(s)),this.getMonthKey(s)!==this.getMonthKey(i)&&t.indexed.add(this.getMonthKey(i)),this.lazyIndexes.set(e.id,t),t}async expandLazyIndex(e,t,s){const i=this.lazyIndexes.get(e);if(!i)return new Set;if(i.pending)return this.pendingIndexes.get(e);i.pending=!0;const r=new Promise(a=>{setTimeout(()=>{const n=new Set,o=new Date(t);for(;o<=s;){const c=o.toDateString();i.indexed.has(c)||(n.add(c),i.indexed.add(c)),o.setDate(o.getDate()+1)}i.pending=!1,this.pendingIndexes.delete(e),a(n)},0)});return this.pendingIndexes.set(e,r),r}getMonthKey(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}`}cache(e,t,s="event"){if(!this.config.enableCache)return;let i,r;switch(s){case"event":i=this.eventCache,r="events";break;case"query":i=this.queryCache,r="queries";break;case"dateRange":i=this.dateRangeCache,r="dateRanges";break;default:return}i.put(e,t),this.memoryManager&&this.memoryManager.touchCache(r)}getFromCache(e,t="event"){if(!this.config.enableCache)return;let s,i;switch(t){case"event":s=this.eventCache.get(e),i="events";break;case"query":s=this.queryCache.get(e),i="queries";break;case"dateRange":s=this.dateRangeCache.get(e),i="dateRanges";break;default:return}return s!==void 0&&this.memoryManager&&this.memoryManager.touchCache(i),s}invalidateEventCaches(e){this.eventCache.delete(e),this.queryCache.clear(),this.dateRangeCache.clear()}batch(e){return new Promise((t,s)=>{this.batchQueue.push(e),this.batchCallbacks.push({resolve:t,reject:s}),this.batchQueue.length>=this.config.batchSize?this.processBatch():this.batchTimer||(this.batchTimer=setTimeout(()=>this.processBatch(),10))})}processBatch(){if(this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.batchQueue.length===0)return;const e=this.batchQueue.splice(0),t=this.batchCallbacks.splice(0),s=[],i=[];e.forEach((r,a)=>{try{s[a]=r()}catch(n){i[a]=n}}),t.forEach((r,a)=>{i[a]?r.reject(i[a]):r.resolve(s[a])})}startCleanupTimer(){this.cleanupTimer=setInterval(()=>{this.cleanupOldIndexes()},this.config.cleanupInterval)}cleanupOldIndexes(){const e=Date.now(),t=this.config.maxIndexAge;for(const[s,i]of this.lazyIndexes)i.end.getTime()<e-t&&this.lazyIndexes.delete(s);this.metrics.slowQueries.length>100&&(this.metrics.slowQueries=this.metrics.slowQueries.slice(-100))}optimizeQuery(e,t){const s=this.getFromCache(e,"query");if(s!==void 0)return s;const i=this.measure(`query:${e}`,t);return this.cache(e,i,"query"),i}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.eventCache.clear(),this.queryCache.clear(),this.dateRangeCache.clear(),this.lazyIndexes.clear(),this.pendingIndexes.clear()}}class Y{constructor(e){this.eventStore=e,this.conflictIdCounter=0}checkConflicts(e,t={}){const s={checkAttendees:!0,checkResources:!0,checkLocation:!0,ignoreAllDay:!1,excludeEventIds:[],includeStatuses:["confirmed","tentative"],bufferMinutes:0,...t};if(!e.start||!e.end)throw new Error("Event must have start and end dates");const i=[],r=new Set,a=new Set,n=new Date(e.start.getTime()-s.bufferMinutes*6e4),o=new Date(e.end.getTime()+s.bufferMinutes*6e4),c=this.eventStore.getEventsInRange(n,o,!1).filter(l=>!(l.id===e.id||s.excludeEventIds.includes(l.id)||!s.includeStatuses.includes(l.status)||s.ignoreAllDay&&(l.allDay||e.allDay)||l.status==="cancelled"));for(const l of c){const d=this._detectEventConflicts(e,l,s);d.length>0&&(i.push(...d),r.add(e.id),r.add(l.id),e.attendees&&e.attendees.forEach(h=>a.add(h.email)),l.attendees&&l.attendees.forEach(h=>a.add(h.email)))}return this._buildConflictSummary(i,r,a)}checkEventPairConflicts(e,t,s={}){const i={checkAttendees:!0,checkResources:!0,checkLocation:!0,bufferMinutes:0,...s};return this._detectEventConflicts(e,t,i)}getBusyPeriods(e,t,s,i={}){const r={includeStatuses:["confirmed","tentative"],mergePeriods:!0,...i},a=[];return this.eventStore.getEventsInRange(t,s,!1).filter(c=>!r.includeStatuses.includes(c.status)||c.status==="cancelled"?!1:c.attendees&&c.attendees.some(l=>e.includes(l.email))).forEach(c=>{a.push({start:c.start,end:c.end,eventIds:[c.id]})}),r.mergePeriods&&a.length>1?this._mergeBusyPeriods(a):a.sort((c,l)=>c.start-l.start)}getFreePeriods(e,t,s,i={}){const r={attendeeEmails:[],businessHoursOnly:!1,businessHours:{start:"09:00",end:"17:00"},excludeWeekends:!1,...i},a=[],n=r.attendeeEmails.length>0?this.getBusyPeriods(r.attendeeEmails,e,t):this._getAllBusyPeriods(e,t);let o=new Date(e);for(const c of n)o<c.start&&(c.start-o)/6e4>=s&&(!r.businessHoursOnly||this._isWithinBusinessHours(o,c.start,r))&&a.push({start:new Date(o),end:new Date(c.start)}),o=new Date(Math.max(o.getTime(),c.end.getTime()));return o<t&&(t-o)/6e4>=s&&(!r.businessHoursOnly||this._isWithinBusinessHours(o,t,r))&&a.push({start:new Date(o),end:new Date(t)}),a}_detectEventConflicts(e,t,s){const i=[];if(this._checkTimeOverlap(e,t,s.bufferMinutes)){const a=this._createTimeConflict(e,t);if(i.push(a),s.checkAttendees){const n=this._checkAttendeeConflicts(e,t);i.push(...n)}if(s.checkResources){const n=this._checkResourceConflicts(e,t);i.push(...n)}if(s.checkLocation){const n=this._checkLocationConflict(e,t);n&&i.push(n)}}return i}_checkTimeOverlap(e,t,s=0){const i=s*6e4,r=e.start.getTime()-i,a=e.end.getTime()+i,n=t.start.getTime(),o=t.end.getTime();return!(a<=n||o<=r)}_createTimeConflict(e,t){const s=new Date(Math.max(e.start.getTime(),t.start.getTime())),i=new Date(Math.min(e.end.getTime(),t.end.getTime())),r=(i-s)/6e4;let a="low";return r>=60?a="high":r>=30&&(a="medium"),e.status==="confirmed"&&t.status==="confirmed"&&(a=a==="low"?"medium":a==="medium"?"high":"critical"),{id:`conflict_${++this.conflictIdCounter}`,type:"time",severity:a,eventId:e.id,conflictingEventId:t.id,description:`Time overlap: ${e.title} conflicts with ${t.title}`,overlapStart:s,overlapEnd:i,overlapMinutes:r,metadata:{event1Title:e.title,event2Title:t.title,event1Status:e.status,event2Status:t.status}}}_checkAttendeeConflicts(e,t){const s=[];if(!e.attendees||!t.attendees)return s;const i=[];for(const r of e.attendees)for(const a of t.attendees)r.email===a.email&&i.push(r.email);if(i.length>0){let r="medium";i.some(n=>{const o=e.attendees.find(l=>l.email===n),c=t.attendees.find(l=>l.email===n);return(o==null?void 0:o.responseStatus)==="accepted"&&(c==null?void 0:c.responseStatus)==="accepted"})&&(r="critical"),s.push({id:`conflict_${++this.conflictIdCounter}`,type:"attendee",severity:r,eventId:e.id,conflictingEventId:t.id,description:`Attendee conflict: ${i.length} attendee(s) double-booked`,conflictingAttendees:i,metadata:{attendeeCount:i.length,attendeeEmails:i}})}return s}_checkResourceConflicts(e,t){var a,n;const s=[],i=((a=e.attendees)==null?void 0:a.filter(o=>o.resource))||[],r=((n=t.attendees)==null?void 0:n.filter(o=>o.resource))||[];for(const o of i)for(const c of r)o.email===c.email&&s.push({id:`conflict_${++this.conflictIdCounter}`,type:"resource",severity:"critical",eventId:e.id,conflictingEventId:t.id,description:`Resource conflict: ${o.name} is double-booked`,conflictingResource:o.email,metadata:{resourceName:o.name,resourceEmail:o.email}});return s}_checkLocationConflict(e,t){if(!e.location||!t.location)return null;const s=e.location.trim().toLowerCase(),i=t.location.trim().toLowerCase();return s===i?{id:`conflict_${++this.conflictIdCounter}`,type:"location",severity:"high",eventId:e.id,conflictingEventId:t.id,description:`Location conflict: ${e.location} is double-booked`,metadata:{location:e.location}}:null}_buildConflictSummary(e,t,s){const i={},r={};for(const a of e)i[a.type]=(i[a.type]||0)+1,r[a.severity]=(r[a.severity]||0)+1;return{hasConflicts:e.length>0,totalConflicts:e.length,conflicts:e,conflictsByType:i,conflictsBySeverity:r,affectedEventIds:Array.from(t),affectedAttendees:Array.from(s)}}_mergeBusyPeriods(e){if(e.length<=1)return e;e.sort((s,i)=>s.start-i.start);const t=[e[0]];for(let s=1;s<e.length;s++){const i=e[s],r=t[t.length-1];i.start<=r.end?(r.end=new Date(Math.max(r.end.getTime(),i.end.getTime())),r.eventIds.push(...i.eventIds)):t.push(i)}return t}_getAllBusyPeriods(e,t){return this.eventStore.getEventsInRange(e,t,!1).filter(i=>i.status!=="cancelled").map(i=>({start:i.start,end:i.end,eventIds:[i.id]})).sort((i,r)=>i.start-r.start)}_isWithinBusinessHours(e,t,s){const i=e.getHours(),r=t.getHours(),a=parseInt(s.businessHours.start.split(":")[0]),n=parseInt(s.businessHours.end.split(":")[0]);return i>=a&&r<=n}}class N{constructor(e={}){this.events=new Map,this.indices={byDate:new Map,byMonth:new Map,recurring:new Set,byCategory:new Map,byStatus:new Map},this.timezoneManager=new $,this.defaultTimezone=e.timezone||this.timezoneManager.getSystemTimezone(),this.optimizer=new V(e.performance),this.conflictDetector=new Y(this),this.isBatchMode=!1,this.batchNotifications=[],this.batchBackup=null,this.version=0,this.listeners=new Set}addEvent(e){return this.optimizer.measure("addEvent",()=>{if(e instanceof C||(e=new C(e)),this.events.has(e.id))throw new Error(`Event with id ${e.id} already exists`);return this.events.set(e.id,e),this.optimizer.cache(e.id,e,"event"),this._indexEvent(e),this.isBatchMode?this.batchNotifications.push({type:"add",event:e,version:++this.version}):this._notifyChange({type:"add",event:e,version:++this.version}),e})}updateEvent(e,t){const s=this.events.get(e);if(!s)throw new Error(`Event with id ${e} not found`);this._unindexEvent(s);const i=s.clone(t);return this.events.set(e,i),this._indexEvent(i),this._notifyChange({type:"update",event:i,oldEvent:s,version:++this.version}),i}removeEvent(e){const t=this.events.get(e);return t?(this.events.delete(e),this._unindexEvent(t),this._notifyChange({type:"remove",event:t,version:++this.version}),!0):!1}getEvent(e){const t=this.optimizer.getFromCache(e,"event");if(t)return t;const s=this.events.get(e)||null;return s&&this.optimizer.cache(e,s,"event"),s}getAllEvents(){return Array.from(this.events.values())}queryEvents(e={}){let t=Array.from(this.events.values());if(e.start||e.end){const s=e.start?new Date(e.start):null,i=e.end?new Date(e.end):null;t=t.filter(r=>!(s&&r.end<s||i&&r.start>i))}if(e.date){const s=new Date(e.date);t=t.filter(i=>i.occursOn(s))}if(e.month&&e.year){const s=`${e.year}-${String(e.month).padStart(2,"0")}`,i=this.indices.byMonth.get(s)||new Set;t=t.filter(r=>i.has(r.id))}return e.hasOwnProperty("allDay")&&(t=t.filter(s=>s.allDay===e.allDay)),e.hasOwnProperty("recurring")&&(t=t.filter(s=>s.recurring===e.recurring)),e.status&&(t=t.filter(s=>s.status===e.status)),e.categories&&e.categories.length>0&&(t=t.filter(s=>e.matchAllCategories?s.hasAllCategories(e.categories):s.hasAnyCategory(e.categories))),e.hasOwnProperty("hasAttendees")&&(t=t.filter(s=>e.hasAttendees?s.hasAttendees:!s.hasAttendees)),e.organizerEmail&&(t=t.filter(s=>s.organizer&&s.organizer.email===e.organizerEmail)),e.sort&&t.sort((s,i)=>{switch(e.sort){case"start":return s.start-i.start;case"end":return s.end-i.end;case"duration":return s.duration-i.duration;case"title":return s.title.localeCompare(i.title);default:return 0}}),t}getEventsForDate(e,t=null){t=t||this.defaultTimezone,u.getLocalDateString(e);const s=new Set,i=new Date(e);for(let l=-1;l<=1;l++){const d=new Date(i);d.setDate(d.getDate()+l);const h=u.getLocalDateString(d),g=this.indices.byDate.get(h);g&&g.forEach(b=>s.add(b))}const r=`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}`,a=this.indices.byMonth.get(r);a&&a.forEach(l=>s.add(l));const n=[],o=new Date(e);o.setHours(0,0,0,0);const c=new Date(e);c.setHours(23,59,59,999);for(const l of s){const d=this.events.get(l);if(d){const h=d.getStartInTimezone(t),g=d.getEndInTimezone(t);h<=c&&g>=o&&n.push(d)}}return n.sort((l,d)=>{const h=l.getStartInTimezone(t),g=d.getStartInTimezone(t),b=h-g;return b!==0?b:d.duration-l.duration})}getOverlappingEvents(e,t,s=null){const i=[],r=u.startOfDay(e),a=u.endOfDay(t),n=u.getDateRange(r,a),o=new Set;return n.forEach(c=>{const l=c.toDateString();(this.indices.byDate.get(l)||new Set).forEach(h=>{if(!o.has(h)&&h!==s){o.add(h);const g=this.events.get(h);g&&g.overlaps({start:e,end:t})&&i.push(g)}})}),i.sort((c,l)=>c.start-l.start)}hasConflicts(e,t,s=null){return this.getOverlappingEvents(e,t,s).length>0}getOverlapGroups(e,t=!0){let s=this.getEventsForDate(e);t&&(s=s.filter(a=>!a.allDay));const i=[],r=new Set;return s.forEach(a=>{if(r.has(a.id))return;const n=[a];r.add(a.id);let o=0;for(;o<n.length;){const c=n[o];s.forEach(l=>{!r.has(l.id)&&c.overlaps(l)&&(n.push(l),r.add(l.id))}),o++}i.push(n)}),i}calculateEventPositions(e){const t=new Map;if(e.length===0)return t;e.sort((r,a)=>{const n=r.start-a.start;return n!==0?n:a.end-a.start-(r.end-r.start)});const s=[];e.forEach(r=>{let a=0;for(;a<s.length&&s[a].some(c=>c.overlaps(r));)a++;s[a]||(s[a]=[]),s[a].push(r),t.set(r.id,{column:a,totalColumns:0})});const i=s.length;return t.forEach(r=>{r.totalColumns=i}),t}getEventsInRange(e,t,s=!0,i=null){typeof s=="string"&&(i=s,s=!0),i=i||this.defaultTimezone;const r=this.timezoneManager.toUTC(e,i),a=this.timezoneManager.toUTC(t,i),n=this.queryEvents({start:r,end:a,sort:"start"});if(!s)return n;const o=[];return n.forEach(c=>{if(c.recurring&&c.recurrenceRule){const l=this.expandRecurringEvent(c,e,t,i);o.push(...l)}else o.push(c)}),o.sort((c,l)=>{const d=c.getStartInTimezone(i),h=l.getStartInTimezone(i);return d-h})}expandRecurringEvent(e,t,s,i=null){if(!e.recurring||!e.recurrenceRule)return[e];i=i||this.defaultTimezone;const r=e.timeZone||i;return U.expandEvent(e,t,s).map((n,o)=>e.clone({id:`${e.id}_occurrence_${o}`,start:n.start,end:n.end,timeZone:r,metadata:{...e.metadata,recurringEventId:e.id,occurrenceIndex:o}}))}clear(){const e=this.getAllEvents();this.events.clear(),this.indices.byDate.clear(),this.indices.byMonth.clear(),this.indices.recurring.clear(),this._notifyChange({type:"clear",oldEvents:e,version:++this.version})}loadEvents(e){this.clear();for(const t of e)this.addEvent(t)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}_indexEvent(e){if(this.optimizer.shouldUseLazyIndexing(e)){this._indexEventLazy(e);return}const t=e.getStartInTimezone(e.timeZone),s=e.getEndInTimezone(e.endTimeZone||e.timeZone),i=u.startOfDay(t),r=u.endOfDay(s);u.getDateRange(i,r).forEach(o=>{const c=u.getLocalDateString(o);this.indices.byDate.has(c)||this.indices.byDate.set(c,new Set),this.indices.byDate.get(c).add(e.id)}),`${i.getFullYear()}${String(i.getMonth()+1).padStart(2,"0")}`,`${r.getFullYear()}${String(r.getMonth()+1).padStart(2,"0")}`;const n=new Date(i.getFullYear(),i.getMonth(),1);for(;n<=r;){const o=`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}`;this.indices.byMonth.has(o)||this.indices.byMonth.set(o,new Set),this.indices.byMonth.get(o).add(e.id),n.setMonth(n.getMonth()+1)}e.categories&&e.categories.length>0&&e.categories.forEach(o=>{this.indices.byCategory.has(o)||this.indices.byCategory.set(o,new Set),this.indices.byCategory.get(o).add(e.id)}),e.status&&(this.indices.byStatus.has(e.status)||this.indices.byStatus.set(e.status,new Set),this.indices.byStatus.get(e.status).add(e.id)),e.recurring&&this.indices.recurring.add(e.id)}_indexEventLazy(e){this.optimizer.createLazyIndexMarkers(e);const t=e.getStartInTimezone(e.timeZone),s=e.getEndInTimezone(e.endTimeZone||e.timeZone),i=u.startOfDay(t),r=u.endOfDay(s),a=new Date(i);if(a.setDate(a.getDate()+7),u.getDateRange(i,a<r?a:r).forEach(c=>{const l=u.getLocalDateString(c);this.indices.byDate.has(l)||this.indices.byDate.set(l,new Set),this.indices.byDate.get(l).add(e.id)}),r>a){const c=new Date(r);c.setDate(c.getDate()-7),u.getDateRange(c>i?c:i,r).forEach(d=>{const h=u.getLocalDateString(d);this.indices.byDate.has(h)||this.indices.byDate.set(h,new Set),this.indices.byDate.get(h).add(e.id)})}const o=new Date(i.getFullYear(),i.getMonth(),1);for(;o<=r;){const c=`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}`;this.indices.byMonth.has(c)||this.indices.byMonth.set(c,new Set),this.indices.byMonth.get(c).add(e.id),o.setMonth(o.getMonth()+1)}e.categories&&e.categories.length>0&&e.categories.forEach(c=>{this.indices.byCategory.has(c)||this.indices.byCategory.set(c,new Set),this.indices.byCategory.get(c).add(e.id)}),e.status&&(this.indices.byStatus.has(e.status)||this.indices.byStatus.set(e.status,new Set),this.indices.byStatus.get(e.status).add(e.id)),e.recurring&&this.indices.recurring.add(e.id)}_unindexEvent(e){for(const[t,s]of this.indices.byDate)s.delete(e.id),s.size===0&&this.indices.byDate.delete(t);for(const[t,s]of this.indices.byMonth)s.delete(e.id),s.size===0&&this.indices.byMonth.delete(t);this.indices.recurring.delete(e.id)}_notifyChange(e){for(const t of this.listeners)try{t(e)}catch(s){console.error("Error in EventStore listener:",s)}}getStats(){return{totalEvents:this.events.size,recurringEvents:this.indices.recurring.size,indexedDates:this.indices.byDate.size,indexedMonths:this.indices.byMonth.size,indexedCategories:this.indices.byCategory.size,indexedStatuses:this.indices.byStatus.size,version:this.version,performanceMetrics:this.optimizer.getMetrics()}}startBatch(e=!1){this.isBatchMode=!0,this.batchNotifications=[],e&&(this.batchBackup={events:new Map(this.events),indices:{byDate:new Map(Array.from(this.indices.byDate.entries()).map(([t,s])=>[t,new Set(s)])),byMonth:new Map(Array.from(this.indices.byMonth.entries()).map(([t,s])=>[t,new Set(s)])),recurring:new Set(this.indices.recurring),byCategory:new Map(Array.from(this.indices.byCategory.entries()).map(([t,s])=>[t,new Set(s)])),byStatus:new Map(Array.from(this.indices.byStatus.entries()).map(([t,s])=>[t,new Set(s)]))},version:this.version})}commitBatch(){this.isBatchMode&&(this.isBatchMode=!1,this.batchBackup=null,this.batchNotifications.length>0&&this._notifyChange({type:"batch",changes:this.batchNotifications,count:this.batchNotifications.length,version:++this.version}),this.batchNotifications=[])}rollbackBatch(){this.isBatchMode&&(this.isBatchMode=!1,this.batchBackup&&(this.events=this.batchBackup.events,this.indices=this.batchBackup.indices,this.version=this.batchBackup.version,this.batchBackup=null,this.optimizer.clearCache()),this.batchNotifications=[])}async executeBatch(e,t=!0){this.startBatch(t);try{const s=await e();return this.commitBatch(),s}catch(s){throw t&&this.rollbackBatch(),s}}addEvents(e){return this.optimizer.measure("addEvents",()=>{this.startBatch();const t=[],s=[];for(const i of e)try{t.push(this.addEvent(i))}catch(r){s.push({event:i,error:r.message})}return this.commitBatch(),s.length>0&&console.warn(`Failed to add ${s.length} events:`,s),t})}updateEvents(e){return this.optimizer.measure("updateEvents",()=>{this.startBatch();const t=[],s=[];for(const{id:i,updates:r}of e)try{t.push(this.updateEvent(i,r))}catch(a){s.push({id:i,error:a.message})}return this.commitBatch(),s.length>0&&console.warn(`Failed to update ${s.length} events:`,s),t})}removeEvents(e){return this.optimizer.measure("removeEvents",()=>{this.startBatch();let t=0;for(const s of e)this.removeEvent(s)&&t++;return this.commitBatch(),t})}getPerformanceMetrics(){return this.optimizer.getMetrics()}clearCaches(){this.optimizer.eventCache.clear(),this.optimizer.queryCache.clear(),this.optimizer.dateRangeCache.clear()}optimizeIndices(e){e||(e=new Date,e.setMonth(e.getMonth()-6)),e.toDateString();let t=0;for(const[s,i]of this.indices.byDate)if(new Date(s)<e){let a=!1;for(const n of i){const o=this.events.get(n);if(o&&o.end>=e){a=!0;break}}a||(this.indices.byDate.delete(s),t++)}return console.log(`Optimized indices: removed ${t} old date entries`),t}destroy(){this.clear(),this.optimizer.destroy(),this.listeners.clear()}checkConflicts(e,t={}){return this.conflictDetector.checkConflicts(e,t)}checkEventPairConflicts(e,t,s={}){const i=this.getEvent(e),r=this.getEvent(t);if(!i||!r)throw new Error("One or both events not found");return this.conflictDetector.checkEventPairConflicts(i,r,s)}getAllConflicts(e,t,s={}){const i=this.getEventsInRange(e,t,!1),r=[],a=new Set;for(let n=0;n<i.length;n++)for(let o=n+1;o<i.length;o++){const c=`${i[n].id}-${i[o].id}`;if(!a.has(c)){a.add(c);const l=this.conflictDetector.checkEventPairConflicts(i[n],i[o],s);r.push(...l)}}return this.conflictDetector._buildConflictSummary(r,new Set(i.map(n=>n.id)),new Set)}getBusyPeriods(e,t,s,i={}){return this.conflictDetector.getBusyPeriods(e,t,s,i)}getFreePeriods(e,t,s,i={}){return this.conflictDetector.getFreePeriods(e,t,s,i)}addEventWithConflictCheck(e,t=!0){const s=this.checkConflicts(e);if(!t&&s.hasConflicts)throw new Error(`Cannot add event: ${s.totalConflicts} conflicts detected`);return{event:this.addEvent(e),conflicts:s}}findEventsWithConflicts(e={}){const t=[],s=this.getAllEvents();for(const i of s){const r=this.checkConflicts(i,e);r.hasConflicts&&t.push({event:i,conflicts:r.conflicts})}return t}}let j=class{constructor(e={}){this.state={view:"month",currentDate:new Date,selectedEventId:null,selectedDate:null,hoveredEventId:null,hoveredDate:null,weekStartsOn:0,showWeekNumbers:!1,showWeekends:!0,fixedWeekCount:!0,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,locale:"en-US",hourFormat:"12h",businessHours:{start:"09:00",end:"17:00"},filters:{searchTerm:"",categories:[],showAllDay:!0,showTimed:!0},isDragging:!1,isResizing:!1,isCreating:!1,isLoading:!1,loadingMessage:"",error:null,metadata:{},...e},this.listeners=new Map,this.globalListeners=new Set,this.history=[],this.historyIndex=-1,this.maxHistorySize=50}getState(){return Object.freeze({...this.state})}get(e){return this.state[e]}setState(e){const t=this.state;typeof e=="function"&&(e=e(t));const s={...t,...e,filters:e.filters?{...t.filters,...e.filters}:t.filters,businessHours:e.businessHours?{...t.businessHours,...e.businessHours}:t.businessHours,metadata:e.metadata?{...t.metadata,...e.metadata}:t.metadata};this._hasChanged(t,s)&&(this.state=s,this._addToHistory(s),this._notifyListeners(t,s))}setView(e){const t=["month","week","day","list"];if(!t.includes(e))throw new Error(`Invalid view: ${e}. Must be one of: ${t.join(", ")}`);this.setState({view:e})}setCurrentDate(e){if(e instanceof Date||(e=new Date(e)),isNaN(e.getTime()))throw new Error("Invalid date");this.setState({currentDate:e})}navigateNext(){const{view:e,currentDate:t}=this.state,s=new Date(t);switch(e){case"month":s.setMonth(s.getMonth()+1);break;case"week":s.setDate(s.getDate()+7);break;case"day":s.setDate(s.getDate()+1);break}this.setCurrentDate(s)}navigatePrevious(){const{view:e,currentDate:t}=this.state,s=new Date(t);switch(e){case"month":s.setMonth(s.getMonth()-1);break;case"week":s.setDate(s.getDate()-7);break;case"day":s.setDate(s.getDate()-1);break}this.setCurrentDate(s)}navigateToday(){this.setCurrentDate(new Date)}selectEvent(e){this.setState({selectedEventId:e})}clearEventSelection(){this.setState({selectedEventId:null})}selectDate(e){e instanceof Date||(e=new Date(e)),this.setState({selectedDate:e})}clearDateSelection(){this.setState({selectedDate:null})}setLoading(e,t=""){this.setState({isLoading:e,loadingMessage:t})}setError(e){this.setState({error:e?e instanceof Error?e.message:e:null})}updateFilters(e){this.setState({filters:{...this.state.filters,...e}})}subscribe(e){return this.globalListeners.add(e),()=>{this.globalListeners.delete(e)}}watch(e,t){const s=Array.isArray(e)?e:[e];return s.forEach(i=>{this.listeners.has(i)||this.listeners.set(i,new Set),this.listeners.get(i).add(t)}),()=>{s.forEach(i=>{const r=this.listeners.get(i);r&&(r.delete(t),r.size===0&&this.listeners.delete(i))})}}canUndo(){return this.historyIndex>0}canRedo(){return this.historyIndex<this.history.length-1}getUndoCount(){return this.historyIndex}getRedoCount(){return this.history.length-1-this.historyIndex}undo(){if(!this.canUndo())return!1;this.historyIndex--;const e=this.history[this.historyIndex],t=this.state;return this.state={...e},this._notifyListeners(t,this.state),!0}redo(){if(!this.canRedo())return!1;this.historyIndex++;const e=this.history[this.historyIndex],t=this.state;return this.state={...e},this._notifyListeners(t,this.state),!0}reset(){const e=this.history[0]||{};this.setState(e),this.history=[e],this.historyIndex=0}_hasChanged(e,t){return!this._deepEqual(e,t)}_deepEqual(e,t,s=new Set){if(e===t)return!0;if(e==null||t==null)return e===t;if(typeof e!=typeof t)return!1;if(typeof e!="object")return e===t;if(s.has(e)||s.has(t))return!1;if(s.add(e),s.add(t),Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return s.delete(e),s.delete(t),!1;for(let a=0;a<e.length;a++)if(!this._deepEqual(e[a],t[a],s))return s.delete(e),s.delete(t),!1;return s.delete(e),s.delete(t),!0}if(e instanceof Date&&t instanceof Date){const a=e.getTime()===t.getTime();return s.delete(e),s.delete(t),a}const i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return s.delete(e),s.delete(t),!1;i.sort(),r.sort();for(let a=0;a<i.length;a++)if(i[a]!==r[a])return s.delete(e),s.delete(t),!1;for(const a of i)if(!this._deepEqual(e[a],t[a],s))return s.delete(e),s.delete(t),!1;return s.delete(e),s.delete(t),!0}_addToHistory(e){this.historyIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyIndex+1)),this.history.push({...e}),this.historyIndex++,this.history.length>this.maxHistorySize&&(this.history.shift(),this.historyIndex--)}_notifyListeners(e,t){for(const s of this.globalListeners)try{s(t,e)}catch(i){console.error("Error in state listener:",i)}for(const[s,i]of this.listeners)if(e[s]!==t[s])for(const r of i)try{r(t[s],e[s],t,e)}catch(a){console.error(`Error in state listener for key "${s}":`,a)}}};class W{constructor(e={}){this.timezoneManager=new $,this.config={view:"month",date:new Date,weekStartsOn:0,locale:"en-US",timeZone:e.timeZone||this.timezoneManager.getSystemTimezone(),showWeekNumbers:!1,showWeekends:!0,fixedWeekCount:!0,businessHours:{start:"09:00",end:"17:00"},...e},this.eventStore=new N({timezone:this.config.timeZone}),this.state=new j({view:this.config.view,currentDate:this.config.date,weekStartsOn:this.config.weekStartsOn,locale:this.config.locale,timeZone:this.config.timeZone,showWeekNumbers:this.config.showWeekNumbers,showWeekends:this.config.showWeekends,fixedWeekCount:this.config.fixedWeekCount,businessHours:this.config.businessHours}),this.listeners=new Map,this.plugins=new Set,this.views=new Map,this._setupInternalListeners(),e.events&&this.setEvents(e.events)}setView(e,t=null){this.state.setView(e),t&&this.state.setCurrentDate(t),this._emit("viewChange",{view:e,date:t||this.state.get("currentDate")})}getView(){return this.state.get("view")}next(){this.state.navigateNext(),this._emit("navigate",{direction:"next",date:this.state.get("currentDate"),view:this.state.get("view")})}previous(){this.state.navigatePrevious(),this._emit("navigate",{direction:"previous",date:this.state.get("currentDate"),view:this.state.get("view")})}today(){this.state.navigateToday(),this._emit("navigate",{direction:"today",date:this.state.get("currentDate"),view:this.state.get("view")})}goToDate(e){this.state.setCurrentDate(e),this._emit("navigate",{direction:"goto",date:e,view:this.state.get("view")})}setDate(e){this.goToDate(e)}getCurrentDate(){return new Date(this.state.get("currentDate"))}addEvent(e){!(e instanceof C)&&!e.timeZone&&(e={...e,timeZone:this.config.timeZone});const t=this.eventStore.addEvent(e);return this._emit("eventAdd",{event:t}),t}updateEvent(e,t){const s=this.eventStore.getEvent(e),i=this.eventStore.updateEvent(e,t);return this._emit("eventUpdate",{event:i,oldEvent:s}),i}removeEvent(e){const t=this.eventStore.getEvent(e),s=this.eventStore.removeEvent(e);return s&&this._emit("eventRemove",{event:t}),s}deleteEvent(e){return this.removeEvent(e)}getEvent(e){return this.eventStore.getEvent(e)}getEvents(){return this.eventStore.getAllEvents()}setEvents(e){this.eventStore.loadEvents(e),this._emit("eventsSet",{events:this.getEvents()})}queryEvents(e){return this.eventStore.queryEvents(e)}getEventsForDate(e,t=null){return this.eventStore.getEventsForDate(e,t||this.config.timeZone)}getEventsInRange(e,t,s=null){return this.eventStore.getEventsInRange(e,t,!0,s||this.config.timeZone)}setTimezone(e){const t=this.timezoneManager.parseTimezone(e),s=this.config.timeZone;this.config.timeZone=t,this.eventStore.defaultTimezone=t,this.state.setState({timeZone:t}),this._emit("timezoneChange",{timezone:t,previousTimezone:s})}getTimezone(){return this.config.timeZone}setLocale(e){this.config.locale=e,this.state.setState({locale:e}),this._emit("localeChange",{locale:e})}setWeekStartsOn(e){this.config.weekStartsOn=e,this.state.setState({weekStartsOn:e}),this._emit("weekStartsOnChange",{weekStartsOn:e})}convertTimezone(e,t,s){return this.timezoneManager.convertTimezone(e,t,s)}toCalendarTimezone(e,t){return this.timezoneManager.convertTimezone(e,t,this.config.timeZone)}fromCalendarTimezone(e,t){return this.timezoneManager.convertTimezone(e,this.config.timeZone,t)}formatInTimezone(e,t=null,s={}){return this.timezoneManager.formatInTimezone(e,t||this.config.timeZone,s)}getTimezones(){return this.timezoneManager.getCommonTimezones()}getOverlapGroups(e,t=!0){return this.eventStore.getOverlapGroups(e,t)}calculateEventPositions(e){return this.eventStore.calculateEventPositions(e)}getViewData(){const e=this.state.get("view"),t=this.state.get("currentDate");switch(e){case"month":return this._getMonthViewData(t);case"week":return this._getWeekViewData(t);case"day":return this._getDayViewData(t);case"list":return this._getListViewData(t);default:return null}}_getMonthViewData(e){const t=e.getFullYear(),s=e.getMonth(),i=this.state.get("weekStartsOn"),r=this.state.get("fixedWeekCount"),a=new Date(t,s,1),n=new Date(t,s+1,0),o=u.startOfWeek(a,i),c=[];let l=new Date(o);const d=r?6:Math.ceil((n.getDate()+u.getDayOfWeek(a,i))/7);for(let h=0;h<d;h++){const g={weekNumber:u.getWeekNumber(l),days:[]};for(let b=0;b<7;b++){const f=new Date(l),T=f.getMonth()===s,D=u.isToday(f),S=f.getDay()===0||f.getDay()===6;g.days.push({date:f,dayOfMonth:f.getDate(),isCurrentMonth:T,isToday:D,isWeekend:S,events:this.getEventsForDate(f)}),l=u.addDays(l,1)}c.push(g)}return{type:"month",year:t,month:s,monthName:u.getMonthName(e,this.state.get("locale")),weeks:c,startDate:o,endDate:new Date(l.getTime()-1)}}_getWeekViewData(e){const t=this.state.get("weekStartsOn"),s=u.startOfWeek(e,t),i=u.endOfWeek(e,t),r=[],a=new Date(s);for(let n=0;n<7;n++){const o=new Date(a);r.push({date:o,dayOfMonth:o.getDate(),dayOfWeek:o.getDay(),dayName:u.getDayName(o,this.state.get("locale")),isToday:u.isToday(o),isWeekend:o.getDay()===0||o.getDay()===6,events:this.getEventsForDate(o),overlapGroups:this.eventStore.getOverlapGroups(o,!0),getEventPositions:c=>this.eventStore.calculateEventPositions(c)}),a.setDate(a.getDate()+1)}return{type:"week",weekNumber:u.getWeekNumber(s),startDate:s,endDate:i,days:r}}_getDayViewData(e){const t=this.getEventsForDate(e),s=t.filter(a=>a.allDay),i=t.filter(a=>!a.allDay),r=[];for(let a=0;a<24;a++){const n=new Date(e);n.setHours(a,0,0,0);const o=new Date(e);o.setHours(a+1,0,0,0),r.push({hour:a,time:u.formatTime(n,this.state.get("locale")),events:i.filter(c=>c.start<o&&c.end>n)})}return{type:"day",date:e,dayName:u.getDayName(e,this.state.get("locale")),isToday:u.isToday(e),allDayEvents:s,hours:r}}_getListViewData(e){const t=new Date(e);t.setHours(0,0,0,0);const s=new Date(t);s.setDate(s.getDate()+30);const i=this.getEventsInRange(t,s),r=new Map;i.forEach(n=>{const o=n.start.toDateString();r.has(o)||r.set(o,{date:new Date(n.start),events:[]}),r.get(o).events.push(n)});const a=Array.from(r.values()).sort((n,o)=>n.date-o.date).map(n=>({...n,dayName:u.getDayName(n.date,this.state.get("locale")),isToday:u.isToday(n.date)}));return{type:"list",startDate:t,endDate:s,days:a,totalEvents:i.length}}selectEvent(e){const t=this.getEvent(e);t&&(this.state.selectEvent(e),this._emit("eventSelect",{event:t}))}clearEventSelection(){const e=this.state.get("selectedEventId");this.state.clearEventSelection(),e&&this._emit("eventDeselect",{eventId:e})}selectDate(e){this.state.selectDate(e),this._emit("dateSelect",{date:e})}clearDateSelection(){const e=this.state.get("selectedDate");this.state.clearDateSelection(),e&&this._emit("dateDeselect",{date:e})}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){const s=this.listeners.get(e);s&&(s.delete(t),s.size===0&&this.listeners.delete(e))}_emit(e,t){const s=this.listeners.get(e);s&&s.forEach(i=>{try{i(t)}catch(r){console.error(`Error in event listener for "${e}":`,r)}})}_setupInternalListeners(){this.state.subscribe((e,t)=>{this._emit("stateChange",{newState:e,oldState:t})}),this.eventStore.subscribe(e=>{this._emit("eventStoreChange",e)})}use(e){if(this.plugins.has(e)){console.warn("Plugin already installed");return}if(typeof e.install=="function")e.install(this),this.plugins.add(e);else throw new Error("Plugin must have an install method")}destroy(){this.listeners.clear(),this.eventStore.clear(),this.plugins.forEach(e=>{typeof e.uninstall=="function"&&e.uninstall(this)}),this.plugins.clear(),this._emit("destroy")}}class _{constructor(){this.events=new Map,this.wildcardHandlers=new Set}on(e,t,s={}){const{once:i=!1,priority:r=0}=s;if(e.includes("*")){const o={pattern:e,handler:t,once:i,priority:r};return this.wildcardHandlers.add(o),()=>this.wildcardHandlers.delete(o)}this.events.has(e)||this.events.set(e,[]);const a={handler:t,once:i,priority:r},n=this.events.get(e);return n.push(a),n.sort((o,c)=>c.priority-o.priority),()=>{const o=n.indexOf(a);o>-1&&n.splice(o,1)}}once(e,t,s={}){return this.on(e,t,{...s,once:!0})}off(e,t){if(!this.events.has(e))return;const s=this.events.get(e),i=s.findIndex(r=>r.handler===t);i>-1&&s.splice(i,1),s.length===0&&this.events.delete(e)}async emit(e,t){const s=[];if(this.events.has(e)){const r=[...this.events.get(e)];for(const a of r){const{handler:n,once:o}=a;o&&this.off(e,n);try{const c=n(t,e);c instanceof Promise&&s.push(c)}catch(c){console.error(`Error in event handler for ${e}:`,c)}}}const i=[];for(const r of[...this.wildcardHandlers])if(this.matchesPattern(e,r.pattern)){const{handler:a,once:n}=r;n&&i.push(r);try{const o=a(t,e);o instanceof Promise&&s.push(o)}catch(o){console.error(`Error in wildcard handler for ${e}:`,o)}}return i.forEach(r=>this.wildcardHandlers.delete(r)),Promise.all(s)}matchesPattern(e,t){return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)}clear(){this.events.clear(),this.wildcardHandlers.clear()}getEventNames(){return Array.from(this.events.keys())}getHandlerCount(e){return this.events.has(e)?this.events.get(e).length:0}}const p=new _;class L{constructor(e={}){this.calendar=new W({view:e.view||"month",date:e.date||new Date,weekStartsOn:e.weekStartsOn??0,locale:e.locale||"en-US",timeZone:e.timeZone||Intl.DateTimeFormat().resolvedOptions().timeZone,...e}),this.state={view:this.calendar.getView(),currentDate:this.calendar.getCurrentDate(),events:[],selectedEvent:null,selectedDate:null,loading:!1,error:null,config:{...e}},this.subscribers=new Set,this.subscribe=this.subscribe.bind(this),this.unsubscribe=this.unsubscribe.bind(this),this.setState=this.setState.bind(this)}getState(){return{...this.state}}setState(e,t={}){const{silent:s=!1}=t,i={...this.state};return this.state={...this.state,...e},s||(this.notifySubscribers(i,this.state),this.emitStateChange(i,this.state)),this.state}subscribe(e){return this.subscribers.add(e),()=>this.unsubscribe(e)}unsubscribe(e){this.subscribers.delete(e)}notifySubscribers(e,t){this.subscribers.forEach(s=>{try{s(t,e)}catch(i){console.error("Error in state subscriber:",i)}})}emitStateChange(e,t){const s=Object.keys(t).filter(i=>e[i]!==t[i]);s.forEach(i=>{p.emit(`state:${i}:changed`,{oldValue:e[i],newValue:t[i],state:t})}),s.length>0&&p.emit("state:changed",{oldState:e,newState:t,changedKeys:s})}setView(e){this.calendar.setView(e),this.setState({view:e}),p.emit("view:changed",{view:e})}getView(){return this.state.view}setDate(e){this.calendar.goToDate(e),this.setState({currentDate:this.calendar.getCurrentDate()}),p.emit("date:changed",{date:this.state.currentDate})}getCurrentDate(){return this.state.currentDate}next(){this.calendar.next(),this.setState({currentDate:this.calendar.getCurrentDate()}),p.emit("navigation:next",{date:this.state.currentDate})}previous(){this.calendar.previous(),this.setState({currentDate:this.calendar.getCurrentDate()}),p.emit("navigation:previous",{date:this.state.currentDate})}today(){this.calendar.today(),this.setState({currentDate:this.calendar.getCurrentDate()}),p.emit("navigation:today",{date:this.state.currentDate})}goToDate(e){this.calendar.goToDate(e),this.setState({currentDate:this.calendar.getCurrentDate()}),p.emit("navigation:goto",{date:this.state.currentDate})}addEvent(e){const t=this.calendar.addEvent(e);if(!t)return console.error("Failed to add event to calendar"),p.emit("event:error",{action:"add",event:e,error:"Failed to add event"}),null;const s=[...this.state.events,t];return this.setState({events:s}),p.emit("event:added",{event:t}),t}updateEvent(e,t){const s=this.calendar.updateEvent(e,t);if(!s)return console.error(`Failed to update event: ${e}`),p.emit("event:error",{action:"update",eventId:e,updates:t,error:"Event not found in calendar"}),null;const i=this.state.events.findIndex(a=>a.id===e);if(i===-1)return console.error(`Event ${e} not found in state`),p.emit("event:error",{action:"update",eventId:e,error:"Event not found in state"}),null;const r=[...this.state.events];return r[i]=s,this.setState({events:r}),p.emit("event:updated",{event:s}),s}deleteEvent(e){if(!this.calendar.removeEvent(e))return console.error(`Failed to delete event: ${e}`),p.emit("event:error",{action:"delete",eventId:e,error:"Event not found"}),!1;const s=this.state.events.filter(i=>i.id!==e);return this.setState({events:s}),p.emit("event:deleted",{eventId:e}),!0}getEvents(){return this.calendar.getEvents()}getEventsForDate(e){return this.calendar.getEventsForDate(e)}getEventsInRange(e,t){return this.calendar.getEventsInRange(e,t)}getViewData(){const e=this.calendar.getViewData();return this.enrichViewData(e)}enrichViewData(e){var s;const t=(s=this.state.selectedDate)==null?void 0:s.toDateString();if(e.weeks&&(e.weeks=e.weeks.map(i=>({...i,days:i.days.map(r=>{const a=new Date(r.date);return{...r,isSelected:a.toDateString()===t,events:r.events||this.getEventsForDate(a)}})}))),e.days&&(e.days=e.days.map(i=>{const r=new Date(i.date);return{...i,isSelected:r.toDateString()===t,events:i.events||this.getEventsForDate(r)}})),e.date&&!e.days&&!e.weeks){const i=new Date(e.date);e.isSelected=i.toDateString()===t,e.events=e.events||this.getEventsForDate(i)}return e}selectEvent(e){this.setState({selectedEvent:e}),p.emit("event:selected",{event:e})}selectEventById(e){const t=this.state.events.find(s=>s.id===e);t&&this.selectEvent(t)}deselectEvent(){this.setState({selectedEvent:null}),p.emit("event:deselected",{})}selectDate(e){this.setState({selectedDate:e}),p.emit("date:selected",{date:e})}deselectDate(){this.setState({selectedDate:null}),p.emit("date:deselected",{})}isToday(e){const t=new Date;return e.toDateString()===t.toDateString()}isSelectedDate(e){return this.state.selectedDate&&e.toDateString()===this.state.selectedDate.toDateString()}isWeekend(e){const t=e.getDay();return t===0||t===6}setLoading(e){this.setState({loading:e})}setError(e){this.setState({error:e}),e&&p.emit("error",{error:e})}clearError(){this.setState({error:null})}updateConfig(e){this.setState({config:{...this.state.config,...e}}),e.weekStartsOn!==void 0&&this.calendar.setWeekStartsOn(e.weekStartsOn),e.locale!==void 0&&this.calendar.setLocale(e.locale),e.timeZone!==void 0&&this.calendar.setTimezone(e.timeZone)}destroy(){this.subscribers.clear(),this.state=null,this.calendar=null}}class w extends u{static formatDate(e,t="default",s="en-US"){if(!e)return"";const i={default:{year:"numeric",month:"long",day:"numeric"},short:{year:"numeric",month:"short",day:"numeric"},long:{weekday:"long",year:"numeric",month:"long",day:"numeric"},month:{year:"numeric",month:"long"},monthShort:{year:"numeric",month:"short"},day:{weekday:"long",day:"numeric"},dayShort:{weekday:"short",day:"numeric"},time:{hour:"numeric",minute:"2-digit"},timeShort:{hour:"numeric"},datetime:{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}},r=i[t]||i.default;return new Intl.DateTimeFormat(s,r).format(e)}static formatTime(e,t=!0,s=!1,i="en-US"){if(!e)return"";const r={hour:"numeric",minute:t?"2-digit":void 0,hour12:!s};return new Intl.DateTimeFormat(i,r).format(e)}static formatDateRange(e,t,s="en-US"){if(!e)return"";if(!t||this.isSameDay(e,t))return this.formatDate(e,"default",s);const i=this.isSameYear(e,t)?"short":"default";return`${this.formatDate(e,i,s)} - ${this.formatDate(t,"default",s)}`}static formatTimeRange(e,t,s="en-US"){if(!e)return"";const i=this.formatTime(e,!0,!1,s);if(!t)return i;const r=this.formatTime(t,!0,!1,s);return`${i} - ${r}`}static getRelativeTime(e,t=new Date,s="en-US"){const i=new Intl.RelativeTimeFormat(s,{numeric:"auto"}),r=e-t,a=Math.floor(r/1e3),n=Math.floor(a/60),o=Math.floor(n/60),c=Math.floor(o/24),l=Math.floor(c/7),d=Math.floor(c/30),h=Math.floor(c/365);return Math.abs(a)<60?i.format(a,"second"):Math.abs(n)<60?i.format(n,"minute"):Math.abs(o)<24?i.format(o,"hour"):Math.abs(c)<7?i.format(c,"day"):Math.abs(l)<4?i.format(l,"week"):Math.abs(d)<12?i.format(d,"month"):i.format(h,"year")}static isToday(e){const t=new Date;return this.isSameDay(e,t)}static isPast(e){return e<new Date}static isFuture(e){return e>new Date}static getWeekNumber(e){const t=new Date(e.getFullYear(),0,1),s=(e-t)/864e5;return Math.ceil((s+t.getDay()+1)/7)}static getDayAbbreviation(e,t="en-US"){const s=new Date(2024,0,7+e);return new Intl.DateTimeFormat(t,{weekday:"short"}).format(s)}static getMonthName(e,t="long",s="en-US"){const i=new Date(2024,e,1);return new Intl.DateTimeFormat(s,{month:t}).format(i)}static parseTimeString(e,t=new Date){const s=new Date(t),[i,r]=e.split(/\s+/),[a,n]=i.split(":").map(Number);let o=a;return r&&(r.toLowerCase()==="pm"&&a<12?o=a+12:r.toLowerCase()==="am"&&a===12&&(o=0)),s.setHours(o,n||0,0,0),s}}class E{static createElement(e,t={},s=[]){const i=document.createElement(e);return Object.entries(t).forEach(([r,a])=>{if(r==="className")i.className=a;else if(r==="style"&&typeof a=="object")Object.assign(i.style,a);else if(r.startsWith("data-"))i.setAttribute(r,a);else if(r.startsWith("on")&&typeof a=="function"){const n=r.slice(2).toLowerCase();i.addEventListener(n,a)}else i[r]=a}),s.forEach(r=>{typeof r=="string"?i.appendChild(document.createTextNode(r)):r instanceof Node&&i.appendChild(r)}),i}static addEventListeners(e,t){return Object.entries(t).forEach(([s,i])=>{e.addEventListener(s,i)}),()=>{Object.entries(t).forEach(([s,i])=>{e.removeEventListener(s,i)})}}static delegate(e,t,s,i){const r=a=>{const n=a.target.closest(t);n&&e.contains(n)&&i.call(n,a)};return e.addEventListener(s,r),()=>e.removeEventListener(s,r)}static getPosition(e){const t=e.getBoundingClientRect();return{top:t.top+window.scrollY,left:t.left+window.scrollX,bottom:t.bottom+window.scrollY,right:t.right+window.scrollX,width:t.width,height:t.height}}static isInViewport(e,t=0){const s=e.getBoundingClientRect();return s.top>=-t&&s.left>=-t&&s.bottom<=(window.innerHeight||document.documentElement.clientHeight)+t&&s.right<=(window.innerWidth||document.documentElement.clientWidth)+t}static scrollToElement(e,t={}){const{behavior:s="smooth",block:i="start",inline:r="nearest"}=t;e.scrollIntoView({behavior:s,block:i,inline:r})}static getStyle(e,t){return window.getComputedStyle(e).getPropertyValue(t)}static setStyles(e,t){Object.assign(e.style,t)}static async animateClass(e,t,s=300){e.classList.add(t),await this.wait(s),e.classList.remove(t)}static waitForAnimation(e,t="animationend"){return new Promise(s=>{const i=()=>{e.removeEventListener(t,i),s()};e.addEventListener(t,i)})}static wait(e){return new Promise(t=>setTimeout(t,e))}static parseHTML(e){const t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}static escapeHTML(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}static debounce(e,t=250){let s;return function(...r){const a=()=>{clearTimeout(s),e(...r)};clearTimeout(s),s=setTimeout(a,t)}}static throttle(e,t=250){let s;return function(...i){s||(e.apply(this,i),s=!0,setTimeout(()=>s=!1,t))}}static closest(e,t){return e.closest(t)}static parents(e,t){const s=[];let i=e.parentElement;for(;i;)i.matches(t)&&s.push(i),i=i.parentElement;return s}static getOuterDimensions(e){const t=window.getComputedStyle(e),s={top:parseInt(t.marginTop),right:parseInt(t.marginRight),bottom:parseInt(t.marginBottom),left:parseInt(t.marginLeft)};return{width:e.offsetWidth+s.left+s.right,height:e.offsetHeight+s.top+s.bottom,margin:s}}static cloneWithEvents(e,t=!0){return e.cloneNode(t)}static trapFocus(e){const t=e.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(t.length===0)return e.setAttribute("tabindex","-1"),e.focus(),()=>e.removeAttribute("tabindex");const s=t[0],i=t[t.length-1],r=a=>{a.key==="Tab"&&(a.shiftKey?document.activeElement===s&&(i==null||i.focus(),a.preventDefault()):document.activeElement===i&&(s==null||s.focus(),a.preventDefault()))};return e.addEventListener("keydown",r),s==null||s.focus(),()=>e.removeEventListener("keydown",r)}}class y{static getCSSVariable(e,t=document.documentElement){return getComputedStyle(t).getPropertyValue(e).trim()}static setCSSVariables(e,t=document.documentElement){Object.entries(e).forEach(([s,i])=>{t.style.setProperty(s,i)})}static getBaseStyles(){return`
15
+ `,t=this.template();this.shadowRoot.innerHTML=e+t,this.afterRender()}template(){return""}afterRender(){}$(e){return this.shadowRoot.querySelector(e)}$$(e){return this.shadowRoot.querySelectorAll(e)}static get observedAttributes(){return[]}attributeChangedCallback(e,t,s){this.setProp(e,s),this._initialized&&this.render()}}class A{constructor(){this.timezones={UTC:{offset:0,dst:null},GMT:{offset:0,dst:null},"Africa/Abidjan":{offset:0,dst:null},"Africa/Accra":{offset:0,dst:null},"Africa/Addis_Ababa":{offset:180,dst:null},"Africa/Algiers":{offset:60,dst:null},"Africa/Cairo":{offset:120,dst:null},"Africa/Casablanca":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Africa/Johannesburg":{offset:120,dst:null},"Africa/Lagos":{offset:60,dst:null},"Africa/Nairobi":{offset:180,dst:null},"America/Anchorage":{offset:-540,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Argentina/Buenos_Aires":{offset:-180,dst:null},"America/Bogota":{offset:-300,dst:null},"America/Caracas":{offset:-240,dst:null},"America/Chicago":{offset:-360,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Denver":{offset:-420,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Detroit":{offset:-300,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Halifax":{offset:-240,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Los_Angeles":{offset:-480,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Mexico_City":{offset:-360,dst:{start:{month:4,week:1,day:0},end:{month:10,week:-1,day:0},offset:60}},"America/New_York":{offset:-300,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Phoenix":{offset:-420,dst:null},"America/Regina":{offset:-360,dst:null},"America/Santiago":{offset:-180,dst:{start:{month:9,week:1,day:0},end:{month:4,week:1,day:0},offset:60}},"America/Sao_Paulo":{offset:-180,dst:{start:{month:10,week:3,day:0},end:{month:2,week:3,day:0},offset:60}},"America/St_Johns":{offset:-210,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Toronto":{offset:-300,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"America/Vancouver":{offset:-480,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"Asia/Baghdad":{offset:180,dst:null},"Asia/Bangkok":{offset:420,dst:null},"Asia/Dubai":{offset:240,dst:null},"Asia/Hong_Kong":{offset:480,dst:null},"Asia/Jakarta":{offset:420,dst:null},"Asia/Jerusalem":{offset:120,dst:{start:{month:3,week:-1,day:5},end:{month:10,week:-1,day:0},offset:60}},"Asia/Karachi":{offset:300,dst:null},"Asia/Kolkata":{offset:330,dst:null},"Asia/Kuala_Lumpur":{offset:480,dst:null},"Asia/Manila":{offset:480,dst:null},"Asia/Seoul":{offset:540,dst:null},"Asia/Shanghai":{offset:480,dst:null},"Asia/Singapore":{offset:480,dst:null},"Asia/Taipei":{offset:480,dst:null},"Asia/Tehran":{offset:210,dst:{start:{month:3,week:4,day:0},end:{month:9,week:4,day:0},offset:60}},"Asia/Tokyo":{offset:540,dst:null},"Atlantic/Azores":{offset:-60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Atlantic/Bermuda":{offset:-240,dst:{start:{month:3,week:2,day:0},end:{month:11,week:1,day:0},offset:60}},"Atlantic/Reykjavik":{offset:0,dst:null},"Australia/Adelaide":{offset:570,dst:{start:{month:10,week:1,day:0},end:{month:4,week:1,day:0},offset:60}},"Australia/Brisbane":{offset:600,dst:null},"Australia/Darwin":{offset:570,dst:null},"Australia/Hobart":{offset:600,dst:{start:{month:10,week:1,day:0},end:{month:4,week:1,day:0},offset:60}},"Australia/Melbourne":{offset:600,dst:{start:{month:10,week:1,day:0},end:{month:4,week:1,day:0},offset:60}},"Australia/Perth":{offset:480,dst:null},"Australia/Sydney":{offset:600,dst:{start:{month:10,week:1,day:0},end:{month:4,week:1,day:0},offset:60}},"Europe/Amsterdam":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Athens":{offset:120,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Berlin":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Brussels":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Budapest":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Copenhagen":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Dublin":{offset:0,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Helsinki":{offset:120,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Istanbul":{offset:180,dst:null},"Europe/Kiev":{offset:120,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Lisbon":{offset:0,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/London":{offset:0,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Madrid":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Moscow":{offset:180,dst:null},"Europe/Oslo":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Paris":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Prague":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Rome":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Stockholm":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Vienna":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Warsaw":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Europe/Zurich":{offset:60,dst:{start:{month:3,week:-1,day:0},end:{month:10,week:-1,day:0},offset:60}},"Indian/Maldives":{offset:300,dst:null},"Indian/Mauritius":{offset:240,dst:null},"Pacific/Auckland":{offset:720,dst:{start:{month:9,week:-1,day:0},end:{month:4,week:1,day:0},offset:60}},"Pacific/Fiji":{offset:720,dst:{start:{month:11,week:1,day:0},end:{month:1,week:3,day:0},offset:60}},"Pacific/Guam":{offset:600,dst:null},"Pacific/Honolulu":{offset:-600,dst:null},"Pacific/Midway":{offset:-660,dst:null},"Pacific/Noumea":{offset:660,dst:null},"Pacific/Pago_Pago":{offset:-660,dst:null},"Pacific/Port_Moresby":{offset:600,dst:null},"Pacific/Tahiti":{offset:-600,dst:null}},this.aliases={EST:"America/New_York",EDT:"America/New_York",CST:"America/Chicago",CDT:"America/Chicago",MST:"America/Denver",MDT:"America/Denver",PST:"America/Los_Angeles",PDT:"America/Los_Angeles",AKST:"America/Anchorage",AKDT:"America/Anchorage",HST:"Pacific/Honolulu",AST:"America/Halifax",ADT:"America/Halifax",NST:"America/St_Johns",NDT:"America/St_Johns",BST:"Europe/London",IST:"Asia/Kolkata",WET:"Europe/Lisbon",WEST:"Europe/Lisbon",CET:"Europe/Paris",CEST:"Europe/Paris",EET:"Europe/Athens",EEST:"Europe/Athens",MSK:"Europe/Moscow",JST:"Asia/Tokyo",KST:"Asia/Seoul",CST_CN:"Asia/Shanghai",HKT:"Asia/Hong_Kong",SGT:"Asia/Singapore",AEST:"Australia/Sydney",AEDT:"Australia/Sydney",ACST:"Australia/Adelaide",ACDT:"Australia/Adelaide",AWST:"Australia/Perth",NZST:"Pacific/Auckland",NZDT:"Pacific/Auckland","US/Eastern":"America/New_York","US/Central":"America/Chicago","US/Mountain":"America/Denver","US/Pacific":"America/Los_Angeles","US/Alaska":"America/Anchorage","US/Hawaii":"Pacific/Honolulu","Canada/Eastern":"America/Toronto","Canada/Central":"America/Regina","Canada/Mountain":"America/Denver","Canada/Pacific":"America/Vancouver","Canada/Atlantic":"America/Halifax","Canada/Newfoundland":"America/St_Johns","Mexico/General":"America/Mexico_City","Brazil/East":"America/Sao_Paulo","Chile/Continental":"America/Santiago",GB:"Europe/London","GB-Eire":"Europe/London",Eire:"Europe/Dublin",Israel:"Asia/Jerusalem",Japan:"Asia/Tokyo",Singapore:"Asia/Singapore",Hongkong:"Asia/Hong_Kong",ROK:"Asia/Seoul",PRC:"Asia/Shanghai","Australia/NSW":"Australia/Sydney","Australia/Victoria":"Australia/Melbourne","Australia/Queensland":"Australia/Brisbane","Australia/South":"Australia/Adelaide","Australia/Tasmania":"Australia/Hobart","Australia/West":"Australia/Perth","Australia/North":"Australia/Darwin",NZ:"Pacific/Auckland"}}getTimezone(e){return this.aliases[e]&&(e=this.aliases[e]),this.timezones[e]||null}getAllTimezones(){return Object.keys(this.timezones)}isValidTimezone(e){return this.aliases[e]!==void 0||this.timezones[e]!==void 0}resolveAlias(e){return this.aliases[e]||e}getTimezonesByOffset(e){return Object.entries(this.timezones).filter(([t,s])=>s.offset===e).map(([t,s])=>t)}getCommonTimezones(){return{Americas:["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Toronto","America/Mexico_City","America/Sao_Paulo"],Europe:["Europe/London","Europe/Paris","Europe/Berlin","Europe/Moscow","Europe/Rome","Europe/Madrid","Europe/Amsterdam"],Asia:["Asia/Tokyo","Asia/Shanghai","Asia/Hong_Kong","Asia/Singapore","Asia/Kolkata","Asia/Dubai","Asia/Seoul"],"Australia/Pacific":["Australia/Sydney","Australia/Melbourne","Australia/Brisbane","Australia/Perth","Pacific/Auckland","Pacific/Honolulu"],Africa:["Africa/Cairo","Africa/Lagos","Africa/Johannesburg","Africa/Nairobi"]}}}let $=null;class I{static getInstance(){return $||($=new I),$}static _resetInstance(){$&&$.clearCache(),$=null}constructor(){this.database=new A,this.offsetCache=new Map,this.dstCache=new Map,this.maxCacheSize=1e3,this.cacheHits=0,this.cacheMisses=0}convertTimezone(e,t,s){if(!e)return null;if(t===s)return new Date(e);const i=this.getTimezoneOffset(e,t),n=(this.getTimezoneOffset(e,s)-i)*60*1e3;return new Date(e.getTime()+n)}toUTC(e,t){if(!e)return null;if(t==="UTC")return new Date(e);const s=this.getTimezoneOffset(e,t);return new Date(e.getTime()+s*60*1e3)}fromUTC(e,t){if(!e)return null;if(t==="UTC")return new Date(e);const s=this.getTimezoneOffset(e,t);return new Date(e.getTime()-s*60*1e3)}getTimezoneOffset(e,t){t=this.database.resolveAlias(t);const s=`${t}_${e.getFullYear()}_${e.getMonth()}_${e.getDate()}`;if(this.offsetCache.has(s))return this.cacheHits++,this._manageCacheSize(),this.offsetCache.get(s);if(this.cacheMisses++,typeof Intl<"u"&&Intl.DateTimeFormat)try{const a=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(e),c=(new Date(a.find(l=>l.type==="year").value,a.find(l=>l.type==="month").value-1,a.find(l=>l.type==="day").value,a.find(l=>l.type==="hour").value,a.find(l=>l.type==="minute").value,a.find(l=>l.type==="second").value).getTime()-e.getTime())/(1e3*60);return this.offsetCache.set(s,-c),this._manageCacheSize(),-c}catch{}const i=this.database.getTimezone(t);if(!i)throw new Error(`Unknown timezone: ${t}`);let r=i.offset;return i.dst&&this.isDST(e,t,i.dst)&&(r+=i.dst.offset),this.offsetCache.set(s,r),this._manageCacheSize(),r}isDST(e,t,s=null){if(!s){const a=this.database.getTimezone(t);if(!a||!a.dst)return!1;s=a.dst}const i=e.getFullYear(),r=this.getNthWeekdayOfMonth(i,s.start.month,s.start.week,s.start.day),n=this.getNthWeekdayOfMonth(i,s.end.month,s.end.week,s.end.day);return r>n?e>=r||e<n:e>=r&&e<n}getNthWeekdayOfMonth(e,t,s,i){const r=new Date(e,t,1),n=r.getDay();let a=i-n;if(a<0&&(a+=7),s>0)r.setDate(1+a+(s-1)*7);else{const o=new Date(e,t+1,0).getDate();r.setDate(o);let l=r.getDay()-i;l<0&&(l+=7),r.setDate(o-l+(s+1)*7)}return r}getCommonTimezones(){const e=new Date;return[{value:"America/New_York",label:"Eastern Time (New York)",region:"Americas"},{value:"America/Chicago",label:"Central Time (Chicago)",region:"Americas"},{value:"America/Denver",label:"Mountain Time (Denver)",region:"Americas"},{value:"America/Phoenix",label:"Mountain Time - Arizona (Phoenix)",region:"Americas"},{value:"America/Los_Angeles",label:"Pacific Time (Los Angeles)",region:"Americas"},{value:"America/Anchorage",label:"Alaska Time (Anchorage)",region:"Americas"},{value:"Pacific/Honolulu",label:"Hawaii Time (Honolulu)",region:"Pacific"},{value:"America/Toronto",label:"Eastern Time (Toronto)",region:"Americas"},{value:"America/Vancouver",label:"Pacific Time (Vancouver)",region:"Americas"},{value:"America/Mexico_City",label:"Central Time (Mexico City)",region:"Americas"},{value:"America/Sao_Paulo",label:"Brasilia Time (São Paulo)",region:"Americas"},{value:"Europe/London",label:"GMT/BST (London)",region:"Europe"},{value:"Europe/Paris",label:"Central European Time (Paris)",region:"Europe"},{value:"Europe/Berlin",label:"Central European Time (Berlin)",region:"Europe"},{value:"Europe/Moscow",label:"Moscow Time",region:"Europe"},{value:"Asia/Dubai",label:"Gulf Time (Dubai)",region:"Asia"},{value:"Asia/Kolkata",label:"India Time (Mumbai)",region:"Asia"},{value:"Asia/Shanghai",label:"China Time (Shanghai)",region:"Asia"},{value:"Asia/Tokyo",label:"Japan Time (Tokyo)",region:"Asia"},{value:"Asia/Seoul",label:"Korea Time (Seoul)",region:"Asia"},{value:"Asia/Singapore",label:"Singapore Time",region:"Asia"},{value:"Australia/Sydney",label:"Australian Eastern Time (Sydney)",region:"Oceania"},{value:"Australia/Melbourne",label:"Australian Eastern Time (Melbourne)",region:"Oceania"},{value:"Pacific/Auckland",label:"New Zealand Time (Auckland)",region:"Oceania"},{value:"UTC",label:"UTC",region:"UTC"}].map(s=>{const i=this.getTimezoneOffset(e,s.value),r=-i/60,n=Math.floor(Math.abs(r)),a=Math.round(Math.abs(r%1)*60),c=`UTC${r>=0?"+":"-"}${n.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`;return{...s,offset:c,offsetMinutes:-i}}).sort((s,i)=>s.offsetMinutes-i.offsetMinutes)}formatInTimezone(e,t,s={}){if(!e)return"";const r={...{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0,timeZone:t},...s};try{return new Intl.DateTimeFormat("en-US",r).format(e)}catch{return this.fromUTC(this.toUTC(e,"UTC"),t).toLocaleString("en-US",s)}}getSystemTimezone(){if(typeof Intl<"u"&&Intl.DateTimeFormat)try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}const t=-new Date().getTimezoneOffset()/60;for(const[s,i]of Object.entries(this.database.timezones))if(i.offset/60===t)return s;return"UTC"}parseTimezone(e){if(!e)return"UTC";if(Object.prototype.hasOwnProperty.call(this.database.timezones,e))return e;const t=e.toUpperCase();if(this.database.abbreviations&&Object.prototype.hasOwnProperty.call(this.database.abbreviations,t))return this.database.abbreviations[t];const s=e.match(/^([+-])(\d{2}):?(\d{2})$/);if(s){const i=s[1]==="+"?1:-1,r=parseInt(s[2],10),n=parseInt(s[3],10),a=i*(r+n/60);for(const[o,c]of Object.entries(this.database.timezones))if(c.offset/60===a)return o}return"UTC"}getTimezoneDifference(e,t,s=new Date){const i=this.getTimezoneOffset(s,e);return(this.getTimezoneOffset(s,t)-i)/60}clearCache(){this.offsetCache.clear(),this.dstCache.clear(),this.cacheHits=0,this.cacheMisses=0}isValidTimezone(e){return this.database.isValidTimezone(e)}getCacheStats(){const e=this.cacheHits+this.cacheMisses>0?(this.cacheHits/(this.cacheHits+this.cacheMisses)*100).toFixed(2):0;return{offsetCacheSize:this.offsetCache.size,dstCacheSize:this.dstCache.size,maxCacheSize:this.maxCacheSize,cacheHits:this.cacheHits,cacheMisses:this.cacheMisses,hitRate:`${e}%`}}_manageCacheSize(){if(this.offsetCache.size>this.maxCacheSize){const e=Math.floor(this.offsetCache.size/2),t=Array.from(this.offsetCache.keys());for(let s=0;s<e;s++)this.offsetCache.delete(t[s])}if(this.dstCache.size>this.maxCacheSize/2){const e=Math.floor(this.dstCache.size/2),t=Array.from(this.dstCache.keys());for(let s=0;s<e;s++)this.dstCache.delete(t[s])}}}class E{static normalize(e){const t={...e};return t.start&&(t.start=new Date(t.start)),t.end&&(t.end=new Date(t.end)),t.end||(t.end=t.start?new Date(t.start):null),t.allDay&&t.start&&(t.start.setHours(0,0,0,0),t.end&&t.end.setHours(23,59,59,999)),t.id=String(t.id||"").trim(),t.title=String(t.title||"").trim(),t.description=String(t.description||"").trim(),t.location=String(t.location||"").trim(),t.attendees=Array.isArray(t.attendees)?t.attendees:[],t.reminders=Array.isArray(t.reminders)?t.reminders:[],e.category&&!e.categories?t.categories=[e.category]:t.categories?t.categories=Array.isArray(t.categories)?t.categories:[]:t.categories=[],t.attachments=Array.isArray(t.attachments)?t.attachments:[],["confirmed","tentative","cancelled"].includes(t.status)||(t.status="confirmed"),["public","private","confidential"].includes(t.visibility)||(t.visibility="public"),t.color&&!t.backgroundColor&&(t.backgroundColor=t.color),t.color&&!t.borderColor&&(t.borderColor=t.color),t}static validate(e){if(!e.id)throw new Error("Event must have an id");if(!e.title)throw new Error("Event must have a title");if(!e.start)throw new Error("Event must have a start date");if(!(e.start instanceof Date)||isNaN(e.start.getTime()))throw new Error("Invalid start date");if(e.end&&(!(e.end instanceof Date)||isNaN(e.end.getTime())))throw new Error("Invalid end date");if(e.end&&e.start&&e.end<e.start)throw new Error("Event end time cannot be before start time");if(e.recurring&&!e.recurrenceRule)throw new Error("Recurring events must have a recurrence rule");if(e.attendees&&e.attendees.length>0&&e.attendees.forEach((t,s)=>{if(!t.email||!t.name)throw new Error(`Attendee at index ${s} must have email and name`);if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.email))throw new Error(`Invalid email for attendee: ${t.email}`)}),e.reminders&&e.reminders.length>0&&e.reminders.forEach((t,s)=>{if(!t.method||t.minutesBefore==null)throw new Error(`Reminder at index ${s} must have method and minutesBefore`);if(t.minutesBefore<0)throw new Error("Reminder minutesBefore must be non-negative")}),e.timeZone)try{new Intl.DateTimeFormat("en-US",{timeZone:e.timeZone})}catch{throw new Error(`Invalid timezone: ${e.timeZone}`)}}constructor({id:e,title:t,start:s,end:i,allDay:r=!1,description:n="",location:a="",color:o=null,backgroundColor:c=null,borderColor:l=null,textColor:d=null,recurring:h=!1,recurrenceRule:g=null,timeZone:D=null,endTimeZone:u=null,status:T="confirmed",visibility:b="public",organizer:C=null,attendees:z=[],reminders:_=[],category:Q,categories:J,attachments:X=[],conferenceData:ee=null,metadata:te={},...se}){const m=E.normalize({id:e,title:t,start:s,end:i,allDay:r,description:n,location:a,color:o,backgroundColor:c,borderColor:l,textColor:d,recurring:h,recurrenceRule:g,timeZone:D,endTimeZone:u,status:T,visibility:b,organizer:C,attendees:z,reminders:_,category:Q,categories:J,attachments:X,conferenceData:ee,metadata:te,...se});E.validate(m),this.id=m.id,this.title=m.title,this._timezoneManager=I.getInstance(),this.timeZone=m.timeZone||this._timezoneManager.getSystemTimezone(),this.endTimeZone=m.endTimeZone||this.timeZone,this.start=m.start,this.end=m.end,this.startUTC=this._timezoneManager.toUTC(this.start,this.timeZone),this.endUTC=this._timezoneManager.toUTC(this.end,this.endTimeZone),this.allDay=m.allDay,this.description=m.description,this.location=m.location,this.color=m.color,this.backgroundColor=m.backgroundColor,this.borderColor=m.borderColor,this.textColor=m.textColor,this.recurring=m.recurring,this.recurrenceRule=m.recurrenceRule,this._originalTimeZone=m.timeZone||null,this.status=m.status,this.visibility=m.visibility,this.organizer=m.organizer,this.attendees=[...m.attendees],this.reminders=[...m.reminders],this.categories=m.categories?[...m.categories]:[],this.attachments=[...m.attachments],this.conferenceData=m.conferenceData,this.metadata={...m.metadata},this._cache={},this._validateAttendees(),this._validateReminders()}get duration(){return this._cache.duration||(this._cache.duration=this.endUTC.getTime()-this.startUTC.getTime()),this._cache.duration}getStartInTimezone(e){return e===this.timeZone?new Date(this.start):this._timezoneManager.fromUTC(this.startUTC,e)}getEndInTimezone(e){return e===this.endTimeZone?new Date(this.end):this._timezoneManager.fromUTC(this.endUTC,e)}updateTimes(e,t,s){if(s||this.timeZone,this.start=e instanceof Date?e:new Date(e),this.end=t instanceof Date?t:new Date(t),s&&(this.timeZone=s,this.endTimeZone=s),this.startUTC=this._timezoneManager.toUTC(this.start,this.timeZone),this.endUTC=this._timezoneManager.toUTC(this.end,this.endTimeZone),this._cache={},this.endUTC<this.startUTC)throw new Error("Event end time cannot be before start time")}get durationMinutes(){return Math.floor(this.duration/(1e3*60))}get durationHours(){return this.duration/(1e3*60*60)}get isMultiDay(){if(!Object.prototype.hasOwnProperty.call(this._cache,"isMultiDay")){const e=this.start.toDateString(),t=this.end.toDateString();this._cache.isMultiDay=e!==t}return this._cache.isMultiDay}isRecurring(){return this.recurring&&this.recurrenceRule!==null}occursOn(e){e instanceof Date||(e=new Date(e));const t=e.toDateString(),s=this.start.toDateString(),i=this.end.toDateString();if(this.allDay)return e>=new Date(s)&&e<=new Date(i);if(this.isMultiDay){const r=new Date(t),n=new Date(t);return n.setHours(23,59,59,999),this.start<=n&&this.end>=r}return s===t}overlaps(e){if(e instanceof E)return!(this.end<=e.start||this.start>=e.end);if(e&&e.start&&e.end)return!(this.end<=e.start||this.start>=e.end);throw new Error("Parameter must be an Event instance or have start/end properties")}contains(e){return e instanceof Date||(e=new Date(e)),e>=this.start&&e<=this.end}clone(e={}){return new E({id:this.id,title:this.title,start:new Date(this.start),end:new Date(this.end),allDay:this.allDay,description:this.description,location:this.location,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,textColor:this.textColor,recurring:this.recurring,recurrenceRule:this.recurrenceRule,timeZone:this.timeZone,status:this.status,visibility:this.visibility,organizer:this.organizer?{...this.organizer}:null,attendees:this.attendees.map(t=>({...t})),reminders:this.reminders.map(t=>({...t})),categories:[...this.categories],attachments:this.attachments.map(t=>({...t})),conferenceData:this.conferenceData?{...this.conferenceData}:null,metadata:{...this.metadata},...e})}toObject(){return{id:this.id,title:this.title,start:this.start.toISOString(),end:this.end.toISOString(),allDay:this.allDay,description:this.description,location:this.location,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,textColor:this.textColor,recurring:this.recurring,recurrenceRule:this.recurrenceRule,timeZone:this.timeZone,status:this.status,visibility:this.visibility,organizer:this.organizer,attendees:this.attendees,reminders:this.reminders,categories:this.categories,attachments:this.attachments,conferenceData:this.conferenceData,metadata:{...this.metadata}}}static fromObject(e){return new E(e)}equals(e){return e instanceof E?this.id===e.id&&this.title===e.title&&this.start.getTime()===e.start.getTime()&&this.end.getTime()===e.end.getTime()&&this.allDay===e.allDay&&this.description===e.description&&this.location===e.location&&this.recurring===e.recurring&&this.recurrenceRule===e.recurrenceRule&&this.status===e.status:!1}addAttendee(e){if(!e||!e.email)throw new Error("Attendee must have an email");return this.hasAttendee(e.email)?!1:(e.id||(e.id=`attendee_${Date.now()}_${Math.random().toString(36).substr(2,9)}`),e.responseStatus=e.responseStatus||"needs-action",e.role=e.role||"required",this.attendees.push(e),!0)}removeAttendee(e){const t=this.attendees.findIndex(s=>s.email===e||s.id===e);return t!==-1?(this.attendees.splice(t,1),!0):!1}updateAttendeeResponse(e,t){const s=this.getAttendee(e);return s?(s.responseStatus=t,s.responseTime=new Date,!0):!1}getAttendee(e){return this.attendees.find(t=>t.email===e)||null}hasAttendee(e){return this.attendees.some(t=>t.email===e)}getAttendeesByStatus(e){return this.attendees.filter(t=>t.responseStatus===e)}getAttendeeCounts(){return this.attendees.reduce((e,t)=>{const s=t.responseStatus||"needs-action";return e[s]=(e[s]||0)+1,e},{})}addReminder(e){if(!e||typeof e.minutesBefore!="number")throw new Error("Reminder must have minutesBefore property");return e.id||(e.id=`reminder_${Date.now()}_${Math.random().toString(36).substr(2,9)}`),e.method=e.method||"popup",e.enabled=e.enabled!==!1,this.reminders.some(s=>s.method===e.method&&s.minutesBefore===e.minutesBefore)?!1:(this.reminders.push(e),!0)}removeReminder(e){const t=this.reminders.findIndex(s=>s.id===e);return t!==-1?(this.reminders.splice(t,1),!0):!1}getActiveReminders(){return this.reminders.filter(e=>e.enabled!==!1)}getReminderTriggerTimes(){return this.getActiveReminders().map(e=>{const t=new Date(this.start);return t.setMinutes(t.getMinutes()-e.minutesBefore),t})}addCategory(e){if(!e||typeof e!="string")throw new Error("Category must be a non-empty string");const t=e.trim().toLowerCase();return this.hasCategory(t)?!1:(this.categories.push(t),!0)}removeCategory(e){const t=e.trim().toLowerCase(),s=this.categories.findIndex(i=>i.toLowerCase()===t);return s!==-1?(this.categories.splice(s,1),!0):!1}get category(){return this.categories&&this.categories.length>0?this.categories[0]:null}hasCategory(e){const t=e.trim().toLowerCase();return this.categories.some(s=>s.toLowerCase()===t)}hasAnyCategory(e){return e.some(t=>this.hasCategory(t))}hasAllCategories(e){return e.every(t=>this.hasCategory(t))}_validateAttendees(){for(const e of this.attendees){if(!e.email)throw new Error("All attendees must have an email address");if(e.name||(e.name=e.email),!this._isValidEmail(e.email))throw new Error(`Invalid attendee email: ${e.email}`)}}_validateReminders(){for(const e of this.reminders){if(typeof e.minutesBefore!="number"||e.minutesBefore<0)throw new Error("Reminder minutesBefore must be a positive number");if(!["email","popup","sms"].includes(e.method))throw new Error(`Invalid reminder method: ${e.method}`)}}_isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}get isCancelled(){return this.status==="cancelled"}get isTentative(){return this.status==="tentative"}get isConfirmed(){return this.status==="confirmed"}get isPrivate(){return this.visibility==="private"}get isPublic(){return this.visibility==="public"}get hasAttendees(){return this.attendees.length>0}get hasReminders(){return this.reminders.length>0}get isMeeting(){return this.hasAttendees||this.conferenceData!==null}get isVirtual(){return this.conferenceData!==null}}let f=class M{static startOfDay(e){const t=new Date(e);return t.setHours(0,0,0,0),t}static endOfDay(e){const t=new Date(e);return t.setHours(23,59,59,999),t}static startOfWeek(e,t=0){const s=new Date(e),i=s.getDay(),r=(i<t?7:0)+i-t;return s.setDate(s.getDate()-r),s.setHours(0,0,0,0),s}static endOfWeek(e,t=0){const s=M.startOfWeek(e,t);return s.setDate(s.getDate()+6),s.setHours(23,59,59,999),s}static startOfMonth(e){return new Date(e.getFullYear(),e.getMonth(),1,0,0,0,0)}static endOfMonth(e){return new Date(e.getFullYear(),e.getMonth()+1,0,23,59,59,999)}static startOfYear(e){return new Date(e.getFullYear(),0,1,0,0,0,0)}static endOfYear(e){return new Date(e.getFullYear(),11,31,23,59,59,999)}static addDays(e,t){const s=new Date(e);return s.setDate(s.getDate()+t),s}static addWeeks(e,t){return M.addDays(e,t*7)}static addMonths(e,t){const s=new Date(e),i=s.getDate();return s.setMonth(s.getMonth()+t),s.getDate()!==i&&s.setDate(0),s}static addYears(e,t){const s=new Date(e);return s.setFullYear(s.getFullYear()+t),s}static getUTCDateString(e){const t=e.getUTCFullYear(),s=String(e.getUTCMonth()+1).padStart(2,"0"),i=String(e.getUTCDate()).padStart(2,"0");return`${t}-${s}-${i}`}static getLocalDateString(e){const t=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${s}-${i}`}static isToday(e){const t=new Date;return e.toDateString()===t.toDateString()}static isPast(e){return e<new Date}static isFuture(e){return e>new Date}static isSameDay(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}static isSameWeek(e,t,s=0){const i=M.startOfWeek(e,s),r=M.startOfWeek(t,s);return i.toDateString()===r.toDateString()}static isSameMonth(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()}static isSameYear(e,t){return e.getFullYear()===t.getFullYear()}static differenceInDays(e,t){const s=e.getTime()-t.getTime();return Math.floor(s/(1e3*60*60*24))}static differenceInWeeks(e,t){return Math.floor(M.differenceInDays(e,t)/7)}static differenceInMonths(e,t){const s=e.getFullYear()-t.getFullYear(),i=e.getMonth()-t.getMonth();return s*12+i}static getWeekNumber(e){const t=new Date(e.getFullYear(),0,1),s=(e-t)/864e5;return Math.ceil((s+t.getDay()+1)/7)}static getDayOfWeek(e,t=0){return(e.getDay()-t+7)%7}static getDaysInMonth(e){return new Date(e.getFullYear(),e.getMonth()+1,0).getDate()}static format(e,t="en-US",s={}){return new Intl.DateTimeFormat(t,s).format(e)}static getMonthName(e,t="en-US",s="long"){return M.format(e,t,{month:s})}static getDayName(e,t="en-US",s="long"){return M.format(e,t,{weekday:s})}static formatTime(e,t="en-US",s=!1){return M.format(e,t,{hour:"numeric",minute:"2-digit",hour12:!s})}static parseTime(e){const[t,s]=e.split(":").map(Number);return{hours:t,minutes:s}}static setTime(e,t){const s=new Date(e),{hours:i,minutes:r}=M.parseTime(t);return s.setHours(i,r,0,0),s}static isLeapYear(e){return e%4===0&&e%100!==0||e%400===0}static getDateRange(e,t){const s=[],i=new Date(e),r=t.getTime();for(;i.getTime()<=r;)s.push(new Date(i)),i.setDate(i.getDate()+1);return s}static clone(e){return new Date(e)}static isValidDate(e){return e instanceof Date&&!isNaN(e.getTime())}static toTimeZone(e,t){const i=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(e),r={};return i.forEach(n=>{n.type!=="literal"&&(r[n.type]=n.value)}),new Date(`${r.year}-${r.month}-${r.day}T${r.hour}:${r.minute}:${r.second}`)}static getTimezoneOffset(e,t){const s=new Date(e.toLocaleString("en-US",{timeZone:"UTC"})),i=new Date(e.toLocaleString("en-US",{timeZone:t}));return(s.getTime()-i.getTime())/6e4}static isDST(e,t){const s=new Date(e.getFullYear(),0,1),i=new Date(e.getFullYear(),6,1),r=M.getTimezoneOffset(s,t),n=M.getTimezoneOffset(i,t),a=M.getTimezoneOffset(e,t);return Math.max(r,n)===a}static addHoursWithDST(e,t,s){const i=new Date(e),r=M.getTimezoneOffset(e,s);i.setTime(i.getTime()+t*60*60*1e3);const n=M.getTimezoneOffset(i,s);if(r!==n){const a=(n-r)*6e4;i.setTime(i.getTime()+a)}return i}static createInTimeZone(e,t,s,i=0,r=0,n=0,a){const o=`${e}-${String(t+1).padStart(2,"0")}-${String(s).padStart(2,"0")}`,c=`${String(i).padStart(2,"0")}:${String(r).padStart(2,"0")}:${String(n).padStart(2,"0")}`,l=new Date(`${o}T${c}`),d=M.getTimezoneOffset(l,a),h=l.getTime()+d*6e4;return new Date(h)}};class V{static parse(e){if(typeof e=="object")return this.validateRule(e);const t={freq:null,interval:1,count:null,until:null,byDay:[],byWeekNo:[],byMonth:[],byMonthDay:[],byYearDay:[],bySetPos:[],byHour:[],byMinute:[],bySecond:[],wkst:"MO",exceptions:[],tzid:null},s=e.toUpperCase().split(";");for(const i of s){const[r,n]=i.split("=");switch(r){case"FREQ":t.freq=this.parseFrequency(n);break;case"INTERVAL":t.interval=parseInt(n,10),t.interval<1&&(t.interval=1);break;case"COUNT":t.count=parseInt(n,10);break;case"UNTIL":t.until=this.parseDateTime(n);break;case"BYDAY":t.byDay=this.parseByDay(n);break;case"BYWEEKNO":t.byWeekNo=this.parseIntList(n);break;case"BYMONTH":t.byMonth=this.parseIntList(n);break;case"BYMONTHDAY":t.byMonthDay=this.parseIntList(n);break;case"BYYEARDAY":t.byYearDay=this.parseIntList(n);break;case"BYSETPOS":t.bySetPos=this.parseIntList(n);break;case"BYHOUR":t.byHour=this.parseIntList(n);break;case"BYMINUTE":t.byMinute=this.parseIntList(n);break;case"BYSECOND":t.bySecond=this.parseIntList(n);break;case"WKST":t.wkst=n;break;case"EXDATE":t.exceptions=this.parseExceptionDates(n);break;case"TZID":t.tzid=n;break}}return this.validateRule(t)}static parseFrequency(e){return["SECONDLY","MINUTELY","HOURLY","DAILY","WEEKLY","MONTHLY","YEARLY"].includes(e)?e:"DAILY"}static parseByDay(e){const t=e.split(","),s=["SU","MO","TU","WE","TH","FR","SA"],i=[];for(const r of t){const a=r.trim().toUpperCase().match(/^([+-]?\d*)([A-Z]{2})$/);if(a){const[o,c,l]=a;s.includes(l)&&i.push(c?`${c}${l}`:l)}}return i}static parseIntList(e){return e.split(",").map(t=>parseInt(t.trim(),10)).filter(t=>!isNaN(t))}static parseDateTime(e){if(e.length===8){const t=parseInt(e.substr(0,4),10),s=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10);return new Date(t,s,i)}if(e.length===15&&e[8]==="T"){const t=parseInt(e.substr(0,4),10),s=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10),r=parseInt(e.substr(9,2),10),n=parseInt(e.substr(11,2),10),a=parseInt(e.substr(13,2),10);return new Date(t,s,i,r,n,a)}if(e.length===16&&e[8]==="T"&&e[15]==="Z"){const t=parseInt(e.substr(0,4),10),s=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10),r=parseInt(e.substr(9,2),10),n=parseInt(e.substr(11,2),10),a=parseInt(e.substr(13,2),10);return new Date(Date.UTC(t,s,i,r,n,a))}return new Date(e)}static parseExceptionDates(e){return e.split(",").map(s=>this.parseDateTime(s.trim()))}static validateRule(e){if(e.freq||(e.freq="DAILY"),e.count&&e.until)throw new Error("RRULE cannot have both COUNT and UNTIL");e.interval<1&&(e.interval=1);const t=(s,i,r)=>s.filter(n=>n>=i&&n<=r);return e.byMonth=t(e.byMonth||[],1,12),e.byMonthDay=t(e.byMonthDay||[],-31,31).filter(s=>s!==0),e.byYearDay=t(e.byYearDay||[],-366,366).filter(s=>s!==0),e.byWeekNo=t(e.byWeekNo||[],-53,53).filter(s=>s!==0),e.byHour=t(e.byHour||[],0,23),e.byMinute=t(e.byMinute||[],0,59),e.bySecond=t(e.bySecond||[],0,59),e}static buildRRule(e){const t=[];if(t.push(`FREQ=${e.freq}`),e.interval&&e.interval>1&&t.push(`INTERVAL=${e.interval}`),e.count?t.push(`COUNT=${e.count}`):e.until&&t.push(`UNTIL=${this.formatDateTime(e.until)}`),e.byDay&&e.byDay.length>0){const s=e.byDay.map(i=>typeof i=="string"?i:i.nth?`${i.nth}${i.weekday}`:i.weekday).join(",");t.push(`BYDAY=${s}`)}return e.byMonth&&e.byMonth.length>0&&t.push(`BYMONTH=${e.byMonth.join(",")}`),e.byMonthDay&&e.byMonthDay.length>0&&t.push(`BYMONTHDAY=${e.byMonthDay.join(",")}`),e.byYearDay&&e.byYearDay.length>0&&t.push(`BYYEARDAY=${e.byYearDay.join(",")}`),e.byWeekNo&&e.byWeekNo.length>0&&t.push(`BYWEEKNO=${e.byWeekNo.join(",")}`),e.bySetPos&&e.bySetPos.length>0&&t.push(`BYSETPOS=${e.bySetPos.join(",")}`),e.byHour&&e.byHour.length>0&&t.push(`BYHOUR=${e.byHour.join(",")}`),e.byMinute&&e.byMinute.length>0&&t.push(`BYMINUTE=${e.byMinute.join(",")}`),e.bySecond&&e.bySecond.length>0&&t.push(`BYSECOND=${e.bySecond.join(",")}`),e.wkst&&e.wkst!=="MO"&&t.push(`WKST=${e.wkst}`),t.join(";")}static formatDateTime(e){const t=e.getUTCFullYear(),s=String(e.getUTCMonth()+1).padStart(2,"0"),i=String(e.getUTCDate()).padStart(2,"0"),r=String(e.getUTCHours()).padStart(2,"0"),n=String(e.getUTCMinutes()).padStart(2,"0"),a=String(e.getUTCSeconds()).padStart(2,"0");return`${t}${s}${i}T${r}${n}${a}Z`}static getDescription(e){const t={SECONDLY:"second",MINUTELY:"minute",HOURLY:"hour",DAILY:"day",WEEKLY:"week",MONTHLY:"month",YEARLY:"year"},s={SU:"Sunday",MO:"Monday",TU:"Tuesday",WE:"Wednesday",TH:"Thursday",FR:"Friday",SA:"Saturday"},i={1:"first",2:"second",3:"third",4:"fourth",5:"fifth","-1":"last","-2":"second to last"};let r="Every";if(e.interval>1&&(r+=` ${e.interval}`),r+=` ${t[e.freq]}`,e.interval>1&&(r+="s"),e.byDay&&e.byDay.length>0){const n=a=>{if(typeof a=="string"){const o=a.match(/^(-?\d+)?([A-Z]{2})$/);return o?{nth:o[1]?parseInt(o[1],10):null,weekday:o[2]}:{nth:null,weekday:a}}return a};if(e.freq==="WEEKLY"){const a=e.byDay.map(o=>s[n(o).weekday]).join(", ");r+=` on ${a}`}else if(e.freq==="MONTHLY"||e.freq==="YEARLY"){const a=e.byDay.map(o=>{const c=n(o);return c.nth?`the ${i[c.nth]||c.nth} ${s[c.weekday]}`:s[c.weekday]}).join(", ");r+=` on ${a}`}}if(e.byMonthDay&&e.byMonthDay.length>0){const n=e.byMonthDay.map(a=>a<0?`${Math.abs(a)} day(s) from the end`:`day ${a}`).join(", ");r+=` on ${n}`}if(e.byMonth&&e.byMonth.length>0){const n=["January","February","March","April","May","June","July","August","September","October","November","December"],a=e.byMonth.map(o=>n[o-1]).join(", ");r+=` in ${a}`}return e.count?r+=`, ${e.count} time${e.count>1?"s":""}`:e.until&&(r+=`, until ${e.until.toLocaleDateString()}`),r}}class Y{static expandEvent(e,t,s,i=365,r=null){if(!e.recurring||!e.recurrenceRule)return[{start:e.start,end:e.end,timezone:e.timeZone}];const n=this.parseRule(e.recurrenceRule),a=[],o=e.end-e.start,c=r||e.timeZone||"UTC",l=I.getInstance();let d=new Date(e.start),h=0;n.until&&n.until<s&&(s=n.until);let g=l.getTimezoneOffset(d,c),D=0;const u=3;for(;d<=s&&h<i;){if(d>=t){const b=new Date(d),C=new Date(d.getTime()+o),z=l.getTimezoneOffset(b,c);if(z!==g){const _=g-z;b.setMinutes(b.getMinutes()+_),C.setMinutes(C.getMinutes()+_)}g=z,this.isException(b,n,e.id)||a.push({start:b,end:C,recurringEventId:e.id,timezone:c,originalStart:e.start})}const T=d.getTime();if(d=this.getNextOccurrence(d,n,c),h++,d.getTime()===T){if(D++,D>=u){console.warn("RecurrenceEngine: Date not advancing, breaking to prevent infinite loop");break}}else D=0;if(n.count&&h>=n.count)break}return a}static parseRule(e){return V.parse(e)}static getNextOccurrence(e,t,s="UTC"){const i=new Date(e);switch(t.freq){case"DAILY":i.setDate(i.getDate()+t.interval);break;case"WEEKLY":if(t.byDay&&t.byDay.length>0){let n=0;const a=i.getDate();for(i.setDate(i.getDate()+1);!this.matchesByDay(i,t.byDay)&&n<8;)i.setDate(i.getDate()+1),n++;n>=8&&(console.warn("RecurrenceEngine: Invalid byDay rule, falling back to weekly interval"),i.setDate(a+7*t.interval))}else i.setDate(i.getDate()+7*t.interval);break;case"MONTHLY":if(t.byMonthDay&&t.byMonthDay.length>0){const r=i.getMonth();i.setMonth(r+t.interval),i.setDate(t.byMonthDay[0])}else t.byDay&&t.byDay.length>0?(i.setMonth(i.getMonth()+t.interval),this.setToWeekdayOfMonth(i,t.byDay[0],t.bySetPos[0]||1)):i.setMonth(i.getMonth()+t.interval);break;case"YEARLY":t.byMonth&&t.byMonth.length>0?(i.setFullYear(i.getFullYear()+t.interval),i.setMonth(t.byMonth[0]-1)):i.setFullYear(i.getFullYear()+t.interval);break;default:i.setTime(i.getTime()+24*60*60*1e3)}return i}static matchesByDay(e,t){const s={SU:0,MO:1,TU:2,WE:3,TH:4,FR:5,SA:6},i=e.getDay();return t.some(r=>{const n=r.match(/^(-?\d+)?([A-Z]{2})$/);if(n){const a=n[2];return s[a]===i}return!1})}static setToWeekdayOfMonth(e,t,s=1){const i={SU:0,MO:1,TU:2,WE:3,TH:4,FR:5,SA:6},r=t.match(/^(-?\d+)?([A-Z]{2})$/),n=r?r[2]:t,a=i[n];for(e.setDate(1);e.getDay()!==a;)e.setDate(e.getDate()+1);if(s>1)e.setDate(e.getDate()+7*(s-1));else if(s===-1){const o=new Date(e);for(o.setMonth(o.getMonth()+1),o.setDate(0);o.getDay()!==a;)o.setDate(o.getDate()-1);e.setTime(o.getTime())}}static isException(e,t,s=null){if(!t.exceptions||t.exceptions.length===0)return!1;const i=e.toDateString(),r=e.getTime();return t.exceptions.some(n=>{if(typeof n=="object"&&n.date){const o=n.date instanceof Date?n.date:new Date(n.date);return n.matchTime?Math.abs(o.getTime()-r)<1e3:o.toDateString()===i}return(n instanceof Date?n:new Date(n)).toDateString()===i})}static addExceptions(e,t,s={}){return e.exceptions||(e.exceptions=[]),(Array.isArray(t)?t:[t]).forEach(r=>{s.reason||s.matchTime?e.exceptions.push({date:r,reason:s.reason,matchTime:s.matchTime||!1}):e.exceptions.push(r)}),e}static parseDate(e){if(e.length===8){const t=parseInt(e.substr(0,4),10),s=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10);return new Date(t,s,i)}else if(e.length===15||e.length===16){const t=parseInt(e.substr(0,4),10),s=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10),r=parseInt(e.substr(9,2),10),n=parseInt(e.substr(11,2),10),a=parseInt(e.substr(13,2),10);return e.endsWith("Z")?new Date(Date.UTC(t,s,i,r,n,a)):new Date(t,s,i,r,n,a)}return new Date(e)}static getDescription(e){typeof e=="string"&&(e=this.parseRule(e));let t="";const s=e.interval||1;switch(e.freq){case"DAILY":t=s===1?"Daily":`Every ${s} days`;break;case"WEEKLY":if(t=s===1?"Weekly":`Every ${s} weeks`,e.byDay&&e.byDay.length>0){const i=e.byDay.map(r=>this.getDayName(r)).join(", ");t+=` on ${i}`}break;case"MONTHLY":t=s===1?"Monthly":`Every ${s} months`,e.byMonthDay&&e.byMonthDay.length>0&&(t+=` on day ${e.byMonthDay.join(", ")}`);break;case"YEARLY":t=s===1?"Yearly":`Every ${s} years`;break}return e.count?t+=`, ${e.count} times`:e.until&&(t+=`, until ${e.until.toLocaleDateString()}`),t}static getDayName(e){const t={SU:"Sunday",MO:"Monday",TU:"Tuesday",WE:"Wednesday",TH:"Thursday",FR:"Friday",SA:"Saturday"},s=e.match(/^(-?\d+)?([A-Z]{2})$/),i=s?s[2]:e,r=s&&s[1]?parseInt(s[1],10):null;let n=t[i]||e;return r&&(n=`${r===-1?"Last":["","1st","2nd","3rd","4th","5th"][r]||`${r}th`} ${n}`),n}}class F{constructor(e=100){this.capacity=e,this.cache=new Map,this.hits=0,this.misses=0,this.evictions=0}get(e){if(!this.cache.has(e)){this.misses++;return}const t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),this.hits++,t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){const s=this.cache.keys().next().value;this.cache.delete(s),this.evictions++}this.cache.set(e,t)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear(),this.hits=0,this.misses=0,this.evictions=0}getStats(){const e=this.hits+this.misses>0?(this.hits/(this.hits+this.misses)*100).toFixed(2):0;return{size:this.cache.size,capacity:this.capacity,hits:this.hits,misses:this.misses,evictions:this.evictions,hitRate:`${e}%`}}keys(){return Array.from(this.cache.keys())}get size(){return this.cache.size}}class N{constructor(e={}){this.config={checkInterval:3e4,memoryThreshold:.8,criticalThreshold:.95,minCacheSize:10,maxCacheSize:1e4,adaptiveScaling:!0,...e},this.caches=new Map,this.stats={adjustments:0,emergencyClears:0,lastMemoryUsage:0,lastCheckTime:null,cacheResizes:[]},this.monitoringInterval=null,this.config.adaptiveScaling&&this.startMonitoring()}registerCache(e,t,s={}){this.caches.set(e,{cache:t,priority:s.priority||1,currentCapacity:s.initialCapacity||100,minCapacity:s.minCapacity||this.config.minCacheSize,maxCapacity:s.maxCapacity||this.config.maxCacheSize,scaleFactor:s.scaleFactor||.5,lastAccess:Date.now()})}unregisterCache(e){this.caches.delete(e)}startMonitoring(){this.monitoringInterval||(this.monitoringInterval=setInterval(()=>{this.checkMemoryPressure()},this.config.checkInterval),this.checkMemoryPressure())}stopMonitoring(){this.monitoringInterval&&(clearInterval(this.monitoringInterval),this.monitoringInterval=null)}async checkMemoryPressure(){const e=await this.getMemoryUsage();this.stats.lastMemoryUsage=e,this.stats.lastCheckTime=new Date,e>this.config.criticalThreshold?this.emergencyClear():e>this.config.memoryThreshold?this.reduceCacheSizes(e):e<this.config.memoryThreshold-.2&&this.increaseCacheSizes()}async getMemoryUsage(){if(typeof performance<"u"&&performance.memory){const e=performance.memory;if(e.jsHeapSizeLimit&&e.usedJSHeapSize)return e.usedJSHeapSize/e.jsHeapSizeLimit}try{const e=typeof globalThis<"u"?globalThis:{},t="process",s="memoryUsage",i=e[t];if(i&&typeof i=="object"){const r=i[s];if(typeof r=="function"){const n=r.call(i);return n.heapUsed/n.heapTotal}}}catch{}return this.estimateMemoryUsage()}estimateMemoryUsage(){let e=0,t=0;for(const[s,i]of this.caches)i.cache.size!==void 0&&(e+=i.cache.size,t+=i.maxCapacity);return t>0?e/t:.5}reduceCacheSizes(e){const t=(e-this.config.memoryThreshold)/(this.config.criticalThreshold-this.config.memoryThreshold),s=Array.from(this.caches.entries()).sort((i,r)=>i[1].priority-r[1].priority);for(const[i,r]of s){const n=Math.floor(r.currentCapacity*r.scaleFactor*t),a=Math.max(r.minCapacity,r.currentCapacity-n);a<r.currentCapacity&&this.resizeCache(i,r,a)}this.stats.adjustments++}increaseCacheSizes(){for(const[e,t]of this.caches)if(Date.now()-t.lastAccess<6e4){const i=Math.floor(t.currentCapacity*.2),r=Math.min(t.maxCapacity,t.currentCapacity+i);r>t.currentCapacity&&this.resizeCache(e,t,r)}}resizeCache(e,t,s){const i=t.currentCapacity;t.currentCapacity=s,t.cache.capacity!==void 0&&(t.cache.capacity=s),t.cache.size>s&&this.evictExcessItems(t.cache,s),this.stats.cacheResizes.push({cache:e,timestamp:new Date,oldCapacity:i,newCapacity:s,reason:s<i?"pressure":"available"}),this.stats.cacheResizes.length>100&&this.stats.cacheResizes.shift()}evictExcessItems(e,t){if(e.size<=t)return;const s=e.size-t;if(e.keys){const i=Array.from(e.keys());for(let r=0;r<s;r++)e.delete(i[r])}else e.clear&&e.clear()}emergencyClear(){for(const[e,t]of this.caches)t.cache.clear&&t.cache.clear(),t.currentCapacity=t.minCapacity;this.stats.emergencyClears++,console.warn("AdaptiveMemoryManager: Emergency cache clear triggered")}touchCache(e){const t=this.caches.get(e);t&&(t.lastAccess=Date.now())}getStats(){const e={};for(const[t,s]of this.caches)e[t]={size:s.cache.size||0,capacity:s.currentCapacity,priority:s.priority,lastAccess:new Date(s.lastAccess)};return{...this.stats,memoryUsagePercent:`${(this.stats.lastMemoryUsage*100).toFixed(2)}%`,totalCaches:this.caches.size,cacheStats:e,monitoring:this.monitoringInterval!==null}}async checkNow(){await this.checkMemoryPressure()}setThresholds(e){e.memoryThreshold!==void 0&&(this.config.memoryThreshold=Math.max(.5,Math.min(.95,e.memoryThreshold))),e.criticalThreshold!==void 0&&(this.config.criticalThreshold=Math.max(this.config.memoryThreshold+.05,Math.min(1,e.criticalThreshold)))}destroy(){this.stopMonitoring(),this.caches.clear()}}class j{constructor(e={}){this.config={enableCache:!0,cacheCapacity:500,maxIndexDays:365,batchSize:100,enableMetrics:!0,cleanupInterval:36e5,maxIndexAge:30*24*60*60*1e3,enableAdaptiveMemory:!0,...e},this.eventCache=new F(this.config.cacheCapacity),this.queryCache=new F(Math.floor(this.config.cacheCapacity/2)),this.dateRangeCache=new F(Math.floor(this.config.cacheCapacity/4)),this.config.enableAdaptiveMemory&&(this.memoryManager=new N({checkInterval:3e4,memoryThreshold:.75,criticalThreshold:.9}),this.memoryManager.registerCache("events",this.eventCache,{priority:3,initialCapacity:this.config.cacheCapacity,minCapacity:50,maxCapacity:2e3}),this.memoryManager.registerCache("queries",this.queryCache,{priority:2,initialCapacity:Math.floor(this.config.cacheCapacity/2),minCapacity:25,maxCapacity:1e3}),this.memoryManager.registerCache("dateRanges",this.dateRangeCache,{priority:1,initialCapacity:Math.floor(this.config.cacheCapacity/4),minCapacity:10,maxCapacity:500})),this.lazyIndexes=new Map,this.pendingIndexes=new Map,this.batchQueue=[],this.batchTimer=null,this.batchCallbacks=[],this.metrics={operations:{},averageTimes:{},slowQueries:[]},this.cleanupTimer=null,this.config.cleanupInterval>0&&this.startCleanupTimer()}measure(e,t){if(!this.config.enableMetrics)return t();const s=performance.now();try{const i=t(),r=performance.now()-s;return this.recordMetric(e,r),i}catch(i){const r=performance.now()-s;throw this.recordMetric(e,r,!0),i}}async measureAsync(e,t){if(!this.config.enableMetrics)return await t();const s=performance.now();try{const i=await t(),r=performance.now()-s;return this.recordMetric(e,r),i}catch(i){const r=performance.now()-s;throw this.recordMetric(e,r,!0),i}}recordMetric(e,t,s=!1){this.metrics.operations[e]||(this.metrics.operations[e]={count:0,totalTime:0,errors:0,min:1/0,max:0});const i=this.metrics.operations[e];i.count++,i.totalTime+=t,i.min=Math.min(i.min,t),i.max=Math.max(i.max,t),s&&i.errors++,this.metrics.averageTimes[e]=i.totalTime/i.count,t>100&&(this.metrics.slowQueries.push({operation:e,duration:t,timestamp:new Date,isError:s}),this.metrics.slowQueries.length>100&&this.metrics.slowQueries.shift())}getMetrics(){const e={cacheStats:{event:this.eventCache.getStats(),query:this.queryCache.getStats(),dateRange:this.dateRangeCache.getStats()},operations:{},slowestOperations:[],recentSlowQueries:this.metrics.slowQueries.slice(-10),memoryManagement:this.memoryManager?this.memoryManager.getStats():null};for(const[t,s]of Object.entries(this.metrics.operations))e.operations[t]={count:s.count,avgTime:`${(s.totalTime/s.count).toFixed(2)}ms`,minTime:`${s.min.toFixed(2)}ms`,maxTime:`${s.max.toFixed(2)}ms`,totalTime:`${s.totalTime.toFixed(2)}ms`,errors:s.errors,errorRate:`${(s.errors/s.count*100).toFixed(2)}%`};return e.slowestOperations=Object.entries(this.metrics.averageTimes).sort((t,s)=>s[1]-t[1]).slice(0,5).map(([t,s])=>({operation:t,avgTime:`${s.toFixed(2)}ms`})),e}shouldUseLazyIndexing(e){return Math.ceil((e.end-e.start)/864e5)>this.config.maxIndexDays}createLazyIndexMarkers(e){const t={eventId:e.id,start:e.start,end:e.end,indexed:new Set,pending:!1},s=new Date(e.start.getFullYear(),e.start.getMonth(),1),i=new Date(e.end.getFullYear(),e.end.getMonth(),1);return t.indexed.add(this.getMonthKey(s)),this.getMonthKey(s)!==this.getMonthKey(i)&&t.indexed.add(this.getMonthKey(i)),this.lazyIndexes.set(e.id,t),t}async expandLazyIndex(e,t,s){const i=this.lazyIndexes.get(e);if(!i)return new Set;if(i.pending)return this.pendingIndexes.get(e);i.pending=!0;const r=new Promise(n=>{setTimeout(()=>{const a=new Set,o=new Date(t);for(;o<=s;){const c=o.toDateString();i.indexed.has(c)||(a.add(c),i.indexed.add(c)),o.setDate(o.getDate()+1)}i.pending=!1,this.pendingIndexes.delete(e),n(a)},0)});return this.pendingIndexes.set(e,r),r}getMonthKey(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}`}cache(e,t,s="event"){if(!this.config.enableCache)return;let i,r;switch(s){case"event":i=this.eventCache,r="events";break;case"query":i=this.queryCache,r="queries";break;case"dateRange":i=this.dateRangeCache,r="dateRanges";break;default:return}i.put(e,t),this.memoryManager&&this.memoryManager.touchCache(r)}getFromCache(e,t="event"){if(!this.config.enableCache)return;let s,i;switch(t){case"event":s=this.eventCache.get(e),i="events";break;case"query":s=this.queryCache.get(e),i="queries";break;case"dateRange":s=this.dateRangeCache.get(e),i="dateRanges";break;default:return}return s!==void 0&&this.memoryManager&&this.memoryManager.touchCache(i),s}invalidateEventCaches(e){this.eventCache.delete(e),this.queryCache.clear(),this.dateRangeCache.clear()}batch(e){return new Promise((t,s)=>{this.batchQueue.push(e),this.batchCallbacks.push({resolve:t,reject:s}),this.batchQueue.length>=this.config.batchSize?this.processBatch():this.batchTimer||(this.batchTimer=setTimeout(()=>this.processBatch(),10))})}processBatch(){if(this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.batchQueue.length===0)return;const e=this.batchQueue.splice(0),t=this.batchCallbacks.splice(0),s=[],i=[];e.forEach((r,n)=>{try{s[n]=r()}catch(a){i[n]=a}}),t.forEach((r,n)=>{i[n]?r.reject(i[n]):r.resolve(s[n])})}startCleanupTimer(){this.cleanupTimer=setInterval(()=>{this.cleanupOldIndexes()},this.config.cleanupInterval)}cleanupOldIndexes(){const e=Date.now(),t=this.config.maxIndexAge;for(const[s,i]of this.lazyIndexes)i.end.getTime()<e-t&&this.lazyIndexes.delete(s);this.metrics.slowQueries.length>100&&(this.metrics.slowQueries=this.metrics.slowQueries.slice(-100))}optimizeQuery(e,t){const s=this.getFromCache(e,"query");if(s!==void 0)return s;const i=this.measure(`query:${e}`,t);return this.cache(e,i,"query"),i}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.eventCache.clear(),this.queryCache.clear(),this.dateRangeCache.clear(),this.lazyIndexes.clear(),this.pendingIndexes.clear()}}class W{constructor(e){this.eventStore=e,this.conflictIdCounter=0}checkConflicts(e,t={}){const s={checkAttendees:!0,checkResources:!0,checkLocation:!0,ignoreAllDay:!1,excludeEventIds:[],includeStatuses:["confirmed","tentative"],bufferMinutes:0,...t};if(!e.start||!e.end)throw new Error("Event must have start and end dates");const i=[],r=new Set,n=new Set,a=new Date(e.start.getTime()-s.bufferMinutes*6e4),o=new Date(e.end.getTime()+s.bufferMinutes*6e4),c=this.eventStore.getEventsInRange(a,o,!1).filter(l=>!(l.id===e.id||s.excludeEventIds.includes(l.id)||!s.includeStatuses.includes(l.status)||s.ignoreAllDay&&(l.allDay||e.allDay)||l.status==="cancelled"));for(const l of c){const d=this._detectEventConflicts(e,l,s);d.length>0&&(i.push(...d),r.add(e.id),r.add(l.id),e.attendees&&e.attendees.forEach(h=>n.add(h.email)),l.attendees&&l.attendees.forEach(h=>n.add(h.email)))}return this._buildConflictSummary(i,r,n)}checkEventPairConflicts(e,t,s={}){const i={checkAttendees:!0,checkResources:!0,checkLocation:!0,bufferMinutes:0,...s};return this._detectEventConflicts(e,t,i)}getBusyPeriods(e,t,s,i={}){const r={includeStatuses:["confirmed","tentative"],mergePeriods:!0,...i},n=[];return this.eventStore.getEventsInRange(t,s,!1).filter(c=>!r.includeStatuses.includes(c.status)||c.status==="cancelled"?!1:c.attendees&&c.attendees.some(l=>e.includes(l.email))).forEach(c=>{n.push({start:c.start,end:c.end,eventIds:[c.id]})}),r.mergePeriods&&n.length>1?this._mergeBusyPeriods(n):n.sort((c,l)=>c.start-l.start)}getFreePeriods(e,t,s,i={}){const r={attendeeEmails:[],businessHoursOnly:!1,businessHours:{start:"09:00",end:"17:00"},excludeWeekends:!1,...i},n=[],a=r.attendeeEmails.length>0?this.getBusyPeriods(r.attendeeEmails,e,t):this._getAllBusyPeriods(e,t);let o=new Date(e);for(const c of a)o<c.start&&(c.start-o)/6e4>=s&&(!r.businessHoursOnly||this._isWithinBusinessHours(o,c.start,r))&&n.push({start:new Date(o),end:new Date(c.start)}),o=new Date(Math.max(o.getTime(),c.end.getTime()));return o<t&&(t-o)/6e4>=s&&(!r.businessHoursOnly||this._isWithinBusinessHours(o,t,r))&&n.push({start:new Date(o),end:new Date(t)}),n}_detectEventConflicts(e,t,s){const i=[];if(this._checkTimeOverlap(e,t,s.bufferMinutes)){const n=this._createTimeConflict(e,t);if(i.push(n),s.checkAttendees){const a=this._checkAttendeeConflicts(e,t);i.push(...a)}if(s.checkResources){const a=this._checkResourceConflicts(e,t);i.push(...a)}if(s.checkLocation){const a=this._checkLocationConflict(e,t);a&&i.push(a)}}return i}_checkTimeOverlap(e,t,s=0){const i=s*6e4,r=e.start.getTime()-i,n=e.end.getTime()+i,a=t.start.getTime(),o=t.end.getTime();return!(n<=a||o<=r)}_createTimeConflict(e,t){const s=new Date(Math.max(e.start.getTime(),t.start.getTime())),i=new Date(Math.min(e.end.getTime(),t.end.getTime())),r=(i-s)/6e4;let n="low";return r>=60?n="high":r>=30&&(n="medium"),e.status==="confirmed"&&t.status==="confirmed"&&(n=n==="low"?"medium":n==="medium"?"high":"critical"),{id:`conflict_${++this.conflictIdCounter}`,type:"time",severity:n,eventId:e.id,conflictingEventId:t.id,description:`Time overlap: ${e.title} conflicts with ${t.title}`,overlapStart:s,overlapEnd:i,overlapMinutes:r,metadata:{event1Title:e.title,event2Title:t.title,event1Status:e.status,event2Status:t.status}}}_checkAttendeeConflicts(e,t){const s=[];if(!e.attendees||!t.attendees)return s;const i=[];for(const r of e.attendees)for(const n of t.attendees)r.email===n.email&&i.push(r.email);if(i.length>0){let r="medium";i.some(a=>{const o=e.attendees.find(l=>l.email===a),c=t.attendees.find(l=>l.email===a);return(o==null?void 0:o.responseStatus)==="accepted"&&(c==null?void 0:c.responseStatus)==="accepted"})&&(r="critical"),s.push({id:`conflict_${++this.conflictIdCounter}`,type:"attendee",severity:r,eventId:e.id,conflictingEventId:t.id,description:`Attendee conflict: ${i.length} attendee(s) double-booked`,conflictingAttendees:i,metadata:{attendeeCount:i.length,attendeeEmails:i}})}return s}_checkResourceConflicts(e,t){var n,a;const s=[],i=((n=e.attendees)==null?void 0:n.filter(o=>o.resource))||[],r=((a=t.attendees)==null?void 0:a.filter(o=>o.resource))||[];for(const o of i)for(const c of r)o.email===c.email&&s.push({id:`conflict_${++this.conflictIdCounter}`,type:"resource",severity:"critical",eventId:e.id,conflictingEventId:t.id,description:`Resource conflict: ${o.name} is double-booked`,conflictingResource:o.email,metadata:{resourceName:o.name,resourceEmail:o.email}});return s}_checkLocationConflict(e,t){if(!e.location||!t.location)return null;const s=e.location.trim().toLowerCase(),i=t.location.trim().toLowerCase();return s===i?{id:`conflict_${++this.conflictIdCounter}`,type:"location",severity:"high",eventId:e.id,conflictingEventId:t.id,description:`Location conflict: ${e.location} is double-booked`,metadata:{location:e.location}}:null}_buildConflictSummary(e,t,s){const i={},r={};for(const n of e)i[n.type]=(i[n.type]||0)+1,r[n.severity]=(r[n.severity]||0)+1;return{hasConflicts:e.length>0,totalConflicts:e.length,conflicts:e,conflictsByType:i,conflictsBySeverity:r,affectedEventIds:Array.from(t),affectedAttendees:Array.from(s)}}_mergeBusyPeriods(e){if(e.length<=1)return e;e.sort((s,i)=>s.start-i.start);const t=[e[0]];for(let s=1;s<e.length;s++){const i=e[s],r=t[t.length-1];i.start<=r.end?(r.end=new Date(Math.max(r.end.getTime(),i.end.getTime())),r.eventIds.push(...i.eventIds)):t.push(i)}return t}_getAllBusyPeriods(e,t){return this.eventStore.getEventsInRange(e,t,!1).filter(i=>i.status!=="cancelled").map(i=>({start:i.start,end:i.end,eventIds:[i.id]})).sort((i,r)=>i.start-r.start)}_isWithinBusinessHours(e,t,s){const i=e.getHours(),r=t.getHours(),n=parseInt(s.businessHours.start.split(":")[0]),a=parseInt(s.businessHours.end.split(":")[0]);return i>=n&&r<=a}}class Z{constructor(e={}){this.events=new Map,this.indices={byDate:new Map,byMonth:new Map,recurring:new Set,byCategory:new Map,byStatus:new Map},this.timezoneManager=I.getInstance(),this.defaultTimezone=e.timezone||this.timezoneManager.getSystemTimezone(),this.optimizer=new j(e.performance),this.conflictDetector=new W(this),this.isBatchMode=!1,this.batchNotifications=[],this.batchBackup=null,this.version=0,this.listeners=new Set}addEvent(e){return this.optimizer.measure("addEvent",()=>{if(e instanceof E||(e=new E(e)),this.events.has(e.id))throw new Error(`Event with id ${e.id} already exists`);return this.events.set(e.id,e),this.optimizer.cache(e.id,e,"event"),this._indexEvent(e),this.isBatchMode?this.batchNotifications.push({type:"add",event:e,version:++this.version}):this._notifyChange({type:"add",event:e,version:++this.version}),e})}updateEvent(e,t){const s=this.events.get(e);if(!s)throw new Error(`Event with id ${e} not found`);this._unindexEvent(s);const i=s.clone(t);return this.events.set(e,i),this._indexEvent(i),this._notifyChange({type:"update",event:i,oldEvent:s,version:++this.version}),i}removeEvent(e){const t=this.events.get(e);return t?(this.events.delete(e),this._unindexEvent(t),this._notifyChange({type:"remove",event:t,version:++this.version}),!0):!1}getEvent(e){const t=this.optimizer.getFromCache(e,"event");if(t)return t;const s=this.events.get(e)||null;return s&&this.optimizer.cache(e,s,"event"),s}getAllEvents(){return Array.from(this.events.values())}queryEvents(e={}){let t=Array.from(this.events.values());if(e.start||e.end){const s=e.start?new Date(e.start):null,i=e.end?new Date(e.end):null;t=t.filter(r=>!(s&&r.end<s||i&&r.start>i))}if(e.date){const s=new Date(e.date);t=t.filter(i=>i.occursOn(s))}if(e.month&&e.year){const s=`${e.year}-${String(e.month).padStart(2,"0")}`,i=this.indices.byMonth.get(s)||new Set;t=t.filter(r=>i.has(r.id))}return Object.prototype.hasOwnProperty.call(e,"allDay")&&(t=t.filter(s=>s.allDay===e.allDay)),Object.prototype.hasOwnProperty.call(e,"recurring")&&(t=t.filter(s=>s.recurring===e.recurring)),e.status&&(t=t.filter(s=>s.status===e.status)),e.categories&&e.categories.length>0&&(t=t.filter(s=>e.matchAllCategories?s.hasAllCategories(e.categories):s.hasAnyCategory(e.categories))),Object.prototype.hasOwnProperty.call(e,"hasAttendees")&&(t=t.filter(s=>e.hasAttendees?s.hasAttendees:!s.hasAttendees)),e.organizerEmail&&(t=t.filter(s=>s.organizer&&s.organizer.email===e.organizerEmail)),e.sort&&t.sort((s,i)=>{switch(e.sort){case"start":return s.start-i.start;case"end":return s.end-i.end;case"duration":return s.duration-i.duration;case"title":return s.title.localeCompare(i.title);default:return 0}}),t}getEventsForDate(e,t=null){t=t||this.defaultTimezone,f.getLocalDateString(e);const s=new Set,i=new Date(e);for(let l=-1;l<=1;l++){const d=new Date(i);d.setDate(d.getDate()+l);const h=f.getLocalDateString(d),g=this.indices.byDate.get(h);g&&g.forEach(D=>s.add(D))}const r=`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}`,n=this.indices.byMonth.get(r);n&&n.forEach(l=>s.add(l));const a=[],o=new Date(e);o.setHours(0,0,0,0);const c=new Date(e);c.setHours(23,59,59,999);for(const l of s){const d=this.events.get(l);if(d){const h=d.getStartInTimezone(t),g=d.getEndInTimezone(t);h<=c&&g>=o&&a.push(d)}}return a.sort((l,d)=>{const h=l.getStartInTimezone(t),g=d.getStartInTimezone(t),D=h-g;return D!==0?D:d.duration-l.duration})}getOverlappingEvents(e,t,s=null){const i=[],r=f.startOfDay(e),n=f.endOfDay(t),a=f.getDateRange(r,n),o=new Set;return a.forEach(c=>{const l=f.getLocalDateString(c);(this.indices.byDate.get(l)||new Set).forEach(h=>{if(!o.has(h)&&h!==s){o.add(h);const g=this.events.get(h);g&&g.overlaps({start:e,end:t})&&i.push(g)}})}),i.sort((c,l)=>c.start-l.start)}hasConflicts(e,t,s=null){return this.getOverlappingEvents(e,t,s).length>0}getOverlapGroups(e,t=!0){let s=this.getEventsForDate(e);t&&(s=s.filter(n=>!n.allDay));const i=[],r=new Set;return s.forEach(n=>{if(r.has(n.id))return;const a=[n];r.add(n.id);let o=0;for(;o<a.length;){const c=a[o];s.forEach(l=>{!r.has(l.id)&&c.overlaps(l)&&(a.push(l),r.add(l.id))}),o++}i.push(a)}),i}calculateEventPositions(e){const t=new Map;if(e.length===0)return t;e.sort((r,n)=>{const a=r.start-n.start;return a!==0?a:n.end-n.start-(r.end-r.start)});const s=[];e.forEach(r=>{let n=0;for(;n<s.length&&s[n].some(c=>c.overlaps(r));)n++;s[n]||(s[n]=[]),s[n].push(r),t.set(r.id,{column:n,totalColumns:0})});const i=s.length;return t.forEach(r=>{r.totalColumns=i}),t}getEventsInRange(e,t,s=!0,i=null){typeof s=="string"&&(i=s,s=!0),i=i||this.defaultTimezone;const r=this.timezoneManager.toUTC(e,i),n=this.timezoneManager.toUTC(t,i),a=this.queryEvents({start:r,end:n,sort:"start"});if(!s)return a;const o=[];return a.forEach(c=>{if(c.recurring&&c.recurrenceRule){const l=this.expandRecurringEvent(c,e,t,i);o.push(...l)}else o.push(c)}),o.sort((c,l)=>{const d=c.getStartInTimezone(i),h=l.getStartInTimezone(i);return d-h})}expandRecurringEvent(e,t,s,i=null){if(!e.recurring||!e.recurrenceRule)return[e];i=i||this.defaultTimezone;const r=e.timeZone||i;return Y.expandEvent(e,t,s).map((a,o)=>e.clone({id:`${e.id}_occurrence_${o}`,start:a.start,end:a.end,timeZone:r,metadata:{...e.metadata,recurringEventId:e.id,occurrenceIndex:o}}))}clear(){const e=this.getAllEvents();this.events.clear(),this.indices.byDate.clear(),this.indices.byMonth.clear(),this.indices.recurring.clear(),this._notifyChange({type:"clear",oldEvents:e,version:++this.version})}loadEvents(e){this.clear();for(const t of e)this.addEvent(t)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}_indexEvent(e){if(this.optimizer.shouldUseLazyIndexing(e)){this._indexEventLazy(e);return}const t=e.getStartInTimezone(e.timeZone),s=e.getEndInTimezone(e.endTimeZone||e.timeZone),i=f.startOfDay(t),r=f.endOfDay(s);f.getDateRange(i,r).forEach(o=>{const c=f.getLocalDateString(o);this.indices.byDate.has(c)||this.indices.byDate.set(c,new Set),this.indices.byDate.get(c).add(e.id)}),`${i.getFullYear()}${String(i.getMonth()+1).padStart(2,"0")}`,`${r.getFullYear()}${String(r.getMonth()+1).padStart(2,"0")}`;const a=new Date(i.getFullYear(),i.getMonth(),1);for(;a<=r;){const o=`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}`;this.indices.byMonth.has(o)||this.indices.byMonth.set(o,new Set),this.indices.byMonth.get(o).add(e.id),a.setMonth(a.getMonth()+1)}e.categories&&e.categories.length>0&&e.categories.forEach(o=>{this.indices.byCategory.has(o)||this.indices.byCategory.set(o,new Set),this.indices.byCategory.get(o).add(e.id)}),e.status&&(this.indices.byStatus.has(e.status)||this.indices.byStatus.set(e.status,new Set),this.indices.byStatus.get(e.status).add(e.id)),e.recurring&&this.indices.recurring.add(e.id)}_indexEventLazy(e){this.optimizer.createLazyIndexMarkers(e);const t=e.getStartInTimezone(e.timeZone),s=e.getEndInTimezone(e.endTimeZone||e.timeZone),i=f.startOfDay(t),r=f.endOfDay(s),n=new Date(i);if(n.setDate(n.getDate()+7),f.getDateRange(i,n<r?n:r).forEach(c=>{const l=f.getLocalDateString(c);this.indices.byDate.has(l)||this.indices.byDate.set(l,new Set),this.indices.byDate.get(l).add(e.id)}),r>n){const c=new Date(r);c.setDate(c.getDate()-7),f.getDateRange(c>i?c:i,r).forEach(d=>{const h=f.getLocalDateString(d);this.indices.byDate.has(h)||this.indices.byDate.set(h,new Set),this.indices.byDate.get(h).add(e.id)})}const o=new Date(i.getFullYear(),i.getMonth(),1);for(;o<=r;){const c=`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}`;this.indices.byMonth.has(c)||this.indices.byMonth.set(c,new Set),this.indices.byMonth.get(c).add(e.id),o.setMonth(o.getMonth()+1)}e.categories&&e.categories.length>0&&e.categories.forEach(c=>{this.indices.byCategory.has(c)||this.indices.byCategory.set(c,new Set),this.indices.byCategory.get(c).add(e.id)}),e.status&&(this.indices.byStatus.has(e.status)||this.indices.byStatus.set(e.status,new Set),this.indices.byStatus.get(e.status).add(e.id)),e.recurring&&this.indices.recurring.add(e.id)}_unindexEvent(e){for(const[t,s]of this.indices.byDate)s.delete(e.id),s.size===0&&this.indices.byDate.delete(t);for(const[t,s]of this.indices.byMonth)s.delete(e.id),s.size===0&&this.indices.byMonth.delete(t);this.indices.recurring.delete(e.id)}_notifyChange(e){for(const t of this.listeners)try{t(e)}catch(s){console.error("Error in EventStore listener:",s)}}getStats(){return{totalEvents:this.events.size,recurringEvents:this.indices.recurring.size,indexedDates:this.indices.byDate.size,indexedMonths:this.indices.byMonth.size,indexedCategories:this.indices.byCategory.size,indexedStatuses:this.indices.byStatus.size,version:this.version,performanceMetrics:this.optimizer.getMetrics()}}startBatch(e=!1){this.isBatchMode=!0,this.batchNotifications=[],e&&(this.batchBackup={events:new Map(this.events),indices:{byDate:new Map(Array.from(this.indices.byDate.entries()).map(([t,s])=>[t,new Set(s)])),byMonth:new Map(Array.from(this.indices.byMonth.entries()).map(([t,s])=>[t,new Set(s)])),recurring:new Set(this.indices.recurring),byCategory:new Map(Array.from(this.indices.byCategory.entries()).map(([t,s])=>[t,new Set(s)])),byStatus:new Map(Array.from(this.indices.byStatus.entries()).map(([t,s])=>[t,new Set(s)]))},version:this.version})}commitBatch(){this.isBatchMode&&(this.isBatchMode=!1,this.batchBackup=null,this.batchNotifications.length>0&&this._notifyChange({type:"batch",changes:this.batchNotifications,count:this.batchNotifications.length,version:++this.version}),this.batchNotifications=[])}rollbackBatch(){this.isBatchMode&&(this.isBatchMode=!1,this.batchBackup&&(this.events=this.batchBackup.events,this.indices=this.batchBackup.indices,this.version=this.batchBackup.version,this.batchBackup=null,this.optimizer.clearCache()),this.batchNotifications=[])}async executeBatch(e,t=!0){this.startBatch(t);try{const s=await e();return this.commitBatch(),s}catch(s){throw t&&this.rollbackBatch(),s}}addEvents(e){return this.optimizer.measure("addEvents",()=>{this.startBatch();const t=[],s=[];for(const i of e)try{t.push(this.addEvent(i))}catch(r){s.push({event:i,error:r.message})}return this.commitBatch(),s.length>0&&console.warn(`Failed to add ${s.length} events:`,s),t})}updateEvents(e){return this.optimizer.measure("updateEvents",()=>{this.startBatch();const t=[],s=[];for(const{id:i,updates:r}of e)try{t.push(this.updateEvent(i,r))}catch(n){s.push({id:i,error:n.message})}return this.commitBatch(),s.length>0&&console.warn(`Failed to update ${s.length} events:`,s),t})}removeEvents(e){return this.optimizer.measure("removeEvents",()=>{this.startBatch();let t=0;for(const s of e)this.removeEvent(s)&&t++;return this.commitBatch(),t})}getPerformanceMetrics(){return this.optimizer.getMetrics()}clearCaches(){this.optimizer.eventCache.clear(),this.optimizer.queryCache.clear(),this.optimizer.dateRangeCache.clear()}optimizeIndices(e){e||(e=new Date,e.setMonth(e.getMonth()-6)),e.toDateString();let t=0;for(const[s,i]of this.indices.byDate)if(new Date(s)<e){let n=!1;for(const a of i){const o=this.events.get(a);if(o&&o.end>=e){n=!0;break}}n||(this.indices.byDate.delete(s),t++)}return console.log(`Optimized indices: removed ${t} old date entries`),t}destroy(){this.clear(),this.optimizer.destroy(),this.listeners.clear()}checkConflicts(e,t={}){return this.conflictDetector.checkConflicts(e,t)}checkEventPairConflicts(e,t,s={}){const i=this.getEvent(e),r=this.getEvent(t);if(!i||!r)throw new Error("One or both events not found");return this.conflictDetector.checkEventPairConflicts(i,r,s)}getAllConflicts(e,t,s={}){const i=this.getEventsInRange(e,t,!1),r=[],n=new Set;for(let a=0;a<i.length;a++)for(let o=a+1;o<i.length;o++){const c=`${i[a].id}-${i[o].id}`;if(!n.has(c)){n.add(c);const l=this.conflictDetector.checkEventPairConflicts(i[a],i[o],s);r.push(...l)}}return this.conflictDetector._buildConflictSummary(r,new Set(i.map(a=>a.id)),new Set)}getBusyPeriods(e,t,s,i={}){return this.conflictDetector.getBusyPeriods(e,t,s,i)}getFreePeriods(e,t,s,i={}){return this.conflictDetector.getFreePeriods(e,t,s,i)}addEventWithConflictCheck(e,t=!0){const s=this.checkConflicts(e);if(!t&&s.hasConflicts)throw new Error(`Cannot add event: ${s.totalConflicts} conflicts detected`);return{event:this.addEvent(e),conflicts:s}}findEventsWithConflicts(e={}){const t=[],s=this.getAllEvents();for(const i of s){const r=this.checkConflicts(i,e);r.hasConflicts&&t.push({event:i,conflicts:r.conflicts})}return t}}let q=class{constructor(e={}){this.state={view:"month",currentDate:new Date,selectedEventId:null,selectedDate:null,hoveredEventId:null,hoveredDate:null,weekStartsOn:0,showWeekNumbers:!1,showWeekends:!0,fixedWeekCount:!0,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,locale:"en-US",hourFormat:"12h",businessHours:{start:"09:00",end:"17:00"},filters:{searchTerm:"",categories:[],showAllDay:!0,showTimed:!0},isDragging:!1,isResizing:!1,isCreating:!1,isLoading:!1,loadingMessage:"",error:null,metadata:{},...e},this.listeners=new Map,this.globalListeners=new Set,this.history=[],this.historyIndex=-1,this.maxHistorySize=50}getState(){return Object.freeze({...this.state})}get(e){return this.state[e]}setState(e){const t=this.state;typeof e=="function"&&(e=e(t));const s={...t,...e,filters:e.filters?{...t.filters,...e.filters}:t.filters,businessHours:e.businessHours?{...t.businessHours,...e.businessHours}:t.businessHours,metadata:e.metadata?{...t.metadata,...e.metadata}:t.metadata};this._hasChanged(t,s)&&(this.state=s,this._addToHistory(s),this._notifyListeners(t,s))}setView(e){const t=["month","week","day","list"];if(!t.includes(e))throw new Error(`Invalid view: ${e}. Must be one of: ${t.join(", ")}`);this.setState({view:e})}setCurrentDate(e){if(e instanceof Date||(e=new Date(e)),isNaN(e.getTime()))throw new Error("Invalid date");this.setState({currentDate:e})}navigateNext(){const{view:e,currentDate:t}=this.state,s=new Date(t);switch(e){case"month":s.setMonth(s.getMonth()+1);break;case"week":s.setDate(s.getDate()+7);break;case"day":s.setDate(s.getDate()+1);break}this.setCurrentDate(s)}navigatePrevious(){const{view:e,currentDate:t}=this.state,s=new Date(t);switch(e){case"month":s.setMonth(s.getMonth()-1);break;case"week":s.setDate(s.getDate()-7);break;case"day":s.setDate(s.getDate()-1);break}this.setCurrentDate(s)}navigateToday(){this.setCurrentDate(new Date)}selectEvent(e){this.setState({selectedEventId:e})}clearEventSelection(){this.setState({selectedEventId:null})}selectDate(e){e instanceof Date||(e=new Date(e)),this.setState({selectedDate:e})}clearDateSelection(){this.setState({selectedDate:null})}setLoading(e,t=""){this.setState({isLoading:e,loadingMessage:t})}setError(e){this.setState({error:e?e instanceof Error?e.message:e:null})}updateFilters(e){this.setState({filters:{...this.state.filters,...e}})}subscribe(e){return this.globalListeners.add(e),()=>{this.globalListeners.delete(e)}}watch(e,t){const s=Array.isArray(e)?e:[e];return s.forEach(i=>{this.listeners.has(i)||this.listeners.set(i,new Set),this.listeners.get(i).add(t)}),()=>{s.forEach(i=>{const r=this.listeners.get(i);r&&(r.delete(t),r.size===0&&this.listeners.delete(i))})}}canUndo(){return this.historyIndex>0}canRedo(){return this.historyIndex<this.history.length-1}getUndoCount(){return this.historyIndex}getRedoCount(){return this.history.length-1-this.historyIndex}undo(){if(!this.canUndo())return!1;this.historyIndex--;const e=this.history[this.historyIndex],t=this.state;return this.state={...e},this._notifyListeners(t,this.state),!0}redo(){if(!this.canRedo())return!1;this.historyIndex++;const e=this.history[this.historyIndex],t=this.state;return this.state={...e},this._notifyListeners(t,this.state),!0}reset(){const e=this.history[0]||{};this.setState(e),this.history=[e],this.historyIndex=0}_hasChanged(e,t){return!this._deepEqual(e,t)}_deepEqual(e,t,s=new Set){if(e===t)return!0;if(e==null||t==null)return e===t;if(typeof e!=typeof t)return!1;if(typeof e!="object")return e===t;if(s.has(e)||s.has(t))return!1;if(s.add(e),s.add(t),Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return s.delete(e),s.delete(t),!1;for(let n=0;n<e.length;n++)if(!this._deepEqual(e[n],t[n],s))return s.delete(e),s.delete(t),!1;return s.delete(e),s.delete(t),!0}if(e instanceof Date&&t instanceof Date){const n=e.getTime()===t.getTime();return s.delete(e),s.delete(t),n}const i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return s.delete(e),s.delete(t),!1;i.sort(),r.sort();for(let n=0;n<i.length;n++)if(i[n]!==r[n])return s.delete(e),s.delete(t),!1;for(const n of i)if(!this._deepEqual(e[n],t[n],s))return s.delete(e),s.delete(t),!1;return s.delete(e),s.delete(t),!0}_addToHistory(e){this.historyIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyIndex+1));const t=this._deepClone(e);this.history.push(t),this.historyIndex++,this.history.length>this.maxHistorySize&&(this.history.shift(),this.historyIndex--)}_deepClone(e){if(e===null||typeof e!="object")return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return e.map(s=>this._deepClone(s));const t={};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(t[s]=this._deepClone(e[s]));return t}_notifyListeners(e,t){for(const s of this.globalListeners)try{s(t,e)}catch(i){console.error("Error in state listener:",i)}for(const[s,i]of this.listeners)if(e[s]!==t[s])for(const r of i)try{r(t[s],e[s],t,e)}catch(n){console.error(`Error in state listener for key "${s}":`,n)}}};class K{constructor(e={}){this.timezoneManager=I.getInstance(),this.config={view:"month",date:new Date,weekStartsOn:0,locale:"en-US",timeZone:e.timeZone||this.timezoneManager.getSystemTimezone(),showWeekNumbers:!1,showWeekends:!0,fixedWeekCount:!0,businessHours:{start:"09:00",end:"17:00"},...e},this.eventStore=new Z({timezone:this.config.timeZone}),this.state=new q({view:this.config.view,currentDate:this.config.date,weekStartsOn:this.config.weekStartsOn,locale:this.config.locale,timeZone:this.config.timeZone,showWeekNumbers:this.config.showWeekNumbers,showWeekends:this.config.showWeekends,fixedWeekCount:this.config.fixedWeekCount,businessHours:this.config.businessHours}),this.listeners=new Map,this.plugins=new Set,this.views=new Map,this._setupInternalListeners(),e.events&&this.setEvents(e.events)}setView(e,t=null){this.state.setView(e),t&&this.state.setCurrentDate(t),this._emit("viewChange",{view:e,date:t||this.state.get("currentDate")})}getView(){return this.state.get("view")}next(){this.state.navigateNext(),this._emit("navigate",{direction:"next",date:this.state.get("currentDate"),view:this.state.get("view")})}previous(){this.state.navigatePrevious(),this._emit("navigate",{direction:"previous",date:this.state.get("currentDate"),view:this.state.get("view")})}today(){this.state.navigateToday(),this._emit("navigate",{direction:"today",date:this.state.get("currentDate"),view:this.state.get("view")})}goToDate(e){this.state.setCurrentDate(e),this._emit("navigate",{direction:"goto",date:e,view:this.state.get("view")})}setDate(e){this.goToDate(e)}getCurrentDate(){return new Date(this.state.get("currentDate"))}addEvent(e){!(e instanceof E)&&!e.timeZone&&(e={...e,timeZone:this.config.timeZone});const t=this.eventStore.addEvent(e);return this._emit("eventAdd",{event:t}),t}updateEvent(e,t){const s=this.eventStore.getEvent(e),i=this.eventStore.updateEvent(e,t);return this._emit("eventUpdate",{event:i,oldEvent:s}),i}removeEvent(e){const t=this.eventStore.getEvent(e),s=this.eventStore.removeEvent(e);return s&&this._emit("eventRemove",{event:t}),s}deleteEvent(e){return this.removeEvent(e)}getEvent(e){return this.eventStore.getEvent(e)}getEvents(){return this.eventStore.getAllEvents()}setEvents(e){this.eventStore.loadEvents(e),this._emit("eventsSet",{events:this.getEvents()})}queryEvents(e){return this.eventStore.queryEvents(e)}getEventsForDate(e,t=null){return this.eventStore.getEventsForDate(e,t||this.config.timeZone)}getEventsInRange(e,t,s=null){return this.eventStore.getEventsInRange(e,t,!0,s||this.config.timeZone)}setTimezone(e){const t=this.timezoneManager.parseTimezone(e),s=this.config.timeZone;this.config.timeZone=t,this.eventStore.defaultTimezone=t,this.state.setState({timeZone:t}),this._emit("timezoneChange",{timezone:t,previousTimezone:s})}getTimezone(){return this.config.timeZone}setLocale(e){this.config.locale=e,this.state.setState({locale:e}),this._emit("localeChange",{locale:e})}setWeekStartsOn(e){this.config.weekStartsOn=e,this.state.setState({weekStartsOn:e}),this._emit("weekStartsOnChange",{weekStartsOn:e})}convertTimezone(e,t,s){return this.timezoneManager.convertTimezone(e,t,s)}toCalendarTimezone(e,t){return this.timezoneManager.convertTimezone(e,t,this.config.timeZone)}fromCalendarTimezone(e,t){return this.timezoneManager.convertTimezone(e,this.config.timeZone,t)}formatInTimezone(e,t=null,s={}){return this.timezoneManager.formatInTimezone(e,t||this.config.timeZone,s)}getTimezones(){return this.timezoneManager.getCommonTimezones()}getOverlapGroups(e,t=!0){return this.eventStore.getOverlapGroups(e,t)}calculateEventPositions(e){return this.eventStore.calculateEventPositions(e)}getViewData(){const e=this.state.get("view"),t=this.state.get("currentDate");switch(e){case"month":return this._getMonthViewData(t);case"week":return this._getWeekViewData(t);case"day":return this._getDayViewData(t);case"list":return this._getListViewData(t);default:return null}}_getMonthViewData(e){const t=e.getFullYear(),s=e.getMonth(),i=this.state.get("weekStartsOn"),r=this.state.get("fixedWeekCount"),n=new Date(t,s,1),a=new Date(t,s+1,0),o=f.startOfWeek(n,i),c=[];let l=new Date(o);const d=r?6:Math.ceil((a.getDate()+f.getDayOfWeek(n,i))/7);for(let h=0;h<d;h++){const g={weekNumber:f.getWeekNumber(l),days:[]};for(let D=0;D<7;D++){const u=new Date(l),T=u.getMonth()===s,b=f.isToday(u),C=u.getDay()===0||u.getDay()===6;g.days.push({date:u,dayOfMonth:u.getDate(),isCurrentMonth:T,isToday:b,isWeekend:C,events:this.getEventsForDate(u)}),l=f.addDays(l,1)}c.push(g)}return{type:"month",year:t,month:s,monthName:f.getMonthName(e,this.state.get("locale")),weeks:c,startDate:o,endDate:new Date(l.getTime()-1)}}_getWeekViewData(e){const t=this.state.get("weekStartsOn"),s=f.startOfWeek(e,t),i=f.endOfWeek(e,t),r=[],n=new Date(s);for(let a=0;a<7;a++){const o=new Date(n);r.push({date:o,dayOfMonth:o.getDate(),dayOfWeek:o.getDay(),dayName:f.getDayName(o,this.state.get("locale")),isToday:f.isToday(o),isWeekend:o.getDay()===0||o.getDay()===6,events:this.getEventsForDate(o),overlapGroups:this.eventStore.getOverlapGroups(o,!0),getEventPositions:c=>this.eventStore.calculateEventPositions(c)}),n.setDate(n.getDate()+1)}return{type:"week",weekNumber:f.getWeekNumber(s),startDate:s,endDate:i,days:r}}_getDayViewData(e){const t=this.getEventsForDate(e),s=t.filter(n=>n.allDay),i=t.filter(n=>!n.allDay),r=[];for(let n=0;n<24;n++){const a=new Date(e);a.setHours(n,0,0,0);const o=new Date(e);o.setHours(n+1,0,0,0),r.push({hour:n,time:f.formatTime(a,this.state.get("locale")),events:i.filter(c=>c.start<o&&c.end>a)})}return{type:"day",date:e,dayName:f.getDayName(e,this.state.get("locale")),isToday:f.isToday(e),allDayEvents:s,hours:r}}_getListViewData(e){const t=new Date(e);t.setHours(0,0,0,0);const s=new Date(t);s.setDate(s.getDate()+30);const i=this.getEventsInRange(t,s),r=new Map;i.forEach(a=>{const o=a.start.toDateString();r.has(o)||r.set(o,{date:new Date(a.start),events:[]}),r.get(o).events.push(a)});const n=Array.from(r.values()).sort((a,o)=>a.date-o.date).map(a=>({...a,dayName:f.getDayName(a.date,this.state.get("locale")),isToday:f.isToday(a.date)}));return{type:"list",startDate:t,endDate:s,days:n,totalEvents:i.length}}selectEvent(e){const t=this.getEvent(e);t&&(this.state.selectEvent(e),this._emit("eventSelect",{event:t}))}clearEventSelection(){const e=this.state.get("selectedEventId");this.state.clearEventSelection(),e&&this._emit("eventDeselect",{eventId:e})}selectDate(e){this.state.selectDate(e),this._emit("dateSelect",{date:e})}clearDateSelection(){const e=this.state.get("selectedDate");this.state.clearDateSelection(),e&&this._emit("dateDeselect",{date:e})}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){const s=this.listeners.get(e);s&&(s.delete(t),s.size===0&&this.listeners.delete(e))}_emit(e,t){const s=this.listeners.get(e);s&&s.forEach(i=>{try{i(t)}catch(r){console.error(`Error in event listener for "${e}":`,r)}})}_setupInternalListeners(){this.state.subscribe((e,t)=>{this._emit("stateChange",{newState:e,oldState:t})}),this.eventStore.subscribe(e=>{this._emit("eventStoreChange",e)})}use(e){if(this.plugins.has(e)){console.warn("Plugin already installed");return}if(typeof e.install=="function")e.install(this),this.plugins.add(e);else throw new Error("Plugin must have an install method")}destroy(){this.listeners.clear(),this.eventStore.destroy(),this.plugins.forEach(e=>{typeof e.uninstall=="function"&&e.uninstall(this)}),this.plugins.clear(),this.views.clear(),this._emit("destroy")}}class O{constructor(){this.events=new Map,this.wildcardHandlers=new Set}on(e,t,s={}){const{once:i=!1,priority:r=0}=s;if(e.includes("*")){const o={pattern:e,handler:t,once:i,priority:r};return this.wildcardHandlers.add(o),()=>this.wildcardHandlers.delete(o)}this.events.has(e)||this.events.set(e,[]);const n={handler:t,once:i,priority:r},a=this.events.get(e);return a.push(n),a.sort((o,c)=>c.priority-o.priority),()=>{const o=a.indexOf(n);o>-1&&a.splice(o,1)}}once(e,t,s={}){return this.on(e,t,{...s,once:!0})}off(e,t){if(!this.events.has(e))return;const s=this.events.get(e),i=s.findIndex(r=>r.handler===t);i>-1&&s.splice(i,1),s.length===0&&this.events.delete(e)}async emit(e,t){const s=[];if(this.events.has(e)){const r=[...this.events.get(e)];for(const n of r){const{handler:a,once:o}=n;o&&this.off(e,a);try{const c=a(t,e);c instanceof Promise&&s.push(c)}catch(c){console.error(`Error in event handler for ${e}:`,c)}}}const i=[];for(const r of[...this.wildcardHandlers])if(this.matchesPattern(e,r.pattern)){const{handler:n,once:a}=r;a&&i.push(r);try{const o=n(t,e);o instanceof Promise&&s.push(o)}catch(o){console.error(`Error in wildcard handler for ${e}:`,o)}}return i.forEach(r=>this.wildcardHandlers.delete(r)),Promise.all(s)}matchesPattern(e,t){return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)}clear(){this.events.clear(),this.wildcardHandlers.clear()}getEventNames(){return Array.from(this.events.keys())}getHandlerCount(e){return this.events.has(e)?this.events.get(e).length:0}}const p=new O;class R{constructor(e={}){this.calendar=new K({view:e.view||"month",date:e.date||new Date,weekStartsOn:e.weekStartsOn??0,locale:e.locale||"en-US",timeZone:e.timeZone||Intl.DateTimeFormat().resolvedOptions().timeZone,...e}),this.state={view:this.calendar.getView(),currentDate:this.calendar.getCurrentDate(),events:[],selectedEvent:null,selectedDate:null,loading:!1,error:null,config:{...e}},this.subscribers=new Set,this.subscribe=this.subscribe.bind(this),this.unsubscribe=this.unsubscribe.bind(this),this.setState=this.setState.bind(this)}getState(){return{...this.state}}setState(e,t={}){const{silent:s=!1}=t,i={...this.state};return this.state={...this.state,...e},s||(this.notifySubscribers(i,this.state),this.emitStateChange(i,this.state)),this.state}subscribe(e){return this.subscribers.add(e),()=>this.unsubscribe(e)}unsubscribe(e){this.subscribers.delete(e)}notifySubscribers(e,t){this.subscribers.forEach(s=>{try{s(t,e)}catch(i){console.error("Error in state subscriber:",i)}})}emitStateChange(e,t){const s=Object.keys(t).filter(i=>e[i]!==t[i]);s.forEach(i=>{p.emit(`state:${i}:changed`,{oldValue:e[i],newValue:t[i],state:t})}),s.length>0&&p.emit("state:changed",{oldState:e,newState:t,changedKeys:s})}setView(e){this.calendar.setView(e),this.setState({view:e}),p.emit("view:changed",{view:e})}getView(){return this.state.view}setDate(e){this.calendar.goToDate(e),this.setState({currentDate:this.calendar.getCurrentDate()}),p.emit("date:changed",{date:this.state.currentDate})}getCurrentDate(){return this.state.currentDate}next(){this.calendar.next(),this.setState({currentDate:this.calendar.getCurrentDate()}),p.emit("navigation:next",{date:this.state.currentDate})}previous(){this.calendar.previous(),this.setState({currentDate:this.calendar.getCurrentDate()}),p.emit("navigation:previous",{date:this.state.currentDate})}today(){this.calendar.today(),this.setState({currentDate:this.calendar.getCurrentDate()}),p.emit("navigation:today",{date:this.state.currentDate})}goToDate(e){this.calendar.goToDate(e),this.setState({currentDate:this.calendar.getCurrentDate()}),p.emit("navigation:goto",{date:this.state.currentDate})}addEvent(e){const t=this.calendar.addEvent(e);if(!t)return console.error("Failed to add event to calendar"),p.emit("event:error",{action:"add",event:e,error:"Failed to add event"}),null;const s=[...this.state.events,t];return this.setState({events:s}),p.emit("event:added",{event:t}),t}updateEvent(e,t){const s=this.calendar.updateEvent(e,t);if(!s)return console.error(`Failed to update event: ${e}`),p.emit("event:error",{action:"update",eventId:e,updates:t,error:"Event not found in calendar"}),null;const i=this.state.events.findIndex(n=>n.id===e);if(i===-1)return console.error(`Event ${e} not found in state`),p.emit("event:error",{action:"update",eventId:e,error:"Event not found in state"}),null;const r=[...this.state.events];return r[i]=s,this.setState({events:r}),p.emit("event:updated",{event:s}),s}deleteEvent(e){if(!this.calendar.removeEvent(e))return console.error(`Failed to delete event: ${e}`),p.emit("event:error",{action:"delete",eventId:e,error:"Event not found"}),!1;const s=this.state.events.filter(i=>i.id!==e);return this.setState({events:s}),p.emit("event:deleted",{eventId:e}),!0}getEvents(){return this.calendar.getEvents()}getEventsForDate(e){return this.calendar.getEventsForDate(e)}getEventsInRange(e,t){return this.calendar.getEventsInRange(e,t)}getViewData(){const e=this.calendar.getViewData();return this.enrichViewData(e)}enrichViewData(e){var s;const t=(s=this.state.selectedDate)==null?void 0:s.toDateString();if(e.weeks&&(e.weeks=e.weeks.map(i=>({...i,days:i.days.map(r=>{const n=new Date(r.date);return{...r,isSelected:n.toDateString()===t,events:r.events||this.getEventsForDate(n)}})}))),e.days&&(e.days=e.days.map(i=>{const r=new Date(i.date);return{...i,isSelected:r.toDateString()===t,events:i.events||this.getEventsForDate(r)}})),e.date&&!e.days&&!e.weeks){const i=new Date(e.date);e.isSelected=i.toDateString()===t,e.events=e.events||this.getEventsForDate(i)}return e}selectEvent(e){this.setState({selectedEvent:e}),p.emit("event:selected",{event:e})}selectEventById(e){const t=this.state.events.find(s=>s.id===e);t&&this.selectEvent(t)}deselectEvent(){this.setState({selectedEvent:null}),p.emit("event:deselected",{})}selectDate(e){this.setState({selectedDate:e}),p.emit("date:selected",{date:e})}deselectDate(){this.setState({selectedDate:null}),p.emit("date:deselected",{})}isToday(e){const t=new Date;return e.toDateString()===t.toDateString()}isSelectedDate(e){return this.state.selectedDate&&e.toDateString()===this.state.selectedDate.toDateString()}isWeekend(e){const t=e.getDay();return t===0||t===6}setLoading(e){this.setState({loading:e})}setError(e){this.setState({error:e}),e&&p.emit("error",{error:e})}clearError(){this.setState({error:null})}updateConfig(e){this.setState({config:{...this.state.config,...e}}),e.weekStartsOn!==void 0&&this.calendar.setWeekStartsOn(e.weekStartsOn),e.locale!==void 0&&this.calendar.setLocale(e.locale),e.timeZone!==void 0&&this.calendar.setTimezone(e.timeZone)}destroy(){this.subscribers.clear(),this.state=null,this.calendar=null}}class w extends f{static formatDate(e,t="default",s="en-US"){if(!e)return"";const i={default:{year:"numeric",month:"long",day:"numeric"},short:{year:"numeric",month:"short",day:"numeric"},long:{weekday:"long",year:"numeric",month:"long",day:"numeric"},month:{year:"numeric",month:"long"},monthShort:{year:"numeric",month:"short"},day:{weekday:"long",day:"numeric"},dayShort:{weekday:"short",day:"numeric"},time:{hour:"numeric",minute:"2-digit"},timeShort:{hour:"numeric"},datetime:{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}},r=i[t]||i.default;return new Intl.DateTimeFormat(s,r).format(e)}static formatTime(e,t=!0,s=!1,i="en-US"){if(!e)return"";const r={hour:"numeric",minute:t?"2-digit":void 0,hour12:!s};return new Intl.DateTimeFormat(i,r).format(e)}static formatDateRange(e,t,s="en-US"){if(!e)return"";if(!t||this.isSameDay(e,t))return this.formatDate(e,"default",s);const i=this.isSameYear(e,t)?"short":"default";return`${this.formatDate(e,i,s)} - ${this.formatDate(t,"default",s)}`}static formatTimeRange(e,t,s="en-US"){if(!e)return"";const i=this.formatTime(e,!0,!1,s);if(!t)return i;const r=this.formatTime(t,!0,!1,s);return`${i} - ${r}`}static getRelativeTime(e,t=new Date,s="en-US"){const i=new Intl.RelativeTimeFormat(s,{numeric:"auto"}),r=e-t,n=Math.floor(r/1e3),a=Math.floor(n/60),o=Math.floor(a/60),c=Math.floor(o/24),l=Math.floor(c/7),d=Math.floor(c/30),h=Math.floor(c/365);return Math.abs(n)<60?i.format(n,"second"):Math.abs(a)<60?i.format(a,"minute"):Math.abs(o)<24?i.format(o,"hour"):Math.abs(c)<7?i.format(c,"day"):Math.abs(l)<4?i.format(l,"week"):Math.abs(d)<12?i.format(d,"month"):i.format(h,"year")}static isToday(e){const t=new Date;return this.isSameDay(e,t)}static isPast(e){return e<new Date}static isFuture(e){return e>new Date}static getWeekNumber(e){const t=new Date(e.getFullYear(),0,1),s=(e-t)/864e5;return Math.ceil((s+t.getDay()+1)/7)}static getDayAbbreviation(e,t="en-US"){const s=new Date(2024,0,7+e);return new Intl.DateTimeFormat(t,{weekday:"short"}).format(s)}static getMonthName(e,t="long",s="en-US"){const i=new Date(2024,e,1);return new Intl.DateTimeFormat(s,{month:t}).format(i)}static parseTimeString(e,t=new Date){const s=new Date(t),[i,r]=e.split(/\s+/),[n,a]=i.split(":").map(Number);let o=n;return r&&(r.toLowerCase()==="pm"&&n<12?o=n+12:r.toLowerCase()==="am"&&n===12&&(o=0)),s.setHours(o,a||0,0,0),s}}class S{static createElement(e,t={},s=[]){const i=document.createElement(e);return Object.entries(t).forEach(([r,n])=>{if(r==="className")i.className=n;else if(r==="style"&&typeof n=="object")Object.assign(i.style,n);else if(r.startsWith("data-"))i.setAttribute(r,n);else if(r.startsWith("on")&&typeof n=="function"){const a=r.slice(2).toLowerCase();i.addEventListener(a,n)}else i[r]=n}),s.forEach(r=>{typeof r=="string"?i.appendChild(document.createTextNode(r)):r instanceof Node&&i.appendChild(r)}),i}static addEventListeners(e,t){return Object.entries(t).forEach(([s,i])=>{e.addEventListener(s,i)}),()=>{Object.entries(t).forEach(([s,i])=>{e.removeEventListener(s,i)})}}static delegate(e,t,s,i){const r=n=>{const a=n.target.closest(t);a&&e.contains(a)&&i.call(a,n)};return e.addEventListener(s,r),()=>e.removeEventListener(s,r)}static getPosition(e){const t=e.getBoundingClientRect();return{top:t.top+window.scrollY,left:t.left+window.scrollX,bottom:t.bottom+window.scrollY,right:t.right+window.scrollX,width:t.width,height:t.height}}static isInViewport(e,t=0){const s=e.getBoundingClientRect();return s.top>=-t&&s.left>=-t&&s.bottom<=(window.innerHeight||document.documentElement.clientHeight)+t&&s.right<=(window.innerWidth||document.documentElement.clientWidth)+t}static scrollToElement(e,t={}){const{behavior:s="smooth",block:i="start",inline:r="nearest"}=t;e.scrollIntoView({behavior:s,block:i,inline:r})}static getStyle(e,t){return window.getComputedStyle(e).getPropertyValue(t)}static setStyles(e,t){Object.assign(e.style,t)}static async animateClass(e,t,s=300){e.classList.add(t),await this.wait(s),e.classList.remove(t)}static waitForAnimation(e,t="animationend"){return new Promise(s=>{const i=()=>{e.removeEventListener(t,i),s()};e.addEventListener(t,i)})}static wait(e){return new Promise(t=>setTimeout(t,e))}static parseHTML(e){const t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstChild}static escapeHTML(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}static debounce(e,t=250){let s;return function(...r){const n=()=>{clearTimeout(s),e(...r)};clearTimeout(s),s=setTimeout(n,t)}}static throttle(e,t=250){let s;return function(...i){s||(e.apply(this,i),s=!0,setTimeout(()=>s=!1,t))}}static closest(e,t){return e.closest(t)}static parents(e,t){const s=[];let i=e.parentElement;for(;i;)i.matches(t)&&s.push(i),i=i.parentElement;return s}static getOuterDimensions(e){const t=window.getComputedStyle(e),s={top:parseInt(t.marginTop),right:parseInt(t.marginRight),bottom:parseInt(t.marginBottom),left:parseInt(t.marginLeft)};return{width:e.offsetWidth+s.left+s.right,height:e.offsetHeight+s.top+s.bottom,margin:s}}static cloneWithEvents(e,t=!0){return e.cloneNode(t)}static trapFocus(e){const t=e.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(t.length===0)return e.setAttribute("tabindex","-1"),e.focus(),()=>e.removeAttribute("tabindex");const s=t[0],i=t[t.length-1],r=n=>{n.key==="Tab"&&(n.shiftKey?document.activeElement===s&&(i==null||i.focus(),n.preventDefault()):document.activeElement===i&&(s==null||s.focus(),n.preventDefault()))};return e.addEventListener("keydown",r),s==null||s.focus(),()=>e.removeEventListener("keydown",r)}}class y{static getCSSVariable(e,t=document.documentElement){return getComputedStyle(t).getPropertyValue(e).trim()}static setCSSVariables(e,t=document.documentElement){Object.entries(e).forEach(([s,i])=>{t.style.setProperty(s,i)})}static getBaseStyles(){return`
16
16
  :host {
17
17
  /* Apply CSS variables */
18
18
  ${Object.entries(this.cssVariables).map(([e,t])=>`${e}: ${t};`).join(`
@@ -149,7 +149,7 @@
149
149
  padding: 0;
150
150
  border-radius: var(--fc-border-radius-full);
151
151
  }
152
- `}static darken(e,t){const s=parseInt(e.replace("#",""),16),i=Math.round(2.55*t),r=(s>>16)-i,a=(s>>8&255)-i,n=(s&255)-i;return"#"+(16777216+(r<255?r<1?0:r:255)*65536+(a<255?a<1?0:a:255)*256+(n<255?n<1?0:n:255)).toString(16).slice(1)}static lighten(e,t){const s=parseInt(e.replace("#",""),16),i=Math.round(2.55*t),r=(s>>16)+i,a=(s>>8&255)+i,n=(s&255)+i;return"#"+(16777216+(r<255?r<1?0:r:255)*65536+(a<255?a<1?0:a:255)*256+(n<255?n<1?0:n:255)).toString(16).slice(1)}static getContrastColor(e){const t=e.replace("#",""),s=parseInt(t.substr(0,2),16),i=parseInt(t.substr(2,2),16),r=parseInt(t.substr(4,2),16);return(s*299+i*587+r*114)/1e3>=128?"#000000":"#FFFFFF"}static sanitizeColor(e,t="var(--fc-primary-color)"){if(!e||typeof e!="string")return t;const s=e.trim();return/[;{}()<>\"\'\\]/.test(s)?t:/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/.test(s)||/^var\(--[a-zA-Z0-9-]+\)$/.test(s)||/^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(,\s*(0|1|0?\.\d+))?\s*\)$/.test(s)||["transparent","currentColor","inherit","black","white","red","green","blue","yellow","orange","purple","pink","brown","gray","grey","cyan","magenta","lime","navy","teal","aqua","maroon","olive","silver","fuchsia"].includes(s.toLowerCase())?s:t}static hexToRgba(e,t=1){const s=e.replace("#",""),i=parseInt(s.substr(0,2),16),r=parseInt(s.substr(2,2),16),a=parseInt(s.substr(4,2),16);return`rgba(${i}, ${r}, ${a}, ${t})`}static getGridStyles(){return`
152
+ `}static darken(e,t){const s=parseInt(e.replace("#",""),16),i=Math.round(2.55*t),r=(s>>16)-i,n=(s>>8&255)-i,a=(s&255)-i;return"#"+(16777216+(r<255?r<1?0:r:255)*65536+(n<255?n<1?0:n:255)*256+(a<255?a<1?0:a:255)).toString(16).slice(1)}static lighten(e,t){const s=parseInt(e.replace("#",""),16),i=Math.round(2.55*t),r=(s>>16)+i,n=(s>>8&255)+i,a=(s&255)+i;return"#"+(16777216+(r<255?r<1?0:r:255)*65536+(n<255?n<1?0:n:255)*256+(a<255?a<1?0:a:255)).toString(16).slice(1)}static getContrastColor(e){const t=e.replace("#",""),s=parseInt(t.substr(0,2),16),i=parseInt(t.substr(2,2),16),r=parseInt(t.substr(4,2),16);return(s*299+i*587+r*114)/1e3>=128?"#000000":"#FFFFFF"}static sanitizeColor(e,t="var(--fc-primary-color)"){if(!e||typeof e!="string")return t;const s=e.trim();return/[;{}()<>\"\'\\]/.test(s)?t:/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/.test(s)||/^var\(--[a-zA-Z0-9-]+\)$/.test(s)||/^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(,\s*(0|1|0?\.\d+))?\s*\)$/.test(s)||["transparent","currentColor","inherit","black","white","red","green","blue","yellow","orange","purple","pink","brown","gray","grey","cyan","magenta","lime","navy","teal","aqua","maroon","olive","silver","fuchsia"].includes(s.toLowerCase())?s:t}static hexToRgba(e,t=1){const s=e.replace("#",""),i=parseInt(s.substr(0,2),16),r=parseInt(s.substr(2,2),16),n=parseInt(s.substr(4,2),16);return`rgba(${i}, ${r}, ${n}, ${t})`}static getGridStyles(){return`
153
153
  .fc-grid {
154
154
  display: grid;
155
155
  gap: 1px;
@@ -235,7 +235,7 @@
235
235
  .fc-scale-in {
236
236
  animation: fc-scale-in var(--fc-transition);
237
237
  }
238
- `}}I(y,"colors",{primary:"#3B82F6",secondary:"#64748B",accent:"#F59E0B",danger:"#EF4444",warning:"#F97316",info:"#06B6D4",success:"#22C55E",light:"#F8FAFC",dark:"#0F172A",white:"#FFFFFF",gray:{50:"#F8FAFC",100:"#F1F5F9",200:"#E2E8F0",300:"#CBD5E1",400:"#94A3B8",500:"#64748B",600:"#475569",700:"#334155",800:"#1E293B",900:"#0F172A"}}),I(y,"cssVariables",{"--fc-primary-color":"#2563EB","--fc-primary-hover":"#1D4ED8","--fc-primary-light":"#EFF6FF","--fc-text-color":"#111827","--fc-text-secondary":"#6B7280","--fc-text-light":"#9CA3AF","--fc-border-color":"#E5E7EB","--fc-border-color-hover":"#D1D5DB","--fc-background":"#FFFFFF","--fc-background-alt":"#FAFAFA","--fc-background-hover":"#F3F4F6","--fc-background-active":"#E5E7EB","--fc-accent-color":"#F59E0B","--fc-danger-color":"#EF4444","--fc-success-color":"#10B981","--fc-font-family":'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"--fc-font-size-xs":"11px","--fc-font-size-sm":"12px","--fc-font-size-base":"13px","--fc-font-size-lg":"15px","--fc-font-size-xl":"18px","--fc-font-size-2xl":"24px","--fc-line-height":"1.4","--fc-font-weight-normal":"400","--fc-font-weight-medium":"500","--fc-font-weight-semibold":"600","--fc-font-weight-bold":"700","--fc-spacing-xs":"2px","--fc-spacing-sm":"6px","--fc-spacing-md":"10px","--fc-spacing-lg":"14px","--fc-spacing-xl":"20px","--fc-spacing-2xl":"28px","--fc-border-width":"1px","--fc-border-radius-sm":"3px","--fc-border-radius":"5px","--fc-border-radius-lg":"8px","--fc-border-radius-full":"9999px","--fc-shadow-sm":"0 1px 1px rgba(0,0,0,0.05)","--fc-shadow":"0 1px 3px rgba(0,0,0,0.1), 0 1px 2px rgba(0,0,0,0.06)","--fc-shadow-md":"0 4px 6px -1px rgba(0, 0, 0, 0.1)","--fc-shadow-lg":"0 10px 15px -3px rgba(0, 0, 0, 0.1)","--fc-transition-fast":"100ms ease-out","--fc-transition":"150ms ease-out","--fc-transition-slow":"250ms ease-out","--fc-z-dropdown":"1000","--fc-z-modal":"2000","--fc-z-tooltip":"3000"}),I(y,"breakpoints",{xs:"320px",sm:"576px",md:"768px",lg:"992px",xl:"1200px","2xl":"1400px"});class F extends k{constructor(){super(),this._stateManager=null,this.viewData=null,this.config={maxEventsToShow:3},this._registryCheckInterval=null}connectedCallback(){super.connectedCallback(),console.log("[MonthView] connectedCallback - starting registry polling"),this._startRegistryPolling()}disconnectedCallback(){super.disconnectedCallback(),this._stopRegistryPolling()}_startRegistryPolling(){this._checkRegistry();let e=0;this._registryCheckInterval=setInterval(()=>{if(e++,this._stateManager||e>50){this._stopRegistryPolling();return}this._checkRegistry()},100)}_stopRegistryPolling(){this._registryCheckInterval&&(clearInterval(this._registryCheckInterval),this._registryCheckInterval=null)}_checkRegistry(){const e=this.getAttribute("data-state-registry");if(console.log("[MonthView] Checking registry for ID:",e),e&&window.__forceCalendarRegistry&&window.__forceCalendarRegistry[e]){const t=window.__forceCalendarRegistry[e];console.log("[MonthView] Found stateManager in registry"),this._stopRegistryPolling(),this.setStateManager(t)}}set stateManager(e){console.log("[MonthView] stateManager setter called with:",!!e),this.setStateManager(e)}setStateManager(e){if(console.log("[MonthView] setStateManager method called with:",!!e),this._stateManager===e){console.log("[MonthView] stateManager already set, skipping");return}this._stateManager=e,e&&(console.log("[MonthView] Subscribing to state changes and loading view data"),this.unsubscribe=e.subscribe(this.handleStateUpdate.bind(this)),this.loadViewData())}get stateManager(){return this._stateManager}handleStateUpdate(e,t){if(e.currentDate!==t.currentDate){this.loadViewData();return}e.events!==t.events&&this.updateEvents(),e.selectedDate!==t.selectedDate&&this.updateSelection(e.selectedDate,t.selectedDate)}updateEvents(){this.loadViewData()}updateSelection(e,t){if(t){const s=this.shadowRoot.querySelector(`[data-date^="${t.toISOString().split("T")[0]}"]`);s&&s.classList.remove("selected")}if(e){const s=this.shadowRoot.querySelector(`[data-date^="${e.toISOString().split("T")[0]}"]`);s&&s.classList.add("selected")}}loadViewData(){if(console.log("[MonthView] loadViewData called, stateManager:",!!this.stateManager),!this.stateManager)return;const e=this.stateManager.getViewData();console.log("[MonthView] viewData from stateManager:",e),this.viewData=this.processViewData(e),console.log("[MonthView] processed viewData:",this.viewData),this.render(),console.log("[MonthView] render completed")}processViewData(e){var i,r;if(!e||!e.weeks)return null;const t=(r=(i=this.stateManager)==null?void 0:i.getState())==null?void 0:r.selectedDate,s=e.weeks.map(a=>a.days.map(n=>{const o=new Date(n.date),c=t&&o.toDateString()===t.toDateString(),l=n.events.map(d=>({...d,textColor:this.getContrastingTextColor(d.backgroundColor)}));return{...n,date:o,isOtherMonth:!n.isCurrentMonth,isSelected:c,events:l}}));return{...e,weeks:s,month:e.month,year:e.year}}getContrastingTextColor(e){if(!e||typeof e!="string")return"white";const t=e.charAt(0)==="#"?e.substring(1):e;if(!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(t))return"white";const s=t.length===3?t[0]+t[0]+t[1]+t[1]+t[2]+t[2]:t,i=parseInt(s.substring(0,2),16),r=parseInt(s.substring(2,4),16),a=parseInt(s.substring(4,6),16);if(isNaN(i)||isNaN(r)||isNaN(a))return"white";const o=[i/255,r/255,a/255].map(l=>l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4));return .2126*o[0]+.7152*o[1]+.0722*o[2]>.179?"black":"white"}isSelectedDate(e){var s,i;const t=(i=(s=this.stateManager)==null?void 0:s.getState())==null?void 0:i.selectedDate;return t&&e.toDateString()===t.toDateString()}getStyles(){return`
238
+ `}}L(y,"colors",{primary:"#3B82F6",secondary:"#64748B",accent:"#F59E0B",danger:"#EF4444",warning:"#F97316",info:"#06B6D4",success:"#22C55E",light:"#F8FAFC",dark:"#0F172A",white:"#FFFFFF",gray:{50:"#F8FAFC",100:"#F1F5F9",200:"#E2E8F0",300:"#CBD5E1",400:"#94A3B8",500:"#64748B",600:"#475569",700:"#334155",800:"#1E293B",900:"#0F172A"}}),L(y,"cssVariables",{"--fc-primary-color":"#2563EB","--fc-primary-hover":"#1D4ED8","--fc-primary-light":"#EFF6FF","--fc-text-color":"#111827","--fc-text-secondary":"#6B7280","--fc-text-light":"#9CA3AF","--fc-border-color":"#E5E7EB","--fc-border-color-hover":"#D1D5DB","--fc-background":"#FFFFFF","--fc-background-alt":"#FAFAFA","--fc-background-hover":"#F3F4F6","--fc-background-active":"#E5E7EB","--fc-accent-color":"#F59E0B","--fc-danger-color":"#EF4444","--fc-success-color":"#10B981","--fc-font-family":'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"--fc-font-size-xs":"11px","--fc-font-size-sm":"12px","--fc-font-size-base":"13px","--fc-font-size-lg":"15px","--fc-font-size-xl":"18px","--fc-font-size-2xl":"24px","--fc-line-height":"1.4","--fc-font-weight-normal":"400","--fc-font-weight-medium":"500","--fc-font-weight-semibold":"600","--fc-font-weight-bold":"700","--fc-spacing-xs":"2px","--fc-spacing-sm":"6px","--fc-spacing-md":"10px","--fc-spacing-lg":"14px","--fc-spacing-xl":"20px","--fc-spacing-2xl":"28px","--fc-border-width":"1px","--fc-border-radius-sm":"3px","--fc-border-radius":"5px","--fc-border-radius-lg":"8px","--fc-border-radius-full":"9999px","--fc-shadow-sm":"0 1px 1px rgba(0,0,0,0.05)","--fc-shadow":"0 1px 3px rgba(0,0,0,0.1), 0 1px 2px rgba(0,0,0,0.06)","--fc-shadow-md":"0 4px 6px -1px rgba(0, 0, 0, 0.1)","--fc-shadow-lg":"0 10px 15px -3px rgba(0, 0, 0, 0.1)","--fc-transition-fast":"100ms ease-out","--fc-transition":"150ms ease-out","--fc-transition-slow":"250ms ease-out","--fc-z-dropdown":"1000","--fc-z-modal":"2000","--fc-z-tooltip":"3000"}),L(y,"breakpoints",{xs:"320px",sm:"576px",md:"768px",lg:"992px",xl:"1200px","2xl":"1400px"});class H extends k{constructor(){super(),this._stateManager=null,this.viewData=null,this.config={maxEventsToShow:3},this._registryCheckInterval=null}connectedCallback(){super.connectedCallback(),console.log("[MonthView] connectedCallback - starting registry polling"),this._startRegistryPolling()}disconnectedCallback(){super.disconnectedCallback(),this._stopRegistryPolling()}_startRegistryPolling(){this._checkRegistry();let e=0;this._registryCheckInterval=setInterval(()=>{if(e++,this._stateManager||e>50){this._stopRegistryPolling();return}this._checkRegistry()},100)}_stopRegistryPolling(){this._registryCheckInterval&&(clearInterval(this._registryCheckInterval),this._registryCheckInterval=null)}_checkRegistry(){const e=this.getAttribute("data-state-registry");if(console.log("[MonthView] Checking registry for ID:",e),e&&window.__forceCalendarRegistry&&window.__forceCalendarRegistry[e]){const t=window.__forceCalendarRegistry[e];console.log("[MonthView] Found stateManager in registry"),this._stopRegistryPolling(),this.setStateManager(t)}}set stateManager(e){console.log("[MonthView] stateManager setter called with:",!!e),this.setStateManager(e)}setStateManager(e){if(console.log("[MonthView] setStateManager method called with:",!!e),this._stateManager===e){console.log("[MonthView] stateManager already set, skipping");return}this._stateManager=e,e&&(console.log("[MonthView] Subscribing to state changes and loading view data"),this.unsubscribe=e.subscribe(this.handleStateUpdate.bind(this)),this.loadViewData())}get stateManager(){return this._stateManager}handleStateUpdate(e,t){if(e.currentDate!==t.currentDate){this.loadViewData();return}e.events!==t.events&&this.updateEvents(),e.selectedDate!==t.selectedDate&&this.updateSelection(e.selectedDate,t.selectedDate)}updateEvents(){this.loadViewData()}updateSelection(e,t){if(t){const s=this.shadowRoot.querySelector(`[data-date^="${t.toISOString().split("T")[0]}"]`);s&&s.classList.remove("selected")}if(e){const s=this.shadowRoot.querySelector(`[data-date^="${e.toISOString().split("T")[0]}"]`);s&&s.classList.add("selected")}}loadViewData(){if(console.log("[MonthView] loadViewData called, stateManager:",!!this.stateManager),!this.stateManager)return;const e=this.stateManager.getViewData();console.log("[MonthView] viewData from stateManager:",e),this.viewData=this.processViewData(e),console.log("[MonthView] processed viewData:",this.viewData),this.render(),console.log("[MonthView] render completed")}processViewData(e){var i,r;if(!e||!e.weeks)return null;const t=(r=(i=this.stateManager)==null?void 0:i.getState())==null?void 0:r.selectedDate,s=e.weeks.map(n=>n.days.map(a=>{const o=new Date(a.date),c=t&&o.toDateString()===t.toDateString(),l=a.events.map(d=>({...d,textColor:this.getContrastingTextColor(d.backgroundColor)}));return{...a,date:o,isOtherMonth:!a.isCurrentMonth,isSelected:c,events:l}}));return{...e,weeks:s,month:e.month,year:e.year}}getContrastingTextColor(e){if(!e||typeof e!="string")return"white";const t=e.charAt(0)==="#"?e.substring(1):e;if(!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(t))return"white";const s=t.length===3?t[0]+t[0]+t[1]+t[1]+t[2]+t[2]:t,i=parseInt(s.substring(0,2),16),r=parseInt(s.substring(2,4),16),n=parseInt(s.substring(4,6),16);if(isNaN(i)||isNaN(r)||isNaN(n))return"white";const o=[i/255,r/255,n/255].map(l=>l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4));return .2126*o[0]+.7152*o[1]+.0722*o[2]>.179?"black":"white"}isSelectedDate(e){var s,i;const t=(i=(s=this.stateManager)==null?void 0:s.getState())==null?void 0:i.selectedDate;return t&&e.toDateString()===t.toDateString()}getStyles(){return`
239
239
  :host {
240
240
  display: block;
241
241
  height: 100%;
@@ -460,7 +460,7 @@
460
460
  <div class="month-view">
461
461
  <div class="month-loading">Loading calendar...</div>
462
462
  </div>
463
- `}renderHeader(){const{config:e}=this.stateManager.getState(),t=[],s=e.weekStartsOn||0;for(let i=0;i<7;i++){const r=(s+i)%7,a=w.getDayAbbreviation(r,e.locale);t.push(`<div class="month-header-cell">${a}</div>`)}return`
463
+ `}renderHeader(){const{config:e}=this.stateManager.getState(),t=[],s=e.weekStartsOn||0;for(let i=0;i<7;i++){const r=(s+i)%7,n=w.getDayAbbreviation(r,e.locale);t.push(`<div class="month-header-cell">${n}</div>`)}return`
464
464
  <div class="month-header">
465
465
  ${t.join("")}
466
466
  </div>
@@ -481,7 +481,7 @@
481
481
  <div class="month-week">
482
482
  ${e.map(s=>this.renderDay(s)).join("")}
483
483
  </div>
484
- `}renderDay(e){const{date:t,dayOfMonth:s,isOtherMonth:i,isToday:r,isSelected:a,isWeekend:n,events:o=[]}=e,c=s,l=["month-day"];i&&l.push("other-month"),r&&l.push("today"),a&&l.push("selected"),n&&l.push("weekend");const d=o.slice(0,this.config.maxEventsToShow),h=o.length-this.config.maxEventsToShow,g=d.map(f=>this.renderEvent(f)).join(""),b=h>0?`<div class="more-events">+${h} more</div>`:"";return`
484
+ `}renderDay(e){const{date:t,dayOfMonth:s,isOtherMonth:i,isToday:r,isSelected:n,isWeekend:a,events:o=[]}=e,c=s,l=["month-day"];i&&l.push("other-month"),r&&l.push("today"),n&&l.push("selected"),a&&l.push("weekend");const d=o.slice(0,this.config.maxEventsToShow),h=o.length-this.config.maxEventsToShow,g=d.map(u=>this.renderEvent(u)).join(""),D=h>0?`<div class="more-events">+${h} more</div>`:"";return`
485
485
  <div class="${l.join(" ")}"
486
486
  data-date="${t.toISOString()}"
487
487
  data-day="${c}">
@@ -490,18 +490,18 @@
490
490
  </div>
491
491
  <div class="day-events">
492
492
  ${g}
493
- ${b}
493
+ ${D}
494
494
  </div>
495
495
  </div>
496
- `}renderEvent(e){const{title:t,start:s,allDay:i,backgroundColor:r,textColor:a}=e;let n="";if(r){const l=y.sanitizeColor(r),d=y.sanitizeColor(a,"white");n+=`background-color: ${l}; color: ${d};`}let o="";!i&&s&&(o=w.formatTime(new Date(s),!1,!1));const c=["event-item"];return i&&c.push("all-day"),`
496
+ `}renderEvent(e){const{title:t,start:s,allDay:i,backgroundColor:r,textColor:n}=e;let a="";if(r){const l=y.sanitizeColor(r),d=y.sanitizeColor(n,"white");a+=`background-color: ${l}; color: ${d};`}let o="";!i&&s&&(o=w.formatTime(new Date(s),!1,!1));const c=["event-item"];return i&&c.push("all-day"),`
497
497
  <div class="${c.join(" ")}"
498
- style="${n}"
498
+ style="${a}"
499
499
  data-event-id="${e.id}"
500
- title="${E.escapeHTML(t)}">
500
+ title="${S.escapeHTML(t)}">
501
501
  ${o?`<span class="event-time">${o}</span>`:""}
502
- <span class="event-title">${E.escapeHTML(t)}</span>
502
+ <span class="event-title">${S.escapeHTML(t)}</span>
503
503
  </div>
504
- `}afterRender(){this.$$(".month-day").forEach(e=>{this.addListener(e,"click",this.handleDayClick)}),this.$$(".event-item").forEach(e=>{this.addListener(e,"click",this.handleEventClick)}),this.$$(".more-events").forEach(e=>{this.addListener(e,"click",this.handleMoreClick)})}handleDayClick(e){e.stopPropagation();const t=e.currentTarget,s=new Date(t.dataset.date);this.stateManager.selectDate(s),this.emit("day-click",{date:s})}handleEventClick(e){e.stopPropagation();const s=e.currentTarget.dataset.eventId,i=this.stateManager.getEvents().find(r=>r.id===s);i&&(this.stateManager.selectEvent(i),this.emit("event-click",{event:i}))}handleMoreClick(e){e.stopPropagation();const t=e.currentTarget.closest(".month-day"),s=new Date(t.dataset.date),i=this.stateManager.getEventsForDate(s);this.emit("more-events-click",{date:s,events:i})}unmount(){this.unsubscribe&&this.unsubscribe()}}class O extends k{constructor(){super(),this._stateManager=null,this.viewData=null,this.hours=Array.from({length:24},(e,t)=>t),this._registryCheckInterval=null}connectedCallback(){super.connectedCallback(),this._startRegistryPolling()}disconnectedCallback(){super.disconnectedCallback(),this._registryCheckInterval&&clearInterval(this._registryCheckInterval)}_startRegistryPolling(){this._checkRegistry();let e=0;this._registryCheckInterval=setInterval(()=>{if(e++,this._stateManager||e>50){clearInterval(this._registryCheckInterval);return}this._checkRegistry()},100)}_checkRegistry(){const e=this.getAttribute("data-state-registry");e&&window.__forceCalendarRegistry&&window.__forceCalendarRegistry[e]&&(clearInterval(this._registryCheckInterval),this.setStateManager(window.__forceCalendarRegistry[e]))}set stateManager(e){this.setStateManager(e)}setStateManager(e){this._stateManager!==e&&(this._stateManager=e,e&&(this.unsubscribe=e.subscribe(this.handleStateUpdate.bind(this)),this.loadViewData()))}get stateManager(){return this._stateManager}handleStateUpdate(e,t){if(e.currentDate!==(t==null?void 0:t.currentDate)||e.view!==(t==null?void 0:t.view)){this.loadViewData();return}e.events!==(t==null?void 0:t.events)&&this.loadViewData(),e.selectedDate!==(t==null?void 0:t.selectedDate)&&this.updateSelection(e.selectedDate,t==null?void 0:t.selectedDate)}updateSelection(e,t){if(t){const s=this.shadowRoot.querySelector(`[data-date^="${t.toISOString().split("T")[0]}"]`);s&&s.classList.remove("selected")}if(e){const s=this.shadowRoot.querySelector(`[data-date^="${e.toISOString().split("T")[0]}"]`);s&&s.classList.add("selected")}}loadViewData(){if(!this.stateManager)return;const e=this.stateManager.getViewData();this.viewData=this.processViewData(e),this.render()}processViewData(e){if(!e)return null;let t=[];return e.weeks&&e.weeks.length>0?t=e.weeks[0].days:e.days&&(t=e.days),!t||t.length===0?null:{...e,days:t.map(s=>{const i=new Date(s.date);return{...s,date:i,isToday:w.isToday(i),timedEvents:(s.events||[]).filter(r=>!r.allDay),allDayEvents:(s.events||[]).filter(r=>r.allDay)}})}}getStyles(){return`
504
+ `}afterRender(){this.$$(".month-day").forEach(e=>{this.addListener(e,"click",this.handleDayClick)}),this.$$(".event-item").forEach(e=>{this.addListener(e,"click",this.handleEventClick)}),this.$$(".more-events").forEach(e=>{this.addListener(e,"click",this.handleMoreClick)})}handleDayClick(e){e.stopPropagation();const t=e.currentTarget,s=new Date(t.dataset.date);this.stateManager.selectDate(s),this.emit("day-click",{date:s})}handleEventClick(e){e.stopPropagation();const s=e.currentTarget.dataset.eventId,i=this.stateManager.getEvents().find(r=>r.id===s);i&&(this.stateManager.selectEvent(i),this.emit("event-click",{event:i}))}handleMoreClick(e){e.stopPropagation();const t=e.currentTarget.closest(".month-day"),s=new Date(t.dataset.date),i=this.stateManager.getEventsForDate(s);this.emit("more-events-click",{date:s,events:i})}unmount(){this.unsubscribe&&this.unsubscribe()}}class B extends k{constructor(){super(),this._stateManager=null,this.viewData=null,this.hours=Array.from({length:24},(e,t)=>t),this._registryCheckInterval=null}connectedCallback(){super.connectedCallback(),this._startRegistryPolling()}disconnectedCallback(){super.disconnectedCallback(),this._registryCheckInterval&&clearInterval(this._registryCheckInterval)}_startRegistryPolling(){this._checkRegistry();let e=0;this._registryCheckInterval=setInterval(()=>{if(e++,this._stateManager||e>50){clearInterval(this._registryCheckInterval);return}this._checkRegistry()},100)}_checkRegistry(){const e=this.getAttribute("data-state-registry");e&&window.__forceCalendarRegistry&&window.__forceCalendarRegistry[e]&&(clearInterval(this._registryCheckInterval),this.setStateManager(window.__forceCalendarRegistry[e]))}set stateManager(e){this.setStateManager(e)}setStateManager(e){this._stateManager!==e&&(this._stateManager=e,e&&(this.unsubscribe=e.subscribe(this.handleStateUpdate.bind(this)),this.loadViewData()))}get stateManager(){return this._stateManager}handleStateUpdate(e,t){if(e.currentDate!==(t==null?void 0:t.currentDate)||e.view!==(t==null?void 0:t.view)){this.loadViewData();return}e.events!==(t==null?void 0:t.events)&&this.loadViewData(),e.selectedDate!==(t==null?void 0:t.selectedDate)&&this.updateSelection(e.selectedDate,t==null?void 0:t.selectedDate)}updateSelection(e,t){if(t){const s=this.shadowRoot.querySelector(`[data-date^="${t.toISOString().split("T")[0]}"]`);s&&s.classList.remove("selected")}if(e){const s=this.shadowRoot.querySelector(`[data-date^="${e.toISOString().split("T")[0]}"]`);s&&s.classList.add("selected")}}loadViewData(){if(!this.stateManager)return;const e=this.stateManager.getViewData();this.viewData=this.processViewData(e),this.render()}processViewData(e){if(!e)return null;let t=[];return e.weeks&&e.weeks.length>0?t=e.weeks[0].days:e.days&&(t=e.days),!t||t.length===0?null:{...e,days:t.map(s=>{const i=new Date(s.date);return{...s,date:i,isToday:w.isToday(i),timedEvents:(s.events||[]).filter(r=>!r.allDay),allDayEvents:(s.events||[]).filter(r=>r.allDay)}})}}getStyles(){return`
505
505
  :host {
506
506
  display: flex;
507
507
  flex-direction: column;
@@ -723,20 +723,20 @@
723
723
  `).join("")}
724
724
  </div>
725
725
  </div>
726
- `:'<div class="week-view">Loading...</div>'}renderTimedEvent(e){const t=new Date(e.start),s=new Date(e.end),i=t.getHours()*60+t.getMinutes(),r=(s-t)/(1e3*60),a=i,n=Math.max(r,20),o=y.sanitizeColor(e.backgroundColor),c=y.sanitizeColor(y.getContrastColor(o),"white");return`
726
+ `:'<div class="week-view">Loading...</div>'}renderTimedEvent(e){const t=new Date(e.start),s=new Date(e.end),i=t.getHours()*60+t.getMinutes(),r=(s-t)/(1e3*60),n=i,a=Math.max(r,20),o=y.sanitizeColor(e.backgroundColor),c=y.sanitizeColor(y.getContrastColor(o),"white");return`
727
727
  <div class="event-container"
728
- style="top: ${a}px; height: ${n}px; background-color: ${o}; color: ${c};"
728
+ style="top: ${n}px; height: ${a}px; background-color: ${o}; color: ${c};"
729
729
  data-event-id="${e.id}">
730
- <span class="event-title">${E.escapeHTML(e.title)}</span>
730
+ <span class="event-title">${S.escapeHTML(e.title)}</span>
731
731
  <span class="event-time">${w.formatTime(t)}</span>
732
732
  </div>
733
733
  `}renderAllDayEvent(e){const t=y.sanitizeColor(e.backgroundColor),s=y.sanitizeColor(y.getContrastColor(t),"white");return`
734
734
  <div class="event-item"
735
735
  style="background-color: ${t}; color: ${s}; font-size: 10px; padding: 2px 4px; border-radius: 2px; cursor: pointer; margin-bottom: 2px;"
736
736
  data-event-id="${e.id}">
737
- ${E.escapeHTML(e.title)}
737
+ ${S.escapeHTML(e.title)}
738
738
  </div>
739
- `}renderNowIndicator(){const e=new Date;return`<div class="now-indicator" style="top: ${e.getHours()*60+e.getMinutes()}px"></div>`}afterRender(){const e=this.$("#scroll-container");e&&!this._scrolled&&(e.scrollTop=8*60-50,this._scrolled=!0),this.$$("[data-event-id]").forEach(t=>{this.addListener(t,"click",s=>{s.stopPropagation();const i=s.currentTarget.dataset.eventId,r=this.stateManager.getEvents().find(a=>a.id===i);r&&this.emit("event-click",{event:r})})}),this.$$(".day-column").forEach(t=>{this.addListener(t,"click",s=>{const i=s.currentTarget,r=this.$("#scroll-container"),a=i.getBoundingClientRect(),n=s.clientY-a.top+(r?r.scrollTop:0),o=new Date(i.dataset.date);o.setHours(Math.floor(n/60),Math.floor(n%60),0,0),this.stateManager.selectDate(o),this.emit("day-click",{date:o})})})}unmount(){this.unsubscribe&&this.unsubscribe()}}class R extends k{constructor(){super(),this._stateManager=null,this.viewData=null,this.hours=Array.from({length:24},(e,t)=>t),this._registryCheckInterval=null}connectedCallback(){super.connectedCallback(),this._startRegistryPolling()}disconnectedCallback(){super.disconnectedCallback(),this._registryCheckInterval&&clearInterval(this._registryCheckInterval)}_startRegistryPolling(){this._checkRegistry();let e=0;this._registryCheckInterval=setInterval(()=>{if(e++,this._stateManager||e>50){clearInterval(this._registryCheckInterval);return}this._checkRegistry()},100)}_checkRegistry(){const e=this.getAttribute("data-state-registry");e&&window.__forceCalendarRegistry&&window.__forceCalendarRegistry[e]&&(clearInterval(this._registryCheckInterval),this.setStateManager(window.__forceCalendarRegistry[e]))}set stateManager(e){this.setStateManager(e)}setStateManager(e){this._stateManager!==e&&(this._stateManager=e,e&&(this.unsubscribe=e.subscribe(this.handleStateUpdate.bind(this)),this.loadViewData()))}get stateManager(){return this._stateManager}handleStateUpdate(e,t){if(e.currentDate!==(t==null?void 0:t.currentDate)||e.view!==(t==null?void 0:t.view)){this.loadViewData();return}e.events!==(t==null?void 0:t.events)&&this.loadViewData(),e.selectedDate!==(t==null?void 0:t.selectedDate)&&this.updateSelection(e.selectedDate,t==null?void 0:t.selectedDate)}updateSelection(e,t){const s=this.shadowRoot.querySelector(".day-column");if(!s)return;(r=>r&&w.isSameDay(r,new Date(s.dataset.date)))(e)?s.classList.add("selected"):s.classList.remove("selected")}loadViewData(){if(!this.stateManager)return;const e=this.stateManager.getViewData();this.viewData=this.processViewData(e),this.render()}processViewData(e){var a;if(!e)return null;let t=null;const s=(a=this.stateManager)==null?void 0:a.getState(),i=(s==null?void 0:s.currentDate)||new Date;if(e.days&&Array.isArray(e.days)&&e.days.length>0)t=e.days.find(n=>w.isSameDay(new Date(n.date),i))||e.days[0];else if(e.weeks&&Array.isArray(e.weeks)&&e.weeks.length>0){const n=e.weeks.flatMap(o=>o.days||[]);t=n.find(o=>w.isSameDay(new Date(o.date),i))||n[0]}else e.date&&(t=e);if(!t)return null;const r=new Date(t.date);return{...e,day:{...t,date:r,isToday:w.isToday(r),timedEvents:(t.events||[]).filter(n=>!n.allDay),allDayEvents:(t.events||[]).filter(n=>n.allDay)}}}getStyles(){return`
739
+ `}renderNowIndicator(){const e=new Date;return`<div class="now-indicator" style="top: ${e.getHours()*60+e.getMinutes()}px"></div>`}afterRender(){const e=this.$("#scroll-container");e&&!this._scrolled&&(e.scrollTop=8*60-50,this._scrolled=!0),this.$$("[data-event-id]").forEach(t=>{this.addListener(t,"click",s=>{s.stopPropagation();const i=s.currentTarget.dataset.eventId,r=this.stateManager.getEvents().find(n=>n.id===i);r&&this.emit("event-click",{event:r})})}),this.$$(".day-column").forEach(t=>{this.addListener(t,"click",s=>{const i=s.currentTarget,r=this.$("#scroll-container"),n=i.getBoundingClientRect(),a=s.clientY-n.top+(r?r.scrollTop:0),o=new Date(i.dataset.date);o.setHours(Math.floor(a/60),Math.floor(a%60),0,0),this.stateManager.selectDate(o),this.emit("day-click",{date:o})})})}unmount(){this.unsubscribe&&this.unsubscribe()}}class P extends k{constructor(){super(),this._stateManager=null,this.viewData=null,this.hours=Array.from({length:24},(e,t)=>t),this._registryCheckInterval=null}connectedCallback(){super.connectedCallback(),this._startRegistryPolling()}disconnectedCallback(){super.disconnectedCallback(),this._registryCheckInterval&&clearInterval(this._registryCheckInterval)}_startRegistryPolling(){this._checkRegistry();let e=0;this._registryCheckInterval=setInterval(()=>{if(e++,this._stateManager||e>50){clearInterval(this._registryCheckInterval);return}this._checkRegistry()},100)}_checkRegistry(){const e=this.getAttribute("data-state-registry");e&&window.__forceCalendarRegistry&&window.__forceCalendarRegistry[e]&&(clearInterval(this._registryCheckInterval),this.setStateManager(window.__forceCalendarRegistry[e]))}set stateManager(e){this.setStateManager(e)}setStateManager(e){this._stateManager!==e&&(this._stateManager=e,e&&(this.unsubscribe=e.subscribe(this.handleStateUpdate.bind(this)),this.loadViewData()))}get stateManager(){return this._stateManager}handleStateUpdate(e,t){if(e.currentDate!==(t==null?void 0:t.currentDate)||e.view!==(t==null?void 0:t.view)){this.loadViewData();return}e.events!==(t==null?void 0:t.events)&&this.loadViewData(),e.selectedDate!==(t==null?void 0:t.selectedDate)&&this.updateSelection(e.selectedDate,t==null?void 0:t.selectedDate)}updateSelection(e,t){const s=this.shadowRoot.querySelector(".day-column");if(!s)return;(r=>r&&w.isSameDay(r,new Date(s.dataset.date)))(e)?s.classList.add("selected"):s.classList.remove("selected")}loadViewData(){if(!this.stateManager)return;const e=this.stateManager.getViewData();this.viewData=this.processViewData(e),this.render()}processViewData(e){var n;if(!e)return null;let t=null;const s=(n=this.stateManager)==null?void 0:n.getState(),i=(s==null?void 0:s.currentDate)||new Date;if(e.days&&Array.isArray(e.days)&&e.days.length>0)t=e.days.find(a=>w.isSameDay(new Date(a.date),i))||e.days[0];else if(e.weeks&&Array.isArray(e.weeks)&&e.weeks.length>0){const a=e.weeks.flatMap(o=>o.days||[]);t=a.find(o=>w.isSameDay(new Date(o.date),i))||a[0]}else e.date&&(t=e);if(!t)return null;const r=new Date(t.date);return{...e,day:{...t,date:r,isToday:w.isToday(r),timedEvents:(t.events||[]).filter(a=>!a.allDay),allDayEvents:(t.events||[]).filter(a=>a.allDay)}}}getStyles(){return`
740
740
  :host {
741
741
  display: flex;
742
742
  flex-direction: column;
@@ -901,7 +901,7 @@
901
901
  z-index: 15;
902
902
  pointer-events: none;
903
903
  }
904
- `}template(){var i,r,a;if(!this.viewData||!this.viewData.day)return'<div class="day-view" style="padding: 20px; color: var(--fc-text-light);">No data available.</div>';const{day:e}=this.viewData,t=((a=(r=(i=this.stateManager)==null?void 0:i.state)==null?void 0:r.config)==null?void 0:a.locale)||"en-US",s=w.formatDate(e.date,"day",t).split(" ")[0];return`
904
+ `}template(){var i,r,n;if(!this.viewData||!this.viewData.day)return'<div class="day-view" style="padding: 20px; color: var(--fc-text-light);">No data available.</div>';const{day:e}=this.viewData,t=((n=(r=(i=this.stateManager)==null?void 0:i.state)==null?void 0:r.config)==null?void 0:n.locale)||"en-US",s=w.formatDate(e.date,"day",t).split(" ")[0];return`
905
905
  <div class="day-view">
906
906
  <div class="day-header">
907
907
  <div class="time-gutter-header"></div>
@@ -914,7 +914,7 @@
914
914
  <div class="all-day-row">
915
915
  <div class="all-day-label">All day</div>
916
916
  <div class="all-day-cell">
917
- ${e.allDayEvents.map(n=>this.renderAllDayEvent(n)).join("")}
917
+ ${e.allDayEvents.map(a=>this.renderAllDayEvent(a)).join("")}
918
918
  </div>
919
919
  </div>
920
920
 
@@ -924,33 +924,33 @@
924
924
  </div>
925
925
 
926
926
  <div class="time-gutter">
927
- ${this.hours.map(n=>`
927
+ ${this.hours.map(a=>`
928
928
  <div class="time-slot-label">
929
- ${n===0?"":w.formatTime(new Date().setHours(n,0),!1)}
929
+ ${a===0?"":w.formatTime(new Date().setHours(a,0),!1)}
930
930
  </div>
931
931
  `).join("")}
932
932
  </div>
933
933
 
934
934
  <div class="day-column" data-date="${e.date.toISOString()}">
935
935
  ${e.isToday?this.renderNowIndicator():""}
936
- ${e.timedEvents.map(n=>this.renderTimedEvent(n)).join("")}
936
+ ${e.timedEvents.map(a=>this.renderTimedEvent(a)).join("")}
937
937
  </div>
938
938
  </div>
939
939
  </div>
940
- `}renderTimedEvent(e){const t=new Date(e.start),s=new Date(e.end),i=t.getHours()*60+t.getMinutes(),r=(s-t)/(1e3*60),a=i,n=Math.max(r,30),o=y.sanitizeColor(e.backgroundColor),c=y.sanitizeColor(y.getContrastColor(o),"white");return`
940
+ `}renderTimedEvent(e){const t=new Date(e.start),s=new Date(e.end),i=t.getHours()*60+t.getMinutes(),r=(s-t)/(1e3*60),n=i,a=Math.max(r,30),o=y.sanitizeColor(e.backgroundColor),c=y.sanitizeColor(y.getContrastColor(o),"white");return`
941
941
  <div class="event-container"
942
- style="top: ${a}px; height: ${n}px; background-color: ${o}; color: ${c};"
942
+ style="top: ${n}px; height: ${a}px; background-color: ${o}; color: ${c};"
943
943
  data-event-id="${e.id}">
944
- <span class="event-title">${E.escapeHTML(e.title)}</span>
944
+ <span class="event-title">${S.escapeHTML(e.title)}</span>
945
945
  <span class="event-time">${w.formatTime(t)} - ${w.formatTime(s)}</span>
946
946
  </div>
947
947
  `}renderAllDayEvent(e){const t=y.sanitizeColor(e.backgroundColor),s=y.sanitizeColor(y.getContrastColor(t),"white");return`
948
948
  <div class="event-item"
949
949
  style="background-color: ${t}; color: ${s}; font-size: 12px; padding: 4px 8px; border-radius: 4px; cursor: pointer; font-weight: 500; margin-bottom: 2px;"
950
950
  data-event-id="${e.id}">
951
- ${E.escapeHTML(e.title)}
951
+ ${S.escapeHTML(e.title)}
952
952
  </div>
953
- `}renderNowIndicator(){const e=new Date;return`<div class="now-indicator" style="top: ${e.getHours()*60+e.getMinutes()}px"></div>`}afterRender(){const e=this.$("#scroll-container");e&&!this._scrolled&&(e.scrollTop=8*60-50,this._scrolled=!0),this.$$("[data-event-id]").forEach(s=>{this.addListener(s,"click",i=>{i.stopPropagation();const r=i.currentTarget.dataset.eventId,a=this.stateManager.getEvents().find(n=>n.id===r);a&&this.emit("event-click",{event:a})})});const t=this.$(".day-column");t&&this.addListener(t,"click",s=>{const i=s.currentTarget,r=this.$("#scroll-container"),a=i.getBoundingClientRect(),n=s.clientY-a.top+(r?r.scrollTop:0),o=new Date(i.dataset.date);o.setHours(Math.floor(n/60),Math.floor(n%60),0,0),this.stateManager.selectDate(o),this.emit("day-click",{date:o})})}unmount(){this.unsubscribe&&this.unsubscribe()}}class Z extends k{constructor(){super(),this._isVisible=!1,this._cleanupFocusTrap=null,this.config={title:"New Event",defaultDuration:60,colors:[{color:"#2563EB",label:"Blue"},{color:"#10B981",label:"Green"},{color:"#F59E0B",label:"Amber"},{color:"#EF4444",label:"Red"},{color:"#8B5CF6",label:"Purple"},{color:"#6B7280",label:"Gray"}]},this._formData={title:"",start:new Date,end:new Date,allDay:!1,color:this.config.colors[0].color}}static get observedAttributes(){return["open"]}attributeChangedCallback(e,t,s){e==="open"&&(s!==null?this.open():this.close())}getStyles(){return`
953
+ `}renderNowIndicator(){const e=new Date;return`<div class="now-indicator" style="top: ${e.getHours()*60+e.getMinutes()}px"></div>`}afterRender(){const e=this.$("#scroll-container");e&&!this._scrolled&&(e.scrollTop=8*60-50,this._scrolled=!0),this.$$("[data-event-id]").forEach(s=>{this.addListener(s,"click",i=>{i.stopPropagation();const r=i.currentTarget.dataset.eventId,n=this.stateManager.getEvents().find(a=>a.id===r);n&&this.emit("event-click",{event:n})})});const t=this.$(".day-column");t&&this.addListener(t,"click",s=>{const i=s.currentTarget,r=this.$("#scroll-container"),n=i.getBoundingClientRect(),a=s.clientY-n.top+(r?r.scrollTop:0),o=new Date(i.dataset.date);o.setHours(Math.floor(a/60),Math.floor(a%60),0,0),this.stateManager.selectDate(o),this.emit("day-click",{date:o})})}unmount(){this.unsubscribe&&this.unsubscribe()}}class G extends k{constructor(){super(),this._isVisible=!1,this._cleanupFocusTrap=null,this.config={title:"New Event",defaultDuration:60,colors:[{color:"#2563EB",label:"Blue"},{color:"#10B981",label:"Green"},{color:"#F59E0B",label:"Amber"},{color:"#EF4444",label:"Red"},{color:"#8B5CF6",label:"Purple"},{color:"#6B7280",label:"Gray"}]},this._formData={title:"",start:new Date,end:new Date,allDay:!1,color:this.config.colors[0].color}}static get observedAttributes(){return["open"]}attributeChangedCallback(e,t,s){e==="open"&&(s!==null?this.open():this.close())}getStyles(){return`
954
954
  ${y.getBaseStyles()}
955
955
  ${y.getButtonStyles()}
956
956
 
@@ -1172,7 +1172,7 @@
1172
1172
  <button class="fc-btn fc-btn-primary" id="save-btn">Save Event</button>
1173
1173
  </footer>
1174
1174
  </div>
1175
- `}afterRender(){this.modalContent=this.$(".modal-content"),this.titleInput=this.$("#event-title"),this.startInput=this.$("#event-start"),this.endInput=this.$("#event-end"),this.colorContainer=this.$("#color-picker"),this.titleGroup=this.$("#title-group"),this.endGroup=this.$("#end-group"),this.addListener(this.$("#close-x"),"click",()=>this.close()),this.addListener(this.$("#cancel-btn"),"click",()=>this.close()),this.addListener(this.$("#save-btn"),"click",()=>this.save()),this.colorContainer.querySelectorAll(".color-btn").forEach(e=>{this.addListener(e,"click",t=>{this._formData.color=t.currentTarget.dataset.color,this.updateColorSelection()})}),this.addListener(this,"click",e=>{e.target===this&&this.close()}),this._handleKeyDown&&window.removeEventListener("keydown",this._handleKeyDown),this._handleKeyDown=e=>{e.key==="Escape"&&this.hasAttribute("open")&&this.close()},window.addEventListener("keydown",this._handleKeyDown)}updateColorSelection(){this.colorContainer.querySelectorAll(".color-btn").forEach(t=>{const s=t.dataset.color===this._formData.color;t.classList.toggle("selected",s),t.setAttribute("aria-checked",s?"true":"false")})}open(e=new Date){this.hasAttribute("open")||this.setAttribute("open",""),this.titleGroup.classList.remove("has-error"),this.endGroup.classList.remove("has-error"),this._formData.start=e,this._formData.end=new Date(e.getTime()+this.config.defaultDuration*60*1e3),this._formData.title="",this._formData.color=this.config.colors[0].color,this.startInput&&(this.titleInput.value="",this.startInput.value=this.formatDateForInput(this._formData.start),this.endInput.value=this.formatDateForInput(this._formData.end),this.updateColorSelection(),this._cleanupFocusTrap=E.trapFocus(this.modalContent))}close(){this.removeAttribute("open"),this._cleanupFocusTrap&&(this._cleanupFocusTrap(),this._cleanupFocusTrap=null)}validate(){let e=!0;this.titleGroup.classList.remove("has-error"),this.endGroup.classList.remove("has-error"),this.titleInput.value.trim()||(this.titleGroup.classList.add("has-error"),e=!1);const t=new Date(this.startInput.value);return new Date(this.endInput.value)<=t&&(this.endGroup.classList.add("has-error"),e=!1),e}save(){if(!this.validate())return;const e={title:this.titleInput.value.trim(),start:new Date(this.startInput.value),end:new Date(this.endInput.value),backgroundColor:this._formData.color};this.emit("save",e),this.close()}formatDateForInput(e){const t=o=>String(o).padStart(2,"0"),s=e.getFullYear(),i=t(e.getMonth()+1),r=t(e.getDate()),a=t(e.getHours()),n=t(e.getMinutes());return`${s}-${i}-${r}T${a}:${n}`}unmount(){this._cleanupFocusTrap&&this._cleanupFocusTrap(),window.removeEventListener("keydown",this._handleKeyDown)}}customElements.get("forcecal-event-form")||customElements.define("forcecal-event-form",Z),customElements.get("forcecal-month")||customElements.define("forcecal-month",F),customElements.get("forcecal-week")||customElements.define("forcecal-week",O),customElements.get("forcecal-day")||customElements.define("forcecal-day",R);class H extends k{static get observedAttributes(){return["view","date","locale","timezone","week-starts-on","height"]}constructor(){super(),this.stateManager=null,this.currentView=null}initialize(){const e={view:this.getAttribute("view")||"month",date:this.getAttribute("date")?new Date(this.getAttribute("date")):new Date,locale:this.getAttribute("locale")||"en-US",timeZone:this.getAttribute("timezone")||Intl.DateTimeFormat().resolvedOptions().timeZone,weekStartsOn:parseInt(this.getAttribute("week-starts-on")||"0")};this.stateManager=new L(e),this.stateManager.subscribe(this.handleStateChange.bind(this)),this.setupEventListeners()}setupEventListeners(){p.on("navigation:*",(e,t)=>{this.emit("calendar-navigate",{action:t.split(":")[1],...e})}),p.on("view:changed",e=>{this.emit("calendar-view-change",e)}),p.on("event:*",(e,t)=>{this.emit(`calendar-event-${t.split(":")[1]}`,e)}),p.on("date:selected",e=>{this.emit("calendar-date-select",e)})}handleStateChange(e,t){e.view!==(t==null?void 0:t.view)&&(this.currentView=e.view),this.render()}mount(){super.mount(),this.loadView(this.stateManager.getView())}loadView(e){this.currentView=e,this.render()}getStyles(){const e=this.getAttribute("height")||"800px";return`
1175
+ `}afterRender(){this.modalContent=this.$(".modal-content"),this.titleInput=this.$("#event-title"),this.startInput=this.$("#event-start"),this.endInput=this.$("#event-end"),this.colorContainer=this.$("#color-picker"),this.titleGroup=this.$("#title-group"),this.endGroup=this.$("#end-group"),this.addListener(this.$("#close-x"),"click",()=>this.close()),this.addListener(this.$("#cancel-btn"),"click",()=>this.close()),this.addListener(this.$("#save-btn"),"click",()=>this.save()),this.colorContainer.querySelectorAll(".color-btn").forEach(e=>{this.addListener(e,"click",t=>{this._formData.color=t.currentTarget.dataset.color,this.updateColorSelection()})}),this.addListener(this,"click",e=>{e.target===this&&this.close()}),this._handleKeyDown&&window.removeEventListener("keydown",this._handleKeyDown),this._handleKeyDown=e=>{e.key==="Escape"&&this.hasAttribute("open")&&this.close()},window.addEventListener("keydown",this._handleKeyDown)}updateColorSelection(){this.colorContainer.querySelectorAll(".color-btn").forEach(t=>{const s=t.dataset.color===this._formData.color;t.classList.toggle("selected",s),t.setAttribute("aria-checked",s?"true":"false")})}open(e=new Date){this.hasAttribute("open")||this.setAttribute("open",""),this.titleGroup.classList.remove("has-error"),this.endGroup.classList.remove("has-error"),this._formData.start=e,this._formData.end=new Date(e.getTime()+this.config.defaultDuration*60*1e3),this._formData.title="",this._formData.color=this.config.colors[0].color,this.startInput&&(this.titleInput.value="",this.startInput.value=this.formatDateForInput(this._formData.start),this.endInput.value=this.formatDateForInput(this._formData.end),this.updateColorSelection(),this._cleanupFocusTrap=S.trapFocus(this.modalContent))}close(){this.removeAttribute("open"),this._cleanupFocusTrap&&(this._cleanupFocusTrap(),this._cleanupFocusTrap=null)}validate(){let e=!0;this.titleGroup.classList.remove("has-error"),this.endGroup.classList.remove("has-error"),this.titleInput.value.trim()||(this.titleGroup.classList.add("has-error"),e=!1);const t=new Date(this.startInput.value);return new Date(this.endInput.value)<=t&&(this.endGroup.classList.add("has-error"),e=!1),e}save(){if(!this.validate())return;const e={title:this.titleInput.value.trim(),start:new Date(this.startInput.value),end:new Date(this.endInput.value),backgroundColor:this._formData.color};this.emit("save",e),this.close()}formatDateForInput(e){const t=o=>String(o).padStart(2,"0"),s=e.getFullYear(),i=t(e.getMonth()+1),r=t(e.getDate()),n=t(e.getHours()),a=t(e.getMinutes());return`${s}-${i}-${r}T${n}:${a}`}unmount(){this._cleanupFocusTrap&&this._cleanupFocusTrap(),window.removeEventListener("keydown",this._handleKeyDown)}}customElements.get("forcecal-event-form")||customElements.define("forcecal-event-form",G),customElements.get("forcecal-month")||customElements.define("forcecal-month",H),customElements.get("forcecal-week")||customElements.define("forcecal-week",B),customElements.get("forcecal-day")||customElements.define("forcecal-day",P);class U extends k{static get observedAttributes(){return["view","date","locale","timezone","week-starts-on","height"]}constructor(){super(),this.stateManager=null,this.currentView=null}initialize(){const e={view:this.getAttribute("view")||"month",date:this.getAttribute("date")?new Date(this.getAttribute("date")):new Date,locale:this.getAttribute("locale")||"en-US",timeZone:this.getAttribute("timezone")||Intl.DateTimeFormat().resolvedOptions().timeZone,weekStartsOn:parseInt(this.getAttribute("week-starts-on")||"0")};this.stateManager=new R(e),this.stateManager.subscribe(this.handleStateChange.bind(this)),this.setupEventListeners()}setupEventListeners(){p.on("navigation:*",(e,t)=>{this.emit("calendar-navigate",{action:t.split(":")[1],...e})}),p.on("view:changed",e=>{this.emit("calendar-view-change",e)}),p.on("event:*",(e,t)=>{this.emit(`calendar-event-${t.split(":")[1]}`,e)}),p.on("date:selected",e=>{this.emit("calendar-date-select",e)})}handleStateChange(e,t){e.view!==(t==null?void 0:t.view)&&(this.currentView=e.view),this.render()}mount(){super.mount(),this.loadView(this.stateManager.getView())}loadView(e){this.currentView=e,this.render()}getStyles(){const e=this.getAttribute("height")||"800px";return`
1176
1176
  ${y.getBaseStyles()}
1177
1177
  ${y.getButtonStyles()}
1178
1178
  ${y.getGridStyles()}
@@ -1563,7 +1563,7 @@
1563
1563
  <p><strong>Error:</strong> ${r.message||"An error occurred"}</p>
1564
1564
  </div>
1565
1565
  </div>
1566
- `;const a=this.getTitle(t,s);return`
1566
+ `;const n=this.getTitle(t,s);return`
1567
1567
  <div class="force-calendar">
1568
1568
  <header class="fc-header">
1569
1569
  <div class="fc-header-left">
@@ -1576,7 +1576,7 @@
1576
1576
  <button class="fc-nav-arrow" data-action="previous" title="Previous">
1577
1577
  ${this.getIcon("chevron-left")}
1578
1578
  </button>
1579
- <h2 class="fc-title">${a}</h2>
1579
+ <h2 class="fc-title">${n}</h2>
1580
1580
  <button class="fc-nav-arrow" data-action="next" title="Next">
1581
1581
  ${this.getIcon("chevron-right")}
1582
1582
  </button>
@@ -1612,25 +1612,25 @@
1612
1612
 
1613
1613
  <forcecal-event-form id="event-modal"></forcecal-event-form>
1614
1614
  </div>
1615
- `}renderView(){return'<div id="calendar-view-container"></div>'}afterRender(){const e=this.$("#calendar-view-container");if(console.log("[ForceCalendar] afterRender - container:",!!e,"stateManager:",!!this.stateManager,"currentView:",this.currentView),e&&this.stateManager&&this.currentView){if(this._currentViewInstance&&this._currentViewInstance._viewType===this.currentView&&e.children.length>0){console.log("[ForceCalendar] View already exists with content, skipping creation");return}this._currentViewInstance&&(this._currentViewInstance.cleanup&&this._currentViewInstance.cleanup(),this._viewUnsubscribe&&(this._viewUnsubscribe(),this._viewUnsubscribe=null)),console.log("[ForceCalendar] Creating view for:",this.currentView);try{const i=this._createViewRenderer(this.currentView);i&&(i._viewType=this.currentView,this._currentViewInstance=i,i.stateManager=this.stateManager,i.container=e,console.log("[ForceCalendar] Calling viewRenderer.render()"),i.render(),console.log("[ForceCalendar] viewRenderer.render() completed"),this._viewUnsubscribe=this.stateManager.subscribe((r,a)=>{(r.events!==(a==null?void 0:a.events)||r.currentDate!==(a==null?void 0:a.currentDate))&&i&&i.render&&i.render()}))}catch(i){console.error("[ForceCalendar] Error creating/rendering view:",i)}}this.$$("[data-action]").forEach(i=>{this.addListener(i,"click",this.handleNavigation)}),this.$$("[data-view]").forEach(i=>{this.addListener(i,"click",this.handleViewChange)});const t=this.$("#event-modal"),s=this.$("#create-event-btn");s&&t&&this.addListener(s,"click",()=>{t.open(new Date)}),this.addListener(this.shadowRoot,"day-click",i=>{t&&t.open(i.detail.date)}),t&&this.addListener(t,"save",i=>{const r=i.detail,a=window.crypto&&typeof window.crypto.randomUUID=="function"?window.crypto.randomUUID():Math.random().toString(36).substring(2,15);this.stateManager.addEvent({id:a,...r})})}_createViewRenderer(e){const t=e;return{stateManager:null,container:null,_listeners:[],_scrolled:!1,cleanup(){this._listeners.forEach(({element:s,event:i,handler:r})=>{s.removeEventListener(i,r)}),this._listeners=[]},addListener(s,i,r){s.addEventListener(i,r),this._listeners.push({element:s,event:i,handler:r})},render(){if(!this.container||!this.stateManager)return;const s=this.stateManager.getViewData();if(!s){this.container.innerHTML='<div style="padding: 20px; text-align: center; color: #666;">Loading...</div>';return}this.cleanup();const i=this.stateManager.getState().config;let r="";switch(t){case"week":r=this._renderWeekView(s,i);break;case"day":r=this._renderDayView(s,i);break;case"month":default:if(!s.weeks){this.container.innerHTML='<div style="padding: 20px; text-align: center; color: #666;">No data available for month view.</div>';return}r=this._renderMonthView(s,i);break}this.container.innerHTML=r,this._attachEventHandlers(t)},_renderMonthView(s,i){const r=i.weekStartsOn||0,a=[];for(let o=0;o<7;o++){const c=(r+o)%7;a.push(["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][c])}let n=`
1615
+ `}renderView(){return'<div id="calendar-view-container"></div>'}afterRender(){const e=this.$("#calendar-view-container");if(console.log("[ForceCalendar] afterRender - container:",!!e,"stateManager:",!!this.stateManager,"currentView:",this.currentView),e&&this.stateManager&&this.currentView){if(this._currentViewInstance&&this._currentViewInstance._viewType===this.currentView&&e.children.length>0){console.log("[ForceCalendar] View already exists with content, skipping creation");return}this._currentViewInstance&&(this._currentViewInstance.cleanup&&this._currentViewInstance.cleanup(),this._viewUnsubscribe&&(this._viewUnsubscribe(),this._viewUnsubscribe=null)),console.log("[ForceCalendar] Creating view for:",this.currentView);try{const i=this._createViewRenderer(this.currentView);i&&(i._viewType=this.currentView,this._currentViewInstance=i,i.stateManager=this.stateManager,i.container=e,console.log("[ForceCalendar] Calling viewRenderer.render()"),i.render(),console.log("[ForceCalendar] viewRenderer.render() completed"),this._viewUnsubscribe=this.stateManager.subscribe((r,n)=>{(r.events!==(n==null?void 0:n.events)||r.currentDate!==(n==null?void 0:n.currentDate))&&i&&i.render&&i.render()}))}catch(i){console.error("[ForceCalendar] Error creating/rendering view:",i)}}this.$$("[data-action]").forEach(i=>{this.addListener(i,"click",this.handleNavigation)}),this.$$("[data-view]").forEach(i=>{this.addListener(i,"click",this.handleViewChange)});const t=this.$("#event-modal"),s=this.$("#create-event-btn");s&&t&&this.addListener(s,"click",()=>{t.open(new Date)}),this.addListener(this.shadowRoot,"day-click",i=>{t&&t.open(i.detail.date)}),t&&this.addListener(t,"save",i=>{const r=i.detail,n=window.crypto&&typeof window.crypto.randomUUID=="function"?window.crypto.randomUUID():Math.random().toString(36).substring(2,15);this.stateManager.addEvent({id:n,...r})})}_createViewRenderer(e){const t=e;return{stateManager:null,container:null,_listeners:[],_scrolled:!1,cleanup(){this._listeners.forEach(({element:s,event:i,handler:r})=>{s.removeEventListener(i,r)}),this._listeners=[]},addListener(s,i,r){s.addEventListener(i,r),this._listeners.push({element:s,event:i,handler:r})},render(){if(!this.container||!this.stateManager)return;const s=this.stateManager.getViewData();if(!s){this.container.innerHTML='<div style="padding: 20px; text-align: center; color: #666;">Loading...</div>';return}this.cleanup();const i=this.stateManager.getState().config;let r="";switch(t){case"week":r=this._renderWeekView(s,i);break;case"day":r=this._renderDayView(s,i);break;case"month":default:if(!s.weeks){this.container.innerHTML='<div style="padding: 20px; text-align: center; color: #666;">No data available for month view.</div>';return}r=this._renderMonthView(s,i);break}this.container.innerHTML=r,this._attachEventHandlers(t)},_renderMonthView(s,i){const r=i.weekStartsOn||0,n=[];for(let o=0;o<7;o++){const c=(r+o)%7;n.push(["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][c])}let a=`
1616
1616
  <div class="fc-month-view" style="display: flex; flex-direction: column; height: 100%; min-height: 400px; background: #fff; border: 1px solid #e5e7eb;">
1617
1617
  <div class="fc-month-header" style="display: grid; grid-template-columns: repeat(7, 1fr); border-bottom: 1px solid #e5e7eb; background: #f9fafb;">
1618
- ${a.map(o=>`<div class="fc-month-header-cell" style="padding: 12px 8px; text-align: center; font-size: 11px; font-weight: 600; color: #6b7280; text-transform: uppercase;">${o}</div>`).join("")}
1618
+ ${n.map(o=>`<div class="fc-month-header-cell" style="padding: 12px 8px; text-align: center; font-size: 11px; font-weight: 600; color: #6b7280; text-transform: uppercase;">${o}</div>`).join("")}
1619
1619
  </div>
1620
1620
  <div class="fc-month-body" style="display: flex; flex-direction: column; flex: 1;">
1621
- `;return s.weeks.forEach(o=>{n+='<div class="fc-month-week" style="display: grid; grid-template-columns: repeat(7, 1fr); flex: 1; min-height: 80px;">',o.days.forEach(c=>{const l=!c.isCurrentMonth,d=c.isToday,h=l?"#f3f4f6":"#fff",g=l?"#9ca3af":"#111827",b=d?"background: #2563eb; color: white; border-radius: 50%; width: 24px; height: 24px; display: flex; align-items: center; justify-content: center;":"",f=c.events||[],T=f.slice(0,3),D=f.length-3;n+=`
1621
+ `;return s.weeks.forEach(o=>{a+='<div class="fc-month-week" style="display: grid; grid-template-columns: repeat(7, 1fr); flex: 1; min-height: 80px;">',o.days.forEach(c=>{const l=!c.isCurrentMonth,d=c.isToday,h=l?"#f3f4f6":"#fff",g=l?"#9ca3af":"#111827",D=d?"background: #2563eb; color: white; border-radius: 50%; width: 24px; height: 24px; display: flex; align-items: center; justify-content: center;":"",u=c.events||[],T=u.slice(0,3),b=u.length-3;a+=`
1622
1622
  <div class="fc-month-day" data-date="${c.date}" style="background: ${h}; border-right: 1px solid #e5e7eb; border-bottom: 1px solid #e5e7eb; padding: 4px; min-height: 80px; cursor: pointer;">
1623
- <div class="fc-day-number" style="font-size: 13px; font-weight: 500; color: ${g}; padding: 2px 4px; margin-bottom: 4px; ${b}">${c.dayOfMonth}</div>
1623
+ <div class="fc-day-number" style="font-size: 13px; font-weight: 500; color: ${g}; padding: 2px 4px; margin-bottom: 4px; ${D}">${c.dayOfMonth}</div>
1624
1624
  <div class="fc-day-events" style="display: flex; flex-direction: column; gap: 2px;">
1625
- ${T.map(S=>`
1626
- <div class="fc-event" data-event-id="${S.id}" style="background-color: ${S.backgroundColor||"#2563eb"}; font-size: 11px; padding: 2px 6px; border-radius: 3px; color: white; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer;">
1627
- ${S.title}
1625
+ ${T.map(C=>`
1626
+ <div class="fc-event" data-event-id="${C.id}" style="background-color: ${C.backgroundColor||"#2563eb"}; font-size: 11px; padding: 2px 6px; border-radius: 3px; color: white; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer;">
1627
+ ${C.title}
1628
1628
  </div>
1629
1629
  `).join("")}
1630
- ${D>0?`<div class="fc-more-events" style="font-size: 10px; color: #6b7280; padding: 2px 4px; font-weight: 500;">+${D} more</div>`:""}
1630
+ ${b>0?`<div class="fc-more-events" style="font-size: 10px; color: #6b7280; padding: 2px 4px; font-weight: 500;">+${b} more</div>`:""}
1631
1631
  </div>
1632
1632
  </div>
1633
- `}),n+="</div>"}),n+="</div></div>",n},_renderWeekView(s,i){const r=s.days||[];if(r.length===0)return'<div style="padding: 20px; text-align: center; color: #666;">No data available for week view.</div>';i.weekStartsOn;const a=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],n=Array.from({length:24},(l,d)=>d),o=r.map(l=>{const d=new Date(l.date),h=l.events||[];return{...l,date:d,dayName:a[d.getDay()],dayOfMonth:d.getDate(),isToday:this._isToday(d),timedEvents:h.filter(g=>!g.allDay),allDayEvents:h.filter(g=>g.allDay)}});return`
1633
+ `}),a+="</div>"}),a+="</div></div>",a},_renderWeekView(s,i){const r=s.days||[];if(r.length===0)return'<div style="padding: 20px; text-align: center; color: #666;">No data available for week view.</div>';i.weekStartsOn;const n=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],a=Array.from({length:24},(l,d)=>d),o=r.map(l=>{const d=new Date(l.date),h=l.events||[];return{...l,date:d,dayName:n[d.getDay()],dayOfMonth:d.getDate(),isToday:this._isToday(d),timedEvents:h.filter(g=>!g.allDay),allDayEvents:h.filter(g=>g.allDay)}});return`
1634
1634
  <div class="fc-week-view" style="display: flex; flex-direction: column; height: 100%; background: #fff; overflow: hidden;">
1635
1635
  <!-- Header -->
1636
1636
  <div style="display: grid; grid-template-columns: 60px repeat(7, 1fr); border-bottom: 1px solid #e5e7eb; background: #f9fafb; flex-shrink: 0;">
@@ -1662,7 +1662,7 @@
1662
1662
  <div style="display: grid; grid-template-columns: 60px repeat(7, 1fr); position: relative; height: 1440px;">
1663
1663
  <!-- Time Gutter -->
1664
1664
  <div style="border-right: 1px solid #e5e7eb; background: #fafafa;">
1665
- ${n.map(l=>`
1665
+ ${a.map(l=>`
1666
1666
  <div style="height: 60px; font-size: 10px; color: #6b7280; text-align: right; padding-right: 8px; font-weight: 500;">
1667
1667
  ${l===0?"":this._formatHour(l)}
1668
1668
  </div>
@@ -1673,7 +1673,7 @@
1673
1673
  ${o.map(l=>`
1674
1674
  <div class="fc-week-day-column" data-date="${l.date.toISOString()}" style="border-right: 1px solid #e5e7eb; position: relative; cursor: pointer;">
1675
1675
  <!-- Hour grid lines -->
1676
- ${n.map(()=>'<div style="height: 60px; border-bottom: 1px solid #f3f4f6;"></div>').join("")}
1676
+ ${a.map(()=>'<div style="height: 60px; border-bottom: 1px solid #f3f4f6;"></div>').join("")}
1677
1677
 
1678
1678
  <!-- Now indicator for today -->
1679
1679
  ${l.isToday?this._renderNowIndicator():""}
@@ -1685,14 +1685,14 @@
1685
1685
  </div>
1686
1686
  </div>
1687
1687
  </div>
1688
- `},_renderDayView(s,i){var g,b;const r=((b=(g=this.stateManager)==null?void 0:g.getState())==null?void 0:b.currentDate)||new Date;let a,n,o,c,l;if(s.type==="day"&&s.date)if(a=new Date(s.date),n=s.dayName||["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][a.getDay()],o=s.isToday!==void 0?s.isToday:this._isToday(a),c=s.allDayEvents||[],s.hours&&Array.isArray(s.hours)){const f=new Map;s.hours.forEach(T=>{(T.events||[]).forEach(D=>{f.has(D.id)||f.set(D.id,D)})}),l=Array.from(f.values())}else l=[];else if(s.days&&s.days.length>0){const f=s.days.find(D=>this._isSameDay(new Date(D.date),r))||s.days[0];a=new Date(f.date),n=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][a.getDay()],o=this._isToday(a);const T=f.events||[];c=T.filter(D=>D.allDay),l=T.filter(D=>!D.allDay)}else return'<div style="padding: 20px; text-align: center; color: #666;">No data available for day view.</div>';const d=Array.from({length:24},(f,T)=>T);return`
1688
+ `},_renderDayView(s,i){var g,D;const r=((D=(g=this.stateManager)==null?void 0:g.getState())==null?void 0:D.currentDate)||new Date;let n,a,o,c,l;if(s.type==="day"&&s.date)if(n=new Date(s.date),a=s.dayName||["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][n.getDay()],o=s.isToday!==void 0?s.isToday:this._isToday(n),c=s.allDayEvents||[],s.hours&&Array.isArray(s.hours)){const u=new Map;s.hours.forEach(T=>{(T.events||[]).forEach(b=>{u.has(b.id)||u.set(b.id,b)})}),l=Array.from(u.values())}else l=[];else if(s.days&&s.days.length>0){const u=s.days.find(b=>this._isSameDay(new Date(b.date),r))||s.days[0];n=new Date(u.date),a=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][n.getDay()],o=this._isToday(n);const T=u.events||[];c=T.filter(b=>b.allDay),l=T.filter(b=>!b.allDay)}else return'<div style="padding: 20px; text-align: center; color: #666;">No data available for day view.</div>';const d=Array.from({length:24},(u,T)=>T);return`
1689
1689
  <div class="fc-day-view" style="display: flex; flex-direction: column; height: 100%; background: #fff; overflow: hidden;">
1690
1690
  <!-- Header -->
1691
1691
  <div style="display: grid; grid-template-columns: 60px 1fr; border-bottom: 1px solid #e5e7eb; background: #f9fafb; flex-shrink: 0;">
1692
1692
  <div style="border-right: 1px solid #e5e7eb;"></div>
1693
1693
  <div style="padding: 16px 24px;">
1694
- <div style="font-size: 12px; font-weight: 700; color: #6b7280; text-transform: uppercase; letter-spacing: 0.1em;">${n}</div>
1695
- <div style="font-size: 24px; font-weight: 600; margin-top: 4px; ${o?"color: #dc2626;":"color: #111827;"}">${a.getDate()}</div>
1694
+ <div style="font-size: 12px; font-weight: 700; color: #6b7280; text-transform: uppercase; letter-spacing: 0.1em;">${a}</div>
1695
+ <div style="font-size: 24px; font-weight: 600; margin-top: 4px; ${o?"color: #dc2626;":"color: #111827;"}">${n.getDate()}</div>
1696
1696
  </div>
1697
1697
  </div>
1698
1698
 
@@ -1700,9 +1700,9 @@
1700
1700
  <div style="display: grid; grid-template-columns: 60px 1fr; border-bottom: 1px solid #e5e7eb; background: #fafafa; min-height: 36px; flex-shrink: 0;">
1701
1701
  <div style="font-size: 9px; color: #6b7280; display: flex; align-items: center; justify-content: center; border-right: 1px solid #e5e7eb; text-transform: uppercase; font-weight: 700;">All day</div>
1702
1702
  <div style="padding: 6px 12px; display: flex; flex-wrap: wrap; gap: 4px;">
1703
- ${c.map(f=>`
1704
- <div class="fc-event" data-event-id="${f.id}" style="background-color: ${f.backgroundColor||"#2563eb"}; font-size: 12px; padding: 4px 8px; border-radius: 4px; color: white; cursor: pointer; font-weight: 500;">
1705
- ${f.title}
1703
+ ${c.map(u=>`
1704
+ <div class="fc-event" data-event-id="${u.id}" style="background-color: ${u.backgroundColor||"#2563eb"}; font-size: 12px; padding: 4px 8px; border-radius: 4px; color: white; cursor: pointer; font-weight: 500;">
1705
+ ${u.title}
1706
1706
  </div>
1707
1707
  `).join("")}
1708
1708
  </div>
@@ -1713,15 +1713,15 @@
1713
1713
  <div style="display: grid; grid-template-columns: 60px 1fr; position: relative; height: 1440px;">
1714
1714
  <!-- Time Gutter -->
1715
1715
  <div style="border-right: 1px solid #e5e7eb; background: #fafafa;">
1716
- ${d.map(f=>`
1716
+ ${d.map(u=>`
1717
1717
  <div style="height: 60px; font-size: 11px; color: #6b7280; text-align: right; padding-right: 12px; font-weight: 500;">
1718
- ${f===0?"":this._formatHour(f)}
1718
+ ${u===0?"":this._formatHour(u)}
1719
1719
  </div>
1720
1720
  `).join("")}
1721
1721
  </div>
1722
1722
 
1723
1723
  <!-- Day Column -->
1724
- <div class="fc-day-column" data-date="${a.toISOString()}" style="position: relative; cursor: pointer;">
1724
+ <div class="fc-day-column" data-date="${n.toISOString()}" style="position: relative; cursor: pointer;">
1725
1725
  <!-- Hour grid lines -->
1726
1726
  ${d.map(()=>'<div style="height: 60px; border-bottom: 1px solid #f3f4f6;"></div>').join("")}
1727
1727
 
@@ -1729,30 +1729,30 @@
1729
1729
  ${o?this._renderNowIndicator():""}
1730
1730
 
1731
1731
  <!-- Timed events -->
1732
- ${l.map(f=>this._renderTimedEventDay(f)).join("")}
1732
+ ${l.map(u=>this._renderTimedEventDay(u)).join("")}
1733
1733
  </div>
1734
1734
  </div>
1735
1735
  </div>
1736
1736
  </div>
1737
- `},_renderTimedEvent(s){const i=new Date(s.start),r=new Date(s.end),a=i.getHours()*60+i.getMinutes(),n=Math.max((r-i)/(1e3*60),20),o=s.backgroundColor||"#2563eb";return`
1737
+ `},_renderTimedEvent(s){const i=new Date(s.start),r=new Date(s.end),n=i.getHours()*60+i.getMinutes(),a=Math.max((r-i)/(1e3*60),20),o=s.backgroundColor||"#2563eb";return`
1738
1738
  <div class="fc-event" data-event-id="${s.id}"
1739
- style="position: absolute; top: ${a}px; height: ${n}px; left: 2px; right: 2px;
1739
+ style="position: absolute; top: ${n}px; height: ${a}px; left: 2px; right: 2px;
1740
1740
  background-color: ${o}; border-radius: 4px; padding: 4px 8px; font-size: 11px;
1741
1741
  font-weight: 500; color: white; overflow: hidden; box-shadow: 0 1px 2px rgba(0,0,0,0.1);
1742
1742
  cursor: pointer; z-index: 5;">
1743
1743
  <div style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${s.title}</div>
1744
1744
  <div style="font-size: 10px; opacity: 0.9;">${this._formatTime(i)}</div>
1745
1745
  </div>
1746
- `},_renderTimedEventDay(s){const i=new Date(s.start),r=new Date(s.end),a=i.getHours()*60+i.getMinutes(),n=Math.max((r-i)/(1e3*60),30),o=s.backgroundColor||"#2563eb";return`
1746
+ `},_renderTimedEventDay(s){const i=new Date(s.start),r=new Date(s.end),n=i.getHours()*60+i.getMinutes(),a=Math.max((r-i)/(1e3*60),30),o=s.backgroundColor||"#2563eb";return`
1747
1747
  <div class="fc-event" data-event-id="${s.id}"
1748
- style="position: absolute; top: ${a}px; height: ${n}px; left: 12px; right: 24px;
1748
+ style="position: absolute; top: ${n}px; height: ${a}px; left: 12px; right: 24px;
1749
1749
  background-color: ${o}; border-radius: 6px; padding: 8px 12px; font-size: 13px;
1750
1750
  font-weight: 500; color: white; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1);
1751
1751
  cursor: pointer; z-index: 5;">
1752
1752
  <div style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${s.title}</div>
1753
1753
  <div style="font-size: 11px; opacity: 0.9;">${this._formatTime(i)} - ${this._formatTime(r)}</div>
1754
1754
  </div>
1755
- `},_renderNowIndicator(){const s=new Date;return`<div style="position: absolute; left: 0; right: 0; top: ${s.getHours()*60+s.getMinutes()}px; height: 2px; background: #dc2626; z-index: 15; pointer-events: none;"></div>`},_formatHour(s){const i=s>=12?"PM":"AM";return`${s%12||12} ${i}`},_formatTime(s){const i=s.getHours(),r=s.getMinutes(),a=i>=12?"PM":"AM",n=i%12||12;return r===0?`${n} ${a}`:`${n}:${r.toString().padStart(2,"0")} ${a}`},_isToday(s){const i=new Date;return s.getDate()===i.getDate()&&s.getMonth()===i.getMonth()&&s.getFullYear()===i.getFullYear()},_isSameDay(s,i){return s.getDate()===i.getDate()&&s.getMonth()===i.getMonth()&&s.getFullYear()===i.getFullYear()},_attachEventHandlers(s){const i=this.stateManager;if(this.container.querySelectorAll(".fc-month-day").forEach(r=>{this.addListener(r,"click",a=>{const n=new Date(r.dataset.date);i.selectDate(n)})}),this.container.querySelectorAll(".fc-week-day-column").forEach(r=>{this.addListener(r,"click",a=>{if(a.target.closest(".fc-event"))return;const n=new Date(r.dataset.date),o=r.getBoundingClientRect(),c=this.container.querySelector("#week-scroll-container"),l=a.clientY-o.top+(c?c.scrollTop:0);n.setHours(Math.floor(l/60),Math.floor(l%60),0,0),i.selectDate(n)})}),this.container.querySelectorAll(".fc-day-column").forEach(r=>{this.addListener(r,"click",a=>{if(a.target.closest(".fc-event"))return;const n=new Date(r.dataset.date),o=r.getBoundingClientRect(),c=this.container.querySelector("#day-scroll-container"),l=a.clientY-o.top+(c?c.scrollTop:0);n.setHours(Math.floor(l/60),Math.floor(l%60),0,0),i.selectDate(n)})}),this.container.querySelectorAll(".fc-event").forEach(r=>{this.addListener(r,"click",a=>{a.stopPropagation();const n=r.dataset.eventId,o=i.getEvents().find(c=>c.id===n);o&&i.selectEvent(o)})}),s==="week"||s==="day"){const r=s==="week"?"#week-scroll-container":"#day-scroll-container",a=this.container.querySelector(r);a&&!this._scrolled&&(a.scrollTop=8*60-50,this._scrolled=!0)}}}}handleNavigation(e){switch(e.currentTarget.dataset.action){case"today":this.stateManager.today();break;case"previous":this.stateManager.previous();break;case"next":this.stateManager.next();break}}handleViewChange(e){const t=e.currentTarget.dataset.view;this.stateManager.setView(t)}getTitle(e,t){const s=this.stateManager.state.config.locale;switch(t){case"month":return w.formatDate(e,"month",s);case"week":const i=w.startOfWeek(e),r=w.endOfWeek(e);return w.formatDateRange(i,r,s);case"day":return w.formatDate(e,"long",s);default:return w.formatDate(e,"month",s)}}getIcon(e){return{"chevron-left":`
1755
+ `},_renderNowIndicator(){const s=new Date;return`<div style="position: absolute; left: 0; right: 0; top: ${s.getHours()*60+s.getMinutes()}px; height: 2px; background: #dc2626; z-index: 15; pointer-events: none;"></div>`},_formatHour(s){const i=s>=12?"PM":"AM";return`${s%12||12} ${i}`},_formatTime(s){const i=s.getHours(),r=s.getMinutes(),n=i>=12?"PM":"AM",a=i%12||12;return r===0?`${a} ${n}`:`${a}:${r.toString().padStart(2,"0")} ${n}`},_isToday(s){const i=new Date;return s.getDate()===i.getDate()&&s.getMonth()===i.getMonth()&&s.getFullYear()===i.getFullYear()},_isSameDay(s,i){return s.getDate()===i.getDate()&&s.getMonth()===i.getMonth()&&s.getFullYear()===i.getFullYear()},_attachEventHandlers(s){const i=this.stateManager;if(this.container.querySelectorAll(".fc-month-day").forEach(r=>{this.addListener(r,"click",n=>{const a=new Date(r.dataset.date);i.selectDate(a)})}),this.container.querySelectorAll(".fc-week-day-column").forEach(r=>{this.addListener(r,"click",n=>{if(n.target.closest(".fc-event"))return;const a=new Date(r.dataset.date),o=r.getBoundingClientRect(),c=this.container.querySelector("#week-scroll-container"),l=n.clientY-o.top+(c?c.scrollTop:0);a.setHours(Math.floor(l/60),Math.floor(l%60),0,0),i.selectDate(a)})}),this.container.querySelectorAll(".fc-day-column").forEach(r=>{this.addListener(r,"click",n=>{if(n.target.closest(".fc-event"))return;const a=new Date(r.dataset.date),o=r.getBoundingClientRect(),c=this.container.querySelector("#day-scroll-container"),l=n.clientY-o.top+(c?c.scrollTop:0);a.setHours(Math.floor(l/60),Math.floor(l%60),0,0),i.selectDate(a)})}),this.container.querySelectorAll(".fc-event").forEach(r=>{this.addListener(r,"click",n=>{n.stopPropagation();const a=r.dataset.eventId,o=i.getEvents().find(c=>c.id===a);o&&i.selectEvent(o)})}),s==="week"||s==="day"){const r=s==="week"?"#week-scroll-container":"#day-scroll-container",n=this.container.querySelector(r);n&&!this._scrolled&&(n.scrollTop=8*60-50,this._scrolled=!0)}}}}handleNavigation(e){switch(e.currentTarget.dataset.action){case"today":this.stateManager.today();break;case"previous":this.stateManager.previous();break;case"next":this.stateManager.next();break}}handleViewChange(e){const t=e.currentTarget.dataset.view;this.stateManager.setView(t)}getTitle(e,t){const s=this.stateManager.state.config.locale;switch(t){case"month":return w.formatDate(e,"month",s);case"week":const i=w.startOfWeek(e),r=w.endOfWeek(e);return w.formatDateRange(i,r,s);case"day":return w.formatDate(e,"long",s);default:return w.formatDate(e,"month",s)}}getIcon(e){return{"chevron-left":`
1756
1756
  <svg class="fc-icon" viewBox="0 0 24 24">
1757
1757
  <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
1758
1758
  </svg>
@@ -1764,5 +1764,5 @@
1764
1764
  <svg class="fc-icon" viewBox="0 0 24 24">
1765
1765
  <path d="M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11zM7 10h5v5H7z"/>
1766
1766
  </svg>
1767
- `}[e]||""}addEvent(e){return this.stateManager.addEvent(e)}updateEvent(e,t){return this.stateManager.updateEvent(e,t)}deleteEvent(e){return this.stateManager.deleteEvent(e)}getEvents(){return this.stateManager.getEvents()}setView(e){this.stateManager.setView(e)}setDate(e){this.stateManager.setDate(e)}next(){this.stateManager.next()}previous(){this.stateManager.previous()}today(){this.stateManager.today()}destroy(){this.stateManager&&this.stateManager.destroy(),p.clear(),super.cleanup()}}customElements.get("forcecal-main")||customElements.define("forcecal-main",H),typeof window<"u"&&typeof customElements<"u"&&console.log("Force Calendar Interface loading..."),v.BaseComponent=k,v.DOMUtils=E,v.DateUtils=w,v.DayView=R,v.EventBus=_,v.ForceCalendar=H,v.MonthView=F,v.StateManager=L,v.StyleUtils=y,v.WeekView=O,v.eventBus=p,Object.defineProperty(v,Symbol.toStringTag,{value:"Module"})});
1767
+ `}[e]||""}addEvent(e){return this.stateManager.addEvent(e)}updateEvent(e,t){return this.stateManager.updateEvent(e,t)}deleteEvent(e){return this.stateManager.deleteEvent(e)}getEvents(){return this.stateManager.getEvents()}setView(e){this.stateManager.setView(e)}setDate(e){this.stateManager.setDate(e)}next(){this.stateManager.next()}previous(){this.stateManager.previous()}today(){this.stateManager.today()}destroy(){this.stateManager&&this.stateManager.destroy(),p.clear(),super.cleanup()}}customElements.get("forcecal-main")||customElements.define("forcecal-main",U),typeof window<"u"&&typeof customElements<"u"&&console.log("Force Calendar Interface loading..."),v.BaseComponent=k,v.DOMUtils=S,v.DateUtils=w,v.DayView=P,v.EventBus=O,v.ForceCalendar=U,v.MonthView=H,v.StateManager=R,v.StyleUtils=y,v.WeekView=B,v.eventBus=p,Object.defineProperty(v,Symbol.toStringTag,{value:"Module"})});
1768
1768
  //# sourceMappingURL=force-calendar-interface.umd.js.map