import { p as proxyCustomElement, H, e as createEvent, h } from './p-ae373651.js';
import { p as provideRtkDesignSystem, d as deepMerge } from './p-7e34f516.js';
import { u as uiStore, i as useLanguage, c as createDefaultConfig, e as defaultIconPack, f as defaultOverrides, b as createPeerStore } from './p-5b3a7f00.js';
import { R as Render } from './p-88bd1053.js';
import { g as generateConfig } from './p-b220448d.js';
import './p-a83ccdbd.js';
import { i as index } from './p-f47d4fe8.js';
import { g as getJoinErrorInfo } from './p-f7c2daba.js';
import { d as defineCustomElement$q } from './p-a3bf84d7.js';
import { d as defineCustomElement$p } from './p-85587a5c.js';
import { d as defineCustomElement$o } from './p-a642ad81.js';
import { d as defineCustomElement$n } from './p-465af231.js';
import { d as defineCustomElement$m } from './p-b3a98a90.js';
import { d as defineCustomElement$l } from './p-5d232d53.js';
import { d as defineCustomElement$k } from './p-d6a71424.js';
import { d as defineCustomElement$j } from './p-1a6308ec.js';
import { d as defineCustomElement$i } from './p-0e5b6daf.js';
import { d as defineCustomElement$h } from './p-5ba9c3d1.js';
import { d as defineCustomElement$g } from './p-5644d937.js';
import { d as defineCustomElement$f } from './p-0da52a33.js';
import { d as defineCustomElement$e } from './p-3e0452c4.js';
import { d as defineCustomElement$d } from './p-60d401f8.js';
import { d as defineCustomElement$c } from './p-549ab58f.js';
import { d as defineCustomElement$b } from './p-241583c3.js';
import { d as defineCustomElement$a } from './p-0304f83a.js';
import { d as defineCustomElement$9 } from './p-02d63986.js';
import { d as defineCustomElement$8 } from './p-10552fa5.js';
import { d as defineCustomElement$7 } from './p-7dd3acf5.js';
import { d as defineCustomElement$6 } from './p-06bfb00c.js';
import { d as defineCustomElement$5 } from './p-e6245534.js';
import { d as defineCustomElement$4 } from './p-670b184f.js';
import { d as defineCustomElement$3 } from './p-51b6f520.js';
import { d as defineCustomElement$2 } from './p-bece0226.js';

const sm = 640;
const md = 768;
const lg = 1080;
const xl = 2160;
const breakpoints = {
	sm: sm,
	md: md,
	lg: lg,
	xl: xl
};

/**
 * Get the screen breakpoint from a given width
 * @param width The width of the container
 * @returns The screen breakpoint value
 */
const getSize = (width) => {
    if (width >= breakpoints.lg)
        return 'lg';
    else if (width >= breakpoints.md)
        return 'md';
    else
        return 'sm';
};

const rtkMeetingCss = ":host{line-height:initial;font-family:var(--rtk-font-family, sans-serif);font-feature-settings:normal;font-variation-settings:normal}p{margin:var(--rtk-space-0, 0px);padding:var(--rtk-space-0, 0px)}:host{box-sizing:border-box;display:flex;flex-direction:column;--tw-bg-opacity:1;background-color:rgba(var(--rtk-colors-background-1000, 8 8 8) / var(--tw-bg-opacity));color:rgb(var(--rtk-colors-text-900, 255 255 255 / 0.88));overflow:hidden;position:fixed;top:var(--rtk-space-0, 0px);right:var(--rtk-space-0, 0px);bottom:var(--rtk-space-0, 0px);left:var(--rtk-space-0, 0px);height:100%;width:100%}:host([mode='fill']){position:relative}";
const RtkMeetingStyle0 = rtkMeetingCss;

const RtkMeeting$1 = /*@__PURE__*/ proxyCustomElement(class RtkMeeting extends H {
    constructor() {
        super();
        this.__registerHost();
        this.__attachShadow();
        this.statesUpdate = createEvent(this, "rtkStatesUpdate", 7);
        /** Since RtkMeeting by design works as a provider for component, to be in sync with other providers, added provider id */
        this.providerId = 'provider-' + Math.floor(Math.random() * 100);
        this.roomJoinedListener = () => {
            this.updateStates({ meeting: 'joined', joinError: undefined, joinErrorCode: undefined });
        };
        this.waitlistedListener = () => {
            this.updateStates({ meeting: 'waiting' });
        };
        this.roomLeftListener = ({ state }) => {
            // Let socketConnectionUpdate listener handle this case.
            if (state === 'disconnected' || state === 'failed')
                return;
            this.updateStates({ meeting: 'ended', roomLeftState: state });
        };
        this.mediaPermissionUpdateListener = ({ kind, message }) => {
            if (['audio', 'video'].includes(kind)) {
                if ((message === 'DENIED' || message === 'SYSTEM_DENIED') &&
                    (this.peerStore || uiStore).state.states.activeDebugger !== true) {
                    const permissionModalSettings = {
                        enabled: true,
                        kind,
                    };
                    this.updateStates({ activePermissionsMessage: permissionModalSettings });
                }
            }
        };
        this.socketConnectionUpdateListener = ({ state }) => {
            if (state === 'failed') {
                setTimeout(() => {
                    this.meeting.leave('disconnected');
                }, this.leaveRoomTimer);
            }
        };
        this.peerStore = null; // peer specific store for this meeting peer instance
        /** Whether to load config from preset */
        this.loadConfigFromPreset = false;
        /** Whether to apply the design system on the document root from config */
        this.applyDesignSystem = false;
        /** Fill type */
        this.mode = 'fixed';
        /** Whether participant should leave when this component gets unmounted */
        this.leaveOnUnmount = false;
        /** Language */
        this.t = useLanguage();
        /** UI Config */
        this.config = createDefaultConfig();
        /** Grid layout */
        this.gridLayout = 'row';
        /** Icon pack */
        this.iconPack = defaultIconPack;
        /** UI Kit Overrides */
        this.overrides = defaultOverrides;
        this.handleChangingMeeting = (destinationMeetingId) => {
            const currentStates = (this.peerStore || uiStore).state.states;
            this.updateStates({
                activeBreakoutRoomsManager: Object.assign(Object.assign({}, currentStates.activeBreakoutRoomsManager), { destinationMeetingId }),
            });
        };
    }
    connectedCallback() {
        var _a;
        if (typeof window !== 'undefined') {
            this.authErrorListener = (ev) => {
                if (ev.detail.message.includes('401')) {
                    this.updateStates({ meeting: 'ended', roomLeftState: 'unauthorized' });
                }
            };
            window.addEventListener('rtkError', this.authErrorListener);
        }
        // Initialize default values
        this.leaveRoomTimer = 10000;
        this.loadConfigFromPreset = true;
        this.applyDesignSystem = true;
        // Setup event listeners
        this.setupStoreRequestListener();
        this.setupStateUpdateListener();
        this.meetingChanged(this.meeting);
        this.iconPackChanged(this.iconPack);
        this.tChanged(this.t);
        this.configChanged(this.config);
        this.overridesChanged(this.overrides);
        this.resizeObserver = new index(() => this.handleResize());
        this.resizeObserver.observe(this.host);
        if (this.applyDesignSystem &&
            ((_a = this.config) === null || _a === void 0 ? void 0 : _a.designTokens) != null &&
            typeof document !== 'undefined' &&
            (this.peerStore || uiStore).state.states.activeDebugger !== true) {
            provideRtkDesignSystem(document.documentElement, this.config.designTokens);
        }
    }
    disconnectedCallback() {
        var _a;
        if (this.leaveOnUnmount) {
            (_a = this.meeting) === null || _a === void 0 ? void 0 : _a.leave();
        }
        this.resizeObserver.disconnect();
        window.removeEventListener('rtkError', this.authErrorListener);
        // Remove event listeners
        if (this.storeRequestListener) {
            this.host.removeEventListener('rtkRequestStore', this.storeRequestListener);
            this.storeRequestListener = null;
        }
        if (this.stateUpdateListener) {
            this.host.removeEventListener('rtkStateUpdate', this.stateUpdateListener);
            this.stateUpdateListener = null;
        }
        // Clear meeting listeners
        if (this.meeting) {
            this.clearListeners(this.meeting);
        }
    }
    setupStoreRequestListener() {
        // Remove existing listener if any
        if (this.storeRequestListener) {
            this.host.removeEventListener('rtkRequestStore', this.storeRequestListener);
        }
        // Listen for store requests from child components
        this.storeRequestListener = (event) => {
            // Provide peer specific store if available, otherwise fall back to global store
            if (!this.peerStore)
                return;
            const storeToProvide = this.peerStore;
            const responseEvent = new CustomEvent('rtkProvideStore', {
                detail: { store: storeToProvide, requestId: event.detail.requestId },
            });
            document.dispatchEvent(responseEvent);
            // Stop the event from bubbling further to prevent other meetings from handling it
            event.stopPropagation();
        };
        this.host.addEventListener('rtkRequestStore', this.storeRequestListener);
    }
    setupStateUpdateListener() {
        if (this.stateUpdateListener) {
            this.host.removeEventListener('rtkStateUpdate', this.stateUpdateListener);
        }
        this.stateUpdateListener = (event) => {
            const eventTarget = event.target;
            if (!this.host.contains(eventTarget)) {
                return;
            }
            this.updateStates(event.detail);
        };
        this.host.addEventListener('rtkStateUpdate', this.stateUpdateListener);
    }
    clearListeners(meeting) {
        if (!meeting)
            return;
        meeting.self.removeListener('roomLeft', this.roomLeftListener);
        meeting.self.removeListener('roomJoined', this.roomJoinedListener);
        meeting.self.removeListener('waitlisted', this.waitlistedListener);
        meeting.self.removeListener('mediaPermissionUpdate', this.mediaPermissionUpdateListener);
        meeting.meta.removeListener('socketConnectionUpdate', this.socketConnectionUpdateListener);
    }
    meetingChanged(meeting, oldMeeting) {
        var _a, _b;
        if (!meeting)
            return;
        // Create peer specific store for this meeting peer instance
        if (meeting) {
            this.peerStore = createPeerStore({
                meeting,
                config: this.config,
                iconPack: this.iconPack,
                t: this.t,
                providerId: this.providerId,
                overrides: deepMerge(Object.assign({}, defaultOverrides), this.overrides),
            });
            // Notify components that peer specific store is now available
            document.dispatchEvent(new CustomEvent('rtkPeerStoreReady', {
                detail: {
                    peerId: meeting.self.id,
                },
            }));
        }
        else {
            this.peerStore = null;
        }
        const targetStore = this.peerStore || uiStore;
        /** Honor user's explicit choice for captions, but respect preset default if no explicit choice */
        const desiredActiveCaptionsState = !oldMeeting
            ? !!meeting.self.permissions.transcriptionEnabled
            : !!targetStore.state.states.activeCaptions;
        this.updateStates({
            viewType: meeting.meta.viewType,
            activeCaptions: desiredActiveCaptionsState,
        });
        if (this.loadConfigFromPreset && meeting.self.config != null) {
            const theme = meeting.self.config;
            const { config, data } = generateConfig(theme, meeting);
            this.config = config;
            if (this.showSetupScreen == null) {
                this.showSetupScreen = data.showSetupScreen;
            }
            if ((_a = targetStore.state.states.activeBreakoutRoomsManager) === null || _a === void 0 ? void 0 : _a.destinationMeetingId) {
                this.showSetupScreen = false;
            }
        }
        if (this.applyDesignSystem &&
            ((_b = this.config) === null || _b === void 0 ? void 0 : _b.designTokens) != null &&
            typeof document !== 'undefined' &&
            targetStore.state.states.activeDebugger !== true) {
            provideRtkDesignSystem(document.documentElement, this.config.designTokens);
        }
        meeting.self.addListener('roomJoined', this.roomJoinedListener);
        meeting.self.addListener('waitlisted', this.waitlistedListener);
        meeting.self.addListener('roomLeft', this.roomLeftListener);
        meeting.self.addListener('mediaPermissionUpdate', this.mediaPermissionUpdateListener);
        meeting.meta.addListener('socketConnectionUpdate', this.socketConnectionUpdateListener);
        meeting.connectedMeetings.once('changingMeeting', this.handleChangingMeeting);
        if (meeting.self.roomJoined) {
            this.updateStates({ meeting: 'joined' });
        }
        else {
            if (this.showSetupScreen) {
                this.updateStates({ meeting: 'setup' });
            }
            else {
                meeting
                    .join()
                    .then(() => {
                    this.updateStates({ joinError: undefined, joinErrorCode: undefined });
                })
                    .catch((err) => {
                    const { message, code } = getJoinErrorInfo(this.t, err);
                    this.updateStates({ joinError: message, joinErrorCode: code });
                });
            }
        }
        window.removeEventListener('rtkError', this.authErrorListener);
    }
    iconPackChanged(newIconPack) {
        if (this.peerStore) {
            this.peerStore.state.iconPack = newIconPack;
        }
    }
    tChanged(newT) {
        if (this.peerStore) {
            this.peerStore.state.t = newT;
        }
    }
    configChanged(config) {
        if (this.peerStore) {
            this.peerStore.state.config = config;
        }
        if ((config === null || config === void 0 ? void 0 : config.designTokens) &&
            typeof document !== 'undefined' &&
            (this.peerStore || uiStore).state.states.activeDebugger !== true) {
            provideRtkDesignSystem(document.documentElement, config.designTokens);
        }
    }
    overridesChanged(overrides) {
        if (this.peerStore) {
            this.peerStore.state.overrides = deepMerge(Object.assign({}, defaultOverrides), overrides);
        }
    }
    handleResize() {
        this.size = getSize(this.host.clientWidth);
    }
    updateStates(states) {
        // Use peer specific store if available, otherwise fall back to global store
        const targetStore = this.peerStore || uiStore;
        const newStates = Object.assign({}, targetStore.state.states);
        targetStore.state.states = deepMerge(newStates, states);
        // Emit unscoped event for backward compatibility
        this.statesUpdate.emit(targetStore.state.states);
        // Also emit a scoped event that only this meeting's components should listen to
        const scopedEvent = new CustomEvent('rtkStatesUpdate', {
            detail: targetStore.state.states,
            bubbles: true,
            composed: true,
        });
        this.host.dispatchEvent(scopedEvent);
    }
    render() {
        const defaults = {
            meeting: this.meeting,
            size: this.size,
            states: (this.peerStore || uiStore).state.states,
            config: this.config || createDefaultConfig(),
            iconPack: this.iconPack,
            t: this.t,
        };
        if ((this.peerStore || uiStore).state.states.viewType === 'CHAT') {
            return h("rtk-chat", Object.assign({}, defaults));
        }
        const elementProps = {
            'rtk-grid': {
                layout: this.gridLayout,
            },
        };
        return h(Render, { element: "rtk-meeting", defaults: defaults, asHost: true, elementProps: elementProps });
    }
    get host() { return this; }
    static get watchers() { return {
        "meeting": ["meetingChanged"],
        "iconPack": ["iconPackChanged"],
        "t": ["tChanged"],
        "config": ["configChanged"],
        "overrides": ["overridesChanged"]
    }; }
    static get style() { return RtkMeetingStyle0; }
}, [1, "rtk-meeting", {
        "loadConfigFromPreset": [1028, "load-config-from-preset"],
        "applyDesignSystem": [1028, "apply-design-system"],
        "mode": [513],
        "leaveOnUnmount": [4, "leave-on-unmount"],
        "meeting": [16],
        "showSetupScreen": [1028, "show-setup-screen"],
        "t": [16],
        "config": [1040],
        "size": [1537],
        "gridLayout": [1, "grid-layout"],
        "iconPack": [16],
        "overrides": [16]
    }, undefined, {
        "meeting": ["meetingChanged"],
        "iconPack": ["iconPackChanged"],
        "t": ["tChanged"],
        "config": ["configChanged"],
        "overrides": ["overridesChanged"]
    }]);
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["rtk-meeting", "rtk-avatar", "rtk-button", "rtk-chat", "rtk-chat-composer-view", "rtk-chat-header", "rtk-chat-messages-ui-paginated", "rtk-chat-selector", "rtk-draft-attachment-view", "rtk-emoji-picker", "rtk-emoji-picker-button", "rtk-file-message-view", "rtk-file-picker-button", "rtk-icon", "rtk-image-message-view", "rtk-markdown-view", "rtk-menu", "rtk-menu-item", "rtk-menu-list", "rtk-message-view", "rtk-paginated-list", "rtk-pinned-message-selector", "rtk-spinner", "rtk-text-composer-view", "rtk-text-message-view", "rtk-tooltip"];
    components.forEach(tagName => { switch (tagName) {
        case "rtk-meeting":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, RtkMeeting$1);
            }
            break;
        case "rtk-avatar":
            if (!customElements.get(tagName)) {
                defineCustomElement$q();
            }
            break;
        case "rtk-button":
            if (!customElements.get(tagName)) {
                defineCustomElement$p();
            }
            break;
        case "rtk-chat":
            if (!customElements.get(tagName)) {
                defineCustomElement$o();
            }
            break;
        case "rtk-chat-composer-view":
            if (!customElements.get(tagName)) {
                defineCustomElement$n();
            }
            break;
        case "rtk-chat-header":
            if (!customElements.get(tagName)) {
                defineCustomElement$m();
            }
            break;
        case "rtk-chat-messages-ui-paginated":
            if (!customElements.get(tagName)) {
                defineCustomElement$l();
            }
            break;
        case "rtk-chat-selector":
            if (!customElements.get(tagName)) {
                defineCustomElement$k();
            }
            break;
        case "rtk-draft-attachment-view":
            if (!customElements.get(tagName)) {
                defineCustomElement$j();
            }
            break;
        case "rtk-emoji-picker":
            if (!customElements.get(tagName)) {
                defineCustomElement$i();
            }
            break;
        case "rtk-emoji-picker-button":
            if (!customElements.get(tagName)) {
                defineCustomElement$h();
            }
            break;
        case "rtk-file-message-view":
            if (!customElements.get(tagName)) {
                defineCustomElement$g();
            }
            break;
        case "rtk-file-picker-button":
            if (!customElements.get(tagName)) {
                defineCustomElement$f();
            }
            break;
        case "rtk-icon":
            if (!customElements.get(tagName)) {
                defineCustomElement$e();
            }
            break;
        case "rtk-image-message-view":
            if (!customElements.get(tagName)) {
                defineCustomElement$d();
            }
            break;
        case "rtk-markdown-view":
            if (!customElements.get(tagName)) {
                defineCustomElement$c();
            }
            break;
        case "rtk-menu":
            if (!customElements.get(tagName)) {
                defineCustomElement$b();
            }
            break;
        case "rtk-menu-item":
            if (!customElements.get(tagName)) {
                defineCustomElement$a();
            }
            break;
        case "rtk-menu-list":
            if (!customElements.get(tagName)) {
                defineCustomElement$9();
            }
            break;
        case "rtk-message-view":
            if (!customElements.get(tagName)) {
                defineCustomElement$8();
            }
            break;
        case "rtk-paginated-list":
            if (!customElements.get(tagName)) {
                defineCustomElement$7();
            }
            break;
        case "rtk-pinned-message-selector":
            if (!customElements.get(tagName)) {
                defineCustomElement$6();
            }
            break;
        case "rtk-spinner":
            if (!customElements.get(tagName)) {
                defineCustomElement$5();
            }
            break;
        case "rtk-text-composer-view":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "rtk-text-message-view":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "rtk-tooltip":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
    } });
}
defineCustomElement$1();

const RtkMeeting = RtkMeeting$1;
const defineCustomElement = defineCustomElement$1;

export { RtkMeeting, defineCustomElement };
