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

import { useCallback, useState } from 'react';
import { chainRaf } from '../../../utils/raf.js';
// =============================================================================
// Hook
// =============================================================================
/**
 * Hook to manage tab title editing state.
 *
 * Provides state and callbacks for inline title editing with support for:
 * - Starting edit mode (selecting the tab and focusing input)
 * - Submitting changes (with tab-level or parent-level callback)
 * - Canceling edits
 */
export function useTabEditing({ onChange, onTitleChange, } = {}) {
    const [editingKey, setEditingKey] = useState(null);
    const [editValue, setEditValue] = useState('');
    const startEditing = useCallback((key, currentTitle) => {
        // Also select the tab being edited
        onChange?.(key);
        // Use chainRaf to ensure DOM is ready before entering edit mode
        chainRaf(() => {
            setEditingKey(key);
            setEditValue(currentTitle);
        }, 2);
    }, [onChange]);
    const cancelEditing = useCallback(() => {
        setEditingKey(null);
        setEditValue('');
    }, []);
    const submitEditing = useCallback((key, newTitle, tabOnTitleChange) => {
        const trimmed = newTitle.trim();
        if (trimmed) {
            // Tab-level callback takes precedence
            if (tabOnTitleChange) {
                tabOnTitleChange(trimmed);
            }
            else if (onTitleChange) {
                onTitleChange(key, trimmed);
            }
        }
        setEditingKey(null);
        setEditValue('');
    }, [onTitleChange]);
    return {
        editingKey,
        editValue,
        setEditValue,
        startEditing,
        cancelEditing,
        submitEditing,
    };
}

        