/**
 * ClarificationItemBody - Shared rendering for a single clarification item's zones.
 *
 * Uses "Inset Panels" design: issue zone is recessed (tinted bg + inset shadow),
 * response zone is elevated (white surface). A centered gradient divider with label
 * creates a clear break between "what's wrong" and "how to respond."
 *
 * Used by both ClarificationCard (single item) and ClarificationGroupCard (per-item rows).
 *
 * Layout:
 * ┌─ Sub-header (optional, for GroupCard per-item rows) ──────┐
 * │  [Status Icon] [Status Badge]  Field Label  [Action Btns] │
 * ├─ Issue Zone (recessed) ───────────────────────────────────┤
 * │  [!] ISSUE FOUND · RULE_NAME                              │
 * │  Issue description (RED if pending, MUTED if responded)   │
 * │  Validation details (italic, same color logic)            │
 * │  Referenced Documents (optional)                          │
 * ├─ Divider ─────────────────────────────────────────────────┤
 * │  ──────── [icon] YOUR RESPONSE ────────                   │
 * ├─ Response Zone (elevated) ────────────────────────────────┤
 * │  ClarificationResponseForm                                │
 * └───────────────────────────────────────────────────────────┘
 */
'use client';
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useCallback, useState } from 'react';
import { cn } from '../../utils/cn.js';
import { ClarificationDocReferenceList } from './clarification_doc_reference.js';
import { ClarificationResponseForm } from './clarification_response_form.js';
import { ClarificationThread } from './clarification_thread.js';
import { ResolutionStatusStrip } from './resolution_status_strip.js';
import { STATUS_CONFIG, get_issue_text_class, get_issue_detail_text_class } from './clarification_status_config.js';
import { IoAlertCircle, IoCheckmarkCircle } from 'react-icons/io5';
/** Removed inset shadow styles — using flat zone design */
export const ClarificationItemBody = React.memo(function ClarificationItemBody({ item, show_doc_references = true, read_only = false, hide_submit, submit_label, hide_response_form, file_manager, on_respond, on_resolve, on_dismiss, on_reopen, on_doc_click, on_doc_view, on_doc_delete, on_field_click, on_response_change, file_validation, response_validation, on_validation_click, file_validation_details, file_pipeline_status, compact, resolution_api_url, extract_response_fields, initial_extracted_fields, resolution_mismatch_options, }) {
    const is_actionable = item.status === 'pending' || item.status === 'responded';
    const is_closed = item.status === 'resolved' || item.status === 'dismissed';
    const is_responded = item.status === 'responded' || item.status === 'resolved';
    const config = STATUS_CONFIG[item.status] ?? STATUS_CONFIG.pending;
    // ── Resolution state (sum_match path) ─────────────────────────────────
    const [pending_check, set_pending_check] = useState(null);
    const [mismatch_active, set_mismatch_active] = useState(false);
    const [resolver_running, set_resolver_running] = useState(false);
    const [pending_response, set_pending_response] = useState(null);
    const has_resolver = Boolean(resolution_api_url && item.expectation);
    const run_resolver = useCallback(async (response) => {
        if (!resolution_api_url || !item.expectation)
            return null;
        const files = response.response_files ?? [];
        const enriched_files = await Promise.all(files.map(async (f) => {
            const existing = initial_extracted_fields?.[f.file_id];
            if (existing)
                return { file_id: f.file_id, file_name: f.file_name, extracted_fields: existing };
            if (extract_response_fields) {
                try {
                    const fields = await extract_response_fields(f.file_id, f.file_name, f.mime_type);
                    return {
                        file_id: f.file_id,
                        file_name: f.file_name,
                        ...(fields ? { extracted_fields: fields } : {}),
                    };
                }
                catch (err) {
                    console.warn('[clarification] extract_response_fields failed', err);
                }
            }
            return { file_id: f.file_id, file_name: f.file_name };
        }));
        try {
            const res = await fetch(resolution_api_url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ expectation: item.expectation, response_files: enriched_files }),
            });
            const data = await res.json();
            if (!res.ok || data?.success === false) {
                console.warn('[clarification] resolution API returned non-success', data);
                return null;
            }
            return (data.check ?? null);
        }
        catch (err) {
            console.warn('[clarification] resolution call failed', err);
            return null;
        }
    }, [resolution_api_url, item.expectation, extract_response_fields, initial_extracted_fields]);
    const handle_respond = useCallback(async (response) => {
        if (!has_resolver) {
            on_respond?.(item.id, response);
            return;
        }
        set_resolver_running(true);
        const check = await run_resolver(response);
        set_resolver_running(false);
        if (!check) {
            // Resolver unreachable — let the response through without the check.
            on_respond?.(item.id, response);
            return;
        }
        set_pending_check(check);
        if (check.passed) {
            on_respond?.(item.id, { ...response, resolution_check: check });
            set_pending_response(null);
            set_mismatch_active(false);
            return;
        }
        if (mismatch_active) {
            // Second submit attempt — client has already chosen a fallback path.
            // Forward the response through with the check so the agent can review.
            on_respond?.(item.id, { ...response, resolution_check: check });
            return;
        }
        // First failure — surface mismatch sub-form
        set_pending_response(response);
        set_mismatch_active(true);
    }, [has_resolver, run_resolver, on_respond, item.id, mismatch_active]);
    const handle_mismatch_submit = useCallback(async (sub_response) => {
        if (!pending_response)
            return;
        // Merge: sub_response carries the mismatch_choice, optional comment, and
        // optional new files. Combine with the held pending_response.
        const merged_files = [
            ...(pending_response.response_files ?? []),
            ...(sub_response.response_files ?? []),
        ];
        const merged = {
            response_choice: pending_response.response_choice,
            user_comment: pending_response.user_comment,
            response_files: merged_files.length > 0 ? merged_files : undefined,
            mismatch_choice: sub_response.response_choice,
            mismatch_comment: sub_response.user_comment,
        };
        set_resolver_running(true);
        const check = await run_resolver(merged);
        set_resolver_running(false);
        if (check)
            set_pending_check(check);
        on_respond?.(item.id, { ...merged, ...(check ? { resolution_check: check } : {}) });
        set_pending_response(null);
        set_mismatch_active(false);
    }, [pending_response, run_resolver, on_respond, item.id]);
    const handle_doc_delete = useCallback((file_id) => {
        on_doc_delete?.(item.id, file_id);
    }, [on_doc_delete, item.id]);
    const handle_response_change = useCallback((response) => {
        on_response_change?.(item.id, response);
    }, [on_response_change, item.id]);
    return (_jsxs("div", { className: cn(is_closed && 'opacity-70'), "data-clarification-id": item.id, "data-clarification-field": item.target_field_id, children: [_jsx("div", { className: cn('px-4 py-3.5', config.issue_bg), children: item.thread && item.thread.length > 0 ? (_jsx(ClarificationThread, { thread: item.thread, response_options: item.response_options, on_file_view: on_doc_view })) : (
                /* Standard issue panel (first-time clarifications with no thread history) */
                _jsxs("div", { className: cn('rounded-lg border p-3.5', config.issue_bg, 'border-stone-200/80 dark:border-stone-700/50'), children: [!compact && (_jsxs("div", { className: "flex items-center gap-2 mb-2", children: [is_responded ? (_jsx(IoCheckmarkCircle, { className: cn('w-3.5 h-3.5 flex-shrink-0', config.issue_icon_color) })) : (_jsx(IoAlertCircle, { className: cn('w-3.5 h-3.5 flex-shrink-0', config.issue_icon_color) })), _jsx("span", { className: cn('text-[10px] font-bold uppercase tracking-[0.08em]', config.issue_label_color), children: is_responded ? 'Issue (Responded)' : 'Issue Found' }), item.rule_name && (_jsxs(_Fragment, { children: [_jsx("span", { className: "text-muted-foreground/30 mx-0.5", children: "\u00B7" }), _jsx("span", { className: "text-[10px] text-muted-foreground/50 uppercase tracking-wide", children: item.rule_name })] }))] })), _jsxs("div", { className: "pl-[22px]", children: [_jsx("p", { className: cn('text-sm leading-relaxed', get_issue_text_class(item.status)), children: item.issue_description }), item.validation_details && item.validation_details !== item.issue_description && (_jsx("p", { className: cn('text-sm mt-1.5 italic leading-relaxed', get_issue_detail_text_class(item.status)), children: item.validation_details })), show_doc_references && item.doc_references.length > 0 && (_jsx(ClarificationDocReferenceList, { references: item.doc_references, on_click: on_doc_click, on_view: on_doc_view, on_delete: on_doc_delete && !is_closed ? handle_doc_delete : undefined, file_validation: file_validation }))] })] })) }), !hide_response_form && (_jsx("div", { className: "px-4 py-3.5", children: _jsxs("div", { className: cn('rounded-lg border p-3.5', config.response_bg, config.response_border), children: [_jsx("div", { className: cn('text-[10px] font-bold uppercase tracking-[0.08em] mb-3', config.response_label_color), children: item.thread && item.thread.length > 0 && item.status === 'pending'
                                ? 'Response Required'
                                : config.divider_label }), _jsx(ClarificationResponseForm, { action_description: item.action_description, response_options: item.response_options, initial_choice: item.response_choice, initial_comment: item.user_comment, initial_files: item.response_files, read_only: read_only || !is_actionable || mismatch_active, on_submit: is_actionable && !mismatch_active ? handle_respond : undefined, hide_submit: hide_submit || mismatch_active, submit_label: submit_label, on_change: on_response_change ? handle_response_change : undefined, file_manager: file_manager, radio_accent: config.response_radio_accent, submit_bg: config.submit_bg, response_validation: response_validation, file_validations: file_validation, on_validation_click: on_validation_click, file_validation_details: file_validation_details, file_pipeline_status: file_pipeline_status }), (pending_check || resolver_running) && (_jsx("div", { className: "mt-3", children: resolver_running && !pending_check ? (_jsx(ResolutionStatusStrip, { check: {
                                    passed: false,
                                    delta: 0,
                                    sum_actual: 0,
                                    sum_expected: 0,
                                    file_notes: {},
                                    summary: 'Checking response against expected total…',
                                    ran_at: new Date().toISOString(),
                                }, loading: true })) : pending_check ? (_jsx(ResolutionStatusStrip, { check: pending_check, loading: resolver_running })) : null })), mismatch_active && resolution_mismatch_options && resolution_mismatch_options.length > 0 && (_jsxs("div", { className: "mt-3 rounded-lg border border-amber-200 bg-amber-50/50 p-3 dark:border-amber-900/40 dark:bg-amber-950/20", children: [_jsx("p", { className: "text-[10px] font-bold uppercase tracking-[0.08em] text-amber-700 dark:text-amber-300 mb-2", children: "How would you like to proceed?" }), _jsx(ClarificationResponseForm, { response_options: resolution_mismatch_options, read_only: read_only, on_submit: handle_mismatch_submit, file_manager: file_manager, radio_accent: "accent-amber-600", submit_bg: "bg-amber-600 hover:bg-amber-700", submit_label: "Send response" })] }))] }) }))] }));
});
/** Action buttons (Resolve / Dismiss / Re-open) — extracted to reduce duplication */
function ActionButtons({ item, is_closed, on_resolve, on_dismiss, on_reopen, }) {
    return (_jsxs("div", { className: "flex items-center gap-1.5 flex-shrink-0", children: [item.status === 'responded' && on_resolve && (_jsx("button", { onClick: () => on_resolve(item.id), className: "px-2 py-1 text-xs font-medium rounded bg-green-100 text-green-700 hover:bg-green-200 dark:bg-green-900/30 dark:text-green-400 dark:hover:bg-green-900/50 transition-colors", children: "Resolve" })), (item.status === 'pending' || item.status === 'responded') && on_dismiss && (_jsx("button", { onClick: () => on_dismiss(item.id), className: "px-2 py-1 text-xs font-medium rounded bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700 transition-colors", children: "Dismiss" })), is_closed && on_reopen && (_jsx("button", { onClick: () => on_reopen(item.id), className: "px-2 py-1 text-xs font-medium rounded bg-amber-100 text-amber-700 hover:bg-amber-200 dark:bg-amber-900/30 dark:text-amber-400 dark:hover:bg-amber-900/50 transition-colors", children: "Re-open" }))] }));
}
//# sourceMappingURL=clarification_item_body.js.map