import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/**
 * Group renderer for HazoDataForm
 * Renders a group (ViewFieldConfig with fields) with optional sub-section header,
 * badge, item_code, style_variant, orientation, and column alignment
 */
import { useState, useCallback, useMemo } from 'react';
import { cn } from '../../utils/cn.js';
import { get_field_uploads } from '../../utils/data_form_uploads.js';
import { DataFormFieldRenderer } from './field_renderers/index.js';
import { DataFormLabel } from './shared/data_form_label.js';
import { DataFormBadge } from './shared/data_form_badge.js';
import { DataFormFileColumn } from './shared/data_form_file_column.js';
import { format_currency } from '../../utils/financial_format.js';
/**
 * Format a ReferenceValueData into a display annotation string
 */
function format_reference_annotation(ref) {
    // Array values are handled by TableReferenceAccordion, not inline text
    if (Array.isArray(ref.value))
        return undefined;
    let formatted;
    if (typeof ref.value === 'boolean') {
        formatted = ref.value ? 'Yes' : 'No';
    }
    else if (typeof ref.value === 'number') {
        formatted = format_currency(ref.value, '$', 2);
    }
    else {
        formatted = String(ref.value);
    }
    return ref.label ? `${ref.label}: ${formatted}` : `Ref: ${formatted}`;
}
/**
 * Collect and deduplicate doc_links and file_uploads from child fields
 */
function collect_row_doc_links(fields, file_uploads, form_data) {
    const seen_keys = new Set();
    const seen_file_ids = new Set();
    const doc_links = [];
    const uploads = [];
    for (const field of fields) {
        for (const link of field.doc_links ?? []) {
            const key = link.file_id || link.url;
            if (!seen_keys.has(key)) {
                seen_keys.add(key);
                doc_links.push(link);
            }
        }
        const field_file_uploads = file_uploads?.[field.id] ?? get_field_uploads(form_data ?? {}, field.id);
        for (const upload of field_file_uploads) {
            if (!seen_file_ids.has(upload.file_id)) {
                seen_file_ids.add(upload.file_id);
                uploads.push(upload);
            }
        }
    }
    return { doc_links, uploads };
}
export function GroupRenderer({ group, mode, form_data, config, on_field_change, on_doc_link_click, file_uploads, on_upload_click, upload_enabled, reference_data, on_reference_delete, collapsible = false, initial_collapsed = false, on_collapse_toggle, section_id, field_action_components, field_actions, }) {
    const fields = group.fields || [];
    const orientation = group.orientation || 'vertical';
    const is_horizontal = orientation === 'horizontal';
    const has_header = Boolean(group.label);
    const is_row_doc_display = group.doc_link_display === 'row';
    // Consolidated doc links for row-level display
    const row_doc_data = useMemo(() => {
        if (!is_row_doc_display)
            return null;
        return collect_row_doc_links(fields, file_uploads, form_data);
    }, [is_row_doc_display, fields, file_uploads, form_data]);
    // Collapse state — only meaningful when has_header && collapsible
    const is_collapsible = collapsible && has_header;
    const [is_collapsed, set_is_collapsed] = useState(initial_collapsed);
    const handle_toggle = useCallback(() => {
        const new_state = !is_collapsed;
        set_is_collapsed(new_state);
        on_collapse_toggle?.(group.id, new_state);
    }, [is_collapsed, group.id, on_collapse_toggle]);
    // Style for group header
    const variant_style = group.style_variant && config.style_resolver.has_style(group.style_variant)
        ? config.style_resolver.to_style(group.style_variant)
        : undefined;
    // Column headers for paired layouts
    const column_headers = group.column_headers;
    return (_jsxs("div", { className: cn('cls_data_form_group', 'mb-2'), children: [has_header && (_jsxs("div", { className: cn('cls_data_form_group_header', 'flex items-center gap-2 py-1.5 px-2 mb-1', is_collapsible && 'cursor-pointer select-none'), style: {
                    ...variant_style,
                    ...(!variant_style && !group.item_code ? { borderBottom: '1px solid #e5e7eb' } : {}),
                }, onClick: is_collapsible ? handle_toggle : undefined, role: is_collapsible ? 'button' : undefined, tabIndex: is_collapsible ? 0 : undefined, onKeyDown: is_collapsible ? (e) => {
                    if (e.key === 'Enter' || e.key === ' ') {
                        e.preventDefault();
                        handle_toggle();
                    }
                } : undefined, children: [is_collapsible && (_jsx("svg", { className: cn('w-3.5 h-3.5 shrink-0 transition-transform', is_collapsed && '-rotate-90'), fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: _jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M19 9l-7 7-7-7" }) })), group.item_code && (_jsx(DataFormLabel, { field: group, config: config })), !group.item_code && (_jsx("span", { className: "font-semibold text-sm text-gray-900", children: group.label })), (group.badge || group.formula_label) && (_jsx(DataFormBadge, { badge: group.badge, formula_label: group.formula_label, config: config }))] })), !(is_collapsible && is_collapsed) && (_jsxs(_Fragment, { children: [column_headers && column_headers.length > 0 && (_jsxs("div", { className: "cls_data_form_column_headers flex items-center gap-2 px-2 py-1 border-b border-gray-200 mb-1", children: [_jsx("div", { className: "flex-1" }), group.badge_column_width && (_jsx("div", { style: { width: group.badge_column_width }, className: "shrink-0" })), column_headers.map((header, idx) => (_jsx("div", { className: "shrink-0 text-xs font-medium text-gray-500 text-center", style: { width: header.width || group.value_column_width || '200px' }, children: header.label }, idx)))] })), _jsxs("div", { className: cn('cls_data_form_group_fields', is_horizontal ? 'flex flex-wrap gap-4' : 'flex flex-col'), children: [fields.map((field) => {
                                // Skip hidden fields
                                if (field.visibility === 'hidden')
                                    return null;
                                // Handle nested groups (recursive)
                                if (field.field_type === 'group') {
                                    const group_el = (_jsx(GroupRenderer, { group: field, mode: mode, form_data: form_data, config: config, on_field_change: on_field_change, on_doc_link_click: on_doc_link_click, file_uploads: file_uploads, on_upload_click: on_upload_click, upload_enabled: upload_enabled, reference_data: reference_data, collapsible: field.collapsible ?? collapsible, initial_collapsed: field.initial_collapsed ?? false, on_collapse_toggle: on_collapse_toggle, section_id: section_id, field_action_components: field_action_components, field_actions: field_actions }, field.id));
                                    // Wrap nested groups in flex:1 for even distribution in horizontal layout
                                    if (is_horizontal) {
                                        return (_jsx("div", { style: { flex: 1, minWidth: 0 }, children: group_el }, field.id));
                                    }
                                    return group_el;
                                }
                                const field_value = form_data[field.id];
                                const paired_value = field.paired_field ? form_data[field.paired_field.id] : undefined;
                                // Resolve accept_files: field-level overrides form-level default
                                const field_accepts_files = field.accept_files ?? config.default_accept_files;
                                const is_upload_enabled = field_accepts_files && upload_enabled;
                                // Get field uploads from explicit prop or from form_data convention
                                const resolved_uploads = file_uploads?.[field.id] ?? get_field_uploads(form_data, field.id);
                                // Resolve reference annotation — supports single or array
                                const raw_ref = reference_data?.[field.id];
                                const ref_entries_array = raw_ref ? (Array.isArray(raw_ref) ? raw_ref : [raw_ref]) : [];
                                const single_ref = !Array.isArray(raw_ref) ? raw_ref : undefined;
                                const ref_annotation = single_ref ? format_reference_annotation(single_ref) : undefined;
                                const ref_bg_color = single_ref?.background_color;
                                // Build reference_entries for multi-entry rendering
                                const ref_entries = ref_entries_array.length > 0
                                    ? ref_entries_array
                                        .map(r => {
                                        const ann = format_reference_annotation(r);
                                        return ann ? { value: ann, background_color: r.background_color, id: r.id } : null;
                                    })
                                        .filter((e) => e !== null)
                                    : undefined;
                                // For table fields, pass the full reference data object (accordion rendering)
                                const ref_value_data = field.field_type === 'table' && single_ref && Array.isArray(single_ref.value) ? single_ref : undefined;
                                // Reference delete callback bound to field
                                const field_ref_delete = on_reference_delete
                                    ? (index) => {
                                        const entry = ref_entries_array[index];
                                        on_reference_delete(field.id, index, entry?.id);
                                    }
                                    : undefined;
                                const field_el = (_jsx(DataFormFieldRenderer, { field: field, mode: mode, value: field_value, config: config, on_change: (val) => on_field_change(field.id, val), on_doc_link_click: !is_row_doc_display && on_doc_link_click && field.doc_links?.length
                                        ? () => on_doc_link_click({ field_id: field.id, doc_links: field.doc_links })
                                        : undefined, badge_column_width: group.badge_column_width, value_column_width: group.value_column_width, paired_value: paired_value, paired_on_change: field.paired_field
                                        ? (val) => on_field_change(field.paired_field.id, val)
                                        : undefined, field_uploads: is_row_doc_display ? undefined : resolved_uploads, on_upload_click: is_row_doc_display ? undefined : (on_upload_click ? () => on_upload_click(field.id) : undefined), upload_enabled: is_row_doc_display ? false : is_upload_enabled, reserve_file_column: is_row_doc_display ? false : upload_enabled, force_layout: is_horizontal ? 'stacked' : undefined, reference_annotation: ref_annotation, reference_background_color: ref_bg_color, reference_entries: ref_entries && ref_entries.length > 1 ? ref_entries : undefined, on_reference_delete: field_ref_delete, reference_value_data: ref_value_data, form_data: field.field_type === 'table' ? form_data : undefined, on_field_change: field.field_type === 'table' ? on_field_change : undefined, section_id: section_id, group_id: group.id, field_action_components: field_action_components, field_actions: field_actions }, field.id));
                                // Wrap fields in flex:1 for even distribution in horizontal layout
                                if (is_horizontal) {
                                    return (_jsx("div", { style: { flex: 1, minWidth: 0 }, children: field_el }, field.id));
                                }
                                return field_el;
                            }), is_row_doc_display && row_doc_data && (row_doc_data.doc_links.length > 0 || row_doc_data.uploads.length > 0) && (_jsx("div", { className: "flex items-center shrink-0 self-center", children: _jsx(DataFormFileColumn, { doc_links: row_doc_data.doc_links, field_uploads: row_doc_data.uploads, on_doc_link_click: on_doc_link_click && row_doc_data.doc_links.length > 0
                                        ? () => on_doc_link_click({ field_id: group.id, doc_links: row_doc_data.doc_links })
                                        : undefined, on_upload_click: on_upload_click ? () => on_upload_click(group.id) : undefined, upload_enabled: false, mode: mode, config: config }) }))] })] }))] }));
}
//# sourceMappingURL=group_renderer.js.map