import { getFirstFocusableDescendant } from "../../../utils/accessibility-utils.js";
import { defer, once } from "../../../utils/utils.js";
import { updateBreakpoints } from "../../../utils/replace-breakpoint-utils.js";
const resultComponentClass = 'result-component';
class ItemListCommon {
    updateBreakpoints() {
        this.updateBreakpointsOnce();
    }
    getResultId(uniqueIdOnResult, searchResponseId, density, imageSize) {
        return `${uniqueIdOnResult}${searchResponseId}${density}${imageSize}`;
    }
    setNewResultRef(element, resultIndex) {
        if (0 === resultIndex) this.firstResultEl = element;
        if (resultIndex !== this.indexOfResultToFocus) return;
        if (!element.children.length && !element.shadowRoot?.children.length) return;
        this.indexOfResultToFocus = void 0;
        const elementToFocus = getFirstFocusableDescendant(element) ?? element;
        this.props.nextNewItemTarget.setTarget(elementToFocus);
    }
    focusOnNextNewResult() {
        this.indexOfResultToFocus = this.props.getCurrentNumberOfItems();
        this.props.nextNewItemTarget.focusOnNextTarget();
    }
    async focusOnFirstResultAfterNextSearch() {
        await defer();
        return new Promise((resolve)=>{
            if (this.props.getIsLoading()) this.firstResultEl = void 0;
            const unsub = this.props.engineSubscribe(async ()=>{
                await defer();
                if (!this.props.getIsLoading() && this.firstResultEl) {
                    const elementToFocus = getFirstFocusableDescendant(this.firstResultEl) ?? this.firstResultEl;
                    this.props.nextNewItemTarget.setTarget(elementToFocus);
                    this.props.nextNewItemTarget.focus();
                    this.firstResultEl = void 0;
                    unsub();
                    resolve();
                }
            });
        });
    }
    constructor(props){
        this.props = props;
        this.props.store.setLoadingFlag(this.props.loadingFlag);
        this.props.store.state.resultList = this;
        this.updateBreakpointsOnce = once(()=>updateBreakpoints(this.props.host));
        this.props.nextNewItemTarget.registerFocusCallback(()=>{
            this.indexOfResultToFocus = void 0;
        });
    }
}
export { ItemListCommon, resultComponentClass };
