import { r as registerInstance, c as createEvent, h, d as getElement } from './index-D4ALLk7q.js';
import { c as classNames } from './index-D7YaJBkB.js';
import { g as getIconElementProps } from './icon-utils-SXopALR1.js';
import { f as floatingElementAutoUpdate, a as applyStyles } from './position-utils-BiHzhysf.js';
import { r as renderHint } from './hint-utils-BJaEKoxW.js';
import { v as v4 } from './v4-CK3_k8jD.js';
import './test-id-utils-BDMnqEGL.js';

const INTERNAL_CURRENCY_LIST = [
    { code: 'USD', id: 'US', symbol: '$', name: 'US Dollar', decimalSeparator: '.', thousandsSeparator: ',' },
    { code: 'EUR', id: 'DE', symbol: '€', name: 'Euro', decimalSeparator: ',', thousandsSeparator: '.' },
    { code: 'GBP', id: 'GB', symbol: '£', name: 'British Pound', decimalSeparator: '.', thousandsSeparator: ',' },
    { code: 'TRY', id: 'TR', symbol: '₺', name: 'Turkish Lira', decimalSeparator: ',', thousandsSeparator: '.' },
    { code: 'JPY', id: 'JP', symbol: '¥', name: 'Japanese Yen', decimalSeparator: '.', thousandsSeparator: ',' },
    { code: 'CAD', id: 'CA', symbol: 'C$', name: 'Canadian Dollar', decimalSeparator: '.', thousandsSeparator: ',' },
    { code: 'AUD', id: 'AU', symbol: 'A$', name: 'Australian Dollar', decimalSeparator: '.', thousandsSeparator: ',' },
    { code: 'CHF', id: 'CH', symbol: 'Fr', name: 'Swiss Franc', decimalSeparator: '.', thousandsSeparator: ',' },
    { code: 'CNY', id: 'CN', symbol: '¥', name: 'Chinese Yuan', decimalSeparator: '.', thousandsSeparator: ',' },
    { code: 'SEK', id: 'SE', symbol: 'kr', name: 'Swedish Krona', decimalSeparator: ',', thousandsSeparator: ' ' },
];

const validSeparators = [',', '.', ' '];
/**
 * Returns an alternative separator that is different from the provided one.
 * Used to prevent conflicts when only one separator is provided.
 */
const getAlternativeSeparator = (oppositeSep) => {
    const alternatives = [',', '.'];
    //aynı değer olmaması için yapıldı
    return alternatives.find(sep => sep !== oppositeSep);
};
/**
 * Validates that a separator is one of the allowed values.
 * Returns the separator if valid, undefined if invalid or not provided.
 */
const validateSeparator = (separator) => {
    if (!separator)
        return undefined;
    if (!validSeparators.includes(separator)) {
        console.warn(`TkCurrencyInput: Invalid separator '${separator}'. Must be one of: ${validSeparators.join(', ')}`);
        return undefined;
    }
    return separator;
};
/**
 * @param targetSeparator - Custom separator from component prop (if called in decimalSeparator, decimalSeparator)
 * @param oppositeSeparator - The opposite custom separator (if called in decimalSeparator, targetSeparator) to avoid conflicts
 * @param targetSelectedSeparator - Separator from selected currency (e.g., selectedCurrency.decimalSeparator)
 * @param oppositeSelectedSeparator - The opposite separator from currency (e.g., selectedCurrency.thousandsSeparator)
 * @param fallback - Final fallback separator if all other options are undefined
 * @returns The appropriate separator to use
 *
 */
const getValidSeparator = (targetSeparator, oppositeSeparator, targetSelectedSeparator, oppositeSelectedSeparator, fallback) => {
    // Validate all separators
    const validTarget = validateSeparator(targetSeparator);
    const validOpposite = validateSeparator(oppositeSeparator);
    const validTargetSelected = validateSeparator(targetSelectedSeparator);
    const validOppositeSelected = validateSeparator(oppositeSelectedSeparator);
    // Check for conflicts in custom props
    if (validTarget && validOpposite && validTarget === validOpposite) {
        console.error(`TkCurrencyInput: Both separator props are set to '${validTarget}' they cannot be the same.`);
        return validTarget;
    }
    // Check for conflicts in interface fields
    if (validTargetSelected && validOppositeSelected && validTargetSelected === validOppositeSelected) {
        console.error(`TkCurrencyInput: Both interface separator fields set to '${validTargetSelected}' they cannot be the same.`);
        return validTargetSelected;
    }
    // Priority 1: Use valid target separator if provided
    if (validTarget) {
        return validTarget;
    }
    // Priority 2: Auto-select if opposite separator is provided but target is not
    if (validOpposite) {
        return getAlternativeSeparator(validOpposite);
    }
    // Priority 3: Use currency's default for target separator
    if (validTargetSelected) {
        return validTargetSelected;
    }
    // Priority 4: Auto-select from currency's opposite separator
    if (validOppositeSelected) {
        return getAlternativeSeparator(validOppositeSelected);
    }
    // Priority 5: Final fallback
    return fallback;
};

const tkCurrencyInputCss = () => `@font-face{font-family:"Material Symbols Outlined";src:url("./assets/fonts/material-symbols/Material-Symbols-Outlined.woff2") format("woff2");font-weight:400;font-style:normal;font-display:swap}.material-symbols-outlined{font-family:"Material Symbols Outlined";font-weight:normal;font-style:normal;font-size:24px;line-height:1;letter-spacing:normal;text-transform:none;display:inline-block;white-space:nowrap;word-wrap:normal;direction:ltr;-webkit-font-feature-settings:"liga";-webkit-font-smoothing:antialiased}.material-symbols-outlined{font-variation-settings:"FILL" 0}.material-symbols-outlined.fill{font-variation-settings:"FILL" 1}@font-face{font-family:"Material Symbols Rounded";src:url("./assets/fonts/material-symbols/Material-Symbols-Rounded.woff2") format("woff2");font-weight:400;font-style:normal;font-display:swap}.material-symbols-rounded{font-family:"Material Symbols Rounded";font-weight:normal;font-style:normal;font-size:24px;line-height:1;letter-spacing:normal;text-transform:none;display:inline-block;white-space:nowrap;word-wrap:normal;direction:ltr;-webkit-font-feature-settings:"liga";-webkit-font-smoothing:antialiased}.material-symbols-rounded{font-variation-settings:"FILL" 0}.material-symbols-rounded.fill{font-variation-settings:"FILL" 1}@font-face{font-family:"Material Symbols Sharp";src:url("./assets/fonts/material-symbols/Material-Symbols-Sharp.woff2") format("woff2");font-weight:400;font-style:normal;font-display:swap}.material-symbols-sharp{font-family:"Material Symbols Sharp";font-weight:normal;font-style:normal;font-size:24px;line-height:1;letter-spacing:normal;text-transform:none;display:inline-block;white-space:nowrap;word-wrap:normal;direction:ltr;-webkit-font-feature-settings:"liga";-webkit-font-smoothing:antialiased}.material-symbols-sharp{font-variation-settings:"FILL" 0}.material-symbols-sharp.fill{font-variation-settings:"FILL" 1}:host{display:block;min-width:0}.tk-currency-input-container{display:flex;flex-direction:column;align-items:flex-start;color:var(--text-darkest);font-family:var(--family-body);gap:var(--input-external-label-small-container-gap);min-width:0}.tk-currency-input-container .tk-currency-input-label{font-weight:var(--weight-regular)}.tk-currency-input-container .tk-currency-input-label .tk-currency-input-label-title{color:var(--text-darkest)}.tk-currency-input-container .tk-currency-input-label .tk-currency-input-label-asterisk{color:var(--states-danger-base);font-size:var(--desktop-label-l-size);line-height:var(--line-height-xs-none);font-weight:var(--weight-light)}.tk-currency-input-container .tk-currency-input-wrapper{display:flex;align-items:center;gap:var(--input-external-label-small-container-gap);align-self:stretch;border-radius:var(--button-sizes-large-radius);border:var(--spacing-px) solid var(--border-light);background:var(--static-light);overflow:hidden}.tk-currency-input-container .tk-currency-input-wrapper:focus{border:var(--spacing-px) solid var(--states-info-base)}.tk-currency-input-container .tk-currency-input-wrapper:hover{background-color:var(--background-lightest)}.tk-currency-input-container .tk-currency-input-input{flex:1;min-width:0;border:none;background-color:transparent;outline:none}.tk-currency-input-container .tk-currency-input-input::placeholder{color:var(--text-sub-base)}.tk-currency-input-container .tk-currency-input-dropdown{flex-shrink:0}.tk-currency-input-container .tk-currency-input-dropdown .tk-currency-input-dropdown-button{display:flex;align-items:center;border:none;background-color:transparent;padding:0}.tk-currency-input-container .tk-currency-input-dropdown .tk-currency-input-dropdown-button:not([aria-disabled]){cursor:pointer}.tk-currency-input-container .tk-currency-input-dropdown .tk-currency-input-dropdown-button .tk-currency-input-dropdown-button-selected{display:flex;align-items:center;gap:var(--spacing-xs);padding-left:var(--spacing-m-base);border-left:var(--spacing-px) solid var(--border-light)}.tk-currency-input-container .tk-currency-input-dropdown .tk-currency-input-dropdown-menu{position:fixed;z-index:800;background:var(--static-light);border:var(--spacing-px) solid var(--border-light);border-radius:var(--button-sizes-large-radius);box-shadow:var(--effect-1-default-sm);display:flex;flex-direction:column;overflow:hidden}.tk-currency-input-container .tk-currency-input-dropdown .tk-currency-input-dropdown-menu .tk-currency-input-dropdown-menu-list{list-style:none;overflow-y:auto;margin:var(--spacing-m-base)}.tk-currency-input-container .tk-currency-input-dropdown .tk-currency-input-dropdown-menu .tk-currency-input-dropdown-menu-list::-webkit-scrollbar{width:4px;height:4px}.tk-currency-input-container .tk-currency-input-dropdown .tk-currency-input-dropdown-menu .tk-currency-input-dropdown-menu-list::-webkit-scrollbar-track{background:var(--background-lightest);border-radius:2px}.tk-currency-input-container .tk-currency-input-dropdown .tk-currency-input-dropdown-menu .tk-currency-input-dropdown-menu-list::-webkit-scrollbar-thumb{border-radius:3px;background:var(--secondary-sub-base)}.tk-currency-input-container .tk-currency-input-dropdown .tk-currency-input-dropdown-menu .tk-currency-input-dropdown-menu-list::-webkit-scrollbar-thumb:hover{background:var(--secondary-dark)}.tk-currency-input-container .tk-currency-input-dropdown .tk-currency-input-dropdown-menu .tk-currency-input-dropdown-menu-list::-webkit-scrollbar-corner{background:var(--background-lightest)}.tk-currency-input-container .tk-currency-input-dropdown .tk-currency-input-dropdown-menu .tk-currency-input-dropdown-menu-list .tk-currency-input-dropdown-menu-list-item{display:flex;align-items:center;gap:var(--spacing-xs);padding:var(--input-external-label-base-input-v-padding) var(--spacing-4xl);cursor:pointer;transition:background-color 0.2s}.tk-currency-input-container .tk-currency-input-dropdown .tk-currency-input-dropdown-menu .tk-currency-input-dropdown-menu-list .tk-currency-input-dropdown-menu-list-item:hover{background-color:var(--background-lightest)}.tk-currency-input-container[aria-invalid] .tk-currency-input-wrapper{border-color:var(--states-danger-base)}.tk-currency-input-container[aria-disabled],.tk-currency-input-container[aria-readonly]{pointer-events:none}.tk-currency-input-container[aria-disabled] .tk-currency-input-wrapper,.tk-currency-input-container[aria-readonly] .tk-currency-input-wrapper{background-color:var(--background-lightest)}.tk-currency-input-container[aria-disabled] .tk-currency-input-label-title,.tk-currency-input-container[aria-disabled] .tk-currency-input-label-asterisk,.tk-currency-input-container[aria-disabled] .tk-currency-input-dropdown-button,.tk-currency-input-container[aria-readonly] .tk-currency-input-label-title,.tk-currency-input-container[aria-readonly] .tk-currency-input-label-asterisk,.tk-currency-input-container[aria-readonly] .tk-currency-input-dropdown-button{color:var(--text-sub-base)}.tk-currency-input-container[aria-disabled] .tk-currency-input-input{color:var(--text-sub-base)}.tk-currency-input-container.tk-currency-input-container-large .tk-currency-input-label{padding:var(--input-external-label-large-label-v-padding) var(--external-label-large-label-h-padding)}.tk-currency-input-container.tk-currency-input-container-large .tk-currency-input-label .tk-currency-input-label-title{font-size:var(--desktop-body-m-size);line-height:var(--desktop-body-m-line-height)}.tk-currency-input-container.tk-currency-input-container-large .tk-currency-input-wrapper{padding:var(--input-external-label-large-input-v-padding) var(--input-external-label-large-input-h-padding);gap:var(--input-external-label-large-input-gap);height:var(--spacing-12xl)}.tk-currency-input-container.tk-currency-input-container-large .tk-currency-input-wrapper .tk-currency-input-input,.tk-currency-input-container.tk-currency-input-container-large .tk-currency-input-wrapper .tk-currency-input-dropdown-button,.tk-currency-input-container.tk-currency-input-container-large .tk-currency-input-wrapper .tk-currency-input-dropdown-menu-list-item{font-size:var(--desktop-body-m-size);line-height:var(--desktop-body-m-line-height)}.tk-currency-input-container.tk-currency-input-container-large .tk-currency-input-dropdown-menu-list{max-height:280px}.tk-currency-input-container.tk-currency-input-container-base .tk-currency-input-label{padding:var(--input-external-label-base-label-v-padding) var(--input-external-label-base-label-h-padding)}.tk-currency-input-container.tk-currency-input-container-base .tk-currency-input-label .tk-currency-input-label-title{font-size:var(--desktop-body-s-size);line-height:var(--desktop-body-s-line-height)}.tk-currency-input-container.tk-currency-input-container-base .tk-currency-input-wrapper{padding:var(--input-external-label-base-input-v-padding) var(--input-external-label-base-input-h-padding);gap:var(--input-external-label-base-input-gap);height:var(--spacing-10xl)}.tk-currency-input-container.tk-currency-input-container-base .tk-currency-input-wrapper .tk-currency-input-input,.tk-currency-input-container.tk-currency-input-container-base .tk-currency-input-wrapper .tk-currency-input-dropdown-button,.tk-currency-input-container.tk-currency-input-container-base .tk-currency-input-wrapper .tk-currency-input-dropdown-menu-list-item{font-size:var(--desktop-body-s-size);line-height:var(--desktop-body-s-line-height)}.tk-currency-input-container.tk-currency-input-container-base .tk-currency-input-dropdown-menu-list{max-height:268px}.tk-currency-input-container.tk-currency-input-container-small .tk-currency-input-label{padding:var(--input-external-label-small-label-v-padding) var(--input-external-label-small-label-h-padding)}.tk-currency-input-container.tk-currency-input-container-small .tk-currency-input-label .tk-currency-input-label-title{font-size:var(--desktop-body-xs-size);line-height:var(--desktop-line-height-xs-normal)}.tk-currency-input-container.tk-currency-input-container-small .tk-currency-input-wrapper{padding:var(--input-external-label-small-input-v-padding) var(--input-external-label-small-input-h-padding);gap:var(--input-external-label-small-input-gap);height:var(--spacing-8xl)}.tk-currency-input-container.tk-currency-input-container-small .tk-currency-input-wrapper .tk-currency-input-input,.tk-currency-input-container.tk-currency-input-container-small .tk-currency-input-wrapper .tk-currency-input-dropdown-button,.tk-currency-input-container.tk-currency-input-container-small .tk-currency-input-wrapper .tk-currency-input-dropdown-menu-list-item{font-size:var(--desktop-body-xs-size);line-height:var(--desktop-line-height-xs-normal)}.tk-currency-input-container.tk-currency-input-container-small .tk-currency-input-dropdown-menu-list{max-height:256px}`;

const TkCurrencyInput = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.tkChange = createEvent(this, "tk-change", 5);
        this.tkBlur = createEvent(this, "tkBlur", 7);
        this.tkFocus = createEvent(this, "tkFocus", 7);
        this.uniqueId = v4();
        /**
         * The value displayed in the input field, formatted as a currency string.
         * This is updated based on the current numeric value and selected currency.
         */
        this.displayValue = '';
        /**
         * Indicates whether the dropdown for currency selection is open.
         */
        this.isDropdownOpen = false;
        /**
         * Current numeric value of the input, used for calculations and formatting.
         * This is updated based on user input and can be used in form submissions.
         */
        this.currentNumericValue = 0;
        /**
         * The value of the input.
         */
        this.value = 0;
        /**
         * Disables the input field if set to true.
         */
        this.disabled = false;
        /**
         * Marks the input field as invalid if set to true.
         */
        this.invalid = false;
        /**
         * Makes the input field read-only if set to true.
         */
        this.readonly = false;
        /**
         * Sets size for the component.
         */
        this.size = 'base';
        /**
         * Displays a red asterisk (*) next to the label for visual emphasis.
         */
        this.showAsterisk = false;
        /**
         * Disables the currency field if set to true.
         */
        this.currencyDisabled = false;
        /**
         * The number of decimal places to display in the formatted currency value.
         * Default is 2, which is common for most currencies.
         */
        this.precision = 2;
        /**
         * The default currency to use when the component is initialized.
         * Default is 'TRY'.
         */
        this.defaultCurrency = 'TRY';
        /**
         * Allows negative values to be entered if set to true.
         */
        this.allowNegative = false;
        /**
         * Hides the currency flag icon in the dropdown button and list.
         * @default false
         */
        this.hideFlag = false;
        /**
         * Allows the value to be set to null.
         * @default false
         */
        this.allowEmptyValue = false;
        /**
         * Determines the width of the dropdown. Accepts values like 'match-parent', 'auto', or a specific width in '300px'.
         * @defaultValue match-parent
         */
        this.dropdownWidthMode = 'match-parent';
        this.closeDropdown = (event) => {
            var _a;
            if (event.composedPath().includes(this.el) || !this.isDropdownOpen) {
                return;
            }
            const target = event.target;
            if (this.dropdownEl && this.dropdownEl.contains(target)) {
                return;
            }
            const hostElement = (_a = this.inputElement) === null || _a === void 0 ? void 0 : _a.closest('tk-currency-input');
            if (hostElement && hostElement.contains(target)) {
                return;
            }
            this.isDropdownOpen = false;
        };
        this.toggleDropdown = (event) => {
            event.stopPropagation();
            event.preventDefault();
            if (!this.disabled && !this.readonly && !this.currencyDisabled) {
                this.isDropdownOpen = !this.isDropdownOpen;
            }
        };
        this.handleInput = (event) => {
            var _a;
            const target = event.target;
            const inputValue = target.value;
            const cursorPosition = (_a = target.selectionStart) !== null && _a !== void 0 ? _a : 0;
            // Use custom separators if provided, otherwise fall back to currency defaults
            const decimalSeparator = this.getDecimalSeparator();
            const thousandsSeparator = this.getThousandsSeparator();
            // Check if decimal separator was deleted
            if (this.displayValue.includes(decimalSeparator) && !inputValue.includes(decimalSeparator)) {
                const expectedValueWithoutSeparator = this.displayValue.replace(decimalSeparator, '');
                if (inputValue === expectedValueWithoutSeparator) {
                    target.value = this.displayValue;
                    const commaIndex = this.displayValue.indexOf(decimalSeparator);
                    target.setSelectionRange(commaIndex, commaIndex);
                    return;
                }
            }
            // Allow negative sign if allowNegative is true
            const negativePattern = this.allowNegative ? '\\-' : '';
            const allowedChars = new RegExp(`[0-9\\${decimalSeparator}\\${thousandsSeparator}${negativePattern}]`);
            let filteredValue = '';
            let hasNegativeSign = false;
            const parts = inputValue.split(decimalSeparator);
            if (parts.length > 2) {
                const firstSeparatorIndex = inputValue.indexOf(decimalSeparator);
                const newIntegerPart = inputValue.substring(0, firstSeparatorIndex);
                const displayParts = this.displayValue.split(decimalSeparator);
                const oldDecimalPart = displayParts.length > 1 ? displayParts[1] : '';
                filteredValue = newIntegerPart + decimalSeparator + oldDecimalPart;
            }
            else {
                for (let i = 0; i < inputValue.length; i++) {
                    const char = inputValue[i];
                    // Handle negative sign - only allow it at the beginning
                    if (char === '-' && this.allowNegative && i === 0 && !hasNegativeSign) {
                        filteredValue += char;
                        hasNegativeSign = true;
                    }
                    else if (char === '-' && this.allowNegative && hasNegativeSign) ;
                    else if (allowedChars.test(char) && char !== '-') {
                        filteredValue += char;
                    }
                }
            }
            // Truncate decimal digits if they exceed precision
            if (this.precision >= 0) {
                const parts = filteredValue.split(decimalSeparator);
                if (parts.length > 1) {
                    const integerPart = parts[0];
                    const decimalPart = parts[1];
                    if (decimalPart.length > this.precision) {
                        filteredValue = integerPart + decimalSeparator + decimalPart.substring(0, this.precision);
                    }
                }
            }
            const numericValue = this.parseFormattedValue(filteredValue);
            if ((this.allowEmptyValue && cursorPosition === 0) || numericValue === null) {
                this.currentNumericValue = null;
                this.displayValue = '';
                target.value = '';
                this.tkChange.emit({
                    value: null,
                    currency: this.selectedCurrency,
                    formattedValue: '',
                });
                return;
            }
            this.currentNumericValue = numericValue;
            const formattedValue = this.formatCurrency(numericValue);
            this.displayValue = formattedValue;
            target.value = formattedValue;
            const newCursorPosition = this.calculateNewCursorPosition(inputValue, formattedValue, cursorPosition);
            target.setSelectionRange(newCursorPosition, newCursorPosition);
            const eventData = {
                value: numericValue,
                currency: this.selectedCurrency,
                formattedValue: formattedValue,
            };
            this.tkChange.emit(eventData);
        };
        this.handleKeyDown = (event) => {
            const decimalSeparator = this.getDecimalSeparator();
            if (event.key === '.' && decimalSeparator !== '.') {
                event.preventDefault();
            }
        };
        this.handleFocus = () => {
            this.tkFocus.emit();
        };
        this.handleBlur = () => {
            const target = this.inputElement;
            if (!target)
                return;
            const numericValue = this.parseFormattedValue(target.value);
            this.currentNumericValue = numericValue;
            if (numericValue === null) {
                target.value = '';
                this.displayValue = '';
            }
            else {
                const formattedValue = this.formatCurrency(numericValue);
                target.value = formattedValue;
                this.displayValue = formattedValue;
            }
            this.tkBlur.emit();
        };
        this.handleSelectCurrency = (currencyCode, event) => {
            event.stopPropagation();
            event.preventDefault();
            const currencies = this.getCurrencies();
            const currency = currencies.find(c => c.code.toUpperCase() === currencyCode.toUpperCase());
            if (currency) {
                this.selectedCurrency = currency;
                this.updateDisplayValue();
                this.isDropdownOpen = false;
                if (this.inputElement) {
                    this.inputElement.value = this.displayValue;
                }
                const eventData = {
                    value: this.currentNumericValue,
                    currency: this.selectedCurrency,
                    formattedValue: this.displayValue,
                };
                this.tkChange.emit(eventData);
            }
        };
    }
    valueChanged() {
        if (this.value !== this.currentNumericValue) {
            this.currentNumericValue = this.normalizeNumericValue(this.value);
            this.updateDisplayValue();
        }
    }
    disabledChanged(newValue) {
        if (newValue)
            this.isDropdownOpen = false;
    }
    defaultCurrencyChanged() {
        const currencies = this.getCurrencies();
        const currency = currencies.find(c => c.code.toUpperCase() === this.defaultCurrency.toUpperCase());
        if (currency) {
            this.selectedCurrency = currency;
            this.updateDisplayValue();
            if (this.inputElement) {
                this.inputElement.value = this.displayValue;
            }
            const eventData = {
                value: this.currentNumericValue,
                currency: this.selectedCurrency,
                formattedValue: this.displayValue,
            };
            this.tkChange.emit(eventData);
        }
    }
    /**
     * Initialize the component before it is rendered.
     */
    componentWillLoad() {
        this.setSelectedCurrency(this.defaultCurrency);
    }
    /**
     * Update the component when properties change.
     */
    componentDidUpdate() {
        var _a, _b, _c;
        // Handle separator changes
        this.updateDisplayValue();
        // Handle dropdown positioning
        if (this.isDropdownOpen) {
            // Clean up old floating UI listeners before setting up new ones
            (_a = this.cleanup) === null || _a === void 0 ? void 0 : _a.call(this);
            this.updatePosition();
        }
        else {
            // Remove floating UI listeners when dropdown closes
            (_b = this.cleanup) === null || _b === void 0 ? void 0 : _b.call(this);
            // Clear reference to allow garbage collection
            this.cleanup = null;
            (_c = this.dropdownEl) === null || _c === void 0 ? void 0 : _c.remove();
        }
    }
    connectedCallback() {
        document.addEventListener('click', this.closeDropdown);
    }
    disconnectedCallback() {
        var _a;
        // Clean up floating UI listeners on component unmount
        (_a = this.cleanup) === null || _a === void 0 ? void 0 : _a.call(this);
        // Clear reference to allow garbage collection
        this.cleanup = null;
        document.removeEventListener('click', this.closeDropdown);
    }
    updatePosition() {
        const dropdownWidthMode = this.dropdownWidthMode;
        const tkInputRootEl = this.el.querySelector('.tk-currency-input-wrapper');
        this.cleanup = floatingElementAutoUpdate(tkInputRootEl, this.dropdownEl, undefined, {
            placement: 'bottom-start',
            size: {
                apply({ rects, elements }) {
                    if (dropdownWidthMode === 'match-parent') {
                        applyStyles(elements.floating, {
                            width: `${rects.reference.width}px`,
                        });
                    }
                    else if (dropdownWidthMode !== 'auto' && dropdownWidthMode.length > 0) {
                        applyStyles(elements.floating, {
                            width: dropdownWidthMode,
                        });
                    }
                },
            },
        });
    }
    /**
     * Get the currencies list - either from prop or use internal default
     */
    getCurrencies() {
        return this.currencyList || INTERNAL_CURRENCY_LIST;
    }
    setSelectedCurrency(currencyCode) {
        const currencies = this.getCurrencies();
        const currency = currencies.find(c => c.code.toUpperCase() === currencyCode.toUpperCase());
        this.selectedCurrency = currency || currencies[0];
        this.currentNumericValue = this.normalizeNumericValue(this.value);
        this.updateDisplayValue();
    }
    normalizeNumericValue(value) {
        if (this.allowEmptyValue && value === null) {
            return null;
        }
        return value !== null && value !== void 0 ? value : 0;
    }
    updateDisplayValue() {
        if (this.currentNumericValue === null || this.currentNumericValue === undefined || isNaN(this.currentNumericValue)) {
            this.displayValue = '';
            return;
        }
        this.displayValue = this.formatCurrency(this.currentNumericValue);
    }
    /**
     * Get the decimal separator to use - custom prop takes priority over currency default
     */
    getDecimalSeparator() {
        var _a, _b;
        return getValidSeparator(this.decimalSeparator, this.thousandsSeparator, (_a = this.selectedCurrency) === null || _a === void 0 ? void 0 : _a.decimalSeparator, (_b = this.selectedCurrency) === null || _b === void 0 ? void 0 : _b.thousandsSeparator, '.');
    }
    /**
     * Get the thousands separator to use - custom prop takes priority over currency default
     */
    getThousandsSeparator() {
        var _a, _b;
        return getValidSeparator(this.thousandsSeparator, this.decimalSeparator, (_a = this.selectedCurrency) === null || _a === void 0 ? void 0 : _a.thousandsSeparator, (_b = this.selectedCurrency) === null || _b === void 0 ? void 0 : _b.decimalSeparator, ',');
    }
    formatCurrency(amount) {
        if (isNaN(amount))
            return '';
        // Use custom separators if provided, otherwise fall back to currency defaults
        const decimalSeparator = this.getDecimalSeparator();
        const thousandsSeparator = this.getThousandsSeparator();
        const isNegative = amount < 0 || Object.is(amount, -0);
        const absoluteAmount = Math.abs(amount);
        // Format the number with the specified precision
        const fixedAmount = Number(absoluteAmount).toFixed(this.precision);
        const [integerPart, decimalPart] = fixedAmount.split('.');
        // Add thousands separators
        const formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator);
        // Combine with decimal part if precision > 0
        let result = formattedInteger;
        if (this.precision > 0 && decimalPart) {
            result += decimalSeparator + decimalPart;
        }
        // Add negative sign if needed and allowed
        if (isNegative && this.allowNegative) {
            result = '-' + result;
        }
        return result;
    }
    parseFormattedValue(formattedValue) {
        if (!formattedValue) {
            if (this.allowEmptyValue)
                return null;
            return 0;
        }
        // Use custom separators if provided, otherwise fall back to currency defaults
        const decimalSeparator = this.getDecimalSeparator();
        const thousandsSeparator = this.getThousandsSeparator();
        const isNegative = formattedValue.startsWith('-') && this.allowNegative;
        // Remove negative sign temporarily for processing
        let cleanValue = formattedValue.replace('-', '');
        // Remove thousands separators
        if (thousandsSeparator) {
            cleanValue = cleanValue.replace(new RegExp('\\' + thousandsSeparator, 'g'), '');
        }
        // Handle decimal separator: split by separator, keep first part as integer, join rest as decimal
        const parts = cleanValue.split(decimalSeparator);
        if (parts.length > 1) {
            cleanValue = parts[0] + '.' + parts.slice(1).join('');
        }
        // Remove non-numeric characters except decimal point
        cleanValue = cleanValue.replace(/[^0-9.]/g, '');
        const numericValue = parseFloat(cleanValue);
        const result = isNaN(numericValue) ? 0 : numericValue;
        return isNegative ? -result : result;
    }
    calculateNewCursorPosition(inputValue, formattedValue, oldCursorPosition) {
        const decimalSeparator = this.getDecimalSeparator();
        // Find decimal separator positions
        const inputDecimalIndex = inputValue.indexOf(decimalSeparator);
        const formattedDecimalIndex = formattedValue.indexOf(decimalSeparator);
        // If no decimal separator in formatted value (precision 0), treat end as decimal point
        const targetDecimalIndex = formattedDecimalIndex === -1 ? formattedValue.length : formattedDecimalIndex;
        // If no decimal separator in input, treat end as decimal point
        const sourceDecimalIndex = inputDecimalIndex === -1 ? inputValue.length : inputDecimalIndex;
        // Helper to count digits in a range
        const countDigits = (str, start, end) => {
            let count = 0;
            for (let i = Math.min(start, end); i < Math.max(start, end); i++) {
                if (str[i] >= '0' && str[i] <= '9') {
                    count++;
                }
            }
            return count;
        };
        // Calculate logical distance (number of digits) from decimal separator
        const isCursorAfterDecimal = oldCursorPosition > sourceDecimalIndex;
        const logicalDist = countDigits(inputValue, oldCursorPosition, sourceDecimalIndex);
        if (logicalDist === 0) {
            return isCursorAfterDecimal ? targetDecimalIndex + 1 : targetDecimalIndex;
        }
        // Traverse formatted value to find new position
        let currentDist = 0;
        if (isCursorAfterDecimal) {
            // Moving right from decimal separator
            for (let i = targetDecimalIndex + 1; i < formattedValue.length; i++) {
                if (currentDist >= logicalDist) {
                    return i;
                }
                if (formattedValue[i] >= '0' && formattedValue[i] <= '9') {
                    currentDist++;
                }
            }
            return formattedValue.length;
        }
        else {
            // Moving left from decimal separator
            for (let i = targetDecimalIndex - 1; i >= 0; i--) {
                if (formattedValue[i] >= '0' && formattedValue[i] <= '9') {
                    currentDist++;
                }
                if (currentDist > logicalDist) {
                    // Use > because we want to be *after* the digit that completes the count
                    return i + 1;
                }
            }
            // If we run out of digits, go to start, but respect negative sign
            const hasNegative = formattedValue.startsWith('-');
            return hasNegative ? 1 : 0;
        }
    }
    renderLabel() {
        if (this.label) {
            return (h("label", { class: "tk-currency-input-label", htmlFor: this.uniqueId }, h("span", { class: "tk-currency-input-label-title" }, this.label), this.showAsterisk && h("span", { class: "tk-currency-input-label-asterisk" }, "*")));
        }
        return null;
    }
    renderCurrencyInput() {
        return (h("input", { id: this.uniqueId, ref: el => (this.inputElement = el), type: "text", class: "tk-currency-input-input", autoComplete: "off", value: this.displayValue, placeholder: this.placeholder, disabled: this.disabled, readonly: this.readonly, name: this.name, onInput: this.handleInput, onKeyDown: this.handleKeyDown, onFocus: this.handleFocus, onBlur: this.handleBlur }));
    }
    renderCurrencySelector() {
        return (h("div", { class: "tk-currency-input-dropdown" }, this.renderDropdownButton(), this.isDropdownOpen && (h("div", { class: "tk-currency-input-dropdown-menu", role: "listbox", ref: el => (this.dropdownEl = el) }, this.renderCurrencyList()))));
    }
    /**
     * Get the flag class based on the currency's ID.
     */
    getFlagClass(currency) {
        return classNames('flag', (currency === null || currency === void 0 ? void 0 : currency.id) ? `flag-${currency === null || currency === void 0 ? void 0 : currency.id.toLowerCase()}` : 'flag-none');
    }
    renderDropdownButton() {
        var _a;
        return (h("button", { type: "button", class: "tk-currency-input-dropdown-button", onClick: event => this.toggleDropdown(event), disabled: this.currencyDisabled || this.disabled, "aria-disabled": this.currencyDisabled || this.disabled }, h("div", { class: "tk-currency-input-dropdown-button-selected" }, !this.hideFlag && this.renderFlag(this.selectedCurrency), h("span", { class: "tk-currency-input-dropdown-button-currency-code" }, (_a = this.selectedCurrency) === null || _a === void 0 ? void 0 : _a.code), !this.currencyDisabled && h("tk-icon", Object.assign({}, getIconElementProps('keyboard_arrow_down', { variant: null, size: 'large' }, 'rounded', 'span'))))));
    }
    renderCurrencyList() {
        const currencies = this.getCurrencies();
        return (h("ul", { class: "tk-currency-input-dropdown-menu-list" }, currencies.map(currency => (h("li", { class: "tk-currency-input-dropdown-menu-list-item", key: currency.code, role: "option", onClick: event => this.handleSelectCurrency(currency.code, event), "aria-selected": this.selectedCurrency.code === currency.code }, !this.hideFlag && this.renderFlag(currency), h("span", { class: "tk-currency-input-dropdown-menu-list-country-label" }, currency.symbol), h("span", { class: "tk-currency-input-dropdown-menu-list-dial-id" }, currency.name))))));
    }
    /**
     * Render the flag element for a currency. Shows a close icon for currencies without a matching currency ID.
     */
    renderFlag(currency) {
        const flagClass = this.getFlagClass(currency);
        return (currency === null || currency === void 0 ? void 0 : currency.id) ? (h("div", { class: flagClass, "aria-label": `${currency.code} flag` })) : (h("div", { class: flagClass }, h("tk-icon", Object.assign({}, getIconElementProps('close', { color: 'var(--static-white)' })))));
    }
    render() {
        return (h("div", { key: '9719d00968adfba58e4f0eff8c1bbd5dbfcdddbc', class: classNames('tk-currency-input-container', `tk-currency-input-container-${this.size}`), "aria-invalid": this.invalid, "aria-disabled": this.disabled, "aria-readonly": this.readonly }, this.renderLabel(), h("div", { key: '19750f8dd6ddde85b364da27c10fe501667c57c3', class: "tk-currency-input-wrapper" }, this.renderCurrencyInput(), this.renderCurrencySelector()), renderHint(this.hint, this.error, this.invalid)));
    }
    static get formAssociated() { return true; }
    get el() { return getElement(this); }
    static get watchers() { return {
        "value": [{
                "valueChanged": 0
            }],
        "disabled": [{
                "disabledChanged": 0
            }],
        "defaultCurrency": [{
                "defaultCurrencyChanged": 0
            }]
    }; }
};
TkCurrencyInput.style = tkCurrencyInputCss();

export { TkCurrencyInput as tk_currency_input };
