/**
 * HazoCollabFormView - Unified form view component
 *
 * A single component that supports multiple view modes:
 * - **edit**: Full form editing (wraps FormSet logic)
 * - **summary**: Read-only summary display (wraps Summary logic)
 * - **print**: Print/PDF optimized view
 * - **approval**: Workflow view focused on data_ok and reviewer actions
 *
 * All views share the same context, utilities, and field controls,
 * ensuring consistency across all modes.
 *
 * @example Basic usage (summary mode)
 * ```tsx
 * <HazoCollabFormView
 *   mode="summary"
 *   sections={formSections}
 *   form_data={formData}
 * />
 * ```
 *
 * @example Approval workflow
 * ```tsx
 * <HazoCollabFormView
 *   mode="approval"
 *   sections={formSections}
 *   form_data={formData}
 *   field_metadata={fieldMetadata}
 *   enable_data_ok={true}
 *   data_ok_mode="multi_state"
 *   data_ok_editable={true}
 *   on_data_ok_change={handleDataOkChange}
 *   approval_group_by_status={true}
 *   approval_show_progress={true}
 * />
 * ```
 *
 * @example Print mode
 * ```tsx
 * <HazoCollabFormView
 *   mode="print"
 *   sections={formSections}
 *   form_data={formData}
 *   print_header={<CompanyHeader />}
 *   print_footer={<LegalDisclaimer />}
 *   print_page_break_between_sections={true}
 * />
 * ```
 */
'use client';
import { jsx as _jsx } from "react/jsx-runtime";
import React, { forwardRef, useImperativeHandle, useRef, useState, useCallback, useMemo } from 'react';
import { cn } from '../../utils/cn.js';
import { FormViewProvider } from './context.js';
import { EditView } from './views/edit_view.js';
import { SummaryView } from './views/summary_view.js';
import { PrintView } from './views/print_view.js';
import { ApprovalView } from './views/approval_view.js';
import { get_clarifications } from '../clarification/use_clarifications.js';
import { useFieldAuditWiring } from '../field_audit/index.js';
import { build_builtin_actions } from '../../audit/built_in_actions.js';
import { emit_form_intent } from '../../audit/intent_emitter.js';
/**
 * HazoCollabFormView - Unified form view component
 *
 * Supports multiple view modes through a single, consistent interface.
 */
export const HazoCollabFormView = forwardRef(function HazoCollabFormView(props, ref) {
    const { mode: initial_mode, sections, form_data, field_metadata, class_name, 
    // Explicitly destructured for merged_actions / FormViewProvider
    field_audit, field_actions: consumer_field_actions, form_id, 
    // Print mode props
    print_header, print_footer, print_page_break_between_sections, 
    // Approval mode props
    approval_group_by_status, approval_show_progress, on_next_pending, 
    // Other props passed to context
    ...rest } = props;
    // Allow mode to be controlled externally or internally
    const [internal_mode, set_internal_mode] = useState(initial_mode);
    const current_mode = props.mode ?? internal_mode;
    // Refs for scrolling
    const section_refs = useRef([]);
    const field_refs = useRef(new Map());
    // Expose ref methods
    useImperativeHandle(ref, () => ({
        get_form_data: () => form_data,
        get_field_metadata: () => field_metadata ?? {},
        get_sections: () => sections,
        scroll_to_section: (section_index) => {
            const section_el = section_refs.current[section_index];
            if (section_el) {
                section_el.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        },
        scroll_to_field: (field_id) => {
            const field_el = field_refs.current.get(field_id);
            if (field_el) {
                field_el.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
        },
        get_mode: () => current_mode,
        set_mode: (new_mode) => {
            set_internal_mode(new_mode);
        },
        get_files_data: () => {
            const files_data = {};
            const prefix = '__files_';
            for (const key of Object.keys(form_data)) {
                if (key.startsWith(prefix)) {
                    const field_id = key.slice(prefix.length);
                    const files = form_data[key];
                    if (Array.isArray(files)) {
                        files_data[field_id] = files;
                    }
                }
            }
            return files_data;
        },
        get_private_files_data: () => {
            const files_data = {};
            const prefix = '__private_files_';
            for (const key of Object.keys(form_data)) {
                if (key.startsWith(prefix)) {
                    const field_id = key.slice(prefix.length);
                    const files = form_data[key];
                    if (Array.isArray(files)) {
                        files_data[field_id] = files;
                    }
                }
            }
            return files_data;
        },
        get_clarifications: () => get_clarifications(form_data),
        scroll_to_clarification: (id) => {
            const el = document.querySelector(`[data-clarification-id="${id}"]`);
            if (el) {
                el.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
        },
        confirm_all_prefilled: () => {
            const ids = [];
            // Collect IDs first (no callbacks yet)
            for (const [field_id, meta] of Object.entries(field_metadata ?? {})) {
                if (meta?.confirm_state === 'prefilled') {
                    ids.push(field_id);
                }
            }
            if (ids.length > 0) {
                // Emit BEFORE consumer callbacks
                emit_form_intent('field_confirmed', { form_id, field_ids: ids }, field_audit).catch(() => { });
                // Then fire consumer callbacks
                for (const field_id of ids) {
                    props.on_metadata_change?.({ field_id, changes: { confirm_state: 'confirmed' } });
                }
            }
            return ids;
        },
    }), [form_data, field_metadata, sections, current_mode, form_id, field_audit, props.on_metadata_change]);
    // Render the appropriate view based on mode
    const render_view = useCallback(() => {
        switch (current_mode) {
            case 'edit':
                return _jsx(EditView, {});
            case 'summary':
                return _jsx(SummaryView, {});
            case 'print':
                return (_jsx(PrintView, { header: print_header, footer: print_footer, page_break_between_sections: print_page_break_between_sections }));
            case 'approval':
                return (_jsx(ApprovalView, { group_by_status: approval_group_by_status, show_progress: approval_show_progress, enable_next_pending: !!on_next_pending, on_next_pending: on_next_pending }));
            default:
                return _jsx(SummaryView, {});
        }
    }, [
        current_mode,
        print_header,
        print_footer,
        print_page_break_between_sections,
        approval_group_by_status,
        approval_show_progress,
        on_next_pending,
    ]);
    // Dev-only deprecation warnings — fire once per mount
    const deprecation_warned = React.useRef(false);
    React.useEffect(() => {
        if (process.env.NODE_ENV === 'production')
            return;
        if (deprecation_warned.current)
            return;
        deprecation_warned.current = true;
        if (rest.field_action_components && consumer_field_actions && consumer_field_actions.length > 0) {
            console.warn('[hazo_collab_forms] field_action_components is deprecated and ignored when field_actions is set. Use field_actions only.');
        }
        if (rest.enable_field_audit && field_audit) {
            console.warn('[hazo_collab_forms] enable_field_audit is deprecated and ignored when field_audit is set. Migrate to the field_audit prop only.');
        }
        if (rest.enable_field_audit && !field_audit) {
            console.warn('[hazo_collab_forms] enable_field_audit is in-session-only and will be removed in a future major. Install hazo_audit and set field_audit to use the real audit backend.');
        }
    }, []); // eslint-disable-line react-hooks/exhaustive-deps
    // Build the audit wiring. When `enable_field_audit` is true, the helper
    // wraps children in a FieldAuditProvider + auto-watcher and merges the
    // audit icon/panel into `field_action_components`.
    const audit_wiring = useFieldAuditWiring({
        enable_field_audit: rest.enable_field_audit,
        field_action_components: rest.field_action_components,
        form_data,
        current_user: rest.current_user?.name ?? rest.current_user?.id,
        audit_debounce_ms: rest.audit_debounce_ms,
    });
    // Compute merged field_actions: built-in actions (e.g. audit icon via field_audit)
    // merged with consumer-supplied field_actions. Consumer entries with a matching
    // id shadow the corresponding built-in (dedup by id).
    const merged_actions = useMemo(() => {
        const builtins = build_builtin_actions({ field_audit });
        if (!consumer_field_actions || consumer_field_actions.length === 0)
            return builtins;
        const consumer_ids = new Set(consumer_field_actions.map(a => a.id));
        const remaining_builtins = builtins.filter(a => !consumer_ids.has(a.id));
        return [...remaining_builtins, ...consumer_field_actions];
    }, [field_audit, consumer_field_actions]);
    return audit_wiring.wrap(_jsx(FormViewProvider, { props: {
            mode: current_mode,
            sections,
            form_data,
            field_metadata,
            field_audit,
            form_id,
            ...rest,
            field_action_components: audit_wiring.merged_components,
            field_actions: merged_actions,
        }, children: _jsx("div", { className: cn('cls_hazo_collab_form_view', `cls_form_view_mode_${current_mode}`, class_name), children: render_view() }) }));
});
// ========================================
// Re-exports
// ========================================
// Context and hooks
export { FormViewProvider, FormViewContext, useFormViewContext } from './context.js';
export { useViewMode, useFormData, useFieldMetadata, useViewSettings, useViewCallbacks, useShouldRenderField, useFieldValue, useFieldMeta, useIsFieldEmpty, useFieldDataOk, useFieldNotes, useFieldVisibility, useFieldLock, useApprovalStats, } from './use_form_view.js';
// Views (for direct use if needed)
export { EditView } from './views/edit_view.js';
export { SummaryView } from './views/summary_view.js';
export { PrintView } from './views/print_view.js';
export { ApprovalView } from './views/approval_view.js';
export default HazoCollabFormView;
//# sourceMappingURL=index.js.map