import { Host, h } from "@stencil/core";
import { getCountries, getCountryCallingCode } from "libphonenumber-js";
import { computePosition, autoUpdate, offset, flip, shift } from "@floating-ui/dom";
import { ZInput } from "../internal-component/z-input";
import { configStore } from "../../store/store";
export class ZPhoneInput {
    value = '';
    label;
    placeholder = '';
    defaultCountry = 'TH';
    countryCallingCode;
    error;
    disabled = false;
    selectedCountry = 'TH';
    isOpen = false;
    searchQuery = '';
    textChange;
    countryChange;
    triggerEl;
    popperEl;
    cleanup;
    componentWillLoad() {
        if (this.countryCallingCode) {
            this.updateSelectedCountryFromCallingCode(this.countryCallingCode);
        }
        else {
            this.selectedCountry = this.defaultCountry || 'TH';
        }
    }
    defaultCountryChanged(newValue) {
        if (!this.countryCallingCode) {
            this.selectedCountry = newValue || 'TH';
        }
    }
    countryCallingCodeChanged(newValue) {
        this.updateSelectedCountryFromCallingCode(newValue);
    }
    updateSelectedCountryFromCallingCode(callingCode) {
        if (!callingCode)
            return;
        const countries = getCountries();
        const foundCountry = countries.find(c => getCountryCallingCode(c) === callingCode);
        if (foundCountry) {
            this.selectedCountry = foundCountry;
        }
    }
    componentDidLoad() {
        document.addEventListener('click', this.handleClickOutside);
    }
    disconnectedCallback() {
        document.removeEventListener('click', this.handleClickOutside);
        if (this.cleanup)
            this.cleanup();
    }
    handleClickOutside = (e) => {
        if (!this.isOpen)
            return;
        const path = e.composedPath();
        if (!path.includes(this.triggerEl) && !path.includes(this.popperEl)) {
            this.isOpen = false;
            this.searchQuery = '';
        }
    };
    updatePosition() {
        if (!this.triggerEl || !this.popperEl)
            return;
        this.cleanup = autoUpdate(this.triggerEl, this.popperEl, () => {
            computePosition(this.triggerEl, this.popperEl, {
                placement: 'bottom-start',
                middleware: [offset(4), flip(), shift()],
            }).then(({ x, y }) => {
                Object.assign(this.popperEl.style, {
                    left: `${x}px`,
                    top: `${y}px`,
                });
            });
        });
    }
    watchIsOpen(isOpen) {
        if (isOpen) {
            // Small delay to ensure elements are rendered
            requestAnimationFrame(() => {
                this.updatePosition();
                const searchInput = this.popperEl?.querySelector('input');
                if (searchInput)
                    searchInput.focus();
            });
        }
        else {
            if (this.cleanup)
                this.cleanup();
            this.searchQuery = '';
        }
    }
    toggleDropdown = () => {
        if (this.disabled)
            return;
        this.isOpen = !this.isOpen;
    };
    handleSearch = (e) => {
        this.searchQuery = e.target.value;
    };
    selectCountry(country) {
        this.selectedCountry = country;
        this.isOpen = false;
        this.searchQuery = '';
        const callingCode = getCountryCallingCode(country);
        this.countryChange.emit(callingCode);
    }
    handleInput = (val) => {
        this.textChange.emit(val);
    };
    handleCountryChange = (event) => {
        const target = event.target;
        const isoCode = target.value;
        this.selectedCountry = isoCode;
        const callingCode = getCountryCallingCode(isoCode);
        this.countryChange.emit(callingCode);
    };
    getFlagEmoji(countryCode) {
        const codePoints = countryCode
            .toUpperCase()
            .split('')
            .map(char => 127397 + char.charCodeAt(0));
        return String.fromCodePoint(...codePoints);
    }
    render() {
        const theme = configStore.get('theme');
        const allCountries = getCountries();
        const regionNames = new Intl.DisplayNames(['en'], { type: 'region' });
        const filteredCountries = allCountries.filter(country => {
            if (!this.searchQuery)
                return true;
            const query = this.searchQuery.toLowerCase();
            const code = country.toLowerCase();
            const callingCode = getCountryCallingCode(country);
            const name = (regionNames.of(country) || '').toLowerCase();
            return code.includes(query) || callingCode.includes(query) || name.includes(query);
        });
        return (h(Host, { "data-theme": theme }, this.label && h("label", { class: "z-input-label mb-1 block text-sm font-medium text-surface" }, this.label), h("div", { class: "flex gap-2" }, h("div", { class: "relative" }, h("div", { class: `z-input h-10 pr-8! w-auto! flex items-center gap-2 cursor-pointer min-w-[100px] ${this.disabled ? 'opacity-50 cursor-not-allowed' : ''}`, onClick: this.toggleDropdown, ref: (el) => (this.triggerEl = el) }, h("span", null, this.getFlagEmoji(this.selectedCountry)), h("span", null, "+", getCountryCallingCode(this.selectedCountry))), h("div", { class: "pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-surface pb-1" }, h("svg", { class: "h-4 w-4 fill-current", xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20" }, h("path", { d: "M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" }))), this.isOpen && (h("div", { class: "absolute z-50 w-64 mt-1 bg-background border border-divider rounded-md shadow-lg max-h-60 flex flex-col", ref: (el) => (this.popperEl = el) }, h("div", { class: "p-2 border-b border-divider sticky top-0 bg-background z-10" }, h("input", { type: "text", class: "w-full px-2 py-1 text-sm bg-background text-surface border border-divider rounded outline-none focus:border-primary", placeholder: "Search country...", value: this.searchQuery, onInput: this.handleSearch, onClick: (e) => e.stopPropagation() })), h("div", { class: "overflow-y-auto flex-1" }, filteredCountries.map(country => (h("div", { class: `px-3 py-2 text-sm cursor-pointer hover:bg-surface/10 flex items-center gap-2 text-surface
                        ${country === this.selectedCountry ? 'bg-primary/10 text-primary' : ''}`, onClick: () => this.selectCountry(country) }, h("span", null, this.getFlagEmoji(country)), h("span", { class: "flex-1 truncate" }, regionNames.of(country)), h("span", { class: "text-xs text-surface/70" }, "+", getCountryCallingCode(country))))), filteredCountries.length === 0 && (h("div", { class: "px-3 py-2 text-sm text-surface/50 text-center" }, "No countries found")))))), h("div", { class: "flex-1" }, h(ZInput, { placeholder: this.placeholder, value: this.value, onChange: this.handleInput, error: this.error, disabled: this.disabled })))));
    }
    static get is() { return "z-phone-input"; }
    static get originalStyleUrls() {
        return {
            "$": ["z-phone-input.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["z-phone-input.css"]
        };
    }
    static get properties() {
        return {
            "value": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "value",
                "defaultValue": "''"
            },
            "label": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "label"
            },
            "placeholder": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "placeholder",
                "defaultValue": "''"
            },
            "defaultCountry": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "default-country",
                "defaultValue": "'TH'"
            },
            "countryCallingCode": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "country-calling-code"
            },
            "error": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "error"
            },
            "disabled": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "disabled",
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "selectedCountry": {},
            "isOpen": {},
            "searchQuery": {}
        };
    }
    static get events() {
        return [{
                "method": "textChange",
                "name": "textChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                }
            }, {
                "method": "countryChange",
                "name": "countryChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "defaultCountry",
                "methodName": "defaultCountryChanged"
            }, {
                "propName": "countryCallingCode",
                "methodName": "countryCallingCodeChanged"
            }, {
                "propName": "isOpen",
                "methodName": "watchIsOpen"
            }];
    }
}
