import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from 'react';
import { getTransformFromPlacement, Popper } from '@workday/canvas-kit-react/popup';
import { mergeCallback } from '@workday/canvas-kit-react/common';
import { TooltipContainer, useTooltip } from '@workday/canvas-kit-react/tooltip';
const isOverflowed = (element) => {
    return (element.textContent || '').includes('more');
};
function mergeCallbacks(elemProps, componentProps, keys = Object.keys(componentProps)) {
    return keys.reduce((mergedProps, key) => {
        if (typeof elemProps[key] === 'function') {
            mergedProps[key] = mergeCallback(componentProps[key], elemProps[key]);
        }
        else {
            mergedProps[key] = componentProps[key];
        }
        return mergedProps;
    }, {});
}
function getTooltipContents(title) {
    if (title instanceof Array) {
        if (title.length && title[0].value) {
            return title.map(v => v.value).join(', ');
        }
    }
    return '';
}
export const MoreTooltip = ({ placement = 'top', children, title, ...elemProps }) => {
    const [titleText, setTitleText] = React.useState('');
    const { targetProps, popperProps, tooltipProps } = useTooltip({ type: 'describe' });
    const onMouseEnter = (event) => {
        const target = event.currentTarget;
        setTitleText(getTooltipContents(title));
        if (isOverflowed(target)) {
            targetProps.onMouseEnter(event);
        }
    };
    const onFocus = (event) => {
        const target = event.currentTarget;
        setTitleText(getTooltipContents(title));
        if (isOverflowed(target)) {
            targetProps.onFocus(event);
        }
    };
    return (_jsxs(React.Fragment, { children: [React.cloneElement(children, {
                ...targetProps,
                onMouseEnter,
                onFocus,
                'aria-label': undefined,
                ...mergeCallbacks({ ...targetProps, onMouseEnter, onFocus }, children.props),
            }), _jsx(Popper, { placement: placement, ...popperProps, children: ({ placement }) => {
                    const transformOrigin = getTransformFromPlacement(placement);
                    return (_jsx(TooltipContainer, { transformOrigin: transformOrigin, ...tooltipProps, ...elemProps, children: titleText }));
                } })] }));
};
