/**
 * use_clarifications - Hook for reading/writing clarification state from form_data.
 *
 * Clarifications are stored at form_data['__clarifications'] as ClarificationItem[].
 * This follows the existing __files_* pattern for metadata stored alongside field values.
 */
'use client';
import { useMemo, useCallback } from 'react';
/** Storage key in form_data */
export const CLARIFICATIONS_KEY = '__clarifications';
/**
 * Extract clarification items from form_data.
 * Returns empty array if key doesn't exist or isn't an array.
 */
export function get_clarifications(form_data) {
    const raw = form_data[CLARIFICATIONS_KEY];
    if (!Array.isArray(raw))
        return [];
    return raw;
}
/**
 * Hook for managing clarification state stored in form_data.
 *
 * @param form_data - Current form data object
 * @param on_form_data_change - Callback to update form_data (from FormView context)
 */
export function use_clarifications(form_data, on_form_data_change) {
    // Extract items from form_data
    const items = useMemo(() => get_clarifications(form_data), [form_data]);
    // Compute counts by status
    const counts = useMemo(() => {
        const result = { pending: 0, responded: 0, resolved: 0, dismissed: 0, total: 0 };
        for (const item of items) {
            result.total++;
            if (item.status in result) {
                result[item.status]++;
            }
        }
        return result;
    }, [items]);
    const has_pending = counts.pending > 0;
    // Collect file IDs referenced by active (pending/responded) clarifications
    const error_file_ids = useMemo(() => {
        const ids = new Set();
        for (const item of items) {
            if (item.status === 'pending' || item.status === 'responded') {
                for (const ref of item.doc_references) {
                    ids.add(ref.file_id);
                }
            }
        }
        return ids;
    }, [items]);
    // Helper to persist updated items
    const persist = useCallback((updated_items) => {
        if (!on_form_data_change)
            return;
        on_form_data_change({
            ...form_data,
            [CLARIFICATIONS_KEY]: updated_items,
        });
    }, [form_data, on_form_data_change]);
    // Get clarifications for a specific field
    const get_field_clarifications = useCallback((field_id) => {
        return items.filter(item => item.target_field_id === field_id);
    }, [items]);
    // Get pending count for a field
    const get_pending_count = useCallback((field_id) => {
        return items.filter(item => item.target_field_id === field_id && item.status === 'pending').length;
    }, [items]);
    // Add a new clarification
    const add_clarification = useCallback((item) => {
        persist([...items, item]);
    }, [items, persist]);
    // Update with a response
    const update_response = useCallback((id, response) => {
        const updated = items.map(item => {
            if (item.id !== id)
                return item;
            return {
                ...item,
                status: 'responded',
                response_choice: response.response_choice ?? item.response_choice,
                user_comment: response.user_comment ?? item.user_comment,
                response_files: response.response_files ?? item.response_files,
                updated_at: new Date().toISOString(),
            };
        });
        persist(updated);
    }, [items, persist]);
    // Resolve a clarification
    const resolve = useCallback((id) => {
        const updated = items.map(item => {
            if (item.id !== id)
                return item;
            return {
                ...item,
                status: 'resolved',
                updated_at: new Date().toISOString(),
            };
        });
        persist(updated);
    }, [items, persist]);
    // Dismiss a clarification
    const dismiss = useCallback((id) => {
        const updated = items.map(item => {
            if (item.id !== id)
                return item;
            return {
                ...item,
                status: 'dismissed',
                updated_at: new Date().toISOString(),
            };
        });
        persist(updated);
    }, [items, persist]);
    // Re-open a resolved/dismissed clarification
    const reopen = useCallback((id) => {
        const updated = items.map(item => {
            if (item.id !== id)
                return item;
            return {
                ...item,
                status: 'pending',
                updated_at: new Date().toISOString(),
            };
        });
        persist(updated);
    }, [items, persist]);
    // Upsert clarifications with deduplication by rule_id + target_field_id
    const upsert_clarifications = useCallback((new_items) => {
        let updated = [...items];
        for (const new_item of new_items) {
            // Find existing active item with same rule_id + target_field_id
            const match_index = new_item.rule_id
                ? updated.findIndex(existing => existing.rule_id === new_item.rule_id &&
                    existing.target_field_id === new_item.target_field_id &&
                    (existing.status === 'pending' || existing.status === 'responded'))
                : -1;
            if (match_index >= 0) {
                // Update existing in place: new content, reset status, preserve id/created_at
                const existing = updated[match_index];
                updated[match_index] = {
                    ...existing,
                    issue_description: new_item.issue_description,
                    validation_details: new_item.validation_details,
                    doc_references: new_item.doc_references,
                    response_options: new_item.response_options,
                    status: 'pending',
                    // Clear response data
                    response_choice: undefined,
                    user_comment: undefined,
                    response_files: [],
                    updated_at: new Date().toISOString(),
                };
            }
            else {
                // No match - append as new
                updated.push(new_item);
            }
        }
        persist(updated);
    }, [items, persist]);
    // Remove a doc reference; resolve the clarification if no references remain
    const remove_doc_reference = useCallback((clarification_id, file_id) => {
        const updated = items.map(item => {
            if (item.id !== clarification_id)
                return item;
            const remaining_refs = item.doc_references.filter(ref => ref.file_id !== file_id);
            return {
                ...item,
                doc_references: remaining_refs,
                status: (remaining_refs.length === 0 ? 'resolved' : item.status),
                updated_at: new Date().toISOString(),
            };
        });
        persist(updated);
    }, [items, persist]);
    return {
        items,
        get_field_clarifications,
        get_pending_count,
        has_pending,
        counts,
        error_file_ids,
        add_clarification,
        upsert_clarifications,
        update_response,
        resolve,
        dismiss,
        reopen,
        remove_doc_reference,
    };
}
//# sourceMappingURL=use_clarifications.js.map