"use client";
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Section } from "./ui/Section";
import { useEditContext, useFieldsEditContext } from "./client/editContext";
import { FieldListFieldWithFallbacks } from "./FieldListFieldWithFallbacks";
import { SearchInput } from "../components/SearchInput";
import { Fragment, useEffect, useMemo, useState } from "react";
import uuid from "react-uuid";
import { Checkbox } from "../components/ui/checkbox";
import { Tooltip, TooltipContent, TooltipTrigger, } from "../components/ui/tooltip";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger, } from "../components/ui/accordion";
export function FieldList({ fields, compareToFields, sections, validators, filter, simplified, showStandardFieldsEnabled, readonly, }) {
    const editContext = useEditContext();
    const fieldsContext = useFieldsEditContext();
    const [searchFilter, setSearchFilter] = useState("");
    const [showStandardFields, setShowStandardFields] = useState(false);
    const uniqueId = uuid();
    const itemGroups = useMemo(() => fields.map((itemFields, index) => ({
        itemFields,
        value: `item-${index}-${itemFields.fields[0]?.descriptor.item.id || "unknown"}`,
    })), [fields]);
    const collapsibleItemGroups = useMemo(() => itemGroups.filter(({ itemFields }) => !!itemFields.headline), [itemGroups]);
    const collapsibleItemValuesKey = collapsibleItemGroups
        .map(({ value }) => value)
        .join("\u0000");
    const [openItemValue, setOpenItemValue] = useState(collapsibleItemGroups[0]?.value);
    const focusedField = fieldsContext?.focusedField;
    const focusedItemValue = useMemo(() => {
        if (!focusedField)
            return undefined;
        return collapsibleItemGroups.find(({ itemFields }) => itemFields.fields.some((field) => field.descriptor.fieldId === focusedField.fieldId &&
            field.descriptor.item.id === focusedField.item.id &&
            field.descriptor.item.language === focusedField.item.language &&
            field.descriptor.item.version === focusedField.item.version))?.value;
    }, [collapsibleItemGroups, focusedField]);
    // Keep a valid item open as the component's backing items change.
    useEffect(() => {
        const itemValues = collapsibleItemValuesKey
            ? collapsibleItemValuesKey.split("\u0000")
            : [];
        setOpenItemValue((currentValue) => currentValue && itemValues.includes(currentValue)
            ? currentValue
            : itemValues[0]);
    }, [collapsibleItemValuesKey]);
    // Canvas focus can move to a field in a currently collapsed backing item.
    // The complete descriptor is matched above because field IDs can be shared
    // by multiple items based on the same template.
    useEffect(() => {
        if (focusedItemValue)
            setOpenItemValue(focusedItemValue);
    }, [focusedItemValue]);
    if (!editContext)
        return;
    if (!fields)
        return;
    return (_jsxs("div", { className: "text-neutral-grey-100", children: [_jsxs("div", { className: "tour-field-list border-border-default sticky top-0 z-10 flex items-center gap-2 border-b bg-white p-2", children: [_jsx(SearchInput, { className: "flex-1", value: searchFilter, onChange: setSearchFilter, placeholder: "Filter fields..." }), showStandardFieldsEnabled && (_jsx(_Fragment, { children: _jsxs("div", { className: "flex items-center gap-1", children: [_jsx(Checkbox, { id: uniqueId, checked: showStandardFields, onCheckedChange: (checked) => setShowStandardFields(checked) }), " ", _jsx("label", { htmlFor: uniqueId, className: "text-neutral-grey-100 cursor-pointer text-xs", children: "Show standard fields" })] }) }))] }), _jsx(Accordion, { type: "single", collapsible: true, value: openItemValue, onValueChange: (value) => setOpenItemValue(value || undefined), children: itemGroups.map(({ itemFields, value }) => {
                    const fieldList = (_jsx(FieldListForSingleItem, { fields: itemFields.fields, validators: validators, filter: filter, searchFilter: searchFilter, showStandardFields: showStandardFields, simplified: simplified, sections: sections, compareToFields: compareToFields, readonly: readonly }));
                    if (!itemFields.headline) {
                        return _jsx(Fragment, { children: fieldList }, value);
                    }
                    return (_jsxs(AccordionItem, { value: value, className: "mt-2 border-t border-b-0", "data-testid": "field-list-item", children: [_jsx(AccordionTrigger, { className: "hover:bg-neutral-grey-5 px-3 py-2 hover:no-underline", children: _jsxs("span", { className: "min-w-0", children: [_jsxs("span", { className: "flex items-center gap-1 text-sm", children: [itemFields.icon && (_jsx("img", { src: itemFields.icon, alt: "", className: "h-4 w-4 object-contain" })), _jsx("span", { className: "truncate", children: itemFields.headline })] }), itemFields.path && (_jsx("span", { className: "text-neutral-grey-50 mt-1 block truncate text-xs", children: itemFields.fullPath ? (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("span", { className: "cursor-help", children: itemFields.path }) }), _jsx(TooltipContent, { children: itemFields.fullPath })] })) : (itemFields.path) }))] }) }), _jsx(AccordionContent, { children: fieldList })] }, value));
                }) })] }));
}
function FieldListForSingleItem({ fields, validators, filter, searchFilter, simplified, sections, showStandardFields, compareToFields, readonly, }) {
    let fieldsArray = Array.isArray(fields)
        ? fields
        : Object.values(fields);
    // Create section order mapping before any filtering to preserve original order
    const originalSectionOrder = new Map();
    fieldsArray.forEach((field) => {
        const section = field.section || "";
        const sectionSortOrder = field.sectionSortOrder || 0;
        // Use the minimum sectionSortOrder for each section to ensure consistent ordering
        if (!originalSectionOrder.has(section)) {
            originalSectionOrder.set(section, sectionSortOrder);
        }
        else {
            const existing = originalSectionOrder.get(section);
            originalSectionOrder.set(section, Math.min(existing, sectionSortOrder));
        }
    });
    if (filter)
        fieldsArray = fieldsArray.filter(filter);
    if (searchFilter) {
        const searchFilterLower = searchFilter.toLowerCase();
        fieldsArray = fieldsArray.filter((x) => x.name?.toLowerCase().includes(searchFilterLower) ||
            x.displayName?.toLowerCase().includes(searchFilterLower));
    }
    if (!showStandardFields) {
        fieldsArray = fieldsArray.filter((x) => !x.name?.startsWith("__"));
    }
    const sectionsGrouping = fieldsArray.reduce((acc, value) => {
        // Group initialization
        const section = value.section || "";
        if (!acc[section]) {
            acc[section] = [];
        }
        // Only add fields that have a valid descriptor item id
        if (value.descriptor.item.id) {
            acc[section].push(value);
        }
        return acc;
    }, {});
    const sectionList = Object.values(sectionsGrouping);
    // Sort sections using the original section order, not the first field after filtering
    sectionList.sort((a, b) => {
        const sectionA = a[0]?.section || "";
        const sectionB = b[0]?.section || "";
        const orderA = originalSectionOrder.get(sectionA) || 0;
        const orderB = originalSectionOrder.get(sectionB) || 0;
        return orderA - orderB;
    });
    function getSectionFields(fields, startTabIndex) {
        fields.sort((a, b) => a?.sortOrder - b?.sortOrder);
        return fields.map((field, index) => (_jsx(FieldListFieldWithFallbacks, { fieldDescriptor: field.descriptor, simplified: simplified, validators: validators.filter((x) => x.fieldId === field.id), compareToField: compareToFields?.find((x) => x.id === field.id), readonly: readonly, tabIndex: startTabIndex + index }, field.id)));
    }
    // Calculate tab indices across all sections
    let currentTabIndex = 0;
    return sectionList
        .filter((sectionFields) => {
        const section = sectionFields[0]?.section;
        return !sections || sections.includes(section);
    })
        .map((sectionFields) => {
        const section = sectionFields[0]?.section;
        const startIndex = currentTabIndex;
        currentTabIndex += sectionFields.length;
        return simplified ? (getSectionFields(sectionFields, startIndex)) : (_jsx(Section, { title: section, children: getSectionFields(sectionFields, startIndex) }, section));
    });
}
//# sourceMappingURL=FieldList.js.map