/**
 * Collaboration form document upload component
 * Provides a dedicated file dropzone field where documents ARE the primary value
 */
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useRef, useState, useCallback } from 'react';
import { cn } from '../utils/cn.js';
import { use_logger } from '../logger/context.js';
import { API_ENDPOINTS } from '../config/api_endpoints.js';
import { use_collab_form_field, CollabFormFieldContainer, CollabFormFieldLabel, CollabFormFieldError, CollabFormFieldReferenceTag, CollabFormAddEntryIcon, CollabFormDeleteEntryIcon, } from './hazo_collab_form_base.js';
import { UnifiedFieldControls } from './shared/unified_field_controls/index.js';
import { use_field_action_slot } from './shared/use_field_action_slot.js';
import { HiTrash, HiDocument, HiDocumentText, HiCheckCircle, HiLockClosed, HiLockOpen, HiCloudUpload } from 'react-icons/hi';
import { FaSpinner } from 'react-icons/fa';
/**
 * Get file icon based on file type
 */
function get_file_icon(file_type, file_name) {
    const extension = file_name.split('.').pop()?.toLowerCase() || '';
    const mime_type = file_type.toLowerCase();
    if (mime_type === 'application/pdf' || extension === 'pdf') {
        return _jsx(HiDocument, { className: "h-6 w-6 text-sky-500 flex-shrink-0" });
    }
    return _jsx(HiDocumentText, { className: "h-6 w-6 text-sky-500 flex-shrink-0" });
}
/**
 * Format file size for display
 */
function format_file_size(bytes) {
    if (bytes === 0)
        return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}
/**
 * Collaboration form document upload component
 * A dedicated file dropzone field where documents ARE the primary value
 */
export const HazoCollabFormDoc = React.forwardRef((props, ref) => {
    const logger = use_logger();
    // Create internal refs
    const component_ref = useRef(null);
    const file_input_ref = useRef(null);
    const private_file_input_ref = useRef(null);
    // Internal state for uncontrolled mode
    const [internal_files, set_internal_files] = useState([]);
    const [internal_private_files, set_internal_private_files] = useState([]);
    // Upload state
    const [is_dragging, set_is_dragging] = useState(false);
    const [is_dragging_private, set_is_dragging_private] = useState(false);
    const [upload_errors, set_upload_errors] = useState({});
    const [uploading_files, set_uploading_files] = useState(new Set());
    const [processing_files, set_processing_files] = useState(new Set());
    const [processed_files, set_processed_files] = useState(new Set());
    // Permission state for private files
    const [has_permission, set_has_permission] = useState(false);
    const [permission_loading, set_permission_loading] = useState(true);
    // Destructure props
    const { 
    // Value props
    value: controlled_files, onChange, private_value: controlled_private_files, on_private_change, 
    // Document configuration
    min_files = 0, max_files = 1, max_size, file_accept, file_validator, file_processor, files_dir, upload_endpoint = API_ENDPOINTS.file_upload, 
    // Styling
    dropzone_class_name, dropzone_wrapper_class_name, 
    // Base field props
    label, tooltip, error, field_id, field_data_id, field_name, additional_context, on_chat_click, chat_status, is_chat_active, chat_background_color = 'bg-muted', is_data_ok_default, container_class_name, label_class_name, label_actions, error_class_name, field_width_class_name, required, 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_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, hazo_chat_read_only, 
    // 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', 
    // Additional entry props
    additional_entry, max_additional_entries, entry_index, entry_count, on_add_entry, on_delete_entry, is_additional_entry, 
    // Delete field props
    enable_delete, disable_delete, on_delete, 
    // 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, 
    // Private file props (from base)
    accept_files_private, private_files_permission, 
    // Icons behaviour
    icons_behaviour, active_role, } = props;
    // Use controlled files if provided, otherwise use internal state
    const current_files = controlled_files !== undefined ? controlled_files : internal_files;
    const is_controlled = controlled_files !== undefined;
    // Use controlled private files if provided, otherwise use internal state
    const current_private_files = controlled_private_files !== undefined ? controlled_private_files : internal_private_files;
    const is_private_controlled = controlled_private_files !== undefined;
    // Expose ref methods
    React.useImperativeHandle(ref, () => {
        return {
            ...component_ref.current,
            get_file_data: () => current_files,
            get_private_file_data: () => current_private_files,
        };
    }, [current_files, current_private_files]);
    // Use the common field hook
    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,
    });
    // Per-field action slots — placed after UnifiedFieldControls and below the row.
    const { row_end: action_slot, row_below: action_slot_below } = use_field_action_slot(field_data_id || field_id_final);
    // Check permission for private files
    React.useEffect(() => {
        if (!accept_files_private || !private_files_permission) {
            set_permission_loading(false);
            set_has_permission(false);
            return;
        }
        const check_permission = async () => {
            try {
                set_permission_loading(true);
                const response = await fetch(API_ENDPOINTS.auth_get, {
                    credentials: 'include',
                });
                if (response.ok) {
                    const auth_data = await response.json();
                    if (auth_data.authenticated && auth_data.permissions) {
                        const has_perm = auth_data.permissions.includes(private_files_permission);
                        set_has_permission(has_perm);
                    }
                    else {
                        set_has_permission(false);
                    }
                }
                else {
                    set_has_permission(false);
                }
            }
            catch (err) {
                logger.warn('[HazoCollabFormDoc] Error checking permission', {
                    permission: private_files_permission,
                    error: err instanceof Error ? err.message : String(err),
                });
                set_has_permission(false);
            }
            finally {
                set_permission_loading(false);
            }
        };
        check_permission();
    }, [accept_files_private, private_files_permission]);
    // Determine if private files section should be shown
    const show_private_section = !!(accept_files_private && private_files_permission && has_permission && !permission_loading);
    // Check visibility - responders cannot see hidden fields
    const is_hidden = visibility === 'hidden';
    if (is_hidden && user_role === 'responder') {
        return null;
    }
    // Determine if field should be disabled
    const is_chat_field_disabled = is_chat_active !== undefined ? is_chat_active : chat_is_open;
    const is_field_disabled = is_chat_field_disabled || locked || skipped;
    const is_chat_effectively_disabled = is_chat_disabled || is_hidden;
    // Check if required (min_files >= 1)
    const is_required = min_files >= 1;
    // Determine if add entry button should show
    const show_add_entry = additional_entry && on_add_entry && (entry_count === undefined || entry_index === entry_count - 1) && (entry_count === undefined || entry_count < (max_additional_entries ?? 10));
    // Combine errors
    const upload_error_messages = Object.values(upload_errors).filter(Boolean);
    const display_error = error || (upload_error_messages.length > 0 ? upload_error_messages.join(', ') : undefined);
    // Data OK handler
    const handle_data_ok_unified_change = 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]);
    /**
     * Update files state (public files)
     */
    const update_files = useCallback((new_files) => {
        const files_with_visibility = new_files.map(f => ({
            ...f,
            visibility: f.visibility || 'public',
        }));
        if (!is_controlled) {
            set_internal_files(files_with_visibility);
        }
        if (onChange) {
            onChange(files_with_visibility);
        }
    }, [is_controlled, onChange]);
    /**
     * Update private files state
     */
    const update_private_files = useCallback((new_files) => {
        const files_with_visibility = new_files.map(f => ({
            ...f,
            visibility: 'private',
        }));
        if (!is_private_controlled) {
            set_internal_private_files(files_with_visibility);
        }
        if (on_private_change) {
            on_private_change(files_with_visibility);
        }
    }, [is_private_controlled, on_private_change]);
    /**
     * Toggle file visibility (move between public and private)
     */
    const toggle_file_visibility = useCallback((file_id, current_visibility) => {
        if (current_visibility === 'public') {
            const file_to_move = current_files.find(f => f.file_id === file_id);
            if (file_to_move) {
                const new_public_files = current_files.filter(f => f.file_id !== file_id);
                const moved_file = { ...file_to_move, visibility: 'private' };
                update_files(new_public_files);
                update_private_files([...current_private_files, moved_file]);
            }
        }
        else {
            const file_to_move = current_private_files.find(f => f.file_id === file_id);
            if (file_to_move) {
                const new_private_files = current_private_files.filter(f => f.file_id !== file_id);
                const moved_file = { ...file_to_move, visibility: 'public' };
                update_private_files(new_private_files);
                update_files([...current_files, moved_file]);
            }
        }
    }, [current_files, current_private_files, update_files, update_private_files]);
    /**
     * Validate file before upload
     */
    const validate_file = useCallback((file, target_visibility = 'public') => {
        // Run custom validator first
        if (file_validator) {
            const custom_error = file_validator(file);
            if (custom_error) {
                return custom_error;
            }
        }
        // Check total file count
        const total_files = current_files.length + current_private_files.length;
        if (total_files >= max_files) {
            return `Maximum ${max_files} file${max_files !== 1 ? 's' : ''} allowed`;
        }
        // Check file size
        if (max_size && file.size > max_size) {
            return `File size exceeds maximum of ${format_file_size(max_size)}`;
        }
        // Check file type
        if (file_accept) {
            const accept_patterns = file_accept.split(',').map((p) => p.trim());
            const file_extension = '.' + file.name.split('.').pop()?.toLowerCase();
            const file_mime = file.type;
            const matches = accept_patterns.some((pattern) => {
                if (pattern.startsWith('.')) {
                    return file_extension === pattern.toLowerCase();
                }
                else if (pattern.includes('/*')) {
                    const base_type = pattern.split('/')[0];
                    return file_mime.startsWith(base_type + '/');
                }
                else {
                    return file_mime === pattern;
                }
            });
            if (!matches) {
                return `File type not allowed. Accepted: ${file_accept}`;
            }
        }
        return null;
    }, [current_files.length, current_private_files.length, max_files, max_size, file_accept, file_validator]);
    /**
     * Upload file to server
     */
    const upload_file = useCallback(async (file, file_visibility = 'public') => {
        const file_id = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
        const uploading_id = `${file_id}-${file.name}`;
        try {
            set_uploading_files((prev) => new Set(prev).add(uploading_id));
            const form_data = new FormData();
            form_data.append('file', file);
            if (files_dir) {
                form_data.append('files_dir', files_dir);
            }
            form_data.append('visibility', file_visibility);
            if (file_visibility === 'private' && private_files_permission) {
                form_data.append('required_permission', private_files_permission);
            }
            const response = await fetch(upload_endpoint, {
                method: 'POST',
                body: form_data,
                credentials: 'include',
            });
            if (!response.ok) {
                const error_data = await response.json().catch(() => ({ error: 'Upload failed' }));
                throw new Error(error_data.error || `Upload failed: ${response.statusText}`);
            }
            const result = await response.json();
            const ref_id = `ref_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
            const file_data = {
                file_id,
                ref_id,
                file_name: file.name,
                file_size: file.size,
                mime_type: file.type,
                visibility: file_visibility,
                attached_at: new Date().toISOString(),
                file_path: result.file_path || result.path || '',
            };
            // Call file processor if provided
            if (file_processor && component_ref) {
                set_processing_files((prev) => new Set(prev).add(file_data.file_id));
                try {
                    await file_processor(file_data, component_ref);
                    set_processed_files((prev) => new Set(prev).add(file_data.file_id));
                }
                finally {
                    set_processing_files((prev) => {
                        const next = new Set(prev);
                        next.delete(file_data.file_id);
                        return next;
                    });
                }
            }
            set_upload_errors((prev) => {
                const next = { ...prev };
                delete next[uploading_id];
                return next;
            });
            return file_data;
        }
        catch (err) {
            const error_message = err instanceof Error ? err.message : 'Upload failed';
            set_upload_errors((prev) => ({
                ...prev,
                [uploading_id]: error_message,
            }));
            return null;
        }
        finally {
            set_uploading_files((prev) => {
                const next = new Set(prev);
                next.delete(uploading_id);
                return next;
            });
        }
    }, [files_dir, upload_endpoint, file_processor, private_files_permission]);
    /**
     * Handle file selection (public files)
     */
    const handle_files_selected = useCallback(async (selected_files) => {
        if (!selected_files || selected_files.length === 0)
            return;
        const files_to_upload = [];
        const errors = {};
        Array.from(selected_files).forEach((file) => {
            const err = validate_file(file, 'public');
            if (err) {
                errors[file.name] = err;
            }
            else {
                files_to_upload.push(file);
            }
        });
        if (Object.keys(errors).length > 0) {
            set_upload_errors((prev) => ({ ...prev, ...errors }));
        }
        const upload_promises = files_to_upload.map((file) => upload_file(file, 'public'));
        const uploaded_files = await Promise.all(upload_promises);
        const successful_uploads = uploaded_files.filter((f) => f !== null);
        if (successful_uploads.length > 0) {
            update_files([...current_files, ...successful_uploads]);
        }
    }, [current_files, validate_file, upload_file, update_files]);
    /**
     * Handle private file selection
     */
    const handle_private_files_selected = useCallback(async (selected_files) => {
        if (!selected_files || selected_files.length === 0)
            return;
        const files_to_upload = [];
        const errors = {};
        Array.from(selected_files).forEach((file) => {
            const err = validate_file(file, 'private');
            if (err) {
                errors[file.name] = err;
            }
            else {
                files_to_upload.push(file);
            }
        });
        if (Object.keys(errors).length > 0) {
            set_upload_errors((prev) => ({ ...prev, ...errors }));
        }
        const upload_promises = files_to_upload.map((file) => upload_file(file, 'private'));
        const uploaded_files = await Promise.all(upload_promises);
        const successful_uploads = uploaded_files.filter((f) => f !== null);
        if (successful_uploads.length > 0) {
            update_private_files([...current_private_files, ...successful_uploads]);
        }
    }, [current_private_files, validate_file, upload_file, update_private_files]);
    // Drag handlers
    const handle_drag_enter = useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        set_is_dragging(true);
    }, []);
    const handle_drag_leave = useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        set_is_dragging(false);
    }, []);
    const handle_drag_over = useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
    }, []);
    const handle_drop = useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        set_is_dragging(false);
        if (!is_field_disabled) {
            handle_files_selected(e.dataTransfer.files);
        }
    }, [handle_files_selected, is_field_disabled]);
    // Private drag handlers
    const handle_private_drag_enter = useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        set_is_dragging_private(true);
    }, []);
    const handle_private_drag_leave = useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        set_is_dragging_private(false);
    }, []);
    const handle_private_drop = useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        set_is_dragging_private(false);
        if (!is_field_disabled) {
            handle_private_files_selected(e.dataTransfer.files);
        }
    }, [handle_private_files_selected, is_field_disabled]);
    // Input change handlers
    const handle_input_change = useCallback((e) => {
        handle_files_selected(e.target.files);
        if (file_input_ref.current) {
            file_input_ref.current.value = '';
        }
    }, [handle_files_selected]);
    const handle_private_input_change = useCallback((e) => {
        handle_private_files_selected(e.target.files);
        if (private_file_input_ref.current) {
            private_file_input_ref.current.value = '';
        }
    }, [handle_private_files_selected]);
    /**
     * Handle file delete (public)
     */
    const handle_delete_file = useCallback((file_id) => {
        const new_files = current_files.filter((f) => f.file_id !== file_id);
        // Check minimum files constraint
        const total_files = new_files.length + current_private_files.length;
        if (min_files !== undefined && total_files < min_files) {
            set_upload_errors((prev) => ({
                ...prev,
                delete_error: `Minimum ${min_files} file${min_files !== 1 ? 's' : ''} required`,
            }));
            return;
        }
        update_files(new_files);
        set_upload_errors((prev) => {
            const next = { ...prev };
            delete next.delete_error;
            return next;
        });
    }, [current_files, current_private_files.length, min_files, update_files]);
    /**
     * Handle private file delete
     */
    const handle_delete_private_file = useCallback((file_id) => {
        const new_files = current_private_files.filter((f) => f.file_id !== file_id);
        // Check minimum files constraint
        const total_files = current_files.length + new_files.length;
        if (min_files !== undefined && total_files < min_files) {
            set_upload_errors((prev) => ({
                ...prev,
                delete_error: `Minimum ${min_files} file${min_files !== 1 ? 's' : ''} required`,
            }));
            return;
        }
        update_private_files(new_files);
        set_upload_errors((prev) => {
            const next = { ...prev };
            delete next.delete_error;
            return next;
        });
    }, [current_private_files, current_files.length, min_files, update_private_files]);
    /**
     * Get file URL for download/preview
     */
    const get_file_url = useCallback((file_path, file_visibility) => {
        if (file_path.startsWith('/')) {
            return file_path;
        }
        if (file_visibility === 'private' && private_files_permission) {
            return `/api/collab-forms/private-files/${encodeURIComponent(file_path)}?permission=${encodeURIComponent(private_files_permission)}`;
        }
        return `/api/collab-forms/files/${encodeURIComponent(file_path)}`;
    }, [private_files_permission]);
    // Total files for display
    const total_file_count = current_files.length + current_private_files.length;
    const can_add_more = total_file_count < max_files && !is_field_disabled;
    /**
     * Render a file item
     */
    const render_file_item = (file_data, file_visibility, delete_handler) => {
        const is_uploading = Array.from(uploading_files).some((upload_id) => upload_id.startsWith(file_data.file_id));
        const is_processing = processing_files.has(file_data.file_id);
        const is_processed = processed_files.has(file_data.file_id);
        return (_jsxs("div", { className: "cls_collab_doc_file_item flex items-center gap-2 p-2 border rounded-md bg-background hover:bg-muted/50 transition-colors", children: [_jsxs("div", { className: "relative flex-shrink-0", children: [get_file_icon(file_data.mime_type, file_data.file_name), is_processing && (_jsx("div", { className: "absolute -bottom-1 -right-1 bg-background rounded-full p-0.5", children: _jsx(FaSpinner, { className: "h-3 w-3 animate-spin text-primary" }) }))] }), _jsxs("a", { href: get_file_url(file_data.file_path || '', file_visibility), target: "_blank", rel: "noopener noreferrer", className: cn("flex-1 min-w-0", is_uploading && "pointer-events-none opacity-50"), children: [_jsx("div", { className: "text-sm truncate", title: file_data.file_name, children: file_data.file_name }), _jsx("div", { className: "text-xs text-muted-foreground", children: format_file_size(file_data.file_size) })] }), _jsxs("div", { className: "flex items-center gap-1 flex-shrink-0", children: [is_processed && !is_processing && (_jsx(HiCheckCircle, { className: "h-4 w-4 text-green-500" })), show_private_section && (_jsx("button", { type: "button", onClick: () => toggle_file_visibility(file_data.file_id, file_visibility), className: cn("p-1 transition-colors rounded hover:bg-muted", file_visibility === 'private'
                                ? "text-amber-600 hover:text-amber-700"
                                : "text-muted-foreground hover:text-foreground"), disabled: is_uploading || is_field_disabled, "aria-label": file_visibility === 'private' ? `Make ${file_data.file_name} public` : `Make ${file_data.file_name} private`, title: file_visibility === 'private' ? 'Make public' : 'Make private', children: file_visibility === 'private' ? (_jsx(HiLockClosed, { className: "h-4 w-4" })) : (_jsx(HiLockOpen, { className: "h-4 w-4" })) })), _jsx("button", { type: "button", onClick: () => delete_handler(file_data.file_id), className: "p-1 text-destructive hover:text-destructive/80 transition-colors rounded hover:bg-muted", disabled: is_uploading || is_field_disabled, "aria-label": `Delete ${file_data.file_name}`, children: _jsx(HiTrash, { className: "h-4 w-4" }) })] }), is_uploading && (_jsx("div", { className: "absolute inset-0 bg-background/50 flex items-center justify-center rounded-md", children: _jsx(FaSpinner, { className: "h-4 w-4 animate-spin text-primary" }) }))] }, file_data.file_id));
    };
    /**
     * Render dropzone
     */
    const render_dropzone = (section_type, section_is_dragging, section_on_drag_enter, section_on_drag_leave, section_on_drop, section_file_input_ref, section_on_input_change, input_id_suffix) => (_jsxs("div", { className: cn('cls_collab_doc_dropzone border-2 border-dashed rounded-md p-4 text-center transition-colors', section_is_dragging
            ? 'border-primary bg-primary/5'
            : 'border-input hover:border-primary/50 hover:bg-muted/50', !can_add_more && 'opacity-50 cursor-not-allowed', is_field_disabled && 'opacity-50 cursor-not-allowed', dropzone_class_name), onDragEnter: section_on_drag_enter, onDragLeave: section_on_drag_leave, onDragOver: handle_drag_over, onDrop: section_on_drop, children: [_jsx("input", { ref: section_file_input_ref, type: "file", id: `${field_id_final}-${input_id_suffix}`, className: "hidden", accept: file_accept, multiple: max_files > 1, onChange: section_on_input_change, disabled: !can_add_more || is_field_disabled }), _jsxs("label", { htmlFor: `${field_id_final}-${input_id_suffix}`, className: cn('cursor-pointer flex flex-col items-center gap-2', (!can_add_more || is_field_disabled) && 'cursor-not-allowed'), children: [_jsx(HiCloudUpload, { className: "h-8 w-8 text-muted-foreground" }), _jsx("div", { className: "text-sm text-muted-foreground", children: section_type === 'private' ? (_jsxs("span", { children: ["Drop private files here or ", _jsx("span", { className: "text-primary underline", children: "browse" })] })) : (_jsxs("span", { children: ["Drop files here or ", _jsx("span", { className: "text-primary underline", children: "browse" })] })) }), file_accept && (_jsxs("div", { className: "text-xs text-muted-foreground", children: ["Accepted: ", file_accept] })), max_size && (_jsxs("div", { className: "text-xs text-muted-foreground", children: ["Max size: ", format_file_size(max_size)] }))] })] }));
    return (_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: 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(CollabFormFieldLabel, { field_id_final: field_id_final, label: label, tooltip: tooltip, label_class_name: label_class_name, required: required || is_required, visibility: visibility, locked: locked, label_actions: label_actions }), _jsxs("div", { className: cn('cls_collab_doc_wrapper flex items-start gap-2', dropzone_wrapper_class_name, is_hidden && user_role === 'author' && 'opacity-50'), suppressHydrationWarning: true, ref: component_ref, children: [_jsxs("div", { className: cn(field_width_class_name || 'flex-1', field_width_class_name && 'flex-shrink-0'), children: [_jsxs("div", { className: "space-y-2", children: [show_private_section && (_jsx("div", { className: "text-xs font-medium text-muted-foreground", children: "Public Files" })), can_add_more && render_dropzone('public', is_dragging, handle_drag_enter, handle_drag_leave, handle_drop, file_input_ref, handle_input_change, 'file-input'), current_files.length > 0 && (_jsx("div", { className: "space-y-1", children: current_files.map((file) => render_file_item(file, 'public', handle_delete_file)) }))] }), show_private_section && (_jsxs("div", { className: "space-y-2 mt-4 pt-4 border-t", children: [_jsxs("div", { className: "text-xs font-medium text-muted-foreground flex items-center gap-1", children: [_jsx(HiLockClosed, { className: "h-3 w-3" }), "Private Files"] }), can_add_more && render_dropzone('private', is_dragging_private, handle_private_drag_enter, handle_private_drag_leave, handle_private_drop, private_file_input_ref, handle_private_input_change, 'private-file-input'), current_private_files.length > 0 && (_jsx("div", { className: "space-y-1", children: current_private_files.map((file) => render_file_item(file, 'private', handle_delete_private_file)) }))] })), max_files > 1 && (_jsxs("div", { className: "text-xs text-muted-foreground mt-2", children: [total_file_count, " / ", max_files, " file", max_files !== 1 ? 's' : ''] }))] }), show_add_entry && (_jsx(CollabFormAddEntryIcon, { label: label, field_id: field_data_id || field_id_final, on_add_entry: on_add_entry })), is_additional_entry && on_delete_entry && (_jsx(CollabFormDeleteEntryIcon, { label: label, field_id: field_data_id || field_id_final, on_delete_entry: on_delete_entry })), _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,
                        }, 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,
                        }, 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,
                            chat_read_only: hazo_chat_read_only,
                            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,
                        }, 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,
                        } }), action_slot] }), action_slot_below && _jsx("div", { className: "cls_field_action_below", children: action_slot_below }), _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: display_error, error_class_name: error_class_name })] }));
});
HazoCollabFormDoc.displayName = 'HazoCollabFormDoc';
//# sourceMappingURL=hazo_collab_form_doc.js.map