import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * Collapsible accordion for displaying table reference data (e.g., prior year rows)
 * Renders below the main table field when reference_data contains an array value.
 */
import { useState, useMemo } from 'react';
import { cn } from '../../../utils/cn.js';
import { format_currency } from '../../../utils/financial_format.js';
/** Muted reference header — distinct from the main table's dark header */
const REF_HEADER_STYLE = {
    backgroundColor: '#e2e8f0',
    color: '#475569',
    fontSize: '11px',
    fontWeight: '600',
};
export function TableReferenceAccordion({ reference, columns, config, class_name }) {
    const [is_open, set_is_open] = useState(false);
    const rows = reference.value;
    if (!Array.isArray(rows) || rows.length === 0)
        return null;
    // Compute subtotals when more than 1 row
    const subtotals = useMemo(() => {
        if (rows.length <= 1)
            return null;
        const has_subtotal_cols = columns.some(c => c.subtotal);
        if (!has_subtotal_cols)
            return null;
        const result = {};
        for (const col of columns) {
            if (!col.subtotal)
                continue;
            let sum = 0;
            for (const row of rows) {
                const val = row[col.id];
                const num = typeof val === 'number' ? val : parseFloat(String(val));
                if (!isNaN(num))
                    sum += num;
            }
            result[col.id] = sum;
        }
        return result;
    }, [rows, columns]);
    const render_cell = (col, cell_value) => {
        if (cell_value == null || cell_value === '')
            return _jsx("span", { className: "text-gray-300", children: "\u2014" });
        const col_type = col.field_type || 'text';
        const str_val = String(cell_value);
        switch (col_type) {
            case 'currency': {
                const num = typeof cell_value === 'number' ? cell_value : parseFloat(str_val);
                if (isNaN(num))
                    return str_val;
                const sym = col.currency_symbol || config.default_currency_symbol;
                const dec = col.decimal_places ?? config.default_decimal_places;
                return _jsx("span", { className: "text-right block", children: format_currency(num, sym, dec) });
            }
            case 'number': {
                const num = typeof cell_value === 'number' ? cell_value : parseFloat(str_val);
                if (isNaN(num))
                    return str_val;
                const dec = col.decimal_places ?? 0;
                return _jsx("span", { className: "text-right block", children: num.toFixed(dec) });
            }
            case 'boolean':
                return _jsx("span", { children: Boolean(cell_value) ? 'Yes' : 'No' });
            case 'option': {
                const opt = col.options?.find(o => o.value === str_val);
                return _jsx("span", { children: opt?.label || str_val });
            }
            default:
                return _jsx("span", { children: str_val });
        }
    };
    const label_text = reference.label || 'Reference';
    const year_badge = reference.tax_year ? String(reference.tax_year) : undefined;
    return (_jsxs("div", { className: cn('cls_table_reference_accordion', class_name), children: [_jsxs("button", { type: "button", className: cn('flex items-center gap-2 w-full text-left px-2.5 py-1.5 rounded-md text-xs transition-colors', 'border border-dashed border-slate-300 bg-slate-50/80', 'hover:bg-slate-100 hover:border-slate-400'), onClick: () => set_is_open(!is_open), children: [_jsx("svg", { className: cn('w-3 h-3 shrink-0 transition-transform text-slate-400', is_open && '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: "inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-semibold bg-amber-100 text-amber-700 border border-amber-200", children: label_text }), year_badge && (_jsx("span", { className: "inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-slate-200 text-slate-600", children: year_badge })), _jsxs("span", { className: "text-[11px] text-slate-400", children: [rows.length, " ", rows.length === 1 ? 'row' : 'rows'] })] }), is_open && (_jsx("div", { className: "mt-1 ml-4 mr-2 rounded overflow-hidden border border-slate-200/80", children: _jsxs("table", { className: "cls_table_reference_table w-full border-collapse text-xs", children: [_jsx("thead", { children: _jsx("tr", { children: columns.map((col) => (_jsx("th", { className: cn('text-left', (col.field_type === 'number' || col.field_type === 'currency') && 'text-right'), style: {
                                        ...REF_HEADER_STYLE,
                                        padding: '4px 8px',
                                        ...(col.width ? { width: col.width } : {}),
                                    }, children: col.label }, col.id))) }) }), _jsx("tbody", { children: rows.map((row, row_index) => (_jsx("tr", { className: cn('border-b border-slate-100', row_index % 2 === 1 ? 'bg-slate-50/60' : 'bg-white'), children: columns.map((col) => (_jsx("td", { className: cn('px-2 py-0.5 text-slate-600', (col.field_type === 'number' || col.field_type === 'currency') && 'text-right'), children: render_cell(col, row[col.id]) }, col.id))) }, row_index))) }), subtotals && (_jsx("tfoot", { children: _jsx("tr", { className: "bg-slate-100/80 font-semibold text-slate-700", style: { borderTop: '1px solid #cbd5e1' }, children: columns.map((col, col_index) => (_jsx("td", { className: cn('px-2 py-1', (col.field_type === 'number' || col.field_type === 'currency') && 'text-right'), children: col.subtotal && subtotals[col.id] !== undefined ? (col.field_type === 'currency'
                                        ? format_currency(subtotals[col.id], col.currency_symbol || config.default_currency_symbol, col.decimal_places ?? config.default_decimal_places)
                                        : subtotals[col.id].toFixed(col.decimal_places ?? 0)) : col_index === 0 ? (_jsx("span", { style: { opacity: 0.5 }, children: "Total" })) : null }, col.id))) }) }))] }) }))] }));
}
//# sourceMappingURL=table_reference_accordion.js.map