/**
 * CollectedDataView — Agent tab showing all content items grouped by AI category.
 * Checkboxes for selecting what to export. AI auto-checks relevant items.
 */
'use client';
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
import { ExtractedFieldsInline } from './extracted_fields_inline.js';
import { FileInfoDialog } from './file_info_dialog.js';
import { PdfIcon } from './shared.js';
/** Inline info-icon button that opens FileInfoDialog. Agent-only by default. */
function FileInfoButton({ item, classification_results, }) {
    const [open, set_open] = useState(false);
    if (item.type !== 'file' || !item.file)
        return null;
    const classification = item.classification_result
        ?? classification_results?.get(item.content_id)
        ?? null;
    const validation_results = item.validation_rule_results ?? [];
    const has_info = !!classification || validation_results.length > 0;
    if (!has_info)
        return null;
    return (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", onClick: () => set_open(true), className: "p-0.5 rounded text-[#94A3B8] hover:text-blue-500 transition-colors flex-shrink-0 cursor-pointer", title: "File details", children: _jsx("svg", { className: "w-3.5 h-3.5", fill: "currentColor", viewBox: "0 0 20 20", children: _jsx("path", { fillRule: "evenodd", d: "M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z", clipRule: "evenodd" }) }) }), _jsx(FileInfoDialog, { open: open, on_open_change: set_open, file_name: item.file.file_name, classification: classification, validation_results: validation_results })] }));
}
/** Gather all content items across tasks, grouped by category */
function gather_categories(data, classification_results) {
    const categories = new Map();
    function add(cat, item) {
        const arr = categories.get(cat);
        if (arr)
            arr.push(item);
        else
            categories.set(cat, [item]);
    }
    for (const task of data.tasks) {
        for (const msg of task.thread) {
            // Content items from messages
            for (const item of msg.content_items || []) {
                if (item.category_label) {
                    add(item.category_label, item);
                }
                else if (item.classification_result) {
                    const label = item.classification_result.document_type.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
                    add(label, item);
                }
                else if (classification_results?.has(item.content_id)) {
                    // Use pipeline classification result
                    const cr = classification_results.get(item.content_id);
                    const label = cr.document_type.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
                    add(label, item);
                }
                else if (item.type === 'file') {
                    add('Uploaded Files', item);
                }
            }
            // AI analysis: splits + extracted text
            if (msg.ai_analysis) {
                for (const result of msg.ai_analysis.items) {
                    for (const split of result.split_items || []) {
                        if (split.category_label)
                            add(split.category_label, split);
                    }
                    for (const group of result.extracted_data || []) {
                        for (const field of group.fields) {
                            add(group.category, {
                                content_id: `${result.content_ref}_${field.key}`,
                                type: 'text',
                                text: `${field.label}: ${field.value}`,
                                category: group.category.toLowerCase().replace(/\s+/g, '_'),
                                category_label: group.category,
                            });
                        }
                    }
                }
            }
        }
    }
    return categories;
}
/** Sort items into replacement chains with depth. Root items first, then replacements nested below. */
function sort_with_replacement_chains(items) {
    const items_by_id = new Map(items.map(i => [i.content_id, i]));
    const has_parent_in_group = new Set(items.filter(i => i.replaces_content_id && items_by_id.has(i.replaces_content_id)).map(i => i.content_id));
    const result = [];
    const insert_chain = (item, depth) => {
        result.push({ item, depth });
        for (const r of items) {
            if (r.replaces_content_id === item.content_id)
                insert_chain(r, depth + 1);
        }
    };
    for (const item of items) {
        if (!has_parent_in_group.has(item.content_id))
            insert_chain(item, 0);
    }
    return result;
}
/** Default selection for an item — replaced originals default to unchecked, others to checked. */
function default_selected(item) {
    return !item.replaced_by_content_id;
}
/** Effective selection state, honoring the explicit selection or falling back to the default. */
function is_item_selected(item, selections) {
    const explicit = selections[item.content_id];
    return explicit === undefined ? default_selected(item) : explicit;
}
export function CollectedDataView({ data, classification_results, on_selection_change, on_export, on_view_file, render_item_details, show_extracted_fields, document_types, locale, currency_code, truncate_chars, role, on_request_reextraction, }) {
    const categories = gather_categories(data, classification_results);
    const selections = data.collected_data_selections || {};
    // Per-row accordion state. Default: all collapsed. Set membership = expanded.
    const [expanded_rows, set_expanded_rows] = useState(new Set());
    const handle_toggle = (item) => {
        const current = is_item_selected(item, selections);
        on_selection_change?.({ [item.content_id]: !current });
    };
    const toggle_row = (content_id) => {
        set_expanded_rows(prev => {
            const next = new Set(prev);
            if (next.has(content_id))
                next.delete(content_id);
            else
                next.add(content_id);
            return next;
        });
    };
    const all_content_ids = Array.from(categories.values()).flat().map(i => i.content_id);
    const expand_all = () => set_expanded_rows(new Set(all_content_ids));
    const collapse_all = () => set_expanded_rows(new Set());
    const all_expanded = expanded_rows.size > 0 && expanded_rows.size === all_content_ids.length;
    const handle_export = () => {
        const selected = [];
        for (const [, items] of categories) {
            for (const item of items) {
                if (is_item_selected(item, selections))
                    selected.push(item);
            }
        }
        on_export?.(selected);
    };
    const total_selected = Array.from(categories.values())
        .flat()
        .filter(item => is_item_selected(item, selections)).length;
    const total_items = Array.from(categories.values()).flat().length;
    return (_jsxs("div", { className: "space-y-4", children: [_jsxs("div", { className: "flex items-center justify-between text-[13px] text-[#64748B]", children: [_jsxs("span", { children: [total_selected, " of ", total_items, " items selected"] }), _jsx("button", { type: "button", onClick: all_expanded ? collapse_all : expand_all, className: "text-[12px] text-[#2563EB] hover:text-[#1D4ED8] font-medium cursor-pointer", children: all_expanded ? 'Collapse all' : 'Expand all' })] }), Array.from(categories.entries()).map(([cat, items]) => {
                const sel_count = items.filter(i => is_item_selected(i, selections)).length;
                const sorted = sort_with_replacement_chains(items);
                return (_jsxs("div", { className: "rounded-md border border-[#E2E8F0] overflow-hidden border-l-[3px] border-l-[#94A3B8]", children: [_jsxs("div", { className: "flex items-center justify-between px-4 py-2.5 bg-[#F8FAFC] border-b border-[#E2E8F0]", children: [_jsx("span", { className: "text-[13px] font-medium text-[#0F172A]", children: cat }), _jsxs("span", { className: "text-[11px] text-[#94A3B8]", children: [sel_count, "/", items.length, " selected"] })] }), _jsx("div", { className: "p-2 space-y-1.5 bg-[#FAFBFC]", children: sorted.map(({ item, depth }) => {
                                const is_selected = is_item_selected(item, selections);
                                const is_replaced = !!item.replaced_by_content_id;
                                const inline_details = render_item_details
                                    ? render_item_details(item)
                                    : show_extracted_fields
                                        ? _jsx(ExtractedFieldsInline, { item: item, classification_results: classification_results, document_types: document_types, locale: locale, currency_code: currency_code, truncate_chars: truncate_chars, role: role, on_request_reextraction: on_request_reextraction })
                                        : null;
                                const has_details = !!inline_details;
                                const is_expanded = expanded_rows.has(item.content_id);
                                return (_jsxs("div", { className: "rounded-sm border border-[#E2E8F0] bg-white shadow-[0_1px_2px_rgba(15,23,42,0.04)] overflow-hidden", children: [_jsxs("div", { className: `flex items-center gap-3 px-4 py-2.5 text-[13px] hover:bg-[#FAFBFC] ${is_replaced ? 'bg-[#F8FAFC]' : ''}`, style: depth > 0 ? { paddingLeft: `${16 + depth * 20}px` } : undefined, children: [_jsx("input", { type: "checkbox", checked: is_selected, onChange: () => handle_toggle(item), className: "rounded border-[#CBD5E1] text-[#2563EB] focus:ring-[#2563EB] cursor-pointer" }), has_details ? (_jsx("button", { type: "button", onClick: () => toggle_row(item.content_id), "aria-expanded": is_expanded, "aria-label": is_expanded ? 'Collapse details' : 'Expand details', className: "p-0.5 rounded text-[#94A3B8] hover:text-[#475569] transition-colors flex-shrink-0 cursor-pointer", children: _jsx("svg", { className: `w-3.5 h-3.5 transition-transform ${is_expanded ? 'rotate-90' : ''}`, fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: _jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M9 5l7 7-7 7" }) }) })) : (_jsx("span", { className: "w-3.5 flex-shrink-0", "aria-hidden": "true" })), item.type === 'file' ? (_jsxs(_Fragment, { children: [_jsx(PdfIcon, { className: `w-4 h-4 ${is_replaced ? 'opacity-40' : ''}` }), _jsx("span", { className: `truncate flex-1 ${is_replaced ? 'text-[#94A3B8] line-through' : 'text-[#0F172A]'}`, children: item.file?.file_name || item.split_info?.label }), item.split_info?.page_range && (_jsx("span", { className: "text-[11px] text-[#94A3B8]", children: item.split_info.page_range })), is_replaced && (_jsx("span", { className: "text-[10px] text-[#94A3B8] uppercase tracking-wide flex-shrink-0", children: "Replaced" })), role === 'agent' && (_jsx(FileInfoButton, { item: item, classification_results: classification_results })), _jsx("button", { onClick: () => on_view_file?.(item), className: "text-[11px] text-[#2563EB] font-medium cursor-pointer", children: "View" })] })) : (_jsxs(_Fragment, { children: [_jsx("span", { className: `flex-shrink-0 ${is_replaced ? 'text-[#CBD5E1]' : 'text-[#94A3B8]'}`, children: _jsx("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: _jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 1.5, d: "M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" }) }) }), _jsx("span", { className: `truncate flex-1 ${is_replaced ? 'text-[#94A3B8] line-through' : 'text-[#0F172A]'}`, children: item.text }), is_replaced && (_jsx("span", { className: "text-[10px] text-[#94A3B8] uppercase tracking-wide flex-shrink-0", children: "Replaced" }))] }))] }), has_details && is_expanded && (_jsx("div", { className: `px-4 pb-2 text-[13px] ${is_replaced ? 'bg-[#F8FAFC]' : ''}`, style: depth > 0 ? { paddingLeft: `${16 + depth * 20}px` } : undefined, children: inline_details }))] }, item.content_id));
                            }) })] }, cat));
            }), _jsxs("button", { onClick: handle_export, disabled: total_selected === 0, className: "w-full bg-[#0F172A] text-white rounded-md py-2.5 text-[13px] font-medium hover:bg-[#1E293B] disabled:bg-[#E2E8F0] disabled:text-[#94A3B8] cursor-pointer disabled:cursor-not-allowed transition-colors", children: ["Export ", total_selected, " Selected Items to Data Form \u2192"] })] }));
}
//# sourceMappingURL=collected_data_view.js.map