/*!
 * Crafted with ❤ by Salla
 */
import { h, Host } from "@stencil/core";
import { fetchCities, fetchDeliveryMessage } from "./delivery-promise-api";
import { filterCitiesForModal } from "./delivery-promise-city-filter";
import { buildBulletOpenPayload, resolveIntent } from "./delivery-promise-intent";
import { DEFAULT_LABELS, getCityDisplayName, loadLabels } from "./delivery-promise-labels";
/**
 * @name SallaDeliveryPromise
 * @description Displays delivery promise message (from BE) with city selection
 * @tag salla-delivery-promise
 */
export class SallaDeliveryPromise {
    constructor() {
        // ── Feature flags & config ────────────────────────────────────────────
        this.isDeliveryPromiseEnabled = false;
        this.isLoginCycleEnabled = false;
        this.canRender = false;
        // ── Shared display state ──────────────────────────────────────────────
        this.labels = DEFAULT_LABELS;
        this.selectedLabel = null;
        this.deliveryMessage = null;
        this.hasError = false;
        this.errorMessage = '';
        this.isLoadingPromises = false;
        // ── Login-cycle state (bullet delivery integration) ───────────────────
        this.selectedCityLoginCycle = null;
        this.selectedBranchLoginCycle = null;
        // ── Standard flow state (city list) ───────────────────────────────────
        this.cities = [];
        this.selectedCity = null;
        this.isLoadingCities = false;
        // ── City-change modal state (non–login-cycle) ─────────────────────────
        this.modalSearchQuery = '';
        this.cityPendingSelection = null;
        this.isCityPopoverOpen = false;
        // ═══════════════════════════════════════════════════════════════════════
        //  Login-cycle (bullet delivery) integration
        // ═══════════════════════════════════════════════════════════════════════
        this.onBulletDeliveryConfirmed = () => {
            this.applyBulletIntent();
        };
        this.handleModalSearchInput = (event) => {
            this.modalSearchQuery = event.target.value;
            this.isCityPopoverOpen = true;
        };
        this.handleModalComboboxActivate = () => {
            this.isCityPopoverOpen = true;
        };
        // ═══════════════════════════════════════════════════════════════════════
        //  Header click (dispatches to correct flow)
        // ═══════════════════════════════════════════════════════════════════════
        this.handleHeaderClick = (e) => {
            e.stopPropagation();
            if (this.isLoginCycleEnabled) {
                this.openBulletDeliveryModal();
            }
            else {
                void this.openCityChangeModal();
            }
        };
    }
    // ═══════════════════════════════════════════════════════════════════════
    //  Lifecycle
    // ═══════════════════════════════════════════════════════════════════════
    async componentDidLoad() {
        await salla.onReady();
        await salla.lang.onLoaded();
        this.labels = loadLabels();
        this.isDeliveryPromiseEnabled = salla.config.get('store.features', []).includes('delivery-promises');
        this.isLoginCycleEnabled = salla.config.get('store.features', []).includes('bullet-delivery-v2');
        this.productId = salla.config.get('page.id');
        if (!this.isDeliveryPromiseEnabled) {
            this.canRender = false;
            return;
        }
        if (this.isLoginCycleEnabled) {
            this.applyBulletIntent();
            this.canRender = true;
            window.addEventListener('bulletDeliveryConfirmed', this.onBulletDeliveryConfirmed);
        }
        else {
            this.selectedLabel = `${this.labels.deliveryTo} ${this.labels.selectCity}`;
            await this.loadCities();
        }
    }
    disconnectedCallback() {
        window.removeEventListener('bulletDeliveryConfirmed', this.onBulletDeliveryConfirmed);
    }
    applyBulletIntent() {
        const resolved = resolveIntent();
        if (!resolved) {
            this.selectedLabel = `${this.labels.deliveryTo} ${this.labels.selectCity}`;
            this.selectedCityLoginCycle = null;
            this.selectedBranchLoginCycle = null;
            this.deliveryMessage = null;
            return;
        }
        if (resolved.type === 'address') {
            this.selectedCityLoginCycle = resolved.option;
            this.selectedBranchLoginCycle = null;
            this.selectedLabel = `${this.labels.deliveryTo} ${resolved.option.name || this.labels.selectCity}`;
            void this.loadDeliveryMessage(resolved.option.id, 'city');
        }
        else {
            this.selectedBranchLoginCycle = resolved.option;
            this.selectedCityLoginCycle = null;
            this.selectedLabel = `${this.labels.pickupFromBranch} ${resolved.option.name}`;
            void this.loadDeliveryMessage(resolved.option.id, 'branch');
        }
    }
    openBulletDeliveryModal() {
        salla.event.emit('salla::bullet-delivery.modal.open.requested', buildBulletOpenPayload());
    }
    // ═══════════════════════════════════════════════════════════════════════
    //  Standard flow (city list, no login cycle)
    // ═══════════════════════════════════════════════════════════════════════
    async loadCities() {
        this.isLoadingCities = true;
        this.hasError = false;
        try {
            const { cities, preselected } = await fetchCities(this.productId);
            if (cities.length === 0) {
                this.canRender = false;
                return;
            }
            this.cities = cities;
            if (preselected) {
                this.selectedCity = preselected;
                this.selectedLabel = `${this.labels.deliveryTo} ${getCityDisplayName(preselected)}`;
                await this.loadDeliveryMessage(preselected.id, 'city');
            }
            this.canRender = true;
        }
        catch (error) {
            this.hasError = true;
            this.errorMessage = error.message || 'Failed to load cities';
            this.canRender = false;
        }
        finally {
            this.isLoadingCities = false;
        }
    }
    // ═══════════════════════════════════════════════════════════════════════
    //  Delivery message (shared by both flows)
    // ═══════════════════════════════════════════════════════════════════════
    async loadDeliveryMessage(id, optionType) {
        this.isLoadingPromises = true;
        this.hasError = false;
        this.deliveryMessage = null;
        try {
            this.deliveryMessage = await fetchDeliveryMessage(this.productId, id, optionType, this.isLoginCycleEnabled);
        }
        catch (error) {
            this.hasError = true;
            this.errorMessage = optionType === 'city' ? this.labels.errorDeliveryPromise : this.labels.errorPickupPromise;
        }
        finally {
            this.isLoadingPromises = false;
        }
    }
    // ═══════════════════════════════════════════════════════════════════════
    //  City-change modal handlers (non–login-cycle)
    // ═══════════════════════════════════════════════════════════════════════
    async openCityChangeModal() {
        if (!this.cityModalRef)
            return;
        this.cityPendingSelection = null;
        this.modalSearchQuery = '';
        this.isCityPopoverOpen = false;
        await this.cityModalRef.setTitle(this.labels.changeCityTitle);
        await this.cityModalRef.open();
    }
    handleModalSelectCity(city) {
        this.cityPendingSelection = city;
        this.modalSearchQuery = getCityDisplayName(city);
        this.isCityPopoverOpen = false;
    }
    async handleConfirmCityModal() {
        if (!this.cityPendingSelection) {
            await this.cityModalRef?.close();
            return;
        }
        const city = this.cityPendingSelection;
        this.selectedCity = city;
        this.selectedLabel = `${this.labels.deliveryTo} ${getCityDisplayName(city)}`;
        await this.loadDeliveryMessage(city.id, 'city');
        await this.cityModalRef?.close();
    }
    // ═══════════════════════════════════════════════════════════════════════
    //  Render helpers
    // ═══════════════════════════════════════════════════════════════════════
    renderLoadingSkeleton() {
        return (h(Host, { class: "s-delivery-promise-wrapper s-delivery-promise-skeleton" }, h("div", { class: "s-delivery-promise-container" }, h("div", { class: "s-delivery-promise-header s-delivery-promise-header-skeleton" }, h("div", { class: "s-delivery-promise-location" }, h("salla-skeleton", { height: "14px", width: "180px" })), h("salla-skeleton", { height: "18px", width: "18px" })), h("div", { class: "s-delivery-promise-loading" }, h("salla-skeleton", { height: "20px", width: "80%" })))));
    }
    renderDeliveryMessage() {
        if (this.isLoadingPromises) {
            return (h("div", { class: "s-delivery-promise-loading" }, h("salla-skeleton", { height: "20px", width: "80%" })));
        }
        if (!this.deliveryMessage)
            return null;
        return h("div", { class: "s-delivery-promise-message" }, this.deliveryMessage);
    }
    renderCityModalBody() {
        const filtered = filterCitiesForModal(this.cities, this.modalSearchQuery);
        return (h("div", { class: "s-delivery-promise-modal-body" }, h("label", { class: "s-delivery-promise-modal-field-label", htmlFor: "s-delivery-promise-modal-search" }, this.labels.cityFieldLabel, h("span", { class: "s-delivery-promise-required", "aria-hidden": "true" }, " *")), h("div", { class: "s-delivery-promise-modal-combobox" }, h("div", { class: "s-delivery-promise-modal-search", onClick: this.handleModalComboboxActivate }, h("i", { class: "sicon-search", "aria-hidden": "true" }), h("input", { id: "s-delivery-promise-modal-search", type: "text", class: "form-input", placeholder: this.labels.modalSearchPlaceholder, value: this.modalSearchQuery, onInput: this.handleModalSearchInput, autocomplete: "off", "aria-autocomplete": "list", "aria-expanded": this.isCityPopoverOpen ? 'true' : 'false', "aria-controls": "s-delivery-promise-modal-listbox" })), h("div", { id: "s-delivery-promise-modal-listbox", class: "s-delivery-promise-modal-popover", role: "listbox", hidden: !this.isCityPopoverOpen }, h("div", { class: "s-delivery-promise-modal-list s-scrollbar" }, filtered.length === 0 ? (h("div", { class: "s-delivery-promise-modal-empty" }, this.labels.noResults)) : (filtered.map(city => (h("button", { key: city.id, type: "button", role: "option", class: {
                's-delivery-promise-modal-item': true,
                's-delivery-promise-modal-item--selected': this.cityPendingSelection?.id === city.id,
            }, "aria-selected": this.cityPendingSelection?.id === city.id ? 'true' : 'false', onClick: e => {
                e.stopPropagation();
                this.handleModalSelectCity(city);
            } }, h("span", { class: "s-delivery-promise-modal-item-name" }, city.name), this.cityPendingSelection?.id === city.id ? h("i", { class: "sicon-check", "aria-hidden": "true" }) : null)))))))));
    }
    renderCityChangeModal() {
        if (this.isLoginCycleEnabled)
            return null;
        return (h("salla-modal", { id: "s-delivery-promise-city-modal", ref: el => { this.cityModalRef = el; }, class: "s-delivery-promise-city-modal", isClosable: true, width: "md", "modal-title": this.labels.changeCityTitle, subTitle: this.labels.changeCitySubtitle }, this.renderCityModalBody(), h("salla-button", { slot: "footer", width: "wide", disabled: !this.cityPendingSelection, onClick: () => this.handleConfirmCityModal() }, !this.isLoadingPromises && this.labels.confirmAddress)));
    }
    // ═══════════════════════════════════════════════════════════════════════
    //  Main render
    // ═══════════════════════════════════════════════════════════════════════
    render() {
        if (!this.isDeliveryPromiseEnabled)
            return null;
        if (this.isLoadingCities)
            return this.renderLoadingSkeleton();
        if (!this.canRender)
            return null;
        return (h(Host, { class: "s-delivery-promise-wrapper" }, h("div", { class: "s-delivery-promise-container" }, h("div", { class: "s-delivery-promise-header", onClick: this.handleHeaderClick }, h("div", { class: "s-delivery-promise-location" }, h("span", { class: "s-delivery-promise-title" }, this.selectedLabel)), h("i", { class: `sicon-keyboard_arrow_down s-delivery-promise-arrow` })), this.hasError && h("div", { class: "s-delivery-promise-error" }, this.errorMessage), !this.hasError && this.renderDeliveryMessage()), this.renderCityChangeModal()));
    }
    static get is() { return "salla-delivery-promise"; }
    static get states() {
        return {
            "isDeliveryPromiseEnabled": {},
            "isLoginCycleEnabled": {},
            "canRender": {},
            "labels": {},
            "selectedLabel": {},
            "deliveryMessage": {},
            "hasError": {},
            "errorMessage": {},
            "isLoadingPromises": {},
            "selectedCityLoginCycle": {},
            "selectedBranchLoginCycle": {},
            "cities": {},
            "selectedCity": {},
            "isLoadingCities": {},
            "modalSearchQuery": {},
            "cityPendingSelection": {},
            "isCityPopoverOpen": {}
        };
    }
    static get elementRef() { return "host"; }
}
