/* @oracle/oraclejet-preact: undefined */
'use strict';

var jsxRuntime = require('preact/jsx-runtime');
var classNames = require('./classNames-c14c6ef3.js');
var compat = require('preact/compat');
var PRIVATE_BaseLegend_themes_LegendStyles_css = require('./PRIVATE_BaseLegend/themes/LegendStyles.css.js');
var useLegendDnd = require('./useLegendDnd-d44ffd3c.js');
var SvgSymbol = require('./SvgSymbol-5f70e026.js');
var Text = require('./Text-15923d58.js');
var hooks = require('preact/hooks');
var useUser = require('./useUser-c85f9587.js');
var datatipUtils = require('./datatipUtils-1f747b7f.js');
var useDatatip = require('./useDatatip-14e6aeb0.js');
var useContextMenu = require('./useContextMenu-24530094.js');
require('./Menu-77687523.js');
require('./MenuItem-1878e08e.js');
require('preact');
require('./logger-2b636482.js');
require('./LayerHost-8ec73638.js');


require('./hooks/UNSAFE_useTooltip/themes/redwood/TooltipContentVariants.css.js');
require('./tooltipUtils-d461919d.js');

require('./SelectMenuGroupContext-bbb4f7e0.js');
require('./UNSAFE_Separator/themes/SeparatorStyles.css.js');


require('./UNSAFE_Menu/themes/redwood/MenuSeparatorVariants.css.js');

function ImageMarker(props) {
    const { imageMarkerStyle } = PRIVATE_BaseLegend_themes_LegendStyles_css.styles;
    return jsxRuntime.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 } = PRIVATE_BaseLegend_themes_LegendStyles_css.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 (jsxRuntime.jsx("div", { className: legendSymbolBaseStyle, style: { width: props.width, height: props.height }, children: props.source ? (jsxRuntime.jsx(ImageMarker, { source: props.source })) : (jsxRuntime.jsx(SvgSymbol.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 } = PRIVATE_BaseLegend_themes_LegendStyles_css.styles;
    const isTitle = type === 'title';
    return (jsxRuntime.jsx("div", { class: classNames.classNames([
            legendTextBaseStyle,
            isTitle ? legendTextTitle : '',
            isTitle && align === 'start' ? legendTitleStartAlign : '',
            isTitle && align === 'center' ? legendTitleCenterAlign : '',
            isTitle && align === 'end' ? legendTitleEndAlign : ''
        ]), style: {
            ...props
        }, children: jsxRuntime.jsx(Text.Text, { size: "inherit", variant: "inherit", weight: "inherit", truncation: 'ellipsis', id: id, children: text }) }));
};

const BaseLegendItem = compat.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 } = PRIVATE_BaseLegend_themes_LegendStyles_css.styles;
    return (jsxRuntime.jsxs("div", { class: classNames.classNames([
            legendItemBaseStyle,
            useLegendDnd.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: [jsxRuntime.jsx(LegendSymbol, { ...symbolProps, isHidden: isHidden, lineLength: symbolWidth, width: symbolWidth != null ? `${symbolWidth}px` : undefined, height: symbolHeight != null ? `${symbolHeight}px` : undefined }), jsxRuntime.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 } = PRIVATE_BaseLegend_themes_LegendStyles_css.styles;
    return (jsxRuntime.jsx("div", { className: classNames.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 } = useLegendDnd.getItemProps(item, index, sectionIdx, focusedItemInfo, isReadOnly, hoveredItemInfo, hiddenIds, highlightedIds);
            const isFocusedItem = focusedItemInfo.sectionIdx === sectionIdx && focusedItemInfo.itemIdx === index;
            const { gridRow, gridCol } = useLegendDnd.getGridCellIndices(items.length, index, props.itemsPerRow, props.itemsPerCol);
            const needsBottomSpace = gridRow != null && gridRow != props.itemsPerCol;
            const needsTopSpace = gridRow != null && gridRow != 1;
            return (jsxRuntime.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.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 = datatipUtils.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(datatipUtils.DATATIP_OFFSET, Math.max(mainAxisOffset, itemDim.height - rootDim.height + datatipUtils.DATATIP_OFFSET));
    }
    return { crossAxis, mainAxis: mainAxisOffset };
};
const useLegendDatatip = ({ text, rootDimsRef, focusedItemRef, focusedItemInfo, touchResponse, isDisabled }) => {
    const { direction } = useUser.useUser();
    const isRtl = direction === 'rtl';
    const [offset, setOffset] = hooks.useState(calculateOffset(focusedItemRef, rootDimsRef, focusedItemInfo, isRtl));
    hooks.useLayoutEffect(() => {
        setOffset(calculateOffset(focusedItemRef, rootDimsRef, focusedItemInfo, isRtl));
    }, [focusedItemInfo, focusedItemRef, isRtl, rootDimsRef]);
    const anchor = focusedItemInfo?.isCurrent ? 'element' : 'pointer';
    return useDatatip.useDatatip({
        content: text,
        placement: 'top',
        anchor,
        offset,
        touchResponse,
        isDisabled
    });
};

const useLegendContextMenu = ({ rootRef, contextMenuConfig, focusedItemInfo, items, isReadOnly, onContextMenuDismissed }) => {
    const { contextMenuProps, contextMenuContent } = useContextMenu.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 = useLegendDnd.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.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 = useLegendDnd.getItemInfo(target)?.itemIdx;
            const sectionIdx = useLegendDnd.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 };
};

exports.BaseLegend = BaseLegend;
exports.LegendText = LegendText;
exports.useLegendContextMenu = useLegendContextMenu;
exports.useLegendDatatip = useLegendDatatip;
exports.useSectionalLegendContextMenu = useSectionalLegendContextMenu;
//# sourceMappingURL=useLegendContextMenu-d8d7169f.js.map
