/**
 * EditView - Full form editing view
 *
 * Integrates the internal form set component within the unified view architecture.
 * Loops through sections and renders a form set for each section.
 */
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import { useFormViewContext } from '../context.js';
import { useShouldRenderSection } from '../use_form_view.js';
import { HazoCollabFormSet } from '../../_internal_form_set.js';
import { cn } from '../../../utils/cn.js';
import { get_row_color_for_data_ok } from '../../shared/row_color_utils.js';
import { use_view_callbacks } from '../hooks/use_view_callbacks.js';
import { emit_form_intent } from '../../../audit/intent_emitter.js';
import { ClarificationSection } from '../../clarification/index.js';
import { use_clarifications } from '../../clarification/use_clarifications.js';
/**
 * EditSection - Renders a single section with the internal form set
 */
const EditSection = React.memo(function EditSection({ section, section_index, file_manager_override }) {
    const { form_data, field_metadata, reference_data, on_reference_delete, icons_behaviour, chat_config, current_user, can_access_private_files, file_manager, autofill_api_endpoint, settings, callbacks, render_icon, dialog_components, combobox_components, enable_library, library_api_base_url, library_table_name, library_scope_id, styles_config, field_types_config, clarification_callbacks, clarification_display, global_settings, show_confirm_action, disable_section_card, hide_section_header, upload_manager, field_audit, form_id, } = useFormViewContext();
    // All callback wrappers via shared hook
    const { handle_field_change, handle_form_data_change, handle_metadata_change, handle_data_ok_change, handle_notes_change, handle_visibility_change, handle_lock_change, handle_delete, handle_skip_change, handle_add_field_config, handle_add_group_config, handle_edit_field_config, handle_delete_field, handle_files_change, handle_private_files_change, handle_revalidate, } = use_view_callbacks({ callbacks, field_audit, form_id });
    // Emit autofill_applied intent when autofill completes for a group
    const handle_autofill_applied = useCallback((file_id) => {
        emit_form_intent('autofill_applied', { form_id, file_id }, field_audit).catch(() => { });
    }, [field_audit, form_id]);
    // Calculate row color based on data_ok state
    const get_row_color_for_field = useCallback((field_id) => {
        const metadata = field_metadata[field_id];
        return get_row_color_for_data_ok(metadata?.data_ok, settings);
    }, [field_metadata, settings.data_ok_row_color, settings.data_not_ok_row_color, settings.pending_row_color]);
    // Use icons_behaviour from section or from context
    const effective_icons_behaviour = section.icons_behaviour || icons_behaviour;
    // Cast ViewSection to Section (they have compatible shapes)
    const form_section = section;
    return (_jsxs("div", { className: cn('cls_edit_section overflow-hidden', !disable_section_card && 'border rounded-lg bg-card shadow-sm'), children: [!hide_section_header && (_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 dark:bg-orange-900/30", children: render_icon(section.icon) })), _jsx("h3", { className: "font-semibold text-lg text-foreground", children: section.section_name || `Section ${section_index + 1}` })] })), _jsx("div", { className: "p-4", children: _jsx(HazoCollabFormSet
                // Section data
                , { 
                    // Section data
                    section: form_section, initial_data: form_data, field_metadata: field_metadata, icons_behaviour: effective_icons_behaviour, active_role: settings.active_role, user_role: settings.user_role, current_user: current_user, can_access_private_files: can_access_private_files, 
                    // Chat configuration
                    chat_group_id: chat_config?.group_id, chat_read_only: chat_config?.read_only, chat_realtime_mode: chat_config?.realtime_mode, chat_hide_references: chat_config?.hide_references, chat_hide_sidebar: chat_config?.hide_sidebar, chat_hide_preview: chat_config?.hide_preview, chat_display_mode: chat_config?.display_mode, chat_container_element: chat_config?.container_element, chat_log_polling: chat_config?.log_polling, skip_internal_chat_check: true, 
                    // Control enable props
                    enable_data_ok: settings.enable_data_ok, enable_notes: settings.enable_notes, enable_chat: settings.enable_chat, enable_visibility_toggle: settings.enable_visibility_toggle, enable_lock: settings.enable_lock, enable_delete: settings.enable_delete, enable_skip: settings.enable_skip, 
                    // Control editable props
                    data_ok_editable: settings.data_ok_editable, data_ok_mode: settings.data_ok_mode, data_ok_hidden_states: settings.data_ok_hidden_states, 
                    // Notes configuration
                    notes_panel_style: settings.notes_panel_style, notes_background_color: settings.notes_background_color, notes_save_mode: settings.notes_save_mode, notes_mode: settings.notes_mode, 
                    // Dropdown consolidation
                    include_chat_in_dropdown: settings.include_chat_in_dropdown, include_notes_in_dropdown: settings.include_notes_in_dropdown, extract_active_chat: settings.extract_active_chat, extract_active_notes: settings.extract_active_notes, action_buttons_borderless: settings.action_buttons_borderless, 
                    // Callbacks
                    on_field_change: handle_field_change, on_form_data_change: handle_form_data_change, on_field_metadata_change: handle_metadata_change, on_data_ok_change: handle_data_ok_change, on_notes_change: handle_notes_change, on_visibility_change: handle_visibility_change, on_lock_change: handle_lock_change, on_delete: handle_delete, on_skip_change: handle_skip_change, on_add_field_config: handle_add_field_config, on_add_group_config: handle_add_group_config, on_edit_field_config: handle_edit_field_config, on_delete_field: handle_delete_field, 
                    // File manager (with error data merged if available)
                    file_manager: file_manager_override || file_manager, 
                    // Autofill
                    autofill_api_endpoint: autofill_api_endpoint, upload_manager: upload_manager, on_autofill_applied: handle_autofill_applied, 
                    // File callbacks
                    on_field_files_change: handle_files_change, on_field_private_files_change: handle_private_files_change, 
                    // Row color function
                    get_row_color: get_row_color_for_field, 
                    // Reference data
                    reference_data: reference_data, on_reference_delete: on_reference_delete, 
                    // UI components for add field dialog
                    dialog_components: dialog_components, combobox_components: combobox_components, 
                    // Field library integration
                    enable_library: enable_library, library_api_base_url: library_api_base_url, library_table_name: library_table_name, library_scope_id: library_scope_id, 
                    // Style & field type configuration
                    styles_config: styles_config, field_types_config: field_types_config, 
                    // Clarifications
                    clarification_callbacks: clarification_callbacks, clarification_display: clarification_display, 
                    // Re-validate
                    on_revalidate: handle_revalidate, 
                    // File accordion default open
                    default_file_accordion_open: global_settings?.default_file_accordion_open, 
                    // Confirm-required
                    show_confirm_action: show_confirm_action }) })] }));
});
/**
 * EditView component
 *
 * Renders all sections with full form editing capabilities.
 * Each section is rendered as an internal form set instance.
 */
export function EditView() {
    const { sections, form_data, field_metadata, enable_clarifications, clarification_display, clarification_callbacks, callbacks, file_manager } = useFormViewContext();
    const should_render_sec = useShouldRenderSection();
    // Filter sections for responders/non-visibility roles
    const visible_sections = useMemo(() => sections.filter(section => should_render_sec(section)), [sections, should_render_sec]);
    // Clarification state
    const { items: clarification_items, counts: clarification_counts, remove_doc_reference } = use_clarifications(form_data, callbacks.on_form_data_change);
    // Auto-detect edits to prefilled fields and update confirm_state
    const prefill_snapshots_ref = useRef(new Map());
    useEffect(() => {
        if (!callbacks.on_metadata_change)
            return;
        const snapshots = prefill_snapshots_ref.current;
        for (const [field_id, meta] of Object.entries(field_metadata)) {
            const state = meta?.confirm_state;
            if (state === 'prefilled') {
                if (!snapshots.has(field_id)) {
                    // First time seeing this prefilled field — take snapshot
                    snapshots.set(field_id, form_data[field_id]);
                }
                else if (form_data[field_id] !== snapshots.get(field_id)) {
                    // Value changed from snapshot — mark as edited
                    callbacks.on_metadata_change({ field_id, changes: { confirm_state: 'edited' } });
                }
            }
            else if (state === 'edited') {
                if (snapshots.has(field_id) && form_data[field_id] === snapshots.get(field_id)) {
                    // Value returned to snapshot — revert to prefilled
                    callbacks.on_metadata_change({ field_id, changes: { confirm_state: 'prefilled' } });
                }
            }
            else {
                // Field no longer tracked — clean up snapshot
                snapshots.delete(field_id);
            }
        }
    }, [form_data, field_metadata, callbacks.on_metadata_change]);
    // Auto-sync has_clarification flag to field metadata
    // Tracks which fields have active clarifications and emits metadata changes
    const prev_clarification_map_ref = useRef({});
    useEffect(() => {
        if (!enable_clarifications || !callbacks.on_metadata_change)
            return;
        // Build current map: field_id → has active (pending/responded) clarifications
        const current_map = {};
        for (const item of clarification_items) {
            if (item.status === 'pending' || item.status === 'responded') {
                current_map[item.target_field_id] = true;
            }
        }
        // Compare with previous state and emit changes
        const prev_map = prev_clarification_map_ref.current;
        const all_field_ids = new Set([...Object.keys(current_map), ...Object.keys(prev_map)]);
        for (const field_id of all_field_ids) {
            const has_now = !!current_map[field_id];
            const had_before = !!prev_map[field_id];
            const persisted = field_metadata[field_id]?.has_clarification;
            // Only emit if the live status differs from what's persisted
            if (has_now !== had_before && has_now !== persisted) {
                callbacks.on_metadata_change({
                    field_id,
                    changes: { has_clarification: has_now },
                });
            }
        }
        prev_clarification_map_ref.current = current_map;
    }, [clarification_items, enable_clarifications, callbacks.on_metadata_change, field_metadata]);
    // 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]);
    // Compute file error data from active clarifications
    const file_manager_with_errors = useMemo(() => {
        if (!file_manager || !clarification_items.length)
            return file_manager;
        const error_ids = new Set();
        const error_details = {};
        for (const item of clarification_items) {
            if (item.status === 'pending' || item.status === 'responded') {
                for (const ref of item.doc_references) {
                    error_ids.add(ref.file_id);
                    if (!error_details[ref.file_id])
                        error_details[ref.file_id] = [];
                    error_details[ref.file_id].push(item.issue_description);
                }
            }
        }
        if (error_ids.size === 0) {
            return { ...file_manager, clarification_items, clarification_callbacks: merged_clarification_callbacks };
        }
        return { ...file_manager, error_file_ids: error_ids, error_file_details: error_details, clarification_items, clarification_callbacks: merged_clarification_callbacks };
    }, [file_manager, clarification_items, merged_clarification_callbacks]);
    // Memoize section keys to ensure stable rendering
    // Always include index to handle duplicate section names
    const section_keys = useMemo(() => visible_sections.map((section, index) => `${index}_${section.section_name || 'section'}`), [visible_sections]);
    return (_jsxs("div", { className: cn('cls_form_view_edit space-y-6'), children: [visible_sections.map((section, index) => (_jsx(EditSection, { section: section, section_index: index, file_manager_override: file_manager_with_errors }, section_keys[index]))), enable_clarifications && clarification_display !== 'badge_only' && clarification_items.length > 0 && (_jsx(ClarificationSection, { items: clarification_items, counts: clarification_counts, callbacks: merged_clarification_callbacks })), visible_sections.length === 0 && (_jsx("div", { className: "p-8 text-center text-muted-foreground", children: _jsx("p", { children: "No sections to display." }) }))] }));
}
//# sourceMappingURL=edit_view.js.map