export const CHAT_MESSAGE_IMAGE_GRID_MIN_COUNT = 2;
export const CHAT_MESSAGE_IMAGE_GRID_MAX_VISIBLE = 4;

export type ChatMessageImageGridVariant = 'none' | 'pair' | 'triple' | 'quad';

export interface ChatMessageImageGridImageCell {
  kind: 'image';
  index: number;
}

export interface ChatMessageImageGridOverflowCell {
  kind: 'overflow';
  hiddenCount: number;
}

export type ChatMessageImageGridCell = ChatMessageImageGridImageCell | ChatMessageImageGridOverflowCell;

export interface ChatMessageImageGridLayout {
  useGrid: boolean;
  variant: ChatMessageImageGridVariant;
  cells: ChatMessageImageGridCell[];
}

export function buildChatMessageImageGridLayout(imageCount: number): ChatMessageImageGridLayout {
  if (imageCount < CHAT_MESSAGE_IMAGE_GRID_MIN_COUNT) {
    return {
      useGrid: false,
      variant: 'none',
      cells: []
    };
  }

  if (imageCount === 2) {
    return {
      useGrid: true,
      variant: 'pair',
      cells: [{ kind: 'image', index: 0 }, { kind: 'image', index: 1 }]
    };
  }

  if (imageCount === 3) {
    return {
      useGrid: true,
      variant: 'triple',
      cells: [
        { kind: 'image', index: 0 },
        { kind: 'image', index: 1 },
        { kind: 'image', index: 2 }
      ]
    };
  }

  if (imageCount === CHAT_MESSAGE_IMAGE_GRID_MAX_VISIBLE) {
    return {
      useGrid: true,
      variant: 'quad',
      cells: [
        { kind: 'image', index: 0 },
        { kind: 'image', index: 1 },
        { kind: 'image', index: 2 },
        { kind: 'image', index: 3 }
      ]
    };
  }

  return {
    useGrid: true,
    variant: 'quad',
    cells: [
      { kind: 'image', index: 0 },
      { kind: 'image', index: 1 },
      { kind: 'image', index: 2 },
      {
        kind: 'overflow',
        hiddenCount: imageCount - 3
      }
    ]
  };
}

export function formatChatMessageImageOverflowLabel(hiddenCount: number): string {
  return `+${hiddenCount}`;
}
