"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = __importStar(require("react"));
const acui_1 = require("@Acme Corporation/acui");
const UrlInput = (0, react_1.forwardRef)(({ name, label, helperText, error: externalError, isRequired = false, isDisabled = false, isReadOnly = false, isInvalid: externalInvalid, size = 'md', defaultProtocol = 'https', showProtocol = true, allowedProtocols = ['http', 'https'], validateUrl = true, className = '', wrapperClassName = '', labelClassName = '', inputClassName = '', errorClassName = '', helperTextClassName = '', protocolSelectClassName = '', validateOnChange = false, validateOnBlur = true, onChange, onBlur, value, defaultValue, ...props }, ref) => {
    const theme = (0, acui_1.useTheme)();
    const formContext = react_1.default.useContext(FormContext);
    const [localValue, setLocalValue] = react_1.default.useState(value ?? defaultValue ?? '');
    const [selectedProtocol, setSelectedProtocol] = react_1.default.useState(defaultProtocol);
    const inputRef = react_1.default.useRef(null);
    const combinedRef = react_1.default.useCallback((node) => {
        inputRef.current = node;
        if (typeof ref === 'function') {
            ref(node);
        }
        else if (ref) {
            ref.current = node;
        }
    }, [ref]);
    const { errors = {}, touched = {}, setFieldValue, setFieldTouched, setFieldError } = formContext || {};
    const error = externalError || errors[name];
    const isInvalid = externalInvalid || (touched[name] && !!error);
    const isControlled = value !== undefined;
    const validateUrlFormat = (0, react_1.useCallback)((url) => {
        if (!validateUrl)
            return true;
        try {
            new URL(url);
            return true;
        }
        catch {
            return false;
        }
    }, [validateUrl]);
    const handleChange = (0, react_1.useCallback)((e) => {
        const inputValue = e.target.value;
        let urlValue = inputValue;
        // Add protocol if missing and showProtocol is true
        if (showProtocol && !inputValue.startsWith('http://') && !inputValue.startsWith('https://')) {
            urlValue = `${selectedProtocol}://${inputValue}`;
        }
        if (!isControlled) {
            setLocalValue(urlValue);
        }
        onChange?.(e);
        if (formContext && validateOnChange) {
            setFieldValue(name, urlValue);
            if (validateUrl && !validateUrlFormat(urlValue)) {
                setFieldError(name, 'Please enter a valid URL');
            }
        }
    }, [isControlled, onChange, formContext, name, setFieldValue, setFieldError, validateOnChange, showProtocol, selectedProtocol, validateUrl, validateUrlFormat]);
    const handleBlur = (0, react_1.useCallback)((e) => {
        const inputValue = e.target.value;
        let urlValue = inputValue;
        // Add protocol if missing and showProtocol is true
        if (showProtocol && !inputValue.startsWith('http://') && !inputValue.startsWith('https://')) {
            urlValue = `${selectedProtocol}://${inputValue}`;
        }
        if (!isControlled) {
            setLocalValue(urlValue);
        }
        onBlur?.(e);
        if (formContext && validateOnBlur) {
            setFieldTouched(name, true);
            if (validateUrl && !validateUrlFormat(urlValue)) {
                setFieldError(name, 'Please enter a valid URL');
            }
        }
    }, [onBlur, formContext, name, setFieldTouched, setFieldError, validateOnBlur, showProtocol, selectedProtocol, isControlled, validateUrl, validateUrlFormat]);
    const handleProtocolChange = (0, react_1.useCallback)((e) => {
        const protocol = e.target.value;
        setSelectedProtocol(protocol);
        const currentValue = isControlled ? value : localValue;
        const url = new URL(currentValue || `${protocol}://`);
        url.protocol = protocol;
        if (!isControlled) {
            setLocalValue(url.toString());
        }
        // Trigger change event
        const event = {
            target: {
                name,
                value: url.toString(),
            },
        };
        onChange?.(event);
    }, [onChange, name, isControlled, value, localValue]);
    const displayValue = react_1.default.useMemo(() => {
        const urlValue = isControlled ? value : localValue;
        if (!showProtocol || !urlValue)
            return urlValue;
        try {
            const url = new URL(urlValue);
            return url.hostname + url.pathname + url.search + url.hash;
        }
        catch {
            return urlValue;
        }
    }, [isControlled, value, localValue, showProtocol]);
    const labelId = react_1.default.useId();
    const errorId = react_1.default.useId();
    const helperTextId = react_1.default.useId();
    const protocolSelectId = react_1.default.useId();
    const ariaInvalid = isInvalid ? 'true' : undefined;
    const ariaRequired = isRequired ? 'true' : undefined;
    const ariaDescribedBy = error ? errorId : helperText ? helperTextId : undefined;
    return ((0, jsx_runtime_1.jsxs)("div", { className: `bf-url-input-wrapper ${wrapperClassName}`, "data-size": size, "data-invalid": isInvalid, "data-disabled": isDisabled, "data-readonly": isReadOnly, children: [label && ((0, jsx_runtime_1.jsxs)("label", { id: labelId, htmlFor: name, className: `bf-url-input-label ${labelClassName}`, children: [label, isRequired && (0, jsx_runtime_1.jsx)("span", { className: "bf-required-mark", "aria-hidden": "true", children: "*" })] })), (0, jsx_runtime_1.jsxs)("div", { className: "bf-url-input-container", children: [showProtocol && ((0, jsx_runtime_1.jsx)("select", { id: protocolSelectId, value: selectedProtocol, onChange: handleProtocolChange, disabled: isDisabled, className: `bf-url-input-protocol-select ${protocolSelectClassName}`, "aria-label": "URL protocol", children: allowedProtocols.map(protocol => ((0, jsx_runtime_1.jsxs)("option", { value: protocol, children: [protocol, "://"] }, protocol))) })), (0, jsx_runtime_1.jsx)("input", { ref: combinedRef, type: "url", id: name, name: name, value: displayValue, onChange: handleChange, onBlur: handleBlur, disabled: isDisabled, readOnly: isReadOnly, required: isRequired, inputMode: "url", autoComplete: "url", spellCheck: "false", "aria-labelledby": label ? labelId : undefined, "aria-invalid": ariaInvalid, "aria-required": ariaRequired, "aria-describedby": ariaDescribedBy, className: `bf-url-input ${inputClassName} ${className}`, ...props })] }), error && ((0, jsx_runtime_1.jsx)("div", { id: errorId, className: `bf-url-input-error ${errorClassName}`, role: "alert", "aria-live": "assertive", children: error })), helperText && !error && ((0, jsx_runtime_1.jsx)("div", { id: helperTextId, className: `bf-url-input-helper-text ${helperTextClassName}`, role: "status", children: helperText }))] }));
});
UrlInput.displayName = 'UrlInput';
exports.default = (0, react_1.memo)(UrlInput);
//# sourceMappingURL=UrlInput.js.map