/**
 * Copyright 2018 The Pennsylvania State University
 * @license Apache-2.0, see License.md for full text.
 */
import{LitElement as e}from"../../../lit/index.js";globalThis.A11yMediaStateManager=globalThis.A11yMediaStateManager||{},globalThis.A11yMediaStateManager.requestAvailability=()=>(!globalThis.A11yMediaStateManager.instance&&globalThis.document&&(globalThis.A11yMediaStateManager.instance=globalThis.document.createElement("a11y-media-state-manager"),globalThis.document.body.appendChild(globalThis.A11yMediaStateManager.instance)),globalThis.A11yMediaStateManager.instance);class A11yMediaStateManager extends e{static get tag(){return"a11y-media-state-manager"}static get properties(){return{...super.properties,players:{type:Array},activePlayer:{type:Object}}}constructor(){super(),this.windowControllers=new AbortController,this.players=[],this.__stickyManager=e=>this.setStickyPlayer(e.detail),this.__fullscreenManager=e=>this._handleFullscreen(e.detail),this.__playerLoader=e=>this.players.push(e.detail),globalThis.A11yMediaStateManager.instance||(globalThis.A11yMediaStateManager.instance=this)}checkConcurrentPlayers(){let e=this.activePlayer;this.players.forEach((a=>{e&&a!==e&&(a.fullscreen&&a.toggleFullscreen(!1),a.allowConcurrent&&e.allowConcurrent&&!e.fullscreen||a.pause())}))}setActivePlayer(e){this.activePlayer=e,this.checkConcurrentPlayers(),this.observer&&this.observer.disconnect(),this.observer.observe(this.activePlayer)}get observer(){return this._observer=this._observer||new IntersectionObserver(((e,a)=>{globalThis.A11yMediaStateManager.instance._handleIntersect(e,a)}),{root:null,rootMargin:"0px",threshold:[.25,.75]}),this._observer}_handleIntersect(e,a){e.forEach((e=>{!this.activePlayer||this.activePlayer.fullscreen||(this.activePlayer.__playing?this.activePlayer.toggleSticky(!e.isIntersecting):this.activePlayer.toggleSticky(!1))}))}setStickyPlayer(e){e!==this.activePlayer&&void 0!==this.activePlayer&&null!==this.activePlayer&&this.activePlayer.toggleSticky(!1),this.setActivePlayer(e)}_handleFullscreen(e){e&&e.fullscreen&&this.setActivePlayer(e)}connectedCallback(){super.connectedCallback(),globalThis.addEventListener("a11y-player-playing",this.__stickyManager.bind(this),{signal:this.windowControllers.signal}),globalThis.addEventListener("fullscreen-toggle",this._handleFullscreen.bind(this),{signal:this.windowControllers.signal}),globalThis.addEventListener("a11y-player",this.__playerLoader.bind(this),{signal:this.windowControllers.signal})}disconnectedCallback(){this.windowControllers.abort(),super.disconnectedCallback()}}customElements.define(A11yMediaStateManager.tag,A11yMediaStateManager);export{A11yMediaStateManager};