import { __decorate } from '../node_modules/.pnpm/@rollup_plugin-typescript@12.3.0_rollup@4.60.1_tslib@2.8.1_typescript@6.0.2/node_modules/tslib/tslib.es6.js';
import { css, LitElement, nothing, html } from 'lit';
import { property, state, customElement } from 'lit/decorators.js';
import { styleMap } from 'lit/directives/style-map.js';

const DEFAULT_STYLE = {
    fontSize: "1.5rem",
    fontFamily: "system-ui, -apple-system, sans-serif",
    color: "white",
    backgroundColor: "rgba(0, 0, 0, 0.75)",
    textShadow: "2px 2px 4px rgba(0, 0, 0, 0.5)",
    bottom: "5%",
    maxWidth: "90%",
    padding: "0.5em 1em",
    borderRadius: "4px",
};
let FwSubtitleRenderer = class FwSubtitleRenderer extends LitElement {
    constructor() {
        super(...arguments);
        this.currentTime = 0;
        this.enabled = true;
        this.cues = [];
        this.className = "";
        this._liveCues = [];
        this._displayedText = "";
        this._unsubscribe = null;
        this._handleMetaEvent = (event) => {
            if (event.type !== "subtitle") {
                return;
            }
            const cue = this._parseSubtitleCue(event.data);
            if (!cue) {
                return;
            }
            this._liveCues = (() => {
                const existing = this._liveCues.find((value) => value.id === cue.id);
                if (existing) {
                    return this._liveCues;
                }
                return [...this._liveCues, cue].slice(-50);
            })();
        };
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this._teardownSubscription();
    }
    updated(changed) {
        if (changed.has("enabled") ||
            changed.has("subscribeToMetaTrack") ||
            changed.has("metaTrackId")) {
            this._syncSubscription();
        }
        if (changed.has("currentTime") || changed.has("_liveCues")) {
            this._pruneExpiredLiveCues();
        }
        if (changed.has("enabled") ||
            changed.has("currentTime") ||
            changed.has("cues") ||
            changed.has("_liveCues")) {
            this._syncDisplayedCue();
        }
    }
    _syncSubscription() {
        this._teardownSubscription();
        if (!this.enabled || !this.subscribeToMetaTrack || !this.metaTrackId) {
            return;
        }
        this._unsubscribe = this.subscribeToMetaTrack(this.metaTrackId, this._handleMetaEvent);
    }
    _teardownSubscription() {
        if (this._unsubscribe) {
            this._unsubscribe();
            this._unsubscribe = null;
        }
    }
    _parseSubtitleCue(data) {
        if (typeof data !== "object" || data === null) {
            return null;
        }
        const obj = data;
        const text = typeof obj.text === "string" ? obj.text : String(obj.text ?? "");
        if (!text) {
            return null;
        }
        const rawStart = "startTime" in obj ? Number(obj.startTime) : "start" in obj ? Number(obj.start) : 0;
        const rawEnd = "endTime" in obj ? Number(obj.endTime) : "end" in obj ? Number(obj.end) : Infinity;
        const startTime = Number.isFinite(rawStart) ? rawStart : 0;
        const endTime = Number.isFinite(rawEnd) ? rawEnd : Infinity;
        const id = typeof obj.id === "string" ? obj.id : String(Date.now() + Math.random());
        return {
            id,
            text,
            startTime,
            endTime,
            lang: typeof obj.lang === "string" ? obj.lang : undefined,
        };
    }
    _getAllCues() {
        return [...(this.cues ?? []), ...this._liveCues];
    }
    _syncDisplayedCue() {
        if (!this.enabled) {
            if (this._displayedText) {
                this._displayedText = "";
            }
            return;
        }
        const currentTimeMs = this.currentTime;
        const activeCue = this._getAllCues().find((cue) => currentTimeMs >= cue.startTime && currentTimeMs < cue.endTime);
        const nextText = activeCue?.text ?? "";
        if (nextText !== this._displayedText) {
            this._displayedText = nextText;
        }
    }
    _pruneExpiredLiveCues() {
        if (this._liveCues.length === 0) {
            return;
        }
        const currentTimeMs = this.currentTime;
        const filtered = this._liveCues.filter((cue) => {
            const endTime = cue.endTime === Infinity ? cue.startTime + 10000 : cue.endTime;
            return endTime >= currentTimeMs - 30000;
        });
        if (filtered.length !== this._liveCues.length) {
            this._liveCues = filtered;
        }
    }
    render() {
        if (!this.enabled || !this._displayedText) {
            return nothing;
        }
        const mergedStyle = {
            ...DEFAULT_STYLE,
            ...(this.subtitleStyle ?? {}),
        };
        return html `
      <div
        class="subtitle-container ${this.className}"
        style=${styleMap({
            bottom: mergedStyle.bottom,
            maxWidth: mergedStyle.maxWidth,
        })}
        role="region"
        aria-live="polite"
        aria-label="Subtitles"
      >
        <span
          class="subtitle-text"
          style=${styleMap({
            fontSize: mergedStyle.fontSize,
            fontFamily: mergedStyle.fontFamily,
            color: mergedStyle.color,
            backgroundColor: mergedStyle.backgroundColor,
            textShadow: mergedStyle.textShadow,
            padding: mergedStyle.padding,
            borderRadius: mergedStyle.borderRadius,
        })}
        >
          ${this._displayedText}
        </span>
      </div>
    `;
    }
};
FwSubtitleRenderer.styles = css `
    :host {
      display: contents;
    }

    .subtitle-container {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      z-index: 30;
      text-align: center;
      pointer-events: none;
    }

    .subtitle-text {
      display: inline-block;
      white-space: pre-wrap;
    }
  `;
__decorate([
    property({ type: Number })
], FwSubtitleRenderer.prototype, "currentTime", void 0);
__decorate([
    property({ type: Boolean })
], FwSubtitleRenderer.prototype, "enabled", void 0);
__decorate([
    property({ attribute: false })
], FwSubtitleRenderer.prototype, "cues", void 0);
__decorate([
    property({ attribute: false })
], FwSubtitleRenderer.prototype, "subscribeToMetaTrack", void 0);
__decorate([
    property({ type: String, attribute: "meta-track-id" })
], FwSubtitleRenderer.prototype, "metaTrackId", void 0);
__decorate([
    property({ attribute: false })
], FwSubtitleRenderer.prototype, "subtitleStyle", void 0);
__decorate([
    property({ type: String, attribute: "class-name" })
], FwSubtitleRenderer.prototype, "className", void 0);
__decorate([
    state()
], FwSubtitleRenderer.prototype, "_liveCues", void 0);
__decorate([
    state()
], FwSubtitleRenderer.prototype, "_displayedText", void 0);
FwSubtitleRenderer = __decorate([
    customElement("fw-subtitle-renderer")
], FwSubtitleRenderer);

export { FwSubtitleRenderer };
//# sourceMappingURL=fw-subtitle-renderer.js.map
