import { buildSearchStatus } from "@coveo/headless";
import { LitElement, css, html, nothing } from "lit";
import { customElement, state } from "lit/decorators.js";
import { createRef, ref } from "lit/directives/ref.js";
import { renderButton } from "../../common/button.js";
import { bindStateToController } from "../../../decorators/bind-state.js";
import { bindingGuard } from "../../../decorators/binding-guard.js";
import { bindings } from "../../../decorators/bindings.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import arrow_left_rounded from "../../../images/arrow-left-rounded.js";
import arrow_right_rounded from "../../../images/arrow-right-rounded.js";
import "../../common/atomic-icon/atomic-icon.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 AtomicSegmentedFacetScrollable extends LitElement {
    initialize() {
        this.searchStatus = buildSearchStatus(this.bindings.engine);
    }
    connectedCallback() {
        super.connectedCallback();
        this.addEventListener('wheel', this.handleScroll);
        this.addEventListener('touchmove', this.handleScroll);
        this.addEventListener('keydown', this.handleScroll);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.observer?.disconnect();
        this.removeEventListener('wheel', this.handleScroll);
        this.removeEventListener('touchmove', this.handleScroll);
        this.removeEventListener('keydown', this.handleScroll);
    }
    firstUpdated() {
        this.observer = new ResizeObserver(()=>{
            this.handleScroll();
        });
        Array.from(this.children).forEach((el)=>this.observer.observe(el));
        if (this.horizontalScrollRef.value) this.observer.observe(this.horizontalScrollRef.value);
    }
    render() {
        if (this.searchStatusState.hasError) return nothing;
        return html`
      <div part="scrollable-container" class="relative flex">
        ${this.renderArrow('left')}
        <div
          part="horizontal-scroll"
          class="wrapper-segmented flex flex-row overflow-x-scroll scroll-smooth"
          ${ref(this.horizontalScrollRef)}
        >
          <slot></slot>
        </div>
        ${this.renderArrow('right')}
      </div>
    `;
    }
    slideHorizontally(direction) {
        const container = this.horizontalScrollRef.value;
        const arrowsWidth = 2 * this.arrowRef.value.clientWidth;
        const pixelsToScroll = (container.clientWidth - arrowsWidth) * 0.7;
        const isLeftEdge = Math.floor(container.scrollLeft - pixelsToScroll) <= 0;
        const isRightEdge = Math.ceil(container.scrollLeft + pixelsToScroll) >= container.scrollWidth - container.clientWidth;
        this.hideLeftArrow = false;
        this.hideRightArrow = false;
        if ('left' === direction) {
            container.scrollLeft -= pixelsToScroll;
            this.hideLeftArrow = isLeftEdge;
            return;
        }
        container.scrollLeft += pixelsToScroll;
        this.hideRightArrow = isRightEdge;
    }
    renderArrow(direction) {
        const hide = 'left' === direction && this.hideLeftArrow || 'right' === direction && this.hideRightArrow;
        const hiddenClass = hide ? 'invisible opacity-0' : '';
        const transitionClass = 'transition-opacity transition-[visibility] ease-in-out duration-300';
        return html`
      <div
        part="${direction}-arrow-wrapper"
        class="${hiddenClass} ${transitionClass}"
      >
        ${renderButton({
            props: {
                style: 'square-neutral',
                part: `${direction}-arrow-button`,
                class: `absolute top-0 bottom-0 z-1 flex h-10 w-10 shrink-0 basis-8 items-center justify-center rounded ${'left' === direction ? 'left-0' : 'right-0'}`,
                ariaHidden: 'true',
                tabIndex: -1,
                onClick: ()=>this.slideHorizontally(direction),
                ref: this.arrowRef
            }
        })(html`
          <atomic-icon
            part="${direction}-arrow-icon"
            class="w-3.5"
            .icon=${'left' === direction ? arrow_left_rounded : arrow_right_rounded}
          ></atomic-icon>
        `)}
        <div
          part="${direction}-fade"
          class="from-background/60 pointer-events-none absolute top-0 z-0 h-10 w-20 ${'left' === direction ? 'left-0 bg-linear-to-r' : 'right-0 bg-linear-to-l'}"
        ></div>
      </div>
    `;
    }
    constructor(...args){
        super(...args), this.hideLeftArrow = true, this.hideRightArrow = true, this.horizontalScrollRef = createRef(), this.arrowRef = createRef(), this.handleScroll = ()=>{
            if (!this.horizontalScrollRef.value) return;
            const container = this.horizontalScrollRef.value;
            const isScrollable = container.clientWidth < container.scrollWidth;
            const isLeftEdge = Math.floor(container.scrollLeft) <= 0;
            const isRightEdge = Math.ceil(container.scrollLeft) >= container.scrollWidth - container.clientWidth;
            this.hideLeftArrow = !isScrollable || isLeftEdge;
            this.hideRightArrow = !isScrollable || isRightEdge;
        };
    }
}
AtomicSegmentedFacetScrollable.styles = css`.wrapper-segmented{scrollbar-width:none;-ms-overflow-style:none}.wrapper-segmented::-webkit-scrollbar{display:none}`;
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicSegmentedFacetScrollable.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicSegmentedFacetScrollable.prototype, "error", void 0);
_ts_decorate([
    bindStateToController('searchStatus'),
    state(),
    _ts_metadata("design:type", "u" < typeof SearchStatusState ? Object : SearchStatusState)
], AtomicSegmentedFacetScrollable.prototype, "searchStatusState", void 0);
_ts_decorate([
    state()
], AtomicSegmentedFacetScrollable.prototype, "hideLeftArrow", void 0);
_ts_decorate([
    state()
], AtomicSegmentedFacetScrollable.prototype, "hideRightArrow", void 0);
_ts_decorate([
    errorGuard(),
    bindingGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSegmentedFacetScrollable.prototype, "render", null);
AtomicSegmentedFacetScrollable = _ts_decorate([
    customElement('atomic-segmented-facet-scrollable'),
    bindings(),
    withTailwindStyles
], AtomicSegmentedFacetScrollable);
export { AtomicSegmentedFacetScrollable };
