import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { sharedValueTransformers } from '../../../../scalars/lib/shared-value-transformers.js';
import { cn } from '../../../../scalars/lib/utils.js';
import React, { useEffect, useId, useMemo, useRef } from 'react';
import { useResizeObserver } from 'usehooks-ts';
import { CharacterCounter } from '../../../../scalars/components/fragments/character-counter/index.js';
import { FormDescription } from '../../../../scalars/components/fragments/form-description/index.js';
import { FormGroup } from '../../../../scalars/components/fragments/form-group/index.js';
import { FormLabel } from '../../../../scalars/components/fragments/form-label/index.js';
import { FormMessageList } from '../../../../scalars/components/fragments/form-message/index.js';
import ValueTransformer from '../../../../scalars/components/fragments/value-transformer/index.js';
import SplittedTextareaDiff from './subcomponent/splitted-textarea-diff.js';
const textareaBaseStyles = cn(
// Base styles
'flex min-h-9 w-full rounded-md text-sm font-normal leading-5 text-gray-900 dark:text-gray-50', 
// Border & Background
'dark:border-charcoal-700 dark:bg-charcoal-900 border border-gray-300 bg-white', 
// Padding
'px-3 py-[7px]', 
// Placeholder
'font-sans placeholder:text-gray-500 dark:placeholder:text-gray-600', 
// Focus styles
'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-gray-900 focus-visible:ring-offset-0 focus-visible:ring-offset-white', 'dark:focus-visible:ring-charcoal-300 dark:focus-visible:ring-offset-charcoal-900 dark:focus:bg-charcoal-900 focus:bg-gray-50', 
// Disabled state
'disabled:cursor-not-allowed', 'disabled:border-gray-300 disabled:bg-gray-50 disabled:text-gray-700', 'disabled:dark:border-charcoal-800 disabled:dark:bg-charcoal-900 disabled:dark:text-gray-300');
const Textarea = React.forwardRef(({ autoComplete, autoExpand, multiline = true, className, defaultValue, description, errors, id: propId, label, lowercase, maxLength, minLength, name, onChange, onKeyDown, placeholder, required, rows = 3, trim, uppercase, value, warnings, viewMode = 'edition', diffMode = 'words', baseValue, ...props }, ref) => {
    const autoCompleteValue = autoComplete === undefined ? undefined : autoComplete ? 'on' : 'off';
    const hasError = errors && errors.length > 0;
    const hasContentBelow = !!description || (Array.isArray(warnings) && warnings.length > 0) || (Array.isArray(errors) && errors.length > 0);
    const prefix = useId();
    const id = propId ?? `${prefix}-textarea`;
    const textareaRef = useRef(null);
    const mergedRef = (node) => {
        textareaRef.current = node;
        if (typeof ref === 'function') {
            ref(node);
        }
        else if (ref) {
            ref.current = node;
        }
    };
    const adjustHeight = () => {
        if (textareaRef.current) {
            // Reset height to allow shrinking
            textareaRef.current.style.height = 'auto';
            if (textareaRef.current.value === '')
                return;
            // Set to scrollHeight + border to expand based on content
            const cs = getComputedStyle(textareaRef.current);
            const border = cs.boxSizing === 'border-box' ? parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth) : 0;
            textareaRef.current.style.height = `${textareaRef.current.scrollHeight + border}px`;
        }
    };
    useResizeObserver({
        ref: textareaRef,
        onResize: () => {
            if (autoExpand) {
                adjustHeight();
            }
        },
        box: 'border-box',
    });
    const handleKeyDown = (e) => {
        // Prevent Enter key if multiline is falsy
        if (!multiline && e.key === 'Enter') {
            e.preventDefault();
        }
        // Call the original onKeyDown
        onKeyDown?.(e);
    };
    const handleOnChange = (e) => {
        if (autoExpand) {
            adjustHeight();
        }
        // Call the original onChange
        onChange?.(e);
    };
    useEffect(() => {
        if (autoExpand) {
            requestAnimationFrame(adjustHeight);
        }
        else if (textareaRef.current) {
            textareaRef.current.style.height = 'auto';
        }
    }, [autoExpand, multiline, rows, value]);
    const transformers = useMemo(() => [
        sharedValueTransformers.trimOnBlur(!!trim),
        sharedValueTransformers.lowercaseOnChange(!!lowercase),
        sharedValueTransformers.uppercaseOnChange(!!uppercase),
        {
            transformer: (value) => value?.replace(/\n/g, ''),
            options: {
                trigger: 'change',
                if: !multiline,
            },
        },
    ], [trim, lowercase, uppercase, multiline]);
    if (viewMode === 'edition') {
        return (_jsxs(FormGroup, { children: [label && (_jsx(FormLabel, { htmlFor: id, disabled: props.disabled, hasError: hasError, required: required, children: label })), _jsxs("div", { className: "relative", children: [_jsx(ValueTransformer, { transformers: transformers, children: _jsx("textarea", { "aria-invalid": hasError, "aria-required": required, autoComplete: autoCompleteValue, className: cn(textareaBaseStyles, 
                                // Resize behavior based on autoExpand
                                autoExpand
                                    ? 'resize-none overflow-hidden'
                                    : [
                                        'resize-y',
                                        'scrollbar-thin scrollbar-gutter-stable',
                                        'scrollbar-track-transparent',
                                        'scrollbar-thumb-gray-300 hover:scrollbar-thumb-gray-300',
                                        'dark:scrollbar-thumb-charcoal-700 dark:hover:scrollbar-thumb-charcoal-700',
                                        'scrollbar-thumb-rounded-md',
                                    ], className), ref: mergedRef, id: id, name: name, value: value, defaultValue: defaultValue, minLength: minLength, placeholder: placeholder, rows: multiline ? rows : 1, onChange: handleOnChange, onKeyDown: handleKeyDown, ...props }) }), typeof maxLength === 'number' && maxLength > 0 && (_jsx("div", { className: cn('mt-0.5 flex justify-end', hasContentBelow && '-mb-1'), children: _jsx(CharacterCounter, { maxLength: maxLength, value: value ?? '' }) }))] }), description && _jsx(FormDescription, { children: description }), warnings && _jsx(FormMessageList, { messages: warnings, type: "warning" }), errors && _jsx(FormMessageList, { messages: errors, type: "error" })] }));
    }
    return (_jsx(SplittedTextareaDiff, { label: label, value: value ?? defaultValue ?? '', viewMode: viewMode, diffMode: diffMode, baseValue: baseValue, multiline: multiline, rows: rows, "data-testid": "textarea-diff" }));
});
Textarea.displayName = 'Textarea';
export { Textarea };
//# sourceMappingURL=textarea.js.map