/* @oracle/oraclejet-preact: undefined */
import { jsx, jsxs } from 'preact/jsx-runtime';
import { c as classNames } from './classNames-4e12b00d.js';
import { forwardRef } from 'preact/compat';
import { styles } from './PRIVATE_BaseLegend/themes/LegendStyles.css.js';
import { h as getLegendCurrentItemStyle, j as getItemProps, k as getGridCellIndices, b as getItemInfo } from './useLegendDnd-3712d3c2.js';
import { S as SvgSymbol } from './SvgSymbol-2da94135.js';
import { T as Text } from './Text-f8d4ff78.js';
import { useState, useLayoutEffect } from 'preact/hooks';
import { u as useUser } from './useUser-1cd223a9.js';
import { D as DATATIP_OFFSET } from './datatipUtils-13ab34b7.js';
import { u as useDatatip } from './useDatatip-9635bc2f.js';
import { u as useContextMenu } from './useContextMenu-3c62d9eb.js';
import './Menu-a5bf756f.js';
import './MenuItem-54015ca3.js';
import 'preact';
import './logger-c92f309c.js';
import './LayerHost-e6402730.js';
import './TooltipContentStyles.styles.css';
import './hooks/UNSAFE_useTooltip/themes/redwood/TooltipContentBaseTheme.styles.css';
import './hooks/UNSAFE_useTooltip/themes/redwood/TooltipContentVariants.css.js';
import './tooltipUtils-768450a7.js';
import './IconStyle.styles.css';
import './SelectMenuGroupContext-b56cf5d4.js';
import './UNSAFE_Separator/themes/SeparatorStyles.css.js';
import './MenuSeparatorStyles.styles.css';
import './UNSAFE_Menu/themes/redwood/MenuSeparatorBaseTheme.styles.css';
import './UNSAFE_Menu/themes/redwood/MenuSeparatorVariants.css.js';

function ImageMarker(props) {
    const { imageMarkerStyle } = styles;
    return jsx("img", { class: imageMarkerStyle, src: props.source, role: "none" });
}

const LegendSymbol = ({ 
// The default color is not in the redwood pallete.
// TODO: replace default legend color with UX approved pallete color when available.
markerColor = '#a6acb1', lineColor = '#a6acb1', markerShape = 'square', isHidden = false, lineStyle = 'none', ...props }) => {
    const { legendSymbolBaseStyle } = styles;
    const dimensionsNotSet = props.width == null && props.height == null;
    const setAspectRatioNone = !dimensionsNotSet && (markerShape === 'rectangle' || markerShape === 'ellipse');
    const defaultLineWidth = lineStyle != 'none' && markerShape != 'none' ? 2 : 3;
    return (jsx("div", { className: legendSymbolBaseStyle, style: { width: props.width, height: props.height }, children: props.source ? (jsx(ImageMarker, { source: props.source })) : (jsx(SvgSymbol, { setAspectRatioNone: setAspectRatioNone, markerShape: isHidden ? 'square' : markerShape, lineStyle: isHidden ? 'none' : lineStyle, lineColor: lineColor, lineLength: props.lineLength, lineWidth: props.lineWidth != null ? props.lineWidth : defaultLineWidth, markerColor: isHidden ? 'transparent' : markerColor, borderColor: isHidden ? markerColor || lineColor : props.borderColor, setAbsolutePos: true })) }));
};

/**
 * Returns the legend text component.
 */
const LegendText = ({ text, type = 'label', id, align = 'start', ...props }) => {
    const { legendTextBaseStyle, legendTextTitle, legendTitleStartAlign, legendTitleCenterAlign, legendTitleEndAlign } = styles;
    const isTitle = type === 'title';
    return (jsx("div", { class: classNames([
            legendTextBaseStyle,
            isTitle ? legendTextTitle : '',
            isTitle && align === 'start' ? legendTitleStartAlign : '',
            isTitle && align === 'center' ? legendTitleCenterAlign : '',
            isTitle && align === 'end' ? legendTitleEndAlign : ''
        ]), style: {
            ...props
        }, children: jsx(Text, { size: "inherit", variant: "inherit", weight: "inherit", truncation: 'ellipsis', id: id, children: text }) }));
};

const BaseLegendItem = forwardRef(({ id, text, sectionIdx, itemIdx, itemId, isHighlighted, symbolHeight, symbolWidth, isFocused, isCurrent, isHidden, actionable = 'inherit', hoverBehavior = 'none', hideAndShowBehavior = 'off', ...props }, ref) => {
    const textStyles = {
        fontFamily: props.textFontFamily,
        fontSize: props.textFontSize,
        color: props.textColor,
        fontStyle: props.textFontStyle,
        fontWeight: props.textFontWeight,
        textDecoration: props.textTextDecoration
    };
    const symbolProps = {
        lineStyle: props.lineStyle,
        lineWidth: props.lineWidth,
        markerShape: props.markerShape,
        markerColor: props.markerColor,
        source: props.source,
        borderColor: props.borderColor,
        lineColor: props.lineColor
    };
    const isNotDimmed = isHighlighted || isHighlighted == null;
    const { legendItemBaseStyle, legendItemOpacity, legendItemFocusRing } = styles;
    return (jsxs("div", { class: classNames([
            legendItemBaseStyle,
            getLegendCurrentItemStyle(isCurrent, isHighlighted, hideAndShowBehavior, hoverBehavior, isHidden, actionable),
            !isNotDimmed ? legendItemOpacity : '',
            isFocused ? legendItemFocusRing : '',
            props.class
        ]), style: {
            gridRow: props.gridRow,
            gridColumn: props.gridCol,
            minWidth: props.minWidth !== undefined ? `${props.minWidth}px` : undefined
        }, id: id, ref: ref, "data-oj-section": sectionIdx, "data-oj-item": itemIdx, "data-oj-private-item-id": itemId, role: isHidden != null ? 'menuitemcheckbox' : 'img', "aria-checked": isHidden != null ? !isHidden : undefined, "aria-label": props['aria-label'] || text, children: [jsx(LegendSymbol, { ...symbolProps, isHidden: isHidden, lineLength: symbolWidth, width: symbolWidth != null ? `${symbolWidth}px` : undefined, height: symbolHeight != null ? `${symbolHeight}px` : undefined }), jsx(LegendText, { ...textStyles, text: text, type: "label" })] }));
});

/**
 * The controlled legend reponsible only for rendering the legend items.
 */
const BaseLegend = ({ orientation = 'horizontal', highlightedIds, hiddenIds, focusedItemInfo, hoveredItemInfo, sectionIdx, activeId, isReadOnly, items, symbolHeight, symbolWidth, hideAndShowBehavior = 'off', hoverBehavior = 'none', isTestEnv, ...props }) => {
    const isHoriz = orientation === 'horizontal';
    const columTemplates = isHoriz ? `repeat(${props.itemsPerRow}, ${props.itemWidth})` : undefined;
    const { baseLegendStyles, baseLegendHorizontal, baseLegendVertical, baseLegendVerticalItem, baseLegendPaddingBottom, baseLegendPaddingTop, baseLegendPaddingEnd } = styles;
    return (jsx("div", { className: classNames([
            baseLegendStyles,
            isHoriz ? baseLegendHorizontal : baseLegendVertical
        ]), style: {
            gridTemplateColumns: columTemplates,
            // set maxWidth to 100% on second render for text truncation to work.
            maxWidth: '100%'
        }, children: items.map((item, index) => {
            const { markerColor, markerShape, source, borderColor, lineColor, isCurrent, isFocused, isHidden, isHighlighted, key, actionable, text, lineStyle, lineWidth } = getItemProps(item, index, sectionIdx, focusedItemInfo, isReadOnly, hoveredItemInfo, hiddenIds, highlightedIds);
            const isFocusedItem = focusedItemInfo.sectionIdx === sectionIdx && focusedItemInfo.itemIdx === index;
            const { gridRow, gridCol } = getGridCellIndices(items.length, index, props.itemsPerRow, props.itemsPerCol);
            const needsBottomSpace = gridRow != null && gridRow != props.itemsPerCol;
            const needsTopSpace = gridRow != null && gridRow != 1;
            return (jsx(BaseLegendItem, { ref: isFocusedItem ? props.focusedItemRef : undefined, text: text, itemIdx: index, sectionIdx: sectionIdx, itemId: isTestEnv ? item.id : undefined, symbolHeight: symbolHeight, symbolWidth: symbolWidth, markerColor: markerColor, markerShape: markerShape, lineStyle: lineStyle, lineWidth: lineWidth, source: source, borderColor: borderColor, "aria-label": item['aria-label'], lineColor: lineColor, isCurrent: isCurrent, isFocused: isFocused, isHidden: isHidden, isHighlighted: isHighlighted, gridRow: gridRow, gridCol: gridCol, minWidth: props.itemWidth, id: isCurrent ? activeId : '', textColor: props.textColor, textFontFamily: props.textFontFamily, textFontSize: props.textFontSize, textFontStyle: props.textFontStyle, textFontWeight: props.textFontWeight, textTextDecoration: props.textTextDecoration, class: classNames([
                    isHoriz ? '' : baseLegendVerticalItem,
                    needsTopSpace ? baseLegendPaddingTop : '',
                    needsBottomSpace ? baseLegendPaddingBottom : '',
                    baseLegendPaddingEnd
                ]), hideAndShowBehavior: hideAndShowBehavior, hoverBehavior: hoverBehavior, actionable: actionable }, key));
        }) }));
};

/**
 * Calculate the datatip offset for datatip when keyboard focus is active.
 * @param focusedItemRef The ref for currentItem node.
 * @param rootRef The ref for root of the legend.
 * @param currentItem The ItemInfo of the current keyboard focused item.
 * @returns
 */
const calculateOffset = (focusedItemRef, rootDimsRef, currentItem, isRtl) => {
    let crossAxis = 0;
    let mainAxisOffset = DATATIP_OFFSET;
    if (focusedItemRef.current && currentItem.isCurrent && rootDimsRef.current) {
        const rootDim = rootDimsRef.current;
        const itemDim = focusedItemRef.current.getBoundingClientRect();
        crossAxis = itemDim.x + itemDim.width / 2 - (rootDim.x + rootDim.width / 2);
        crossAxis = isRtl ? -1 * crossAxis : crossAxis;
        mainAxisOffset += rootDim.y - itemDim.y;
        mainAxisOffset = Math.min(DATATIP_OFFSET, Math.max(mainAxisOffset, itemDim.height - rootDim.height + DATATIP_OFFSET));
    }
    return { crossAxis, mainAxis: mainAxisOffset };
};
const useLegendDatatip = ({ text, rootDimsRef, focusedItemRef, focusedItemInfo, touchResponse, isDisabled }) => {
    const { direction } = useUser();
    const isRtl = direction === 'rtl';
    const [offset, setOffset] = useState(calculateOffset(focusedItemRef, rootDimsRef, focusedItemInfo, isRtl));
    useLayoutEffect(() => {
        setOffset(calculateOffset(focusedItemRef, rootDimsRef, focusedItemInfo, isRtl));
    }, [focusedItemInfo, focusedItemRef, isRtl, rootDimsRef]);
    const anchor = focusedItemInfo?.isCurrent ? 'element' : 'pointer';
    return useDatatip({
        content: text,
        placement: 'top',
        anchor,
        offset,
        touchResponse,
        isDisabled
    });
};

const useLegendContextMenu = ({ rootRef, contextMenuConfig, focusedItemInfo, items, isReadOnly, onContextMenuDismissed }) => {
    const { contextMenuProps, contextMenuContent } = useContextMenu({
        onContextMenuHandler: ({ gesture, target }) => {
            if (gesture === 'keyboard') {
                const itemIdx = focusedItemInfo.itemIdx;
                const elem = rootRef.current?.querySelector(`[data-oj-item="${itemIdx}"]`) || null;
                const data = items[itemIdx];
                const context = { type: 'item', data };
                return {
                    type: 'element',
                    context,
                    elem
                };
            }
            const itemIdx = getItemInfo(target)?.itemIdx;
            const data = itemIdx !== undefined ? items[itemIdx] : null;
            const context = data ? { type: 'item', data } : { type: 'background' };
            return {
                type: 'pointer',
                context
            };
        },
        contextMenuOptions: {
            isDisabled: !contextMenuConfig || isReadOnly //If there is no context menu renderer or if isReadOnly is true, we disable the hook
        },
        rootRef,
        contextMenuConfig,
        onContextMenuDismissed
    });
    return { contextMenuContent, contextMenuProps };
};
const useSectionalLegendContextMenu = ({ rootRef, contextMenuConfig, focusedItemInfo, sections, isReadOnly, onContextMenuDismissed }) => {
    const { contextMenuProps, contextMenuContent } = useContextMenu({
        onContextMenuHandler: ({ gesture, target }) => {
            if (gesture === 'keyboard') {
                const itemIdx = focusedItemInfo.itemIdx;
                const sectionIdx = focusedItemInfo.sectionIdx;
                const data = sections[sectionIdx]?.items[itemIdx];
                if (data) {
                    const elem = rootRef.current?.querySelector(`[data-oj-item="${itemIdx}"][data-oj-section="${sectionIdx}"]`) || null;
                    const context = { type: 'item', itemIndexPath: [sectionIdx, itemIdx], data };
                    return {
                        type: 'element',
                        context,
                        elem
                    };
                }
            }
            const itemIdx = getItemInfo(target)?.itemIdx;
            const sectionIdx = getItemInfo(target)?.sectionIdx;
            const data = sectionIdx !== undefined && itemIdx !== undefined
                ? sections[sectionIdx]?.items[itemIdx]
                : null;
            const itemIndexPath = [sectionIdx, itemIdx];
            const context = data
                ? { type: 'item', data, itemIndexPath }
                : { type: 'background' };
            return {
                type: 'pointer',
                context
            };
        },
        contextMenuOptions: {
            isDisabled: !contextMenuConfig || isReadOnly //If there is no context menu renderer or if isReadOnly is true, we disable the hook
        },
        rootRef,
        contextMenuConfig,
        onContextMenuDismissed
    });
    return { contextMenuContent, contextMenuProps };
};

export { BaseLegend as B, LegendText as L, useLegendContextMenu as a, useSectionalLegendContextMenu as b, useLegendDatatip as u };
//# sourceMappingURL=useLegendContextMenu-66d6eb7e.js.map
