import { unsafeCSS, LitElement, nothing, html } from "lit";
import { customElement } from "../../decorator.js";
import componentStyle from "./date-item.css.js";
import { property, state } from "lit/decorators.js";
import { classMap } from "lit/directives/class-map.js";
import { repeat } from "lit/directives/repeat.js";
import { EventItemType } from "../event-item/event-item.js";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp(target, key, result);
  return result;
};
var DateItemSize = /* @__PURE__ */ ((DateItemSize2) => {
  DateItemSize2["Small"] = "small";
  DateItemSize2["Large"] = "large";
  return DateItemSize2;
})(DateItemSize || {});
let ObcDateItem = class extends LitElement {
  constructor() {
    super(...arguments);
    this.size = "small";
    this.disabled = false;
    this.events = [];
    this.eventCount = 0;
    this.isToday = false;
    this.checked = false;
    this._date = 1;
    this._maxVisibleEvents = null;
    this._resizeObserver = null;
    this._headerHeight = 48;
    this._eventHeight = 48;
    this._pressing = false;
  }
  get date() {
    return this._date;
  }
  set date(value) {
    const oldValue = this._date;
    if (value < 1) this._date = 1;
    else if (value > 31) this._date = 31;
    else this._date = value;
    this.requestUpdate("date", oldValue);
  }
  // Min height of each event item
  connectedCallback() {
    super.connectedCallback();
    this._setupResizeObserver();
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this._cleanupResizeObserver();
  }
  _setupResizeObserver() {
    if (typeof ResizeObserver === "undefined") return;
    this._resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        this._calculateVisibleEvents(entry.contentRect.height);
      }
    });
  }
  _cleanupResizeObserver() {
    if (this._resizeObserver) {
      this._resizeObserver.disconnect();
      this._resizeObserver = null;
    }
  }
  _calculateVisibleEvents(containerHeight) {
    if (this.size !== "large") {
      this._maxVisibleEvents = null;
      return;
    }
    const availableHeight = containerHeight - this._headerHeight;
    if (availableHeight <= 0) {
      this._maxVisibleEvents = 0;
      return;
    }
    const maxEvents = Math.floor(availableHeight / this._eventHeight);
    if (this._maxVisibleEvents !== maxEvents) {
      this._maxVisibleEvents = maxEvents;
    }
  }
  firstUpdated() {
    if (this._resizeObserver && this.size === "large") {
      this._resizeObserver.observe(this);
    }
  }
  updated(changedProps) {
    if (changedProps.has("size")) {
      if (this._resizeObserver) {
        this._resizeObserver.disconnect();
      }
      if (this.size === "large") {
        this._resizeObserver?.observe(this);
      } else {
        this._maxVisibleEvents = null;
      }
    }
  }
  _handleDateClick(e) {
    if (this.disabled) return;
    if (e?.target !== e?.currentTarget) {
      const target = e?.target;
      if (target?.closest("obc-event-item")) {
        return;
      }
    }
    this.dispatchEvent(
      new CustomEvent("date-click", {
        bubbles: true,
        composed: true,
        detail: {
          date: this.date,
          events: this.events,
          isToday: this.isToday,
          checked: this.checked
        }
      })
    );
  }
  _handleKeyDown(e) {
    if (this.disabled) return;
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      this._pressing = true;
      this._handleDateClick();
      setTimeout(() => {
        this._pressing = false;
      }, 150);
    }
  }
  /**
   * Get the events to display, applying auto-aggregation if needed.
   * Returns an object with visibleEvents and aggregatedCount.
   */
  _getDisplayEvents() {
    const baseEvents = this.eventCount > 0 ? this.events.slice(0, this.eventCount) : this.events;
    if (this._maxVisibleEvents === null || this.size !== "large" || baseEvents.length === 0) {
      return { visibleEvents: baseEvents, aggregatedCount: 0 };
    }
    const totalEvents = baseEvents.length;
    if (totalEvents <= this._maxVisibleEvents) {
      return { visibleEvents: baseEvents, aggregatedCount: 0 };
    }
    if (this._maxVisibleEvents <= 1) {
      return { visibleEvents: [], aggregatedCount: totalEvents };
    }
    const visibleCount = this._maxVisibleEvents - 1;
    const visibleEvents = baseEvents.slice(0, visibleCount);
    const aggregatedCount = totalEvents - visibleCount;
    return { visibleEvents, aggregatedCount };
  }
  render() {
    const { visibleEvents, aggregatedCount } = this._getDisplayEvents();
    const totalEventCount = this.events.length;
    const eventText = totalEventCount === 0 ? "0 events" : totalEventCount === 1 ? "1 event" : `${totalEventCount} events`;
    const isSmallSize = this.size === "small";
    const hasAnyEvents = this.events.length > 0;
    const wrapperClasses = {
      wrapper: true,
      [`size-${this.size}`]: true,
      [`has-events`]: hasAnyEvents,
      disabled: this.disabled,
      isToday: this.isToday,
      checked: this.checked,
      pressing: this._pressing
    };
    if (isSmallSize) {
      return html`
        <button
          type="button"
          class=${classMap(wrapperClasses)}
          aria-label="Date ${this.date}, ${eventText}"
          ?disabled=${this.disabled}
          @click=${this._handleDateClick}
        >
          <div class="date-container">
            <div class="date" aria-hidden="true">${this.date}</div>
            ${hasAnyEvents ? html`<div class="event-dot" aria-hidden="true"></div>` : nothing}
          </div>
        </button>
      `;
    }
    return html`
      <div
        role="button"
        tabindex=${this.disabled ? "-1" : "0"}
        class=${classMap(wrapperClasses)}
        aria-label="Date ${this.date}, ${eventText}"
        aria-disabled=${this.disabled ? "true" : "false"}
        @click=${this._handleDateClick}
        @keydown=${this._handleKeyDown}
      >
        <div class="header-container">
          ${this.isToday ? html`<div class="today-label">Today</div>` : nothing}
          <div class="date-item-small">
            <div class="date-container">
              <div class="date" aria-hidden="true">${this.date}</div>
            </div>
          </div>
        </div>

        ${hasAnyEvents ? html`
              <div class="content-container">
                ${repeat(
      visibleEvents,
      (event, index) => `${event.title}-${event.startTime}-${event.endTime}-${index}`,
      (event) => html`
                    <obc-event-item
                      .title=${event.title}
                      .description=${event.description ?? ""}
                      .startTime=${event.startTime}
                      .endTime=${event.endTime}
                      .eventItemType=${event.eventItemType ?? EventItemType.SingleLine}
                      .hasArrow=${event.hasArrow ?? false}
                      .hasTime=${event.hasTime ?? false}
                      .hasEndTime=${event.hasEndTime ?? false}
                      .aggregatedCount=${event.aggregatedCount ?? 0}
                      .colorCoded=${event.colorCoded ?? false}
                      .disabled=${this.disabled || !!event.disabled}
                    ></obc-event-item>
                  `
    )}
                ${aggregatedCount > 0 ? html`
                      <obc-event-item
                        .eventItemType=${EventItemType.Aggregated}
                        .aggregatedCount=${aggregatedCount}
                        ?disabled=${this.disabled}
                      ></obc-event-item>
                    ` : nothing}
              </div>
            ` : nothing}
      </div>
    `;
  }
};
ObcDateItem.styles = unsafeCSS(componentStyle);
__decorateClass([
  property({ type: String })
], ObcDateItem.prototype, "size", 2);
__decorateClass([
  property({ type: Boolean })
], ObcDateItem.prototype, "disabled", 2);
__decorateClass([
  property({ attribute: false })
], ObcDateItem.prototype, "events", 2);
__decorateClass([
  property({ type: Number })
], ObcDateItem.prototype, "eventCount", 2);
__decorateClass([
  property({ type: Boolean })
], ObcDateItem.prototype, "isToday", 2);
__decorateClass([
  property({ type: Boolean })
], ObcDateItem.prototype, "checked", 2);
__decorateClass([
  state()
], ObcDateItem.prototype, "_date", 2);
__decorateClass([
  property({ type: Number })
], ObcDateItem.prototype, "date", 1);
__decorateClass([
  state()
], ObcDateItem.prototype, "_maxVisibleEvents", 2);
__decorateClass([
  state()
], ObcDateItem.prototype, "_pressing", 2);
ObcDateItem = __decorateClass([
  customElement("obc-date-item")
], ObcDateItem);
export {
  DateItemSize,
  EventItemType,
  ObcDateItem
};
//# sourceMappingURL=date-item.js.map
