import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/**
 * HazoDataForm - Data entry form for working papers
 *
 * Renders form sections/groups/fields using ViewSection/ViewFieldConfig types.
 * Uses form_data + on_field_change pattern (no react-hook-form).
 * Supports computed fields, financial formatting, masked inputs, and tables.
 *
 * When file_panel_display_mode='sidebar', wraps content in a resizable panel
 * with an embedded PdfViewer on the right side.
 */
import React, { useMemo, useCallback, useRef, useState, useEffect } from 'react';
import { cn } from '../../utils/cn.js';
import { create_style_resolver } from '../../utils/style_resolver.js';
import { use_computed_fields } from '../../utils/use_computed_fields.js';
import { DEFAULT_STYLES_CONFIG } from '../../types/style_variant.js';
import { DEFAULT_FIELD_TYPES_CONFIG } from '../../types/field_type_definition.js';
import { get_field_uploads } from '../../utils/data_form_uploads.js';
import { optional_import } from '../../utils/optional_import.js';
import { SectionRenderer } from './section_renderer.js';
import { PdfPanel } from './pdf_panel.js';
import { GhostFormPanel } from './ghost_form_panel.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';
/**
 * Collect computed field definitions from all sections
 */
function collect_computed_fields(sections) {
    const result = [];
    function walk_fields(fields) {
        if (!fields)
            return;
        for (const field of fields) {
            if (field.computed_formula) {
                result.push({
                    field_id: field.id,
                    formula: field.computed_formula,
                    dependencies: field.computed_dependencies,
                });
            }
            if (field.fields) {
                walk_fields(field.fields);
            }
        }
    }
    for (const section of sections) {
        if (section.groups) {
            walk_fields(section.groups);
        }
    }
    return result;
}
/**
 * Find a field label by ID, searching nested groups recursively
 */
function find_field_label(sections, field_id) {
    function search(fields) {
        if (!fields)
            return null;
        for (const field of fields) {
            if (field.id === field_id)
                return field.label || field_id;
            if (field.fields) {
                const found = search(field.fields);
                if (found)
                    return found;
            }
        }
        return null;
    }
    for (const section of sections) {
        const found = search(section.groups);
        if (found)
            return found;
    }
    return field_id;
}
/**
 * Convert UploadedFile[] to hazo_pdf FileItem[] format
 */
function uploads_to_file_items(uploads) {
    return uploads.map((u) => ({
        id: u.file_id,
        name: u.filename,
        url: u.url,
        type: u.mime_type === 'application/pdf' ? 'pdf'
            : u.mime_type.startsWith('image/') ? 'image'
                : 'other',
        mime_type: u.mime_type,
        file_path: u.url,
        size: u.size,
    }));
}
export function HazoDataForm({ sections, mode = 'edit', form_data, on_field_change, on_form_data_change, styles_config, field_types_config, default_currency_symbol = '$', default_decimal_places = 2, percentage_suffix = '%', on_doc_link_click, enable_file_upload = false, default_accept_files = false, on_upload_click, file_panel_display_mode, pdf_panel_default_size = 50, pdf_panel_min_size = 25, pdf_viewer_props, on_panel_open, on_panel_close, on_panel_pop_out, file_access_provider, on_panel_upload, on_panel_file_delete, file_uploads, show_section_headers = true, collapsible_sections = false, collapsed_sections, on_section_toggle, collapsible_groups = false, collapsed_groups, on_group_toggle, reference_data, on_reference_delete, on_submit, field_action_components, enable_field_audit, audit_debounce_ms, field_audit, field_actions: consumer_field_actions, form_id, class_name, }) {
    // 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 (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 (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 (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
    // Resolve audit wiring (no-op when enable_field_audit is false)
    const audit_wiring = useFieldAuditWiring({
        enable_field_audit,
        field_action_components,
        form_data,
        audit_debounce_ms,
    });
    const effective_field_action_components = audit_wiring.merged_components;
    // 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]);
    const form_data_ref = useRef(form_data);
    form_data_ref.current = form_data;
    const is_sidebar_mode = file_panel_display_mode === 'sidebar';
    // ─── Sidebar panel state ────────────────────────────────────
    const [panel_open, set_panel_open] = useState(false);
    const [active_field_id, set_active_field_id] = useState(null);
    const [active_field_label, set_active_field_label] = useState('');
    const [is_popped_out, set_is_popped_out] = useState(false);
    // Dynamic import of PdfViewerDialog for pop-out mode
    const [PdfDialogComponent, set_pdf_dialog] = useState(null);
    useEffect(() => {
        if (!is_sidebar_mode)
            return;
        let cancelled = false;
        optional_import('hazo_pdf')
            .then((mod) => {
            if (!cancelled && mod.PdfViewerDialog)
                set_pdf_dialog(() => mod.PdfViewerDialog);
        })
            .catch(() => { });
        return () => { cancelled = true; };
    }, [is_sidebar_mode]);
    // Derive file items for the active field
    const active_file_items = useMemo(() => {
        if (!active_field_id)
            return [];
        const uploads = file_uploads?.[active_field_id] ?? get_field_uploads(form_data, active_field_id);
        return uploads_to_file_items(uploads);
    }, [form_data, active_field_id, file_uploads]);
    // ─── Sidebar handlers ────────────────────────────────────────
    const handle_sidebar_upload_click = useCallback((field_id) => {
        const label = find_field_label(sections, field_id);
        set_active_field_id(field_id);
        set_active_field_label(label);
        set_panel_open(true);
        set_is_popped_out(false);
        on_panel_open?.(field_id);
    }, [sections, on_panel_open]);
    const handle_panel_close = useCallback(() => {
        set_panel_open(false);
        set_active_field_id(null);
        set_active_field_label('');
        set_is_popped_out(false);
        on_panel_close?.();
    }, [on_panel_close]);
    const handle_pop_out = useCallback(() => {
        if (on_panel_pop_out && active_field_id) {
            on_panel_pop_out(active_field_id, active_file_items);
        }
        else {
            // Use built-in PdfViewerDialog
            set_is_popped_out(true);
        }
    }, [on_panel_pop_out, active_field_id, active_file_items]);
    const handle_pop_out_close = useCallback(() => {
        set_is_popped_out(false);
    }, []);
    // Wrap upload/delete callbacks to inject active_field_id for PdfPanel
    const wrapped_panel_upload = useMemo(() => {
        if (!on_panel_upload)
            return undefined;
        return (file, converted_pdf) => {
            if (!active_field_id)
                return Promise.resolve(undefined);
            return on_panel_upload(active_field_id, file, converted_pdf);
        };
    }, [on_panel_upload, active_field_id]);
    const wrapped_panel_delete = useMemo(() => {
        if (!on_panel_file_delete)
            return undefined;
        return (file_id) => {
            if (!active_field_id)
                return;
            on_panel_file_delete(active_field_id, file_id);
        };
    }, [on_panel_file_delete, active_field_id]);
    // Resolve which upload click handler to use
    const resolved_upload_click = is_sidebar_mode ? handle_sidebar_upload_click : on_upload_click;
    // Create style resolver (memoized)
    const resolved_styles_config = styles_config || DEFAULT_STYLES_CONFIG;
    const resolved_field_types_config = field_types_config || DEFAULT_FIELD_TYPES_CONFIG;
    const style_resolver = useMemo(() => create_style_resolver(resolved_styles_config), [resolved_styles_config]);
    // Build config object
    const config = useMemo(() => ({
        styles_config: resolved_styles_config,
        field_types_config: resolved_field_types_config,
        default_currency_symbol,
        default_decimal_places,
        percentage_suffix,
        style_resolver,
        default_accept_files,
    }), [resolved_styles_config, resolved_field_types_config, default_currency_symbol, default_decimal_places, percentage_suffix, style_resolver, default_accept_files]);
    // Collect computed fields
    const computed_fields = useMemo(() => collect_computed_fields(sections), [sections]);
    // Handle field change
    const handle_field_change = useCallback((field_id, value) => {
        on_field_change?.(field_id, value);
        if (on_form_data_change) {
            const updated = { ...form_data_ref.current, [field_id]: value };
            on_form_data_change(updated);
        }
    }, [on_field_change, on_form_data_change]);
    // Handle computed field value changes
    const handle_computed_change = useCallback((field_id, value) => {
        if (value !== null) {
            handle_field_change(field_id, value);
        }
    }, [handle_field_change]);
    // Use computed fields hook
    use_computed_fields({
        form_data,
        computed_fields,
        on_computed_value_change: handle_computed_change,
        enabled: computed_fields.length > 0,
    });
    // Handle form submit
    const handle_submit = useCallback((e) => {
        e.preventDefault();
        emit_form_intent('form_submitted', { form_id, section_count: sections.length }, field_audit).catch(() => { });
        on_submit?.(form_data_ref.current);
    }, [on_submit, form_id, sections.length, field_audit]);
    const collapsed_set = useMemo(() => new Set(collapsed_sections || []), [collapsed_sections]);
    const collapsed_groups_set = useMemo(() => new Set(collapsed_groups || []), [collapsed_groups]);
    // ─── Form content (shared between both modes) ────────────────
    const form_content = (_jsx("div", { className: cn('cls_data_form', 'w-full', class_name), children: sections.map((section, index) => {
            const section_name = section.section_name || `section_${index}`;
            return (_jsx(SectionRenderer, { section: section, section_index: index, mode: mode, form_data: form_data, config: config, on_field_change: handle_field_change, on_doc_link_click: on_doc_link_click, file_uploads: file_uploads, on_upload_click: resolved_upload_click, upload_enabled: enable_file_upload, reference_data: reference_data, on_reference_delete: on_reference_delete, show_header: show_section_headers, collapsible: collapsible_sections, initial_collapsed: collapsed_set.has(section_name), on_collapse_toggle: on_section_toggle, collapsible_groups: collapsible_groups, collapsed_groups_set: collapsed_groups_set, on_group_toggle: on_group_toggle, field_action_components: effective_field_action_components, field_actions: merged_actions }, section_name));
        }) }));
    // ─── Sidebar layout ──────────────────────────────────────────
    const show_sidebar = is_sidebar_mode && panel_open && active_field_id;
    const render_content = () => {
        if (show_sidebar) {
            return (_jsxs("div", { className: "cls_data_form_sidebar_layout flex w-full", style: { position: 'relative' }, children: [_jsx("div", { style: {
                            width: `${100 - pdf_panel_default_size}%`,
                            borderRight: '1px solid #e5e7eb',
                            paddingBottom: 'calc(100vh - 80px)',
                        }, children: form_content }), _jsx("div", { className: "cls_data_form_ghost_column", style: {
                            position: 'absolute',
                            top: 0,
                            right: 0,
                            width: `${pdf_panel_default_size}%`,
                        }, children: _jsx(GhostFormPanel, { sections: sections, config: config, active_field_id: active_field_id, collapsed_set: collapsed_set, show_section_headers: show_section_headers, upload_enabled: enable_file_upload, collapsible_sections: collapsible_sections, collapsible_groups: collapsible_groups, collapsed_groups_set: collapsed_groups_set, children: _jsx(PdfPanel, { field_label: active_field_label ? `Files — ${active_field_label}` : 'Files', file_items: active_file_items, file_access_provider: file_access_provider, on_upload: wrapped_panel_upload, on_file_delete: wrapped_panel_delete, on_close: handle_panel_close, on_pop_out: handle_pop_out, viewer_props: pdf_viewer_props }) }) })] }));
        }
        return form_content;
    };
    // ─── Pop-out dialog (built-in PdfViewerDialog) ───────────────
    const render_pop_out_dialog = () => {
        if (!is_popped_out || !PdfDialogComponent || !active_field_id)
            return null;
        return (_jsx(PdfDialogComponent, { open: true, on_open_change: (open) => { if (!open)
                handle_pop_out_close(); }, files: active_file_items, file_manager: file_access_provider, on_upload: wrapped_panel_upload, on_file_delete: wrapped_panel_delete, toolbar_enabled: true, show_save_button: false, on_close: handle_pop_out_close, direct_upload: true, viewer_title: active_field_label ? `Files — ${active_field_label}` : 'Files', dialog_width: "90vw", dialog_height: "85vh", ...(pdf_viewer_props || {}) }));
    };
    // Wrap in form tag if on_submit is provided
    if (on_submit) {
        return audit_wiring.wrap(_jsxs("form", { onSubmit: handle_submit, className: "cls_data_form_wrapper", children: [render_content(), render_pop_out_dialog()] }));
    }
    return audit_wiring.wrap(_jsxs(_Fragment, { children: [render_content(), render_pop_out_dialog()] }));
}
//# sourceMappingURL=hazo_data_form.js.map