import { defineCellType } from '../../types';
import { ReferenceEditWrapper } from '../reference/ReferenceEditWrapper';
import { MultiReferenceView } from './View';
import { MultiReferenceEdit } from './Edit';
import type { MultiReferenceValue } from './types';

export { MultiReferenceView, MultiReferenceEdit };
export type {
  MultiReferenceValue,
  ReferenceItem,
  RefSchema,
  ReferenceTypeConfig,
} from './types';

export const multiReferenceCellType = defineCellType<MultiReferenceValue>({
  type: 'multiReference',
  ViewComponent: MultiReferenceView,
  EditComponent: MultiReferenceEdit,
  EditWrapper: ReferenceEditWrapper,
  // Compact, single-line JSON for clipboard TSV (no pretty-printing).
  serialize: (value) => (value && value.length ? JSON.stringify(value) : ''),
  deserialize: (raw) => {
    if (!raw) {
      return null;
    }
    try {
      const parsed = JSON.parse(raw);
      if (Array.isArray(parsed)) {
        return parsed;
      }
    } catch {}
    return null;
  },
  editable: true,
  clearable: true,
  // Single click opens the chip editor (parity with the UX handoff).
  editOnClick: () => true,
  // Enter edit on a printable key without clearing the existing chips — the
  // MultiSelect input takes over typing once edit opens.
  onTypeToEdit: () => ({}),
});
