"use client";
import { jsx as _jsx } from "react/jsx-runtime";
import { useEditContext } from "../client/editContext";
import { useFieldModification } from "../client/fieldModificationStore";
import { useSlotContext } from "../views/editorSlotContext";
import { useEffect, useState, useCallback } from "react";
import { getLookupSources } from "../services/editService";
import { normalizeGuid, stripGuid } from "../utils";
import { Select } from "../../components";
export function DropLinkEditor({ field, readOnly, }) {
    const editContext = useEditContext();
    const slotContext = useSlotContext();
    const [lazyItems, setLazyItems] = useState([]);
    const [lazyLoading, setLazyLoading] = useState(true);
    const fieldItem = field.descriptor.item;
    const { modifiedField } = useFieldModification(field.id, fieldItem.id, fieldItem.language, fieldItem.version, slotContext?.fieldModificationStore);
    const onLazyLoad = useCallback(async () => {
        setLazyLoading(true);
        const response = await getLookupSources(field);
        setLazyItems(response.items);
        setLazyLoading(false);
    }, [field]);
    useEffect(() => {
        onLazyLoad();
    }, [
        field.descriptor.fieldId +
            field.descriptor.item.id +
            field.descriptor.item.language +
            field.descriptor.item.version,
    ]);
    if (!editContext)
        return;
    const selectedItemId = stripGuid(String(modifiedField?.value ?? field.value?.targetItemId ?? field.rawValue ?? ""));
    // Convert ItemIdAndName[] to SelectOption[] with normalized IDs for stable matching.
    const sourceOptions = lazyItems.map((item) => ({
        value: stripGuid(item.id),
        label: item.name,
    }));
    const hasSelectedOption = sourceOptions.some((option) => option.value === selectedItemId);
    const selectOptions = selectedItemId && !hasSelectedOption
        ? [
            {
                value: selectedItemId,
                label: field.value?.targetItemName ?? `[Unknown: ${selectedItemId}]`,
            },
            ...sourceOptions,
        ]
        : sourceOptions;
    return (_jsx(Select, { value: selectedItemId, onValueChange: (value) => {
            editContext?.operations.editField({
                field: field.descriptor,
                rawValue: normalizeGuid(value),
                originatingSlotId: slotContext?.slotId,
            });
        }, options: selectOptions, placeholder: "Select", disabled: readOnly, className: "md:w-14rem w-full rounded-sm", loading: lazyLoading, onLazyLoad: onLazyLoad, emptyMessage: "No options available", searchable: true }));
}
//# sourceMappingURL=DropLinkEditor.js.map