/**
 * FileTextboxPanel — a single purple panel with comment textarea + file grid + upload zone.
 */
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useRef, useState } from 'react';
import { cn } from '../../utils/cn.js';
import { FileChip } from './file_chip.js';
import { FileGroup } from './file_group.js';
import { FileUploadZone } from './file_upload_zone.js';
import { HiX } from 'react-icons/hi';
export function FileTextboxPanel({ entry, entry_index, disabled, placeholder, file_manager, file_accept, max_files = 50, field_id, total_file_count, classification_tags, classification_metadata, classifying_file_ids, queued_file_ids, autofilling_file_ids, validation_errors, validating_file_ids, validated_file_ids, file_response_labels, on_comment_change, on_files_added, on_file_remove, on_remove_panel, on_file_view, on_classify_file, on_download, on_issue_click, on_validated_click, responded_ids, file_validation_details, file_pipeline_status, }) {
    const [upload_progress, set_upload_progress] = useState(null);
    const [uploading_files, set_uploading_files] = useState([]);
    // Drag counter to prevent flicker when hovering over child elements
    const drag_counter_ref = useRef(0);
    const [is_dragging, set_is_dragging] = useState(false);
    // Track active upload count to prevent concurrent uploads clearing each other's state
    const active_upload_ref = useRef(0);
    // Ref to always call the latest on_files_added (avoids stale closure during async upload)
    const on_files_added_ref = useRef(on_files_added);
    on_files_added_ref.current = on_files_added;
    const auto_resize = useCallback((el) => {
        if (!el)
            return;
        el.style.height = 'auto';
        el.style.height = el.scrollHeight + 'px';
    }, []);
    const handle_files = useCallback(async (files) => {
        if (!file_manager)
            return;
        const remaining = max_files - total_file_count;
        const to_upload = Array.from(files).slice(0, remaining);
        if (to_upload.length === 0)
            return;
        active_upload_ref.current++;
        set_uploading_files(prev => [...prev, ...to_upload.map((f) => ({ name: f.name, status: 'uploading' }))]);
        const uploaded = [];
        for (let i = 0; i < to_upload.length; i++) {
            const file = to_upload[i];
            set_upload_progress({ current: i + 1, total: to_upload.length, file_name: file.name });
            try {
                const attachment = await file_manager.upload(file, {
                    entity_id: field_id,
                    visibility: 'public',
                });
                uploaded.push(attachment);
            }
            catch (err) {
                console.error('[FileTextboxPanel] Upload failed:', err);
            }
        }
        active_upload_ref.current--;
        // Only clear upload UI when ALL concurrent uploads are done
        if (active_upload_ref.current === 0) {
            set_upload_progress(null);
            set_uploading_files([]);
        }
        if (uploaded.length > 0) {
            // Use ref to call the latest callback (not the one captured at upload start)
            on_files_added_ref.current(entry_index, uploaded);
        }
    }, [file_manager, max_files, total_file_count, field_id, entry_index]);
    const handle_drag_enter = useCallback((e) => {
        e.preventDefault();
        drag_counter_ref.current++;
        if (drag_counter_ref.current === 1)
            set_is_dragging(true);
    }, []);
    const handle_drag_over = useCallback((e) => { e.preventDefault(); }, []);
    const handle_drag_leave = useCallback((e) => {
        drag_counter_ref.current--;
        if (drag_counter_ref.current === 0)
            set_is_dragging(false);
    }, []);
    const handle_drop = useCallback((e) => {
        e.preventDefault();
        drag_counter_ref.current = 0;
        set_is_dragging(false);
        if (e.dataTransfer.files.length)
            handle_files(e.dataTransfer.files);
    }, [handle_files]);
    // Build blocks array for file_group (linked file detection)
    const file_blocks = entry.files;
    const can_upload = file_manager && !disabled && total_file_count < max_files;
    return (_jsxs("div", { className: cn('rounded-xl border border-violet-200/50 bg-violet-50/30 p-3 relative group/panel transition-colors', is_dragging && 'border-primary bg-primary/5'), onDragEnter: handle_drag_enter, onDragOver: handle_drag_over, onDragLeave: handle_drag_leave, onDrop: handle_drop, children: [!disabled && (_jsx("button", { type: "button", onClick: () => on_remove_panel(entry_index), className: "absolute top-2 right-2 p-1 rounded-md text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 opacity-0 group-hover/panel:opacity-100 transition-all", title: "Remove panel", children: _jsx(HiX, { className: "h-3.5 w-3.5" }) })), _jsx("textarea", { ref: (el) => { if (el)
                    auto_resize(el); }, value: entry.comment, placeholder: placeholder || 'Add a comment...', disabled: disabled, onChange: (e) => {
                    on_comment_change(entry_index, e.target.value);
                    auto_resize(e.target);
                }, className: cn('w-full bg-transparent px-2 py-1.5 text-base md:text-sm resize-none outline-none rounded-md', 'placeholder:text-muted-foreground/50', 'disabled:cursor-not-allowed disabled:opacity-50', 'min-h-[40px]', 'focus:bg-white/50 transition-colors'), rows: 1 }), file_blocks.length > 0 && (_jsx("div", { className: "flex flex-wrap gap-1.5 items-start mt-2", children: file_blocks.map((block, fi) => {
                    if (block.type !== 'file')
                        return null;
                    const is_replaced = !!block.replaced_by;
                    const is_replacement = !!block.replaces;
                    if (is_replacement)
                        return null;
                    const linked = file_blocks.filter(b => b.type === 'file' && b.replaces === block.attachment.file_id);
                    if (linked.length === 0) {
                        return (_jsx(FileChip, { attachment: block.attachment, index: fi, disabled: disabled, classifying: classifying_file_ids?.has(block.attachment.file_id), autofilling: autofilling_file_ids?.has(block.attachment.file_id), queued: queued_file_ids?.has(block.attachment.file_id), validating: validating_file_ids?.has(block.attachment.file_id), validated: validated_file_ids?.has(block.attachment.file_id), validation_errors: validation_errors?.[block.attachment.file_id], response_label: file_response_labels[block.attachment.file_id], classification_tags: classification_tags?.[block.attachment.file_id], classification_meta: classification_metadata?.[block.attachment.file_id], on_download: on_download, on_remove: (idx) => on_file_remove(entry_index, idx), on_view: on_file_view, on_classify: on_classify_file, on_issue_click: on_issue_click, on_validated_click: on_validated_click, responded_ids: responded_ids, validation_details: file_validation_details?.[block.attachment.file_id], pipeline_status_text: file_pipeline_status?.[block.attachment.file_id] }, fi));
                    }
                    return (_jsx(FileGroup, { original_block: block, original_index: fi, linked_blocks: linked, all_blocks: file_blocks, is_replaced: is_replaced, disabled: disabled, classifying_file_ids: classifying_file_ids, autofilling_file_ids: autofilling_file_ids, validating_file_ids: validating_file_ids, validation_errors: validation_errors, validated_file_ids: validated_file_ids, file_response_labels: file_response_labels, classification_tags: classification_tags, classification_metadata: classification_metadata, on_download: on_download, on_remove: (idx) => on_file_remove(entry_index, idx), on_view: on_file_view, on_issue_click: on_issue_click, on_validated_click: on_validated_click, responded_ids: responded_ids }, fi));
                }) })), can_upload && (_jsx("div", { className: "mt-2", children: _jsx(FileUploadZone, { file_accept: file_accept, upload_progress: upload_progress, uploading_files: uploading_files, on_files: handle_files }) }))] }));
}
//# sourceMappingURL=file_textbox_panel.js.map