import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { forwardRef, memo, useCallback, useEffect, useRef, useState } from "react";
import { NODE_TEXT_BOTTOM_OFFSET, NODE_TEXT_BOTTOM_OFFSET_WITH_HANDLES } from "../../constants.js";
import { cx } from "../../utils/CssUtil.js";
import { CanvasTooltip } from "../CanvasTooltip.js";
const BaseTextContainer = ({ hasBottomHandles, shape, children })=>{
    if ('rectangle' === shape) return /*#__PURE__*/ jsx("div", {
        className: "flex flex-1 min-w-0 flex-col items-start text-left",
        children: children
    });
    return /*#__PURE__*/ jsx("div", {
        className: cx('absolute left-1/2 w-[150%] flex flex-col z-10 transition-transform duration-200', hasBottomHandles ? 'items-start text-left translate-x-[20%] translate-y-1/2' : 'items-center text-center -translate-x-1/2 translate-y-full'),
        style: {
            bottom: hasBottomHandles ? NODE_TEXT_BOTTOM_OFFSET_WITH_HANDLES : NODE_TEXT_BOTTOM_OFFSET
        },
        children: children
    });
};
const ConditionalTooltip = ({ content, children })=>{
    if (!content) return children;
    return /*#__PURE__*/ jsx(CanvasTooltip, {
        delay: true,
        placement: "top",
        content: content,
        smartTooltip: true,
        children: children
    });
};
const Header = ({ shape, backgroundColor, onDoubleClick, children, 'data-testid': dataTestId })=>/*#__PURE__*/ jsx("div", {
        "data-testid": dataTestId,
        onDoubleClick: onDoubleClick,
        className: cx('text-center text-sm leading-[18px] font-semibold text-foreground overflow-hidden', backgroundColor && 'px-1.5 py-0.5 rounded-sm', 'rectangle' === shape ? 'w-full text-left whitespace-nowrap text-ellipsis' : 'wrap-break-word line-clamp-3'),
        style: backgroundColor ? {
            backgroundColor
        } : void 0,
        children: children
    });
const SubHeader = ({ shape, onDoubleClick, children, 'data-testid': dataTestId })=>/*#__PURE__*/ jsx("div", {
        "data-testid": dataTestId,
        onDoubleClick: onDoubleClick,
        className: cx('text-center text-xs leading-[18px] text-foreground-muted wrap-break-word overflow-hidden', 'rectangle' === shape ? 'w-full text-left line-clamp-2' : 'line-clamp-5'),
        children: children
    });
const EditableLabel = /*#__PURE__*/ forwardRef(({ shape, backgroundColor, variant, value, placeholder, rows, onChange, onKeyDown, onBlur, 'aria-label': ariaLabel }, ref)=>/*#__PURE__*/ jsx("textarea", {
        ref: ref,
        value: value,
        placeholder: placeholder,
        rows: rows,
        "aria-label": ariaLabel,
        onChange: onChange,
        onKeyDown: onKeyDown,
        onBlur: onBlur,
        className: cx('nodrag nowheel resize-none font-[inherit] text-foreground border-none rounded-sm outline-1 outline-dashed outline-border-de-emp max-w-full', 'subtext' === variant ? 'text-xs leading-[18px] font-normal mb-0' : 'text-sm leading-[18px] font-semibold mb-0.5', 'rectangle' === shape ? 'field-sizing-fixed w-full' : 'field-sizing-content text-center', backgroundColor && 'px-1.5 py-0.5'),
        style: backgroundColor ? {
            backgroundColor
        } : void 0
    }));
EditableLabel.displayName = 'EditableLabel';
const EmptyLabelPlaceholder = ({ onDoubleClick })=>/*#__PURE__*/ jsx("button", {
        type: "button",
        onDoubleClick: onDoubleClick,
        className: "nodrag nowheel text-sm leading-[18px] font-semibold text-foreground-muted bg-transparent border border-dashed border-border-de-emp rounded-sm cursor-pointer opacity-0 transition-opacity duration-200 min-w-5 min-h-5 hover:opacity-100",
        "aria-label": "Add node label",
        "data-testid": "empty-label-placeholder"
    });
const NodeLabelInternal = ({ label = '', subLabel = '', labelTooltip, labelBackgroundColor, shape, hasBottomHandles, selected, dragging, centerAdornment, readonly, onChange })=>{
    const [isEditing, setIsEditing] = useState(false);
    const [localLabel, setLocalLabel] = useState('');
    const [localSubLabel, setLocalSubLabel] = useState('');
    const [focusTarget, setFocusTarget] = useState(null);
    const labelInputRef = useRef(null);
    const subLabelInputRef = useRef(null);
    const handleSave = useCallback(()=>{
        setIsEditing(false);
        setFocusTarget(null);
        if (localLabel !== label || localSubLabel !== subLabel) onChange?.({
            label: localLabel,
            subLabel: localSubLabel
        });
    }, [
        localLabel,
        localSubLabel,
        label,
        subLabel,
        onChange
    ]);
    const startEditing = useCallback((targetRef)=>{
        setIsEditing(true);
        setLocalLabel(label);
        setLocalSubLabel(subLabel);
        setFocusTarget(targetRef);
    }, [
        label,
        subLabel
    ]);
    const handleDoubleClick = useCallback((targetRef)=>(e)=>{
            e.stopPropagation();
            startEditing(targetRef);
        }, [
        startEditing
    ]);
    useEffect(()=>{
        if (isEditing && focusTarget?.current) {
            focusTarget.current.focus();
            focusTarget.current.select();
        }
    }, [
        isEditing,
        focusTarget
    ]);
    useEffect(()=>{
        if (isEditing && (!selected || dragging || readonly)) handleSave();
    }, [
        selected,
        dragging,
        isEditing,
        readonly,
        handleSave
    ]);
    const handleCancel = useCallback(()=>{
        setIsEditing(false);
        setFocusTarget(null);
        setLocalLabel(label);
        setLocalSubLabel(subLabel);
    }, [
        label,
        subLabel
    ]);
    const handleKeyDown = useCallback((e)=>{
        if ('Enter' === e.key) {
            e.preventDefault();
            e.stopPropagation();
            handleSave();
        } else if ('Escape' === e.key) {
            e.preventDefault();
            e.stopPropagation();
            handleCancel();
        }
    }, [
        handleSave,
        handleCancel
    ]);
    const handleBlur = useCallback((e)=>{
        const relatedTarget = e.relatedTarget;
        if (relatedTarget === labelInputRef.current || relatedTarget === subLabelInputRef.current) return;
        handleSave();
    }, [
        handleSave
    ]);
    if (!label && !subLabel && !isEditing) return /*#__PURE__*/ jsxs(BaseTextContainer, {
        hasBottomHandles: hasBottomHandles,
        shape: shape,
        children: [
            /*#__PURE__*/ jsx(EmptyLabelPlaceholder, {
                onDoubleClick: readonly ? void 0 : handleDoubleClick(labelInputRef)
            }),
            centerAdornment
        ]
    });
    return /*#__PURE__*/ jsxs(BaseTextContainer, {
        hasBottomHandles: hasBottomHandles,
        shape: shape,
        children: [
            isEditing ? /*#__PURE__*/ jsxs(Fragment, {
                children: [
                    /*#__PURE__*/ jsx(EditableLabel, {
                        ref: labelInputRef,
                        value: localLabel,
                        onChange: (e)=>setLocalLabel(e.target.value),
                        onKeyDown: handleKeyDown,
                        onBlur: handleBlur,
                        shape: shape,
                        variant: "normal",
                        backgroundColor: labelBackgroundColor,
                        placeholder: "Name",
                        rows: 'rectangle' === shape ? 1 : void 0,
                        "aria-label": "Edit node name"
                    }),
                    /*#__PURE__*/ jsx(EditableLabel, {
                        ref: subLabelInputRef,
                        value: localSubLabel,
                        onChange: (e)=>setLocalSubLabel(e.target.value),
                        onKeyDown: handleKeyDown,
                        onBlur: handleBlur,
                        shape: shape,
                        variant: "subtext",
                        placeholder: "Description",
                        rows: 'rectangle' === shape ? 2 : void 0,
                        "aria-label": "Edit node description"
                    })
                ]
            }) : /*#__PURE__*/ jsxs(ConditionalTooltip, {
                content: labelTooltip,
                children: [
                    /*#__PURE__*/ jsx(Header, {
                        shape: shape,
                        backgroundColor: labelBackgroundColor,
                        onDoubleClick: readonly ? void 0 : handleDoubleClick(labelInputRef),
                        "data-testid": "node-label",
                        children: label
                    }),
                    subLabel && /*#__PURE__*/ jsx(SubHeader, {
                        shape: shape,
                        onDoubleClick: readonly ? void 0 : handleDoubleClick(subLabelInputRef),
                        "data-testid": "node-sublabel",
                        children: subLabel
                    })
                ]
            }),
            centerAdornment
        ]
    });
};
const NodeLabel = /*#__PURE__*/ memo(NodeLabelInternal);
export { BaseTextContainer, NodeLabel };
