import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Button, IconBox, Input } from '@citric/core';
import { ChevronDown } from '@citric/icons';
import { listToClass } from '@stack-spot/portal-theme';
import { useTranslate } from '@stack-spot/portal-translate';
import { useEffect, useMemo, useRef, useState } from 'react';
import { VariableSelector } from './VariableSelector.js';
const variablePattern = /\{\{[^{}]+\}\}/;
export const VariableField = ({ name, onChange, value, disabled, onBlur, variable }) => {
    const t = useTranslate(dictionary);
    const [isOpen, setOpen] = useState(false);
    const isVariable = useMemo(() => value && variablePattern.test(value), [value]);
    const selector = useRef(null);
    useEffect(() => {
        if (!isOpen)
            return;
        function onClick(e) {
            if (e.target && !selector.current?.contains(e.target))
                setOpen(false);
        }
        document.addEventListener('click', onClick);
        return () => document.removeEventListener('click', onClick);
    }, [isOpen]);
    return (_jsxs("div", { className: listToClass(['variable-field', isOpen && 'open', isVariable && 'variable']), children: [_jsx(Input, { type: "text", value: value, onChange: e => onChange(e.target.value), name: name, disabled: disabled, onBlur: onBlur }), !disabled && _jsxs(Button, { type: "button", appearance: "outlined", colorScheme: "inverse", onClick: (e) => {
                    setOpen(v => !v);
                    e.stopPropagation();
                }, children: [t.useVariable, _jsx(IconBox, { className: "chevron", children: _jsx(ChevronDown, {}) })] }), _jsx(VariableSelector, { ref: selector, pattern: variable.config.metadata?.pattern, onSelect: onChange })] }));
};
const dictionary = {
    en: {
        useVariable: 'Use variable',
    },
    pt: {
        useVariable: 'Usar variável',
    },
};
//# sourceMappingURL=VariableField.js.map