/* @oracle/oraclejet-preact: undefined */
import { jsxs, Fragment, jsx } from 'preact/jsx-runtime';
import { useContext, useRef, useState, useMemo } from 'preact/hooks';
import { u as useLegendDatatip, a as useLegendContextMenu, B as BaseLegend } from './useLegendContextMenu-66d6eb7e.js';
import { u as useVisEvent } from './useVisEvents-8877743b.js';
import { g as getGridNums, a as getLegendTextStyle, b as getItemInfo, i as isEqualItem, c as getDatatipText, d as getAriaProps, u as useLegendDnd, l as legendVars, e as getIsLegendItemActionable, f as getKeyUpHandler } from './useLegendDnd-3712d3c2.js';
import { m as mergeProps } from './mergeProps-88ea8306.js';
import { u as useItemFocus } from './useItemFocus-c12e2756.js';
import { styles } from './PRIVATE_BaseLegend/themes/LegendStyles.css.js';
import { u as useCssVars } from './useCssVars-d72a8439.js';
import { c as classNames } from './classNames-4e12b00d.js';
import { u as useTestId } from './useTestId-9b504481.js';
import { u as useVisTouchResponse } from './useVisTouchResponse-a59ab166.js';
import { m as merge } from './stringUtils-16f617bc.js';
import { forwardRef, useImperativeHandle } from 'preact/compat';
import { T as TrackResizeContainer } from './TrackResizeContainer-04a2c642.js';
import { u as useTextDimensions } from './useTextDimensions-e08928cc.js';
import { styles as styles$1 } from './hooks/PRIVATE_useVisDnd/themes/VisDndStyles.css.js';
import { L as LegendRenderedContext } from './LegendRendered-65a3684e.js';

/**
 * @license
 * Copyright (c) %FIRST_YEAR% %CURRENT_YEAR%, Oracle and/or its affiliates.
 * The Universal Permissive License (UPL), Version 1.0
 * as shown at https://oss.oracle.com/licenses/upl/
 * @ignore
 */
function getItem(itemInfo, items) {
    const { itemIdx } = itemInfo;
    if (itemIdx == -1) {
        return items[items.length - 1];
    }
    return items[itemIdx];
}
function getNextItemInfo(itemInfo, items) {
    let itemIdx = itemInfo.itemIdx;
    if (itemIdx == -1) {
        itemIdx = items.length - 1;
    }
    itemIdx = Math.min(items.length - 1, itemIdx + 1);
    if (items[itemIdx].actionable !== 'off') {
        return { sectionIdx: 0, itemIdx };
    }
    else if (itemIdx === items.length - 1) {
        itemIdx = itemIdx - 1;
        return { sectionIdx: 0, itemIdx };
    }
    return getNextItemInfo({ sectionIdx: 0, itemIdx }, items);
}
function getPrevItemInfo(itemInfo, items) {
    let itemIdx = itemInfo.itemIdx;
    if (itemIdx == -1) {
        itemIdx = items.length - 1;
    }
    itemIdx = Math.max(0, itemIdx - 1);
    if (items[itemIdx].actionable !== 'off') {
        return { sectionIdx: 0, itemIdx };
    }
    return getPrevItemInfo({ sectionIdx: 0, itemIdx }, items);
}
/**
 * Returns utils functions for navigation in simple legend.
 * @param items
 * @returns
 */
function getLegendNavUtils(items) {
    return {
        getItem: (itemInfo) => {
            return getItem(itemInfo, items);
        },
        getDetailFromInfo: (itemInfo) => {
            if (!itemInfo || items.length === 0) {
                return { itemId: undefined, data: undefined };
            }
            const item = getItem(itemInfo, items);
            return { itemId: item.id, data: item };
        },
        getPrevItemInfo: (itemInfo) => {
            return getPrevItemInfo(itemInfo, items);
        },
        getNextItemInfo: (itemInfo) => {
            return getNextItemInfo(itemInfo, items);
        }
    };
}

/**
 * @license
 * Copyright (c) %FIRST_YEAR% %CURRENT_YEAR%, Oracle and/or its affiliates.
 * The Universal Permissive License (UPL), Version 1.0
 * as shown at https://oss.oracle.com/licenses/upl/
 * @ignore
 */
const getLinearLegendLayoutInfo = ({ width, getTextDimensions, resolvedVars, orientation, legendFontStylesObj = {}, symbolWidth, items }) => {
    let maxWidth = 0;
    let maxHeight = 0;
    let totalWidth = 0;
    let isWrapped = false;
    const containerWidth = width;
    if (!Object.keys(resolvedVars).length || !getTextDimensions) {
        return;
    }
    const unitLength = parseFloat(resolvedVars['unit']);
    const { maxItemWidth, maxItemHeight, horizontalSectionWidth } = getMaxWidth(items, unitLength, getTextDimensions, legendFontStylesObj, symbolWidth);
    totalWidth = horizontalSectionWidth;
    maxWidth = maxItemWidth;
    maxHeight = maxItemHeight;
    isWrapped = horizontalSectionWidth > containerWidth;
    const legendLayoutInfo = {
        totalWidth,
        maxItemWidth: Math.min(maxWidth, containerWidth),
        maxItemHeight: maxHeight,
        itemsPerRow: orientation === 'vertical' ? 1 : Math.max(1, Math.floor(containerWidth / maxWidth)),
        isWrapped
    };
    return legendLayoutInfo;
};
/**
 * Returns maximum of the width among the items in a section of legend also return the width of the entire section.
 * @param items Legend items array
 * @param unitLength Base  element
 * @param getTextDimensions Text width measurement function
 * @param legendFontStylesObj Legend text font style properties object
 * @param symbolWidth Width of legend symbol
 *
 * @returns
 */
const getMaxWidth = (items, unitLength, getTextDimensions, legendFontStylesObj, symbolWidth, symbolHeight) => {
    let maxItemWidth = 0;
    let maxItemHeight = 0;
    let horizontalSectionWidth = 0;
    let itemSymbolWidth = 0;
    let itemSymbolHeight = 0;
    if (symbolWidth) {
        itemSymbolWidth = unitLength * 1.5 + symbolWidth;
    }
    else {
        //itemSymbolWidth = marginLeft + marginRight + width below expression is simplified
        itemSymbolWidth = 4 * unitLength;
    }
    if (symbolHeight) {
        // symbolHeight/defaultSymbolHeight + symbolPaddingTopBottom
        itemSymbolHeight = symbolHeight + unitLength * 1.7;
    }
    else {
        // symbolHeight/defaultSymbolHeight + symbolPaddingTopBottom
        itemSymbolHeight = 2.5 * unitLength + unitLength * 1.7;
    }
    items?.forEach((item) => {
        const legendItem = item;
        const { width, height } = getTextDimensions(legendItem.text, legendFontStylesObj);
        //itemTextWidth = paddingLeft + paddingRight + width
        const itemTextWidth = unitLength * 2.5 + width;
        //horizontalSectionWidth = total width of the section
        horizontalSectionWidth += itemSymbolWidth + itemTextWidth;
        maxItemWidth = Math.max(maxItemWidth, itemSymbolWidth + itemTextWidth);
        maxItemHeight = Math.max(maxItemHeight, height, itemSymbolHeight);
    });
    return { maxItemWidth, maxItemHeight, horizontalSectionWidth };
};
function _getPreferredSize(_width, _height, items, resolvedVars, orientation, legendFontStylesObj, symbolWidth, symbolHeight, getTextDimensions) {
    if (!getTextDimensions) {
        return undefined;
    }
    const layoutInfo = getLinearLegendLayoutInfo({
        width: _width,
        getTextDimensions,
        resolvedVars,
        orientation,
        legendFontStylesObj,
        symbolWidth: symbolWidth,
        symbolHeight: symbolHeight,
        items
    });
    const { itemsPerCol, itemsPerRow } = getGridNums(items.length, layoutInfo, orientation);
    const unitLength = parseFloat(resolvedVars['unit']);
    const preferredWidth = Math.min(_width, itemsPerCol === 1
        ? layoutInfo.totalWidth
        : itemsPerRow
            ? layoutInfo.maxItemWidth * itemsPerRow
            : layoutInfo.totalWidth);
    const paddingLegendItems = 0.8 * unitLength;
    const paddingLegendTopBottom = 1.5 * unitLength;
    const legendHeight = itemsPerCol
        ? layoutInfo.maxItemHeight * itemsPerCol +
            (itemsPerCol - 1) * paddingLegendItems +
            paddingLegendTopBottom
        : layoutInfo.maxItemHeight + paddingLegendTopBottom;
    const preferredHeight = Math.min(_height, legendHeight);
    return { width: Math.ceil(preferredWidth), height: Math.ceil(preferredHeight) };
}

/**
 * A legend displays an interactive description of symbols, colors, etc., used in graphical information representations.
 */
const Legend = forwardRef(({ orientation = 'horizontal', items, isReadOnly = true, onItemAction, onItemHover, onItemFocus, testId, contextMenuConfig, hideAndShowBehavior = 'off', hoverBehavior = 'none', halign = 'start', valign = 'top', ...props }, ref = null) => {
    // Use the context
    const { isGetPreferredSizeReady, width, height } = useContext(LegendRenderedContext);
    const { textMeasureContent, getTextDimensions } = useTextDimensions();
    const { resolvedVars, cssContent } = useCssVars(legendVars);
    const legendFontStylesObj = getLegendTextStyle({
        fontStyle: props.textFontStyle,
        fontSize: props.textFontSize?.toString(),
        fontWeight: props.textFontWeight?.toString(),
        fontFamily: props.textFontFamily
    }, resolvedVars);
    const rootRef = useRef(null);
    useImperativeHandle(ref, () => ({
        _getPreferredSize: (_width, _height) => {
            return _getPreferredSize(_width, _height, items, resolvedVars, orientation, legendFontStylesObj, props.symbolWidth, props.symbolHeight, getTextDimensions);
        }
    }), [
        getTextDimensions,
        resolvedVars,
        orientation,
        legendFontStylesObj,
        props.symbolWidth,
        props.symbolHeight,
        items
    ]);
    if (getTextDimensions &&
        resolvedVars['unit'] != undefined &&
        resolvedVars['fontSize'] != undefined) {
        isGetPreferredSizeReady?.(true);
    }
    const testIdProps = useTestId(testId);
    const isTestEnv = testIdProps['data-testid'] !== undefined;
    const rootDimsRef = useRef();
    const { getItem, getDetailFromInfo, getPrevItemInfo, getNextItemInfo } = getLegendNavUtils(items);
    const isLegendItemActionable = getIsLegendItemActionable(items, isReadOnly);
    const hasData = items.length > 0;
    const legendKeyUpHandler = (triggerOnAction, updatefocusedItemInfo, focusedItemInfo) => getKeyUpHandler(triggerOnAction, updatefocusedItemInfo, focusedItemInfo, props.hiddenIds != null);
    const { touchResponse, touchResponseStyle } = useVisTouchResponse({
        type: 'touchStart'
    });
    const { focusedItemInfo, hoveredItemInfo, onContextMenuDismissed, activeId, eventsProps } = useVisEvent(touchResponse, !isReadOnly, isLegendItemActionable, legendKeyUpHandler, getDetailFromInfo, getPrevItemInfo, getNextItemInfo, onItemAction, onItemHover, onItemFocus, isEqualItem, getItemInfo, { itemIdx: 0, sectionIdx: 0 }, props.hiddenIds != null);
    const { focusedItemRef } = useItemFocus(focusedItemInfo);
    const datatipText = getDatatipText(items, getItem, focusedItemInfo, hoveredItemInfo);
    const [datatipDisabled, setDatatipDisabled] = useState(false);
    const { datatipContent, datatipProps: { 'aria-describedby': datatipAriaDescribedby, ...datatipProps } } = useLegendDatatip({
        text: datatipText,
        rootDimsRef,
        focusedItemInfo,
        focusedItemRef,
        touchResponse,
        isDisabled: datatipDisabled
    });
    const ariaProps = getAriaProps(isReadOnly, props['aria-label'], props.hiddenIds, merge([props['aria-describedby'], datatipAriaDescribedby]), props['aria-labelledby']);
    const { contextMenuContent, contextMenuProps } = useLegendContextMenu({
        rootRef,
        contextMenuConfig: hasData ? contextMenuConfig : undefined,
        focusedItemInfo,
        items,
        isReadOnly,
        onContextMenuDismissed
    });
    const [dragOver, setDragOver] = useState();
    const { draggable, dndProps, dndContent } = useLegendDnd({
        onDrag: props.onDrag,
        onDragStart: props.onDragStart,
        onDragEnd: props.onDragEnd,
        onDragEnter: props.onDragEnter,
        onDragLeave: props.onDragLeave,
        onDragOver: props.onDragOver,
        onDrop: props.onDrop,
        items,
        setDragOver,
        setDatatipDisabled,
        itemDraggable: props.itemDraggable
    });
    const mergedProps = mergeProps(eventsProps, datatipProps, contextMenuProps, dndProps);
    const { legendStyle, renderedLegendStyle } = styles;
    return (jsxs(Fragment, { children: [!isGetPreferredSizeReady && (jsx(TrackResizeContainer, { width: width ? `${width}px` : '100%', height: height ? `${height}px` : '100%', class: classNames([
                    styles.flexStyle,
                    styles[`${halign}HAlign`],
                    styles[`${valign}VAlign`]
                ]), children: function _(width) {
                    const layoutInfo = useMemo(() => getLinearLegendLayoutInfo({
                        width,
                        getTextDimensions,
                        resolvedVars,
                        orientation,
                        legendFontStylesObj,
                        symbolWidth: props.symbolWidth,
                        symbolHeight: props.symbolHeight,
                        items
                    }), [width]);
                    const { itemsPerCol, itemsPerRow } = getGridNums(items.length, layoutInfo);
                    return (jsxs(Fragment, { children: [jsx("div", { ref: rootRef, tabIndex: isReadOnly ? undefined : 0, role: "application", draggable: draggable, class: classNames([
                                    legendStyle,
                                    renderedLegendStyle,
                                    dragOver
                                        ? styles$1.dndDragOverHTMLStyle
                                        : dragOver === false
                                            ? styles$1.dndRejectedStyle
                                            : undefined
                                ]), style: touchResponseStyle, ...testIdProps, ...ariaProps, ...mergedProps, "aria-activedescendant": activeId, children: jsx(BaseLegend, { ...props, focusedItemRef: focusedItemRef, items: items, isReadOnly: isReadOnly, orientation: orientation, sectionIdx: 0, itemsPerRow: itemsPerRow, itemsPerCol: itemsPerCol, itemWidth: layoutInfo?.isWrapped ? layoutInfo?.maxItemWidth : undefined, focusedItemInfo: focusedItemInfo, hoveredItemInfo: hoveredItemInfo, activeId: activeId, hideAndShowBehavior: hideAndShowBehavior, hoverBehavior: hoverBehavior, isTestEnv: isTestEnv }) }), datatipContent, contextMenuContent, dndContent] }));
                } })), textMeasureContent, cssContent] }));
});

export { Legend as L };
//# sourceMappingURL=Legend-0e274097.js.map
