import React, { useMemo } from 'react';
import { Box, Chip } from '@material-ui/core';
import { StatusChip } from '../../UI/dataDisplay/status/StatusChip';
export const VisualSearchObject = ({ searchObject }) => {
    // 1️⃣ Safely default to an empty object if searchObject is null/undefined:
    const safeSO = searchObject || {};
    // 2️⃣ Destructure with defaults for each property:
    const { filterElements = [], filterGroups = [], logicalSearchOperator = 1, } = safeSO;
    const filtersByGroup = useMemo(() => {
        return filterElements.reduce((acc, fe) => {
            var _a;
            const gid = (_a = fe.groupId) !== null && _a !== void 0 ? _a : 0;
            (acc[gid] = acc[gid] || []).push(fe);
            return acc;
        }, {});
    }, [filterElements]);
    const groupLookup = useMemo(() => {
        const lookup = {};
        filterGroups.forEach(g => {
            lookup[g.groupId] = Object.assign(Object.assign({}, g), { children: [] });
        });
        filterGroups.forEach(g => {
            if (g.parentGroupId && lookup[g.parentGroupId]) {
                lookup[g.parentGroupId].children.push(lookup[g.groupId]);
            }
        });
        return lookup;
    }, [filterGroups]);
    const topLevelGroups = useMemo(() => {
        return filterGroups
            .filter(g => !g.parentGroupId)
            .map(g => groupLookup[g.groupId]);
    }, [filterGroups, groupLookup]);
    // virtual root
    const rootGroup = {
        groupId: 0,
        logicalSearchOperator,
        children: topLevelGroups,
    };
    // 4️⃣ Recursive render
    const OpLabel = { 1: 'AND', 2: 'OR' };
    const renderGroup = (group, level = 0) => (React.createElement(Box, { key: group.groupId, border: 1, borderColor: "grey.300", borderRadius: 4, p: 1, ml: level * 2, mb: 1, bgcolor: level === 0 ? 'grey.100' : 'transparent' }, React.createElement(Box, { mb: 1 }, React.createElement(StatusChip, { label: OpLabel[group.logicalSearchOperator] || 'AND', status: "info", size: "small" })), React.createElement(Box, { display: "flex", flexWrap: "wrap", mb: group.children.length ? 1 : 0 }, (filtersByGroup[group.groupId] || []).map((fe, i) => (React.createElement(Chip, { key: `g${group.groupId}-f${i}`, size: "small", label: `${fe.searchField} ${fe.searchOperator} ${fe.searchValue}`, style: { marginRight: 4, marginBottom: 4 } })))), group.children.map(c => renderGroup(c, level + 1))));
    // 5️⃣ Finally, render nothing if truly empty:
    const hasAnything = filterElements.length > 0 || filterGroups.length > 0;
    if (!hasAnything)
        return null;
    return (React.createElement(Box, null, renderGroup(rootGroup)));
};
//# sourceMappingURL=VisualSearchObject.js.map