/**
 * This Source Code is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Copyright (c) Infonomic Company Limited
 */
import cx from 'clsx';
import { PickerCell, resolveFallbackDisplayField, resolveRowLabel } from './relation-display';
import styles from './relation-summary.module.css';
export function RelationSummary({ targetDefinition, targetAdminConfig, displayField, value, cachedRecord, }) {
    const pickerColumns = targetAdminConfig?.itemView;
    // Unresolved (deleted target).
    if (value._resolved === false) {
        return (<div className={cx('byline-relation-summary-stack', styles.stack)}>
        <span className={cx('byline-relation-summary-kind', styles.kind)}>
          {targetDefinition.labels.singular}
        </span>
        <span className={cx('byline-relation-summary-value-mono byline-relation-summary-missing', styles['value-mono'], styles.missing)}>
          (target not found) {value.targetDocumentId}
        </span>
      </div>);
    }
    // Prefer the populated envelope's document; fall back to the cached
    // picker record; finally fall back to rendering just the raw ref.
    const record = (value._resolved === true && !value._cycle && value.document) || cachedRecord || null;
    if (record && pickerColumns && pickerColumns.length > 0) {
        return (<div className={cx('byline-relation-summary-row', styles.row)}>
        {pickerColumns.map((col) => (<PickerCell key={String(col.fieldName)} column={col} record={record}/>))}
      </div>);
    }
    const resolvedDisplayField = displayField ??
        targetDefinition.useAsTitle ??
        resolveFallbackDisplayField(targetDefinition) ??
        null;
    const label = record ? resolveRowLabel(record, resolvedDisplayField) : null;
    return (<div className={cx('byline-relation-summary-stack', styles.stack)}>
      <span className={cx('byline-relation-summary-kind', styles.kind)}>
        {targetDefinition.labels.singular}
      </span>
      {label ? (<span className={cx('byline-relation-summary-value', styles.value)}>{label}</span>) : (<span className={cx('byline-relation-summary-value-mono', styles['value-mono'])}>
          {value.targetDocumentId}
        </span>)}
    </div>);
}
