/**
 * @license MIT
 * author: Cube Dev Team
 * @cube-dev/ui-kit v0.0.0-canary-e980ce7
 * Released under the MIT license.
 */

import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useLayoutEffect, useRef, useState } from 'react';
import { useTextField } from 'react-aria';
import { useEvent } from '../../../_internal/hooks/index.js';
import { EditableTitleInputElement, HiddenMeasure } from './styled.js';
// =============================================================================
// Component
// =============================================================================
/**
 * Inline editable title component for tab labels.
 *
 * When not editing, displays the title as a span with double-click to edit.
 * When editing, displays an auto-sizing input field.
 */
export function EditableTitle({ title, isEditing, editValue, onEditValueChange, onStartEditing, onSubmit, onCancel, }) {
    const inputRef = useRef(null);
    const measureRef = useRef(null);
    const [inputWidth, setInputWidth] = useState(null);
    const justEnteredEditModeRef = useRef(false);
    // React Aria text field hook
    const { inputProps } = useTextField({
        'aria-label': 'Edit tab title',
        value: editValue,
        onChange: onEditValueChange,
    }, inputRef);
    // Focus and select input when entering edit mode
    useLayoutEffect(() => {
        if (isEditing && inputRef.current) {
            const input = inputRef.current;
            // Set flag to ignore immediate blur events
            justEnteredEditModeRef.current = true;
            input.focus();
            // Use requestAnimationFrame to ensure selection happens after focus
            requestAnimationFrame(() => {
                input.select();
                // Clear the flag after focus is established (allow 2 frames for menu to fully close)
                requestAnimationFrame(() => {
                    requestAnimationFrame(() => {
                        justEnteredEditModeRef.current = false;
                    });
                });
            });
        }
        else {
            justEnteredEditModeRef.current = false;
        }
    }, [isEditing]);
    // Measure text width and update input width
    useLayoutEffect(() => {
        if (isEditing && measureRef.current) {
            const width = measureRef.current.scrollWidth;
            setInputWidth(width);
        }
    }, [isEditing, editValue]);
    const handleKeyDown = useEvent((e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            onSubmit();
        }
        else if (e.key === 'Escape') {
            e.preventDefault();
            onCancel();
        }
        else if (e.key === 'ArrowLeft' ||
            e.key === 'ArrowRight' ||
            e.key === ' ' ||
            e.key === 'Delete' ||
            e.key === 'Backspace') {
            // Stop propagation to prevent tab navigation/deletion while editing
            e.stopPropagation();
        }
    });
    const handleBlur = useEvent(() => {
        // Ignore blur events immediately after entering edit mode (menu closing causes focus loss)
        if (justEnteredEditModeRef.current) {
            // Re-focus the input since something else stole focus
            requestAnimationFrame(() => {
                inputRef.current?.focus();
                inputRef.current?.select();
            });
            return;
        }
        // Submit on blur
        onSubmit();
    });
    const handleDoubleClick = useEvent((e) => {
        e.preventDefault();
        e.stopPropagation();
        onStartEditing();
    });
    if (isEditing) {
        // Merge our handlers with React Aria's inputProps
        const mergedProps = {
            ...inputProps,
            onKeyDown: (e) => {
                handleKeyDown(e);
                inputProps.onKeyDown?.(e);
            },
            onBlur: (e) => {
                handleBlur();
                inputProps.onBlur?.(e);
            },
        };
        return (_jsxs(_Fragment, { children: [_jsx(HiddenMeasure, { ref: measureRef, "aria-hidden": "true", children: editValue || ' ' }), _jsx(EditableTitleInputElement, { ...mergedProps, ref: inputRef, tokens: { '$input-width': inputWidth ? `${inputWidth}px` : 'auto' } })] }));
    }
    return _jsx("span", { onDoubleClick: handleDoubleClick, children: title });
}

        