/**
 * UnifiedFieldControls component
 *
 * A reusable component for rendering field control icons consistently
 * across both form view and summary view.
 *
 * Features:
 * - Role-based visibility and enabled states via icons_behaviour
 * - Consistent icon order and sizing
 * - Kebab menu consolidation for 2+ non-extracted controls
 * - Data OK auto-actions (auto-hide, auto-lock)
 */
'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React, { useState, useCallback, useMemo, useEffect } from 'react';
import { cn } from '../../../utils/cn.js';
import { HazoChat } from 'hazo_chat';
import { createClientLogger } from 'hazo_logs/ui';
import { DataOkMultiState } from '../../data_ok_multi_state.js';
import { CollabFormNotesIcon, CollabFormChatIcon, CollabFormVisibilityIcon, CollabFormLockIcon, CollabFormSkipIcon, CollabFormDeleteFieldIcon, CollabFormEditFieldConfigIcon, CollabFormDeleteFieldStructureIcon, resolve_chat_status as resolve_chat_status_helper, } from '../../hazo_collab_form_base.js';
import { use_control_resolution } from './use_control_resolution.js';
import { KebabMenu } from './kebab_menu.js';
import { HiPencil, HiCheckCircle } from 'react-icons/hi';
import { IoRefresh } from 'react-icons/io5';
// Create default logger for HazoChat
const chat_logger = createClientLogger({ packageName: 'hazo_chat' });
import { NOTES_ICON_SIZE } from './constants.js';
import { ClarificationBadge } from '../../clarification/clarification_badge.js';
/**
 * UnifiedFieldControls component
 */
export function UnifiedFieldControls({ field_id, icons_behaviour, active_role, metadata, callbacks, config, fallback_visibility, fallback_enabled, auto_actions, class_name, clarification_count, on_clarification_click, }) {
    const [chat_open, set_chat_open] = useState(false);
    // Resolve control states using the hook
    const { controls, inline_controls, kebab_controls, show_kebab, has_kebab_indicator, kebab_indicator_status, } = use_control_resolution(icons_behaviour, active_role, metadata, fallback_visibility, fallback_enabled);
    // Resolve effective chat status
    const effective_chat_status = useMemo(() => {
        return resolve_chat_status_helper(metadata.chat_status, metadata.has_chat_messages);
    }, [metadata.chat_status, metadata.has_chat_messages]);
    // Helper to check if notes exist
    const has_notes_data = useMemo(() => {
        return (metadata.notes?.length ?? 0) > 0;
    }, [metadata.notes]);
    // Handle data OK change with auto-actions
    const handle_data_ok_change = useCallback((value) => {
        callbacks.on_data_ok_change?.(value);
        // Auto-actions when data_ok becomes 'ok' or true
        const is_ok = value === 'ok' || value === true;
        const is_not_ok = value === 'not_ok' || value === false;
        if (auto_actions?.on_data_ok_protected) {
            if (is_ok) {
                callbacks.on_lock_change?.(true);
            }
            else if (is_not_ok) {
                callbacks.on_lock_change?.(false);
            }
        }
        if (auto_actions?.on_data_ok_hidden) {
            if (is_ok) {
                callbacks.on_visibility_change?.('hidden');
            }
            else if (is_not_ok) {
                callbacks.on_visibility_change?.('visible');
            }
        }
    }, [callbacks, auto_actions]);
    // Compute effective hidden_states for data_ok by combining config and role-based allowed_values
    const data_ok_hidden_states = useMemo(() => {
        const all_states = ['ok', 'not_ok', 'pending'];
        const base_hidden = config?.data_ok_hidden_states ?? [];
        const allowed = controls.control_data_ok.allowed_values;
        // If no allowed_values restriction, just use base hidden states
        if (!allowed || allowed.length === 0) {
            return base_hidden.length > 0 ? base_hidden : undefined;
        }
        // Add states NOT in allowed_values to hidden
        const hidden_from_role = all_states.filter(state => !allowed.includes(state));
        // Combine base hidden with role-based hidden, deduplicating
        const combined = [...new Set([...base_hidden, ...hidden_from_role])];
        return combined.length > 0 ? combined : undefined;
    }, [config?.data_ok_hidden_states, controls.control_data_ok.allowed_values]);
    // Render Data OK control
    // Note: Data OK is always borderless to match form view styling
    const render_data_ok = useCallback(() => {
        const state = controls.control_data_ok;
        if (!state.visible)
            return null;
        const data_ok_mode = config?.data_ok_mode ?? 'checkbox';
        const data_ok_value = metadata.data_ok;
        const is_editable = state.enabled;
        // Multi-state mode
        if (data_ok_mode === 'multi_state') {
            const value = typeof data_ok_value === 'string'
                ? data_ok_value
                : data_ok_value === true ? 'ok' : 'not_ok';
            return (_jsx(DataOkMultiState, { value: value, onChange: (new_value) => handle_data_ok_change(new_value), disabled: !is_editable, size: "sm", interaction_mode: is_editable ? 'click-cycle' : 'click-only', show_border: false, hidden_states: data_ok_hidden_states, className: "cls_unified_data_ok" }));
        }
        // Checkbox mode - use DataOkMultiState with boolean conversion
        const state_value = data_ok_value === true ? 'ok' : 'not_ok';
        return (_jsx(DataOkMultiState, { value: state_value, onChange: (new_value) => handle_data_ok_change(new_value === 'ok'), disabled: !is_editable, size: "sm", interaction_mode: is_editable ? 'click-cycle' : 'click-only', show_border: false, hidden_states: data_ok_hidden_states, className: "cls_unified_data_ok" }));
    }, [controls.control_data_ok, metadata.data_ok, config, handle_data_ok_change, data_ok_hidden_states]);
    // Render Complete checkbox control
    const render_complete = useCallback(() => {
        const state = controls.control_complete;
        if (!state.visible)
            return null;
        const is_complete = metadata.complete === true;
        const can_click = state.enabled && !!callbacks.on_complete_change;
        return (_jsx("button", { type: "button", onClick: can_click ? () => callbacks.on_complete_change(!is_complete) : undefined, disabled: !can_click, className: cn('inline-flex items-center justify-center flex-shrink-0 transition-colors rounded', state.show_border && 'border border-border/40 p-0.5', can_click ? 'cursor-pointer hover:opacity-70' : 'cursor-default opacity-60'), title: is_complete ? 'Marked complete' : 'Mark as complete', "aria-label": is_complete ? 'Marked complete' : 'Mark as complete', children: is_complete ? (_jsx(HiCheckCircle, { className: "h-4 w-4 text-green-500" })) : (_jsx(HiCheckCircle, { className: "h-4 w-4 text-muted-foreground/40" })) }, "control_complete"));
    }, [controls.control_complete, metadata.complete, callbacks.on_complete_change]);
    // Render Skip control
    const render_skip = useCallback(() => {
        const state = controls.control_skip;
        if (!state.visible)
            return null;
        return (_jsx(CollabFormSkipIcon, { label: config?.label ?? field_id, skipped: metadata.skipped === true, on_skip_change: callbacks.on_skip_change, size: "sm", editable: state.enabled, borderless: !state.show_border }));
    }, [controls.control_skip, metadata.skipped, callbacks, config, field_id]);
    // Render Notes control
    const render_notes = useCallback(() => {
        const state = controls.control_notes;
        if (!state.visible)
            return null;
        // Build notes props based on mode
        const notes_mode = config?.notes_mode ?? 'controlled';
        const notes_props = notes_mode === 'controlled'
            ? {
                notes: metadata.notes || [],
                on_notes_change: state.enabled ? callbacks.on_notes_change : undefined,
                has_notes: has_notes_data,
            }
            : {
            // In API mode, let HazoNotesIcon manage notes via hazo_notes API
            };
        return (_jsx(CollabFormNotesIcon, { label: config?.label ?? field_id, ...notes_props, disabled: !state.enabled, current_user: config?.current_user, field_data_id: config?.field_data_id ?? field_id, icon_size: NOTES_ICON_SIZE, show_border: state.show_border, panel_style: config?.notes_panel_style, background_color: config?.notes_background_color, save_mode: config?.notes_save_mode }));
    }, [controls.control_notes, metadata.notes, has_notes_data, callbacks, config, field_id]);
    // Render Chat control
    const render_chat = useCallback(() => {
        const state = controls.control_chat;
        if (!state.visible)
            return null;
        return (_jsx(CollabFormChatIcon, { label: config?.label ?? field_id, on_click: state.enabled ? () => set_chat_open(!chat_open) : () => { }, button_disabled: !state.enabled, chat_status: effective_chat_status, size: "sm", borderless: !state.show_border }));
    }, [controls.control_chat, config, field_id, chat_open, effective_chat_status]);
    // Render Visibility control
    const render_visibility = useCallback(() => {
        const state = controls.control_visibility;
        if (!state.visible)
            return null;
        return (_jsx(CollabFormVisibilityIcon, { label: field_id, visibility: metadata.visibility || 'visible', on_visibility_change: callbacks.on_visibility_change, user_role: "author", size: "sm", editable: state.enabled, borderless: !state.show_border }));
    }, [controls.control_visibility, metadata.visibility, callbacks, field_id]);
    // Render Lock control
    const render_lock = useCallback(() => {
        const state = controls.control_lock;
        if (!state.visible)
            return null;
        return (_jsx(CollabFormLockIcon, { label: field_id, locked: metadata.locked === true, on_lock_change: callbacks.on_lock_change, user_role: "author", size: "sm", editable: state.enabled, borderless: !state.show_border }));
    }, [controls.control_lock, metadata.locked, callbacks, field_id]);
    // Render Delete control
    const render_delete = useCallback(() => {
        const state = controls.control_delete;
        if (!state.visible)
            return null;
        return (_jsx(CollabFormDeleteFieldIcon, { label: field_id, field_id: field_id, on_delete: state.enabled ? () => callbacks.on_delete?.() : undefined, disabled: !state.enabled, user_role: "author", size: "sm", is_deleted: metadata.deleted === true, borderless: !state.show_border }));
    }, [controls.control_delete, metadata.deleted, callbacks, field_id]);
    // Render Edit Field control (pencil icon - edit field config)
    const render_edit_field = useCallback(() => {
        const state = controls.control_edit_field;
        if (!state.visible)
            return null;
        return (_jsx(CollabFormEditFieldConfigIcon, { field_id: field_id, label: config?.label, on_click: state.enabled ? callbacks.on_edit_field : undefined, disabled: !state.enabled }));
    }, [controls.control_edit_field, callbacks, field_id, config?.label]);
    // Render Edit Group control (pencil icon - edit group config)
    const render_edit_group = useCallback(() => {
        const state = controls.control_edit_group;
        if (!state.visible)
            return null;
        return (_jsx(CollabFormEditFieldConfigIcon, { field_id: field_id, label: config?.label, on_click: state.enabled ? callbacks.on_edit_group : undefined, disabled: !state.enabled }));
    }, [controls.control_edit_group, callbacks, field_id, config?.label]);
    // Render Delete Field control (trash icon - remove field from form)
    const render_delete_field = useCallback(() => {
        const state = controls.control_delete_field;
        if (!state.visible)
            return null;
        return (_jsx(CollabFormDeleteFieldStructureIcon, { field_id: field_id, label: config?.label, on_click: state.enabled ? callbacks.on_delete_field : undefined, disabled: !state.enabled }));
    }, [controls.control_delete_field, callbacks, field_id, config?.label]);
    // Render Edit Elements control (pencil icon)
    const render_edit_elements = useCallback(() => {
        const state = controls.control_edit_elements;
        if (!state.visible)
            return null;
        return (_jsx("button", { type: "button", onClick: state.enabled ? callbacks.on_edit_elements : undefined, disabled: !state.enabled, className: cn('cls_control_edit_elements inline-flex h-7 w-7 items-center justify-center rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2', state.enabled
                ? 'hover:bg-accent hover:text-accent-foreground cursor-pointer'
                : 'opacity-50 cursor-not-allowed', state.show_border ? 'border border-input' : ''), "aria-label": "Edit element", title: "Edit element", children: _jsx(HiPencil, { className: "h-4 w-4 flex-shrink-0" }) }));
    }, [controls.control_edit_elements, callbacks]);
    // Render Re-validate control (refresh icon)
    const render_revalidate = useCallback(() => {
        const state = controls.control_revalidate;
        if (!state.visible)
            return null;
        // Only show when field/group actually has validation rules
        if (!metadata.has_validation_rules)
            return null;
        return (_jsx("button", { type: "button", onClick: state.enabled ? callbacks.on_revalidate : undefined, disabled: !state.enabled, className: cn('cls_control_revalidate inline-flex h-7 w-7 items-center justify-center rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2', state.enabled
                ? 'hover:bg-accent hover:text-accent-foreground cursor-pointer'
                : 'opacity-50 cursor-not-allowed', state.show_border ? 'border border-input' : ''), "aria-label": "Re-run validation rules", title: "Re-run validation rules", children: _jsx(IoRefresh, { className: "h-4 w-4 flex-shrink-0" }) }));
    }, [controls.control_revalidate, metadata.has_validation_rules, callbacks]);
    // Deprecation warning for control_delete
    useEffect(() => {
        if (controls.control_delete.visible) {
            console.warn('[hazo_collab_forms] control_delete is deprecated and will be removed in v2.0.0. ' +
                'Use control_edit_elements instead - delete functionality is integrated into edit dialogs.');
        }
    }, [controls.control_delete.visible]);
    // Map control names to render functions
    const render_control = useCallback((control) => {
        switch (control) {
            case 'control_data_ok':
                return render_data_ok();
            case 'control_complete':
                return render_complete();
            case 'control_skip':
                return render_skip();
            case 'control_notes':
                return render_notes();
            case 'control_chat':
                return render_chat();
            case 'control_visibility':
                return render_visibility();
            case 'control_lock':
                return render_lock();
            case 'control_delete':
                return render_delete();
            case 'control_edit_field':
                return render_edit_field();
            case 'control_edit_group':
                return render_edit_group();
            case 'control_delete_field':
                return render_delete_field();
            case 'control_edit_elements':
                return render_edit_elements();
            case 'control_revalidate':
                return render_revalidate();
            default:
                return null;
        }
    }, [render_data_ok, render_complete, render_skip, render_notes, render_chat, render_visibility, render_lock, render_delete, render_edit_field, render_edit_group, render_delete_field, render_edit_elements, render_revalidate]);
    // If no controls visible, return null
    const has_any_visible = Object.values(controls).some(c => c.visible);
    if (!has_any_visible) {
        return null;
    }
    return (_jsxs(_Fragment, { children: [_jsxs("div", { className: cn('cls_unified_field_controls flex items-center gap-1', class_name), children: [(clarification_count ?? 0) > 0 && (_jsx(ClarificationBadge, { count: clarification_count, on_click: on_clarification_click })), inline_controls.map((control) => (_jsx(React.Fragment, { children: render_control(control) }, control))), show_kebab && (_jsx(KebabMenu, { controls: kebab_controls, control_states: controls, metadata: metadata, callbacks: callbacks, config: config, has_indicator: has_kebab_indicator, indicator_status: kebab_indicator_status, field_id: field_id }))] }), chat_open && config?.chat_group_id && (_jsx("div", { className: "cls_unified_chat_container mt-2", children: _jsx(HazoChat, { ...{
                        chat_group_id: config.chat_group_id,
                        logger: chat_logger,
                        reference_id: field_id,
                        reference_type: "field",
                        api_base_url: config.chat_api_base_url,
                        timezone: config.chat_timezone,
                        read_only: config.chat_read_only,
                        log_polling: config.chat_log_polling ?? false,
                        on_close: () => set_chat_open(false),
                    } }) }))] }));
}
//# sourceMappingURL=unified_field_controls.js.map