/**
 * FormViewContext - Shared context for unified form view
 *
 * Provides consistent state management across all view modes.
 */
'use client';
import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useContext, useMemo } from 'react';
import { normalize_field_metadata_record } from '../shared/field_state/index.js';
import { collect_field_ids_from_sections } from '../shared/field_utils/index.js';
import { use_field_chat_status } from '../../utils/use_field_chat_status.js';
import { DEFAULT_DATE_FORMAT } from '../../utils/date_format.js';
import { can_role_access_private_files } from '../shared/role_utils/index.js';
import { DEFAULT_CLARIFICATION_TEMPLATES } from '../../config/clarification_templates.js';
import { FieldColumnsContext } from '../hazo_collab_form_base.js';
/**
 * Default view settings
 */
const DEFAULT_SETTINGS = {
    // Display
    date_format: DEFAULT_DATE_FORMAT,
    show_empty_fields: true,
    empty_field_text: 'Not provided',
    empty_section_text: 'No information entered in this section',
    empty_table_text: 'No entries',
    check_dependencies: true,
    // Controls
    controls_display: 'inline',
    enable_data_ok: false,
    data_ok_mode: 'checkbox',
    data_ok_editable: false,
    enable_notes: false,
    enable_chat: false,
    enable_visibility_toggle: false,
    visibility_editable: false,
    enable_lock: false,
    lock_editable: false,
    enable_delete: false,
    enable_skip: false,
    skip_editable: false,
    // Row highlighting
    data_ok_row_color: 'bg-green-50 dark:bg-green-900/20',
    data_not_ok_row_color: 'bg-red-50 dark:bg-red-900/20',
    pending_row_color: 'bg-orange-50 dark:bg-orange-900/20',
    // Required field highlighting
    highlight_empty_required: false,
    // Auto-actions
    on_data_ok_hidden: false,
    on_data_ok_protected: false,
    // Dropdown
    include_chat_in_dropdown: true,
    include_notes_in_dropdown: true,
    extract_active_chat: true,
    extract_active_notes: true,
    action_buttons_borderless: false,
};
/**
 * Form View Context
 */
const FormViewContext = createContext(undefined);
/**
 * Hook to consume FormViewContext
 * Throws if used outside of FormViewProvider
 */
export function useFormViewContext() {
    const context = useContext(FormViewContext);
    if (!context) {
        throw new Error('useFormViewContext must be used within a FormViewProvider');
    }
    return context;
}
/**
 * Hook to consume FormViewContext when the caller may render outside a
 * FormViewProvider (e.g. shared field components used by HazoCollabFormView).
 *
 * Returns `undefined` when no provider is mounted, instead of throwing.
 */
export function useFormViewContextOptional() {
    return useContext(FormViewContext);
}
/**
 * FormViewProvider - Provides context for form view components
 *
 * Handles:
 * - Normalizing field metadata
 * - Fetching chat status for all fields
 * - Building unified settings and callbacks
 */
export function FormViewProvider({ children, props }) {
    const { mode, sections, form_data, field_metadata: field_metadata_prop = {}, reference_data, icons_behaviour: icons_behaviour_prop, active_role, user_role, current_user, field_columns = 1, 
    // Display
    date_format = DEFAULT_DATE_FORMAT, show_empty_fields = true, empty_field_text = 'Not provided', empty_section_text = 'No information entered in this section', empty_table_text = 'No entries', check_dependencies = true, 
    // Controls
    controls_display = 'inline', enable_data_ok = false, data_ok_mode = 'checkbox', data_ok_editable = false, data_ok_hidden_states, enable_notes = false, notes_panel_style, notes_background_color, notes_save_mode, notes_mode, enable_chat = false, chat_group_id, chat_api_base_url, chat_timezone, chat_realtime_mode = 'polling', chat_polling_interval, chat_read_only, chat_hide_references, chat_hide_sidebar, chat_hide_preview, chat_display_mode, chat_container_element, chat_log_polling, enable_visibility_toggle = false, visibility_editable = false, enable_lock = false, lock_editable = false, enable_delete = false, enable_skip = false, skip_editable = false, 
    // Row highlighting
    data_ok_row_color = 'bg-green-50 dark:bg-green-900/20', data_not_ok_row_color = 'bg-red-50 dark:bg-red-900/20', pending_row_color = 'bg-orange-50 dark:bg-orange-900/20', 
    // Required field highlighting
    highlight_empty_required = false, 
    // Auto-actions
    on_data_ok_hidden = false, protect_on_dataok = true, on_data_ok_protected = false, // deprecated, fallback
    // Dropdown
    include_chat_in_dropdown = true, include_notes_in_dropdown = true, extract_active_chat = true, extract_active_notes = true, action_buttons_borderless = false, 
    // Callbacks
    on_field_change, on_form_data_change, on_metadata_change, on_data_ok_change, on_notes_change, on_visibility_change, on_lock_change, on_delete, on_skip_change, on_edit_section, on_edit_field, on_add_field, on_add_group_config, on_edit_field_config, on_delete_field, on_revalidate, 
    // File manager
    file_manager, 
    // Autofill
    autofill_api_endpoint, upload_manager, 
    // File callbacks
    on_field_files_change, on_field_private_files_change, 
    // Render slots
    render_icon, render_field_value, render_files, 
    // UI components
    dialog_components, combobox_components, 
    // Per-field action slots
    field_action_components, field_actions, 
    // Audit intent config (forwarded to view layer for emit_form_intent)
    field_audit, form_id, 
    // Field library
    enable_library, library_api_base_url, library_table_name, library_scope_id, 
    // Style & field type configuration
    styles_config, field_types_config, 
    // Reference delete
    on_reference_delete, 
    // Confirm-required (H.7)
    show_confirm_action = false, 
    // Section card chrome opt-out
    disable_section_card = false, hide_section_header = false, 
    // Clarifications
    enable_clarifications = false, clarification_display = 'both', clarification_callbacks, clarification_templates: clarification_templates_prop, 
    // Validation rule assignment (deprecated, use global_settings)
    global_validations, 
    // Global settings
    global_settings, } = props;
    // Normalize field metadata
    const field_metadata_key = JSON.stringify(field_metadata_prop);
    const normalized_field_metadata = useMemo(() => normalize_field_metadata_record(field_metadata_prop), 
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [field_metadata_key]);
    // Extract icons_behaviour: prefer prop, fallback to first section
    const icons_behaviour = useMemo(() => {
        if (icons_behaviour_prop)
            return icons_behaviour_prop;
        return sections[0]?.icons_behaviour;
    }, [icons_behaviour_prop, sections]);
    // Collect all field IDs for chat status
    const all_field_ids = useMemo(() => {
        return collect_field_ids_from_sections(sections);
    }, [sections]);
    // Build a flat lookup so consumers (e.g. BaseFieldLayout) can resolve a
    // row's FieldActionContext without re-walking the section tree per render.
    const field_lookup = useMemo(() => {
        const map = new Map();
        function walk(fields, section_id, group_id) {
            if (!fields)
                return;
            for (const f of fields) {
                map.set(f.id, { field: f, section_id, group_id });
                if (f.field_type === 'group' && f.fields) {
                    walk(f.fields, section_id, f.id);
                }
                else if (f.fields) {
                    // Defensive: nested fields under non-group (paired fields, etc.)
                    walk(f.fields, section_id, group_id);
                }
            }
        }
        for (const s of sections) {
            walk(s.groups, s.section_name, undefined);
        }
        return map;
    }, [sections]);
    // Fetch chat status for all fields
    const { chat_status: fetched_chat_status } = use_field_chat_status({
        field_ids: all_field_ids,
        chat_group_id,
        enabled: enable_chat && !!chat_group_id,
        realtime_mode: chat_realtime_mode,
        poll_interval: chat_polling_interval,
    });
    // Merge fetched chat status with normalized field metadata
    const field_metadata_with_chat = useMemo(() => {
        const merged = { ...normalized_field_metadata };
        for (const field_id of all_field_ids) {
            const fetched_status = fetched_chat_status[field_id];
            if (fetched_status) {
                merged[field_id] = {
                    ...merged[field_id],
                    chat_status: fetched_status,
                };
            }
        }
        return merged;
    }, [normalized_field_metadata, fetched_chat_status, all_field_ids]);
    // Build settings
    const settings = useMemo(() => ({
        date_format,
        show_empty_fields,
        empty_field_text,
        empty_section_text,
        empty_table_text,
        check_dependencies,
        controls_display,
        enable_data_ok,
        data_ok_mode,
        data_ok_editable,
        data_ok_hidden_states,
        enable_notes,
        notes_panel_style,
        notes_background_color,
        notes_save_mode,
        notes_mode,
        enable_chat,
        enable_visibility_toggle,
        visibility_editable,
        enable_lock,
        lock_editable,
        enable_delete,
        enable_skip,
        skip_editable,
        data_ok_row_color,
        data_not_ok_row_color,
        pending_row_color,
        highlight_empty_required,
        on_data_ok_hidden,
        on_data_ok_protected: protect_on_dataok ?? on_data_ok_protected, // Unify new and deprecated props
        include_chat_in_dropdown,
        include_notes_in_dropdown,
        extract_active_chat,
        extract_active_notes,
        action_buttons_borderless,
        active_role,
        user_role,
    }), [
        date_format,
        show_empty_fields,
        empty_field_text,
        empty_section_text,
        empty_table_text,
        check_dependencies,
        controls_display,
        enable_data_ok,
        data_ok_mode,
        data_ok_editable,
        data_ok_hidden_states,
        enable_notes,
        notes_panel_style,
        notes_background_color,
        notes_save_mode,
        notes_mode,
        enable_chat,
        enable_visibility_toggle,
        visibility_editable,
        enable_lock,
        lock_editable,
        enable_delete,
        enable_skip,
        skip_editable,
        data_ok_row_color,
        data_not_ok_row_color,
        pending_row_color,
        highlight_empty_required,
        on_data_ok_hidden,
        protect_on_dataok,
        on_data_ok_protected,
        include_chat_in_dropdown,
        include_notes_in_dropdown,
        extract_active_chat,
        extract_active_notes,
        action_buttons_borderless,
        active_role,
        user_role,
    ]);
    // Build callbacks
    const callbacks = useMemo(() => ({
        on_field_change,
        on_form_data_change,
        on_metadata_change,
        on_data_ok_change,
        on_notes_change,
        on_visibility_change,
        on_lock_change,
        on_delete,
        on_skip_change,
        on_edit_section,
        on_edit_field,
        on_add_field,
        on_add_group_config,
        on_edit_field_config,
        on_delete_field,
        on_revalidate,
        on_field_files_change,
        on_field_private_files_change,
    }), [
        on_field_change,
        on_form_data_change,
        on_metadata_change,
        on_data_ok_change,
        on_notes_change,
        on_visibility_change,
        on_lock_change,
        on_delete,
        on_skip_change,
        on_edit_section,
        on_edit_field,
        on_add_field,
        on_add_group_config,
        on_edit_field_config,
        on_delete_field,
        on_revalidate,
        on_field_files_change,
        on_field_private_files_change,
    ]);
    // Build chat config
    const chat_config = useMemo(() => {
        if (!chat_group_id)
            return undefined;
        return {
            group_id: chat_group_id,
            api_base_url: chat_api_base_url,
            timezone: chat_timezone,
            realtime_mode: chat_realtime_mode,
            polling_interval: chat_polling_interval,
            read_only: chat_read_only,
            hide_references: chat_hide_references,
            hide_sidebar: chat_hide_sidebar,
            hide_preview: chat_hide_preview,
            display_mode: chat_display_mode,
            container_element: chat_container_element,
            log_polling: chat_log_polling,
        };
    }, [
        chat_group_id,
        chat_api_base_url,
        chat_timezone,
        chat_realtime_mode,
        chat_polling_interval,
        chat_read_only,
        chat_hide_references,
        chat_hide_sidebar,
        chat_hide_preview,
        chat_display_mode,
        chat_container_element,
        chat_log_polling,
    ]);
    // Resolve role-based permissions
    const resolved_can_access_private_files = useMemo(() => {
        return can_role_access_private_files(icons_behaviour, active_role);
    }, [icons_behaviour, active_role]);
    // Merge default clarification templates with consumer overrides
    const clarification_templates = useMemo(() => ({
        ...DEFAULT_CLARIFICATION_TEMPLATES,
        ...clarification_templates_prop,
    }), [clarification_templates_prop]);
    // Build context value
    const form_data_key = JSON.stringify(form_data);
    const context_value = useMemo(() => ({
        mode,
        sections,
        form_data,
        field_metadata: field_metadata_with_chat,
        reference_data,
        icons_behaviour,
        chat_config,
        current_user,
        can_access_private_files: resolved_can_access_private_files,
        file_manager,
        autofill_api_endpoint,
        upload_manager,
        settings,
        callbacks,
        render_icon,
        render_field_value,
        render_files,
        dialog_components,
        combobox_components,
        field_action_components,
        field_actions,
        field_audit,
        form_id,
        field_lookup,
        enable_library,
        library_api_base_url,
        library_table_name,
        library_scope_id,
        styles_config,
        field_types_config,
        on_reference_delete,
        show_confirm_action,
        disable_section_card,
        hide_section_header,
        enable_clarifications,
        clarification_display,
        clarification_callbacks,
        clarification_templates,
        global_settings: {
            ...global_settings,
            // Merge deprecated global_validations into global_settings.file_validations
            file_validations: global_settings?.file_validations ?? global_validations,
        },
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }), [
        mode,
        sections,
        form_data_key, // Use key for mutation detection
        field_metadata_with_chat,
        icons_behaviour,
        chat_config,
        current_user,
        resolved_can_access_private_files,
        file_manager,
        autofill_api_endpoint,
        upload_manager,
        settings,
        callbacks,
        render_icon,
        render_field_value,
        render_files,
        dialog_components,
        combobox_components,
        field_action_components,
        field_actions,
        field_audit,
        form_id,
        field_lookup,
        enable_library,
        library_api_base_url,
        library_table_name,
        library_scope_id,
        styles_config,
        field_types_config,
        on_reference_delete,
        show_confirm_action,
        disable_section_card,
        hide_section_header,
        enable_clarifications,
        clarification_display,
        clarification_callbacks,
        clarification_templates,
        global_validations,
        global_settings,
    ]);
    // field_columns_value is stable — coerce to the union type
    const field_columns_value = useMemo(() => ({ field_columns: field_columns }), [field_columns]);
    return (_jsx(FieldColumnsContext.Provider, { value: field_columns_value, children: _jsx(FormViewContext.Provider, { value: context_value, children: children }) }));
}
export { FormViewContext };
//# sourceMappingURL=context.js.map