/**
 * SummaryView - Read-only summary display
 *
 * Renders form data in a read-only format with optional controls.
 * Supports icons_behaviour configuration for role-based icon visibility.
 */
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useMemo, useCallback, useRef, useEffect } from 'react';
import { useFormViewContext } from '../context.js';
import { useShouldRenderField, useShouldRenderGroup, useShouldRenderSection } from '../use_form_view.js';
import { cn } from '../../../utils/cn.js';
import { get_field_value, is_field_empty } from '../../shared/field_utils/index.js';
import { format_date_value, get_field_attachments, get_field_private_attachments } from '../../shared/summary_utils/index.js';
import { UnifiedFieldControls, use_field_control_props } from '../../shared/unified_field_controls/index.js';
import { use_field_action_slot } from '../../shared/use_field_action_slot.js';
import { SummaryFiles } from '../../shared/summary_files/index.js';
import { SummaryDataTable } from './summary_data_table.js';
import { HiddenBadge, ProtectedBadge, ClarificationLabelBadge, FileErrorLabelBadge } from '../../status_badges.js';
import { CollabFormFieldReferenceTag } from '../../hazo_collab_form_base.js';
import { optional_import } from '../../../utils/optional_import.js';
import { IoCheckmarkCircle, IoCloseCircle, IoAlertCircle } from 'react-icons/io5';
import { get_row_color_for_data_ok } from '../../shared/row_color_utils.js';
import { format_currency, format_percentage } from '../../../utils/financial_format.js';
import { format_masked_value } from '../../../utils/mask_format.js';
import { HazoCollabFormSummaryRow } from '../../hazo_collab_form_summary_row.js';
import { ClarificationSection, ClarificationDialog } from '../../clarification/index.js';
import { use_clarifications } from '../../clarification/use_clarifications.js';
import { FieldAccordion } from '../../shared/field_accordion.js';
/**
 * Local context for file preview callback — avoids threading props through every component
 */
const FilePreviewContext = React.createContext(undefined);
function useFilePreview() {
    return React.useContext(FilePreviewContext);
}
/**
 * PDF Preview Dialog - wraps hazo_pdf PdfViewer in a full-screen Radix Dialog.
 */
function PdfPreviewDialog({ PdfViewerComponent, open, on_close, url, file_name, }) {
    const [DialogPrimitive, set_dialog_primitive] = React.useState(null);
    React.useEffect(() => {
        import('@radix-ui/react-dialog').then((mod) => {
            set_dialog_primitive(mod);
        }).catch(() => { });
    }, []);
    if (!DialogPrimitive)
        return null;
    const fullScreenStyles = {
        position: 'fixed',
        top: '16px',
        left: '16px',
        right: '16px',
        bottom: '16px',
        width: 'calc(100vw - 32px)',
        height: 'calc(100vh - 32px)',
        maxWidth: 'none',
        maxHeight: 'none',
        transform: 'none',
        display: 'flex',
        flexDirection: 'column',
        zIndex: 50,
        backgroundColor: 'hsl(var(--background, 0 0% 100%))',
        borderRadius: '8px',
        overflow: 'hidden',
    };
    return (_jsx(DialogPrimitive.Root, { open: open, onOpenChange: (o) => { if (!o)
            on_close(); }, children: _jsxs(DialogPrimitive.Portal, { children: [_jsx(DialogPrimitive.Overlay, { style: { position: 'fixed', inset: 0, zIndex: 50, backgroundColor: 'rgba(0,0,0,0.5)' } }), _jsxs(DialogPrimitive.Content, { style: fullScreenStyles, "aria-describedby": undefined, children: [_jsx(DialogPrimitive.Title, { className: "sr-only", children: file_name }), _jsx("div", { style: { width: '100%', height: '100%' }, children: _jsx(PdfViewerComponent, { url: url, display_filename: file_name, fit_to_width: true, toolbar_enabled: true, on_close: on_close, className: "h-full w-full" }) })] })] }) }));
}
/**
 * SummarySection - Renders a single section
 */
const SummarySection = React.memo(function SummarySection({ section, section_index, }) {
    const { settings, render_icon, form_data, render_files, file_manager } = useFormViewContext();
    const { error_file_ids } = use_clarifications(form_data);
    const on_file_preview = useFilePreview();
    const should_render_sec = useShouldRenderSection();
    // Skip empty sections for responders/non-visibility roles
    if (!should_render_sec(section))
        return null;
    // Get section-level files (use section_name or index as key)
    const section_key = section.section_name?.replace(/\s+/g, '_') || `section_${section_index}`;
    const has_public_files_mode = (section.accept_public_files && section.accept_public_files !== 'none') || section.accept_files_public === true;
    const has_private_files_mode = (section.accept_private_files && section.accept_private_files !== 'none') || section.accept_files_private === true;
    const section_files = has_public_files_mode ? get_field_attachments(form_data, section_key) : [];
    const section_private_files = has_private_files_mode ? get_field_private_attachments(form_data, section_key) : [];
    const has_section_files = section_files.length > 0 || section_private_files.length > 0;
    return (_jsxs("div", { className: "cls_summary_section border rounded-lg bg-card shadow-sm overflow-hidden", children: [_jsxs("div", { className: "flex items-center gap-3 p-4 border-b bg-muted/30", children: [section.icon && render_icon && (_jsx("div", { className: "flex items-center justify-center w-10 h-10 rounded-full bg-orange-100 text-orange-600", children: render_icon(section.icon) })), _jsx("h3", { className: "font-semibold text-lg text-foreground", children: section.section_name || `Section ${section_index + 1}` })] }), _jsxs("div", { className: "p-4 space-y-2", children: [section.groups && section.groups.length > 0 ? (section.groups.map((group, idx) => (_jsx(SummaryGroup, { field: group }, group.id)))) : (_jsx("p", { className: "text-muted-foreground text-sm italic", children: settings.empty_section_text })), (has_public_files_mode || has_private_files_mode) && has_section_files && (render_files ? (render_files(section_files, section_key)) : (_jsx(SummaryFiles, { files: section_files, private_files: section_private_files, field_id: section_key, class_name: "mt-4 pt-4 border-t", get_download_url: file_manager?.callbacks.get_download_url, show_file_status: file_manager?.show_file_status, error_file_ids: error_file_ids, passed_file_ids: file_manager?.passed_file_ids, on_file_click: on_file_preview })))] })] }));
});
/**
 * SummaryGroup - Renders a group of fields
 */
const SummaryGroup = React.memo(function SummaryGroup({ field }) {
    const { field_metadata, icons_behaviour, settings, callbacks, chat_config, current_user, form_data, render_files, file_manager, enable_clarifications, clarification_display, clarification_callbacks } = useFormViewContext();
    const should_render = useShouldRenderField();
    const should_render_grp = useShouldRenderGroup();
    const { items: all_clarification_items, get_pending_count, get_field_clarifications, error_file_ids } = use_clarifications(form_data);
    const on_file_preview = useFilePreview();
    const [clarification_dialog_field, set_clarification_dialog_field] = React.useState(null);
    // Track which file_id triggered the issue dialog (null = opened from field label badge)
    const [issues_dialog_file_id, set_issues_dialog_file_id] = React.useState(null);
    const show_badges = clarification_display !== 'section_only';
    if (!should_render(field)) {
        return null;
    }
    // Skip empty groups for responders/non-visibility roles
    if (field.field_type === 'group' && !should_render_grp(field)) {
        return null;
    }
    const is_group = field.field_type === 'group';
    // Resolve category overrides for group controls
    const group_edit_override = field.show_edit_icons ?? field.show_icons;
    const group_control_override = field.show_control_icons ?? field.show_icons;
    const metadata = field_metadata[field.id];
    // Build control props using shared hook
    const { role_controls, fallback_visibility, fallback_enabled, control_metadata, control_callbacks, control_config, } = use_field_control_props({
        has_controls: true,
        show_edit_icons: group_edit_override,
        show_control_icons: group_control_override,
        field_id: field.id,
        field_label: field.label || field.id,
        entity_type: 'group',
        icons_behaviour,
        active_role: settings.active_role,
        metadata,
        settings,
        chat_config,
        current_user,
        callbacks,
        validation_rules: field.validation_rules,
    });
    // Get data_ok row color for group
    const group_row_color = (!fallback_visibility.data_ok)
        ? undefined
        : (get_row_color_for_data_ok(metadata?.data_ok, settings) || undefined);
    // Get group-level files
    const group_files = get_field_attachments(form_data, field.id);
    const group_private_files = get_field_private_attachments(form_data, field.id);
    const has_group_files = group_files.length > 0 || group_private_files.length > 0;
    // Count group-level file errors
    const group_file_error_count = useMemo(() => {
        if (!error_file_ids || error_file_ids.size === 0)
            return 0;
        let count = 0;
        for (const f of group_files) {
            if (error_file_ids.has(f.file_id))
                count++;
        }
        for (const f of group_private_files) {
            if (error_file_ids.has(f.file_id))
                count++;
        }
        return count;
    }, [error_file_ids, group_files, group_private_files]);
    // Check if group is locked or hidden
    const is_locked = metadata?.locked === true;
    const is_hidden = metadata?.visibility === 'hidden';
    if (is_group && field.fields) {
        return (_jsxs("div", { className: cn('cls_summary_group space-y-2', group_row_color && 'px-3 -mx-3 rounded-sm', group_row_color), children: [field.label && (_jsxs("div", { className: "flex items-center justify-between gap-2", children: [_jsxs("div", { className: "flex items-center gap-2", children: [enable_clarifications && show_badges && get_pending_count(field.id) > 0 ? (_jsx(ClarificationLabelBadge, { count: get_pending_count(field.id) })) : (show_badges && metadata?.has_clarification && (_jsx(ClarificationLabelBadge, { indicator_only: true }))), _jsx("h4", { className: "font-medium text-sm text-muted-foreground uppercase tracking-wide", children: field.label }), group_file_error_count > 0 && (_jsx(FileErrorLabelBadge, { count: group_file_error_count, on_click: () => set_issues_dialog_file_id('__all_group__') })), is_locked && _jsx(ProtectedBadge, {}), is_hidden && _jsx(HiddenBadge, {})] }), role_controls && (_jsx(UnifiedFieldControls, { field_id: field.id, icons_behaviour: icons_behaviour, active_role: settings.active_role, metadata: control_metadata, callbacks: control_callbacks, config: control_config, fallback_visibility: fallback_visibility, fallback_enabled: fallback_enabled, clarification_count: enable_clarifications && show_badges ? get_pending_count(field.id) : undefined, on_clarification_click: enable_clarifications && show_badges ? () => set_clarification_dialog_field(field.id) : undefined }))] })), !field.label && (is_locked || is_hidden) && (_jsxs("div", { className: "flex items-center gap-2 mb-2", children: [is_locked && _jsx(ProtectedBadge, {}), is_hidden && _jsx(HiddenBadge, {})] })), _jsx("div", { className: "pl-2 border-l-2 border-muted space-y-2", children: field.fields.map((child) => (_jsx(SummaryField, { field: child, parent_metadata: metadata }, child.id))) }), has_group_files && (render_files ? (render_files(group_files, field.id)) : (_jsx(SummaryFiles, { files: group_files, private_files: group_private_files, field_id: field.id, class_name: "mt-2", get_download_url: file_manager?.callbacks.get_download_url, show_file_status: file_manager?.show_file_status, error_file_ids: error_file_ids, passed_file_ids: file_manager?.passed_file_ids, on_file_issue_click: enable_clarifications ? (file_id) => set_issues_dialog_file_id(file_id) : undefined, on_file_click: on_file_preview }))), enable_clarifications && clarification_dialog_field && (_jsx(ClarificationDialog, { open: clarification_dialog_field === field.id, on_open_change: (open) => { if (!open)
                        set_clarification_dialog_field(null); }, field_label: field.label || field.id, items: get_field_clarifications(field.id), callbacks: clarification_callbacks, get_download_url: file_manager?.callbacks.get_download_url })), enable_clarifications && issues_dialog_file_id && (() => {
                    // If opened from field-label badge, show all file errors for the group
                    const all_group_file_ids = [...group_files, ...group_private_files].map(f => f.file_id);
                    const target_file_ids = issues_dialog_file_id === '__all_group__'
                        ? new Set(all_group_file_ids.filter(fid => error_file_ids.has(fid)))
                        : new Set([issues_dialog_file_id]);
                    const file_clarifications = all_clarification_items.filter(item => (item.status === 'pending' || item.status === 'responded') &&
                        item.doc_references.some(ref => target_file_ids.has(ref.file_id)));
                    const file_attachment = [...group_files, ...group_private_files].find(f => f.file_id === issues_dialog_file_id);
                    const dialog_label = issues_dialog_file_id === '__all_group__'
                        ? (field.label || field.id)
                        : (file_attachment?.file_name ?? 'File');
                    return (_jsx(ClarificationDialog, { open: true, on_open_change: (open) => { if (!open)
                            set_issues_dialog_file_id(null); }, field_label: dialog_label, items: file_clarifications, callbacks: clarification_callbacks, get_download_url: file_manager?.callbacks.get_download_url }));
                })()] }));
    }
    return _jsx(SummaryField, { field: field });
});
/**
 * SummaryField - Renders a single field
 */
const SummaryField = React.memo(function SummaryField({ field, parent_metadata }) {
    const { form_data, field_metadata, reference_data, settings, icons_behaviour, callbacks, chat_config, current_user, render_files, file_manager, styles_config, enable_clarifications, clarification_display, clarification_callbacks, on_reference_delete, mode } = useFormViewContext();
    const field_action_slot = use_field_action_slot(field.id);
    const should_render = useShouldRenderField();
    const { items: all_clarification_items, get_pending_count, get_field_clarifications, error_file_ids } = use_clarifications(form_data);
    const on_file_preview = useFilePreview();
    const [clarification_dialog_open, set_clarification_dialog_open] = React.useState(false);
    // Track which file_id triggered the issue dialog (null = not open)
    const [issues_dialog_file_id, set_issues_dialog_file_id] = React.useState(null);
    const show_badges = clarification_display !== 'section_only';
    if (!should_render(field)) {
        return null;
    }
    const value = get_field_value(field.id, form_data);
    const is_empty = is_field_empty(value);
    const metadata = field_metadata[field.id];
    // Check if this is a data table field
    const is_data_table = field.component_type === 'HazoCollabFormDataTable';
    // Check if this is a summary row
    const is_summary_row = field.component_type === 'HazoCollabFormSummaryRow';
    // Check if this is a static text field
    const is_static_text = field.component_type === 'HazoCollabFormStaticText';
    // Skip empty fields if configured (data tables with no rows are also empty)
    // Static text and summary rows always render (they don't depend on form_data value)
    if (is_empty && !settings.show_empty_fields && !is_static_text && !is_summary_row) {
        return null;
    }
    // Format value based on field type (skip for data tables and summary rows)
    let display_value = '';
    if (!is_data_table && !is_summary_row) {
        if (is_static_text) {
            display_value = field.static_content || field.label || '';
        }
        else if (is_empty) {
            display_value = settings.empty_field_text;
        }
        else if (field.component_type === 'HazoCollabFormCheckbox') {
            display_value = value === true || value === 'true' ? 'Yes' : 'No';
        }
        else if (field.component_type === 'HazoCollabFormDate') {
            display_value = format_date_value(value, settings.date_format);
        }
        else if (field.component_type === 'HazoCollabFormCombo' || field.component_type === 'HazoCollabFormRadio') {
            const option = field.input_options?.find(opt => opt.value === String(value));
            display_value = option?.label ?? String(value);
        }
        else if (field.component_type === 'HazoCollabFormCurrency') {
            const num = typeof value === 'number' ? value : parseFloat(String(value));
            display_value = !isNaN(num)
                ? format_currency(num, field.currency_symbol || '$', field.decimal_places ?? 2)
                : String(value);
        }
        else if (field.component_type === 'HazoCollabFormPercentage') {
            const num = typeof value === 'number' ? value : parseFloat(String(value));
            display_value = !isNaN(num)
                ? format_percentage(num, field.decimal_places ?? 2)
                : String(value);
        }
        else if (field.component_type === 'HazoCollabFormComputed') {
            const num = typeof value === 'number' ? value : parseFloat(String(value));
            if (!isNaN(num)) {
                if (field.is_percentage) {
                    display_value = format_percentage(num, field.decimal_places ?? 2);
                }
                else {
                    display_value = format_currency(num, field.currency_symbol || '$', field.decimal_places ?? 2);
                }
            }
            else {
                display_value = String(value);
            }
        }
        else if (field.component_type === 'HazoCollabFormMasked') {
            display_value = field.display_format
                ? format_masked_value(String(value), field.display_format)
                : String(value);
        }
        else {
            display_value = String(value);
        }
    }
    // Resolve category overrides for field controls
    const field_edit_override = field.show_edit_icons ?? field.show_icons;
    const field_control_override = field.show_control_icons ?? field.show_icons;
    // Build control props using shared hook
    const { role_controls, fallback_visibility, fallback_enabled, control_metadata, control_callbacks, control_config, } = use_field_control_props({
        has_controls: true,
        show_edit_icons: field_edit_override,
        show_control_icons: field_control_override,
        field_id: field.id,
        field_label: field.label || field.id,
        entity_type: 'field',
        icons_behaviour,
        active_role: settings.active_role,
        metadata,
        settings,
        chat_config,
        current_user,
        callbacks,
        validation_rules: field.validation_rules,
    });
    // Get row color based on data_ok
    // When field doesn't have control icons visible, inherit from parent group
    const row_color = (!fallback_visibility.data_ok)
        ? get_row_color_for_data_ok(parent_metadata?.data_ok, settings)
        : get_row_color_for_data_ok(metadata?.data_ok, settings);
    // Get field-level files (only if field has accept_public_files/accept_private_files enabled)
    const has_field_public_files = (field.accept_public_files && field.accept_public_files !== 'none') || field.accept_files_public === true;
    const has_field_private_files = (field.accept_private_files && field.accept_private_files !== 'none') || field.accept_files_private === true;
    const field_files = has_field_public_files ? get_field_attachments(form_data, field.id) : [];
    const field_private_files = has_field_private_files ? get_field_private_attachments(form_data, field.id) : [];
    const has_field_files = field_files.length > 0 || field_private_files.length > 0;
    // Count field-level file errors
    const field_file_error_count = useMemo(() => {
        if (!error_file_ids || error_file_ids.size === 0)
            return 0;
        let count = 0;
        for (const f of field_files) {
            if (error_file_ids.has(f.file_id))
                count++;
        }
        for (const f of field_private_files) {
            if (error_file_ids.has(f.file_id))
                count++;
        }
        return count;
    }, [error_file_ids, field_files, field_private_files]);
    // Check if field is locked or hidden
    const is_locked = metadata?.locked === true;
    const is_hidden = metadata?.visibility === 'hidden';
    // Get reference value data for this field (form-level reference_data)
    const reference_info = reference_data?.[field.id];
    // Accordion wrapper helper
    const maybe_wrap_accordion = (content) => {
        if (!field.accordion)
            return content;
        return (_jsx(FieldAccordion, { label: field.label || field.id, default_open: field.accordion_default_open, children: content }));
    };
    // Data table rendering
    if (is_data_table && field.table_config) {
        const rows = (Array.isArray(value) ? value : []);
        return maybe_wrap_accordion(_jsxs("div", { className: "cls_summary_field_wrapper", "data-field-id": field.id, children: [_jsxs("div", { className: cn('cls_summary_field py-2 px-3 rounded', row_color), children: [_jsxs("div", { className: "flex justify-between items-start mb-2", children: [_jsxs("div", { className: "flex items-center gap-2", children: [enable_clarifications && show_badges && get_pending_count(field.id) > 0 ? (_jsx(ClarificationLabelBadge, { count: get_pending_count(field.id) })) : (show_badges && metadata?.has_clarification && (_jsx(ClarificationLabelBadge, { indicator_only: true }))), _jsx("span", { className: "text-sm font-medium text-foreground", children: field.label || field.id }), field_file_error_count > 0 && (_jsx(FileErrorLabelBadge, { count: field_file_error_count, on_click: () => set_issues_dialog_file_id('__all_field__') })), is_locked && _jsx(ProtectedBadge, {}), is_hidden && _jsx(HiddenBadge, {})] }), role_controls && (_jsx("div", { className: "flex-shrink-0", children: _jsx(UnifiedFieldControls, { field_id: field.id, icons_behaviour: icons_behaviour, active_role: settings.active_role, metadata: control_metadata, callbacks: control_callbacks, config: control_config, fallback_visibility: fallback_visibility, fallback_enabled: fallback_enabled, clarification_count: enable_clarifications && show_badges ? get_pending_count(field.id) : undefined, on_clarification_click: enable_clarifications && show_badges ? () => set_clarification_dialog_open(true) : undefined }) }))] }), _jsx(SummaryDataTable, { table_config: field.table_config, rows: rows, date_format: settings.date_format, empty_message: settings.empty_table_text }), reference_info && (_jsx("div", { className: "mt-1", children: _jsx(CollabFormFieldReferenceTag, { reference_data: reference_info, on_reference_delete: on_reference_delete ? (index) => {
                                    const entries = Array.isArray(reference_info) ? reference_info : [reference_info];
                                    on_reference_delete(field.id, index, entries[index]?.id);
                                } : undefined }) }))] }), has_field_files && (render_files ? (render_files(field_files, field.id)) : (_jsx(SummaryFiles, { files: field_files, private_files: field_private_files, field_id: field.id, class_name: "mt-2 ml-3", get_download_url: file_manager?.callbacks.get_download_url, show_file_status: file_manager?.show_file_status, error_file_ids: error_file_ids, passed_file_ids: file_manager?.passed_file_ids, on_file_issue_click: enable_clarifications ? (fid) => set_issues_dialog_file_id(fid) : undefined, on_file_click: on_file_preview }))), enable_clarifications && clarification_dialog_open && (_jsx(ClarificationDialog, { open: clarification_dialog_open, on_open_change: set_clarification_dialog_open, field_label: field.label || field.id, items: get_field_clarifications(field.id), callbacks: clarification_callbacks, get_download_url: file_manager?.callbacks.get_download_url })), enable_clarifications && issues_dialog_file_id && (() => {
                    const all_file_ids = [...field_files, ...field_private_files].map(f => f.file_id);
                    const target_file_ids = issues_dialog_file_id === '__all_field__'
                        ? new Set(all_file_ids.filter(fid => error_file_ids.has(fid)))
                        : new Set([issues_dialog_file_id]);
                    const file_clarifications = all_clarification_items.filter(item => (item.status === 'pending' || item.status === 'responded') &&
                        item.doc_references.some(ref => target_file_ids.has(ref.file_id)));
                    const file_attachment = [...field_files, ...field_private_files].find(f => f.file_id === issues_dialog_file_id);
                    const dialog_label = issues_dialog_file_id === '__all_field__'
                        ? (field.label || field.id)
                        : (file_attachment?.file_name ?? 'File');
                    return (_jsx(ClarificationDialog, { open: true, on_open_change: (open) => { if (!open)
                            set_issues_dialog_file_id(null); }, field_label: dialog_label, items: file_clarifications, callbacks: clarification_callbacks, get_download_url: file_manager?.callbacks.get_download_url }));
                })()] }));
    }
    // Summary row rendering - full-width styled row with label + value (no accordion)
    if (is_summary_row) {
        return (_jsx(HazoCollabFormSummaryRow, { field_id: field.id, label: field.label || field.id, value: value ?? '', currency_symbol: field.currency_symbol, decimal_places: field.decimal_places, style_variant: field.style_variant, styles_config: styles_config, item_code: field.item_code, badge: field.badge, summary_note: field.summary_note }));
    }
    return maybe_wrap_accordion(_jsxs("div", { className: "cls_summary_field_wrapper", "data-field-id": field.id, children: [_jsxs("div", { className: cn('cls_summary_field flex justify-between items-start py-2 px-3 rounded', row_color), children: [_jsxs("div", { className: "flex-1 min-w-0", children: [enable_clarifications && show_badges && get_pending_count(field.id) > 0 ? (_jsx(ClarificationLabelBadge, { count: get_pending_count(field.id), className: "mr-1" })) : (show_badges && metadata?.has_clarification && (_jsx(ClarificationLabelBadge, { indicator_only: true, className: "mr-1" }))), _jsx("span", { className: "text-sm font-medium text-foreground", children: field.label || field.id }), field_file_error_count > 0 && (_jsx(FileErrorLabelBadge, { count: field_file_error_count, on_click: () => set_issues_dialog_file_id('__all_field__'), className: "ml-1" })), is_locked && _jsx(ProtectedBadge, { className: "ml-2" }), is_hidden && _jsx(HiddenBadge, { className: "ml-2" }), _jsx("span", { className: cn('text-sm ml-2', is_empty ? 'text-muted-foreground italic' : 'text-foreground'), children: display_value }), reference_info && (_jsx("div", { className: "mt-1", children: _jsx(CollabFormFieldReferenceTag, { reference_data: reference_info, on_reference_delete: on_reference_delete ? (index) => {
                                        const entries = Array.isArray(reference_info) ? reference_info : [reference_info];
                                        on_reference_delete(field.id, index, entries[index]?.id);
                                    } : undefined }) }))] }), role_controls && (_jsx("div", { className: "flex-shrink-0", children: _jsx(UnifiedFieldControls, { field_id: field.id, icons_behaviour: icons_behaviour, active_role: settings.active_role, metadata: control_metadata, callbacks: control_callbacks, config: control_config, fallback_visibility: fallback_visibility, fallback_enabled: fallback_enabled, clarification_count: enable_clarifications && show_badges ? get_pending_count(field.id) : undefined, on_clarification_click: enable_clarifications && show_badges ? () => set_clarification_dialog_open(true) : undefined }) })), field_action_slot.row_end] }), field_action_slot.row_below && (_jsx("div", { className: "cls_field_action_below", children: field_action_slot.row_below })), has_field_files && (render_files ? (render_files(field_files, field.id)) : (_jsx(SummaryFiles, { files: field_files, private_files: field_private_files, field_id: field.id, class_name: "mt-2 ml-3", get_download_url: file_manager?.callbacks.get_download_url, show_file_status: file_manager?.show_file_status, error_file_ids: error_file_ids, passed_file_ids: file_manager?.passed_file_ids, on_file_issue_click: enable_clarifications ? (fid) => set_issues_dialog_file_id(fid) : undefined, on_file_click: on_file_preview }))), enable_clarifications && clarification_dialog_open && (_jsx(ClarificationDialog, { open: clarification_dialog_open, on_open_change: set_clarification_dialog_open, field_label: field.label || field.id, items: get_field_clarifications(field.id), callbacks: clarification_callbacks, get_download_url: file_manager?.callbacks.get_download_url })), enable_clarifications && issues_dialog_file_id && (() => {
                const all_file_ids = [...field_files, ...field_private_files].map(f => f.file_id);
                const target_file_ids = issues_dialog_file_id === '__all_field__'
                    ? new Set(all_file_ids.filter(fid => error_file_ids.has(fid)))
                    : new Set([issues_dialog_file_id]);
                const file_clarifications = all_clarification_items.filter(item => (item.status === 'pending' || item.status === 'responded') &&
                    item.doc_references.some(ref => target_file_ids.has(ref.file_id)));
                const file_attachment = [...field_files, ...field_private_files].find(f => f.file_id === issues_dialog_file_id);
                const dialog_label = issues_dialog_file_id === '__all_field__'
                    ? (field.label || field.id)
                    : (file_attachment?.file_name ?? 'File');
                return (_jsx(ClarificationDialog, { open: true, on_open_change: (open) => { if (!open)
                        set_issues_dialog_file_id(null); }, field_label: dialog_label, items: file_clarifications, callbacks: clarification_callbacks, get_download_url: file_manager?.callbacks.get_download_url }));
            })()] }));
});
/**
 * Collect all field IDs from sections (including groups and fields)
 */
function collect_all_field_ids(sections) {
    const field_ids = [];
    const collect_from_field = (field) => {
        field_ids.push(field.id);
        if (field.fields) {
            field.fields.forEach(collect_from_field);
        }
    };
    sections.forEach((section) => {
        section.groups?.forEach(collect_from_field);
    });
    return field_ids;
}
/**
 * SummaryView component
 */
export function SummaryView() {
    const { sections, field_metadata, callbacks, form_data, file_manager, enable_clarifications, clarification_display, clarification_callbacks } = useFormViewContext();
    const original_metadata_ref = useRef({});
    const clarification_section_ref = useRef(null);
    // PDF preview state
    const [preview_file, set_preview_file] = React.useState(null);
    const [PdfViewer, set_pdf_viewer] = React.useState(null);
    const [is_mounted, set_is_mounted] = React.useState(false);
    React.useEffect(() => { set_is_mounted(true); }, []);
    // Try to load PdfViewer from hazo_pdf (optional peer dependency)
    React.useEffect(() => {
        if (!is_mounted)
            return;
        optional_import('hazo_pdf').then((mod) => {
            set_pdf_viewer(() => mod.PdfViewer || mod.default?.PdfViewer);
        }).catch(() => {
            // hazo_pdf not installed — PDF preview disabled
        });
    }, [is_mounted]);
    // File preview handler — opens PDF in preview dialog, falls back to download URL
    const handle_file_preview = useCallback((attachment) => {
        if (PdfViewer && file_manager?.callbacks.get_download_url) {
            set_preview_file(attachment);
        }
        else if (file_manager?.callbacks.get_download_url) {
            // Fallback: open download URL in new tab
            const url = file_manager.callbacks.get_download_url(attachment.file_id, attachment.visibility);
            window.open(url, '_blank');
        }
    }, [PdfViewer, file_manager]);
    // Clarification state
    const { items: clarification_items, counts: clarification_counts, remove_doc_reference } = use_clarifications(form_data, callbacks.on_form_data_change);
    // Merge remove_doc_reference into clarification_callbacks
    const merged_clarification_callbacks = useMemo(() => {
        if (!clarification_callbacks && !remove_doc_reference)
            return undefined;
        return {
            ...clarification_callbacks,
            on_doc_delete: remove_doc_reference,
        };
    }, [clarification_callbacks, remove_doc_reference]);
    // Scroll to clarification section
    const handle_scroll_to_clarifications = useCallback(() => {
        clarification_section_ref.current?.scrollIntoView({ behavior: 'smooth' });
    }, []);
    // Scroll to a field by ID (used by clarification card field linking)
    const handle_field_click = useCallback((field_id) => {
        const el = document.querySelector(`[data-field-id="${field_id}"]`);
        if (el) {
            el.scrollIntoView({ behavior: 'smooth', block: 'center' });
            // Brief highlight
            el.classList.add('ring-2', 'ring-amber-400', 'ring-offset-2');
            setTimeout(() => el.classList.remove('ring-2', 'ring-amber-400', 'ring-offset-2'), 2000);
        }
    }, []);
    // Store original metadata on mount
    useEffect(() => {
        if (Object.keys(original_metadata_ref.current).length === 0) {
            original_metadata_ref.current = { ...field_metadata };
        }
    }, [field_metadata]);
    // Collect all field IDs
    const all_field_ids = useMemo(() => collect_all_field_ids(sections), [sections]);
    // Bulk operation handlers
    const handle_all_ok = useCallback(() => {
        all_field_ids.forEach((field_id) => {
            callbacks.on_data_ok_change?.(field_id, 'ok');
        });
    }, [all_field_ids, callbacks]);
    const handle_all_not_ok = useCallback(() => {
        all_field_ids.forEach((field_id) => {
            callbacks.on_data_ok_change?.(field_id, 'not_ok');
        });
    }, [all_field_ids, callbacks]);
    const handle_clear = useCallback(() => {
        all_field_ids.forEach((field_id) => {
            const original_data_ok = original_metadata_ref.current[field_id]?.data_ok;
            // If original was undefined, default to 'not_ok' (matches visual behavior)
            callbacks.on_data_ok_change?.(field_id, original_data_ok ?? 'not_ok');
        });
    }, [all_field_ids, callbacks]);
    return (_jsxs(FilePreviewContext.Provider, { value: handle_file_preview, children: [_jsxs("div", { className: "cls_form_view_summary space-y-4", children: [_jsx("div", { className: "border rounded-lg bg-card shadow-sm p-4", children: _jsxs("div", { className: "flex items-center justify-between gap-2", children: [enable_clarifications && clarification_display !== 'badge_only' && clarification_counts.pending > 0 && (_jsxs("button", { onClick: handle_scroll_to_clarifications, className: "flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-md bg-amber-100 text-amber-700 hover:bg-amber-200 dark:bg-amber-900/30 dark:text-amber-400 dark:hover:bg-amber-900/50 transition-colors", children: [_jsx(IoAlertCircle, { className: "w-4 h-4" }), "Clarifications (", clarification_counts.pending, " pending)"] })), !(enable_clarifications && clarification_display !== 'badge_only' && clarification_counts.pending > 0) && _jsx("div", {}), _jsxs("div", { className: "flex items-center gap-2", children: [_jsxs("button", { onClick: handle_all_ok, className: "flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-md bg-green-100 text-green-700 hover:bg-green-200 dark:bg-green-900/30 dark:text-green-400 dark:hover:bg-green-900/50 transition-colors", children: ["All", _jsx(IoCheckmarkCircle, { className: "w-4 h-4" })] }), _jsxs("button", { onClick: handle_all_not_ok, className: "flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-md bg-red-100 text-red-700 hover:bg-red-200 dark:bg-red-900/30 dark:text-red-400 dark:hover:bg-red-900/50 transition-colors", children: ["All", _jsx(IoCloseCircle, { className: "w-4 h-4" })] }), _jsx("button", { onClick: handle_clear, className: "px-3 py-1.5 text-sm font-medium rounded-md bg-gray-100 text-gray-700 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700 transition-colors", children: "Clear" })] })] }) }), sections.map((section, index) => (_jsx(SummarySection, { section: section, section_index: index }, `${section.section_name || 'section'}_${index}`))), enable_clarifications && clarification_display !== 'badge_only' && clarification_items.length > 0 && (_jsx("div", { ref: clarification_section_ref, children: _jsx(ClarificationSection, { items: clarification_items, counts: clarification_counts, callbacks: merged_clarification_callbacks, on_field_click: handle_field_click }) }))] }), PdfViewer && preview_file && file_manager?.callbacks.get_download_url && (_jsx(PdfPreviewDialog, { PdfViewerComponent: PdfViewer, open: !!preview_file, on_close: () => set_preview_file(null), url: file_manager.callbacks.get_download_url(preview_file.file_id, preview_file.visibility), file_name: preview_file.file_name }))] }));
}
//# sourceMappingURL=summary_view.js.map