/**
 * Collaboration form group component
 * Groups multiple collab form fields together with a single data ok checkbox and chat icon at the group level
 */
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from 'react';
import { cn } from '../utils/cn.js';
import { use_collab_form_field, CollabFormFieldContainer, CollabFormFieldLabel, CollabFormFieldError, CollabFormFieldReferenceTag, CollabFormFileUploadSection, useFieldColumns, } from './hazo_collab_form_base.js';
import { UnifiedFieldControls } from './shared/unified_field_controls/index.js';
/**
 * List of collab form component display names to identify them
 */
const COLLAB_FORM_COMPONENT_NAMES = [
    'HazoCollabFormInputbox',
    'HazoCollabFormTextArea',
    'HazoCollabFormCheckbox',
    'HazoCollabFormCombo',
    'HazoCollabFormRadio',
];
/**
 * Check if a React element is a collab form component
 */
function is_collab_form_component(element) {
    if (!element || typeof element !== 'object') {
        return false;
    }
    const element_type = element.type;
    // Helper function to check displayName
    const check_display_name = (type_to_check) => {
        if (!type_to_check)
            return false;
        // Check displayName directly
        if (type_to_check.displayName) {
            if (COLLAB_FORM_COMPONENT_NAMES.includes(type_to_check.displayName)) {
                return true;
            }
            // Also check if it starts with "HazoCollabForm" as a fallback
            if (type_to_check.displayName.startsWith('HazoCollabForm')) {
                return true;
            }
        }
        // Check render.displayName for forwardRef components
        if (type_to_check.render && type_to_check.render.displayName) {
            if (COLLAB_FORM_COMPONENT_NAMES.includes(type_to_check.render.displayName)) {
                return true;
            }
            // Also check if it starts with "HazoCollabForm" as a fallback
            if (type_to_check.render.displayName.startsWith('HazoCollabForm')) {
                return true;
            }
        }
        return false;
    };
    // Check if it's a forwardRef component (object with render function)
    if (element_type && typeof element_type === 'object' && element_type !== null) {
        if (check_display_name(element_type)) {
            return true;
        }
    }
    // Check if it's a regular function component
    if (element_type && typeof element_type === 'function') {
        if (check_display_name(element_type)) {
            return true;
        }
    }
    // Fallback: Check props to see if it has collab form component props
    // This is a more lenient check - if it has the base props, assume it's a collab form component
    if (element.props) {
        const has_label = typeof element.props.label === 'string';
        // Check for any collab form component indicators
        const has_collab_value = element.props.value !== undefined ||
            element.props.checked !== undefined ||
            element.props.options !== undefined;
        const has_collab_callbacks = element.props.onChange !== undefined;
        // Also check for common collab form props
        const has_collab_props = element.props.field_id !== undefined ||
            element.props.field_data_id !== undefined ||
            element.props.field_name !== undefined ||
            element.props.disable_data_ok !== undefined ||
            element.props.disable_chat !== undefined;
        // If it has a label and any collab form indicators, treat it as a collab form component
        // Very lenient: if it has a label and onChange, it's likely a collab form component
        if (has_label && (has_collab_value || has_collab_callbacks || has_collab_props || element.props.onChange)) {
            return true;
        }
    }
    return false;
}
/**
 * Collaboration form group component
 * Groups multiple collab form fields together with group-level data ok checkbox and chat icon
 */
export const HazoCollabFormGroup = React.forwardRef((props, ref) => {
    // Create internal ref for component reference (for file_processor)
    const component_ref = React.useRef(null);
    const [internal_files, set_internal_files] = React.useState([]);
    // Read field_columns from context to determine inner grid layout
    const field_columns = useFieldColumns();
    // Use controlled files if provided, otherwise use internal state
    const current_files = props.files !== undefined ? props.files : internal_files;
    // Expose get_file_data method and forward ref to div element
    React.useImperativeHandle(ref, () => {
        return {
            ...component_ref.current,
            get_file_data: () => current_files,
        };
    }, [current_files]);
    const { label, tooltip, ihelp_context_key, error, field_id, field_data_id, field_name, children, on_chat_click, chat_status, is_chat_active, chat_background_color = 'bg-muted', is_data_ok_default, container_class_name, label_class_name, group_wrapper_class_name, error_class_name, multi_state_radio, data_ok_checked, on_data_ok_change, data_ok_mode, data_ok_value, on_data_ok_value_change, data_ok_default, data_ok_hidden_states, data_ok_editable, disable_data_ok, disable_border = false, accept_files_public, accept_files_private, hide_upload_dropzone, files_dir, default_file_accordion_open, max_size, min_files, max_files, file_accept, file_validator, file_manager, files: controlled_files, on_files_change, 
    // Chat visibility
    disable_chat, 
    // Notes props
    enable_notes, disable_notes, notes, on_notes_change, has_notes, is_notes_active, notes_panel_style, notes_background_color, notes_save_mode, current_user, id, 
    // HazoChat props
    hazo_chat_group_id, hazo_chat_reference_id, hazo_chat_reference_type, hazo_chat_api_base_url, hazo_chat_timezone, hazo_chat_title, hazo_chat_subtitle, hazo_chat_realtime_mode, hazo_chat_polling_interval, hazo_chat_messages_per_page, hazo_chat_class_name, hazo_chat_on_close, hazo_chat_is_open, hazo_chat_on_open_change, hazo_chat_show_sidebar_toggle, hazo_chat_show_delete_button, hazo_chat_bubble_radius, 
    // Reference tag props
    reference_value, reference_label, reference_tag_background_color, 
    // Visibility toggle props
    enable_visibility_toggle, disable_visibility_toggle, visibility = 'visible', on_visibility_change, user_role = 'responder', 
    // Delete field props
    enable_delete, disable_delete, on_delete, 
    // Edit/delete field structure props (control_edit_field/control_delete_field)
    on_edit_field, on_delete_field, 
    // Lock field props
    enable_lock, disable_lock, locked = false, on_lock_change, 
    // Skip/N/A field props
    enable_skip, disable_skip, skipped = false, on_skip_change, 
    // Edit actions display mode
    edit_actions_display, 
    // Consolidated dropdown props
    include_chat_in_dropdown, include_notes_in_dropdown, extract_active_chat, extract_active_notes, 
    // Action buttons styling
    action_buttons_borderless, 
    // Icons behaviour
    icons_behaviour, 
    // Active role for icons_behaviour
    active_role, 
    // Private file props
    private_files_permission, can_access_private_files, private_files, on_private_files_change, 
    // File validation state
    validating_file_ids, 
    // File error state
    error_file_ids, passed_file_ids, error_file_details, 
    // Clarification props
    clarification_count, has_clarification, on_clarification_click, 
    // Re-validate props
    on_revalidate, validation_rules, 
    // Autofill dropzone
    autofill_dropzone, } = props;
    const { field_id_final, handle_chat_icon_click, handle_chat_close, chat_is_open, is_chat_disabled } = use_collab_form_field({
        label,
        field_id,
        id,
        field_data_id,
        field_name,
        on_chat_click,
        hazo_chat_group_id,
        hazo_chat_on_open_change,
        hazo_chat_is_open,
        hazo_chat_on_close,
    });
    // Check visibility - responders cannot see hidden groups
    const is_hidden = visibility === 'hidden';
    if (is_hidden && user_role === 'responder') {
        return null;
    }
    // Chat is disabled when group is hidden (for authors viewing hidden groups) or explicitly disabled
    const is_chat_effectively_disabled = is_chat_disabled || is_hidden || disable_chat;
    // Handler to adapt data OK changes for both checkbox and multi-state modes
    const handle_data_ok_unified_change = React.useCallback((value) => {
        if (typeof value === 'boolean') {
            on_data_ok_change?.(value);
        }
        else {
            on_data_ok_value_change?.(value);
        }
    }, [on_data_ok_change, on_data_ok_value_change]);
    // Count files with validation errors for this group
    const file_error_count = React.useMemo(() => {
        if (!error_file_ids || error_file_ids.size === 0)
            return 0;
        let count = 0;
        for (const f of current_files) {
            if (error_file_ids.has(f.file_id))
                count++;
        }
        if (private_files) {
            for (const f of private_files) {
                if (error_file_ids.has(f.file_id))
                    count++;
            }
        }
        return count;
    }, [error_file_ids, current_files, private_files]);
    /**
     * Clone children and add disable props when group has corresponding controls enabled
     * This prevents both group and child from showing the same controls
     * Also pass locked state to children so they respect group-level lock
     *
     * The logic is: only disable a child's control if the GROUP is showing that control.
     * - disable_data_ok: true when group shows data_ok (i.e., !disable_data_ok)
     * - disable_chat: true when group has chat configured (hazo_chat_group_id is set)
     * - disable_notes: true when group shows notes (enable_notes && !disable_notes)
     */
    const group_has_data_ok = !disable_data_ok;
    const group_has_skip = enable_skip && !disable_skip;
    const group_has_notes = enable_notes && !disable_notes;
    const group_has_chat = !!hazo_chat_group_id; // Group shows chat when chat_group_id is configured
    const cloned_children = React.Children.map(children, (child) => {
        if (!React.isValidElement(child)) {
            return child;
        }
        // Check if this child is a collab form component
        if (is_collab_form_component(child)) {
            // Clone the element and add disable props only when group shows those controls
            // Merge with existing props to ensure we don't override important props
            // Also pass locked state from group to children
            return React.cloneElement(child, {
                ...child.props,
                // Only disable child controls when group is showing them at group level
                disable_data_ok: group_has_data_ok ? true : child.props.disable_data_ok,
                disable_skip: group_has_skip ? true : child.props.disable_skip,
                disable_chat: group_has_chat ? true : child.props.disable_chat,
                disable_notes: group_has_notes ? true : child.props.disable_notes,
                // Cascade locked state to children (child's own locked takes precedence)
                locked: child.props.locked !== undefined ? child.props.locked : locked,
                // Cascade skipped state to children (child's own skipped takes precedence)
                skipped: child.props.skipped !== undefined ? child.props.skipped : skipped,
            });
        }
        // If not a collab form component, return as-is
        return child;
    });
    return (_jsxs("div", { className: cn('cls_collab_group_root space-y-2', is_hidden && user_role === 'author' && 'opacity-50'), "data-group-id": field_data_id || field_id_final, ref: component_ref, children: [_jsxs("div", { className: "cls_collab_group_label_row flex items-center justify-between gap-2", children: [_jsx(CollabFormFieldLabel, { field_id_final: field_id_final, label: label, tooltip: tooltip, ihelp_context_key: ihelp_context_key, label_class_name: label_class_name, visibility: visibility, locked: locked, clarification_count: clarification_count, has_clarification: has_clarification, file_error_count: file_error_count, on_file_error_click: file_error_count > 0 ? on_clarification_click : undefined }), _jsx("div", { className: "cls_collab_group_actions flex items-center gap-1 flex-shrink-0", suppressHydrationWarning: true, children: _jsx(UnifiedFieldControls, { field_id: field_data_id || field_id_final, icons_behaviour: icons_behaviour, active_role: active_role, metadata: {
                                data_ok: data_ok_value ?? data_ok_checked,
                                skipped,
                                locked,
                                deleted: false,
                                visibility,
                                notes,
                                chat_status,
                                has_validation_rules: !!validation_rules?.length,
                            }, callbacks: {
                                on_data_ok_change: handle_data_ok_unified_change,
                                on_skip_change,
                                on_notes_change: on_notes_change,
                                on_chat_click: handle_chat_icon_click,
                                on_visibility_change,
                                on_lock_change,
                                on_delete: on_delete ? () => on_delete(field_data_id || field_id_final) : undefined,
                                on_edit_field,
                                on_delete_field,
                                on_revalidate,
                            }, config: {
                                data_ok_mode: data_ok_mode === 'multi_state' ? 'multi_state' : 'checkbox',
                                data_ok_hidden_states,
                                chat_group_id: hazo_chat_group_id,
                                current_user,
                                field_data_id: field_data_id || field_id_final,
                                label,
                                chat_api_base_url: hazo_chat_api_base_url,
                                chat_timezone: hazo_chat_timezone,
                                notes_panel_style,
                                notes_background_color,
                                notes_save_mode,
                            }, fallback_visibility: {
                                data_ok: !disable_data_ok,
                                skip: enable_skip && !disable_skip,
                                notes: enable_notes && !disable_notes,
                                chat: !disable_chat && !!hazo_chat_group_id,
                                visibility: enable_visibility_toggle && !disable_visibility_toggle,
                                lock: enable_lock && !disable_lock,
                                delete: enable_delete && !disable_delete,
                                edit_field: !!on_edit_field,
                                delete_field: !!on_delete_field,
                                revalidate: !!validation_rules?.length,
                            }, fallback_enabled: {
                                data_ok: data_ok_editable !== false,
                                skip: !disable_skip,
                                notes: !disable_notes,
                                chat: !is_chat_effectively_disabled,
                                visibility: !disable_visibility_toggle,
                                lock: !disable_lock,
                                delete: !disable_delete,
                                edit_field: !!on_edit_field,
                                delete_field: !!on_delete_field,
                                revalidate: !!on_revalidate,
                            }, clarification_count: clarification_count, on_clarification_click: on_clarification_click }) })] }), _jsxs(CollabFormFieldContainer, { chat_status: chat_status, is_chat_active: is_chat_active, chat_background_color: chat_background_color, is_data_ok_default: is_data_ok_default, container_class_name: cn(!disable_border && 'border border-input rounded-md p-4', container_class_name), hazo_chat_is_open: chat_is_open, hazo_chat_group_id: hazo_chat_group_id, hazo_chat_reference_id: hazo_chat_reference_id, hazo_chat_reference_type: hazo_chat_reference_type, hazo_chat_api_base_url: hazo_chat_api_base_url, hazo_chat_timezone: hazo_chat_timezone, hazo_chat_title: hazo_chat_title, hazo_chat_subtitle: hazo_chat_subtitle, hazo_chat_realtime_mode: hazo_chat_realtime_mode, hazo_chat_polling_interval: hazo_chat_polling_interval, hazo_chat_messages_per_page: hazo_chat_messages_per_page, hazo_chat_class_name: hazo_chat_class_name, hazo_chat_on_close: handle_chat_close, hazo_chat_show_sidebar_toggle: hazo_chat_show_sidebar_toggle, hazo_chat_show_delete_button: hazo_chat_show_delete_button, hazo_chat_bubble_radius: hazo_chat_bubble_radius, field_data_id: field_data_id, field_name: field_name, label: label, files: current_files, children: [_jsx("div", { className: cn('cls_collab_group_wrapper grid', field_columns === 3 ? 'grid-cols-3 gap-3'
                            : field_columns === 2 ? 'grid-cols-2 gap-3'
                                : 'grid-cols-[1fr_minmax(0,1fr)_400px] gap-y-2', skipped && 'bg-slate-100 opacity-60 rounded-md p-2', group_wrapper_class_name), children: cloned_children }), _jsx(CollabFormFieldReferenceTag, { reference_value: reference_value, reference_label: reference_label, reference_tag_background_color: reference_tag_background_color }), _jsx(CollabFormFieldError, { field_id_final: field_id_final, error: error, error_class_name: error_class_name }), _jsx(CollabFormFileUploadSection, { field_id_final: field_id_final, accept_files_public: accept_files_public && !locked, accept_files_private: accept_files_private && !locked, hide_upload_dropzone: hide_upload_dropzone, autofill_dropzone: autofill_dropzone, files_dir: files_dir, default_file_accordion_open: default_file_accordion_open, max_size: max_size, min_files: min_files, max_files: max_files, file_accept: file_accept, file_validator: file_validator, file_manager: file_manager, files: current_files, on_files_change: (new_files) => {
                            if (controlled_files === undefined) {
                                set_internal_files(new_files);
                            }
                            if (on_files_change) {
                                on_files_change(new_files);
                            }
                        }, private_files_permission: private_files_permission, can_access_private_files: can_access_private_files, private_files: private_files, on_private_files_change: on_private_files_change, validating_file_ids: validating_file_ids, error_file_ids: error_file_ids, passed_file_ids: passed_file_ids, error_file_details: error_file_details })] })] }));
});
HazoCollabFormGroup.displayName = 'HazoCollabFormGroup';
//# sourceMappingURL=hazo_collab_form_group.js.map