import { LitElement } from "lit";
import { customElement, property } from "lit/decorators.js";
import { booleanConverter } from "../../../converters/boolean-converter.js";
import { watch } from "../../../decorators/watch.js";
import { LightDomMixin } from "../../../mixins/light-dom.js";
import { getFirstFocusableDescendant } from "../../../utils/accessibility-utils.js";
import { defer, getFocusedElement, getParent, isAncestorOf } from "../../../utils/utils.js";
function _ts_decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
    else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function _ts_metadata(k, v) {
    if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
}
class AtomicFocusTrap extends LightDomMixin(LitElement) {
    connectedCallback() {
        super.connectedCallback();
        document.addEventListener('focusin', this.onFocusChanged);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.showAll();
        document.removeEventListener('focusin', this.onFocusChanged);
    }
    hide(element) {
        if (element.hasAttribute('aria-hidden') || element.hasAttribute('aria-live') || 'atomic-aria-live' === element.tagName.toLowerCase()) return;
        element.setAttribute('aria-hidden', 'true');
        this.hiddenElements.push(element);
    }
    showAll() {
        let el = this.hiddenElements.pop();
        while(el){
            el.removeAttribute('aria-hidden');
            el = this.hiddenElements.pop();
        }
    }
    hideSiblingsRecursively(element) {
        const parent = getParent(element);
        if (null === parent) return;
        Array.from(parent.children).forEach((sibling)=>{
            if (sibling === element) return;
            if (sibling.assignedSlot && isAncestorOf(this, sibling.assignedSlot)) return;
            this.hide(sibling);
        });
        if (parent !== this.scope) this.hideSiblingsRecursively(parent);
    }
    showSelf() {
        this.parentToHide.removeAttribute('aria-hidden');
        this.parentToHide.removeAttribute('tabindex');
    }
    hideSelf() {
        if (this.shouldHideSelf) {
            this.parentToHide.setAttribute('aria-hidden', 'true');
            this.parentToHide.setAttribute('tabindex', '-1');
        }
    }
    async onDeactivated(isInitialLoad) {
        this.showAll();
        if (!isInitialLoad) {
            await defer();
            this.source?.focus();
        }
        this.hideSelf();
    }
    async onActivated(isInitialLoad) {
        this.showSelf();
        if (!isInitialLoad) {
            await defer();
            getFirstFocusableDescendant(this)?.focus();
        }
        this.hideSiblingsRecursively(this);
    }
    async handleActiveChange(_prev, next) {
        const isInitialLoad = next === _prev;
        if (next) await this.onActivated(isInitialLoad);
        else await this.onDeactivated(isInitialLoad);
    }
    get parentToHide() {
        return this.container ?? this;
    }
    constructor(...args){
        super(...args), this.active = false, this.shouldHideSelf = true, this.scope = document.body, this.hiddenElements = [], this.onFocusChanged = (e)=>{
            const elementIsPartOfHost = (focusedElement)=>isAncestorOf(this, focusedElement);
            const elementIsPartOfScope = (focusedElement)=>isAncestorOf(this.scope, focusedElement);
            if (!e.target || !this.active) return;
            const focusedElement = getFocusedElement();
            if (focusedElement && (elementIsPartOfHost(focusedElement) || !elementIsPartOfScope(focusedElement))) return;
            getFirstFocusableDescendant(this)?.focus();
        };
    }
}
_ts_decorate([
    property({
        type: Boolean,
        converter: booleanConverter
    })
], AtomicFocusTrap.prototype, "active", void 0);
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof HTMLElement ? Object : HTMLElement)
], AtomicFocusTrap.prototype, "source", void 0);
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof HTMLElement ? Object : HTMLElement)
], AtomicFocusTrap.prototype, "container", void 0);
_ts_decorate([
    property({
        type: Boolean,
        attribute: 'should-hide-self',
        converter: booleanConverter
    })
], AtomicFocusTrap.prototype, "shouldHideSelf", void 0);
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof Element ? Object : Element)
], AtomicFocusTrap.prototype, "scope", void 0);
_ts_decorate([
    watch('active', {
        waitUntilFirstUpdate: true
    }),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        Boolean,
        Boolean
    ]),
    _ts_metadata("design:returntype", Promise)
], AtomicFocusTrap.prototype, "handleActiveChange", null);
AtomicFocusTrap = _ts_decorate([
    customElement('atomic-focus-trap')
], AtomicFocusTrap);
export { AtomicFocusTrap };
