import { type ActiveCategory } from '../types';

import {
  promoteChipOrder,
  resolveCategoryChipLayout,
} from './categoriesFilters';

const makeCategories = (count: number): ActiveCategory[] =>
  Array.from({ length: count }, (_, index) => ({
    id: index + 1,
    name: `Category ${index + 1}`,
  }));

describe('resolveCategoryChipLayout', () => {
  it('returns empty lists when there are no active categories', () => {
    expect(
      resolveCategoryChipLayout({
        activeCategories: undefined,
        selectedCategoryId: null,
        chipOrderIds: [],
      }),
    ).toEqual({
      visibleCategories: [],
      hiddenCategories: [],
    });
  });

  it('shows the first 4 categories by default when chip order is not set', () => {
    const activeCategories = makeCategories(6);

    const { visibleCategories, hiddenCategories } = resolveCategoryChipLayout({
      activeCategories,
      selectedCategoryId: null,
      chipOrderIds: [],
    });

    expect(visibleCategories.map(({ id }) => id)).toEqual([1, 2, 3, 4]);
    expect(hiddenCategories.map(({ id }) => id)).toEqual([5, 6]);
  });

  it('uses custom chip order from the drawer', () => {
    const activeCategories = makeCategories(6);

    const { visibleCategories, hiddenCategories } = resolveCategoryChipLayout({
      activeCategories,
      selectedCategoryId: 5,
      chipOrderIds: [5, 1, 2, 3],
    });

    expect(visibleCategories.map(({ id }) => id)).toEqual([5, 1, 2, 3]);
    expect(hiddenCategories.map(({ id }) => id)).toEqual([4, 6]);
  });

  it('promotes a deep-linked category into the chip strip when it is hidden', () => {
    const activeCategories = makeCategories(6);

    const { visibleCategories, hiddenCategories } = resolveCategoryChipLayout({
      activeCategories,
      selectedCategoryId: 5,
      chipOrderIds: [],
    });

    expect(visibleCategories.map(({ id }) => id)).toEqual([5, 1, 2, 3]);
    expect(hiddenCategories.map(({ id }) => id)).toEqual([4, 6]);
  });

  it('does not reorder chips when the selected category is already visible', () => {
    const activeCategories = makeCategories(6);

    const { visibleCategories } = resolveCategoryChipLayout({
      activeCategories,
      selectedCategoryId: 2,
      chipOrderIds: [],
    });

    expect(visibleCategories.map(({ id }) => id)).toEqual([1, 2, 3, 4]);
  });

  it('keeps custom chip order when no category is selected in the URL', () => {
    const activeCategories = makeCategories(6);

    const { visibleCategories } = resolveCategoryChipLayout({
      activeCategories,
      selectedCategoryId: null,
      chipOrderIds: [5, 1, 2, 3],
    });

    expect(visibleCategories.map(({ id }) => id)).toEqual([5, 1, 2, 3]);
  });
});

describe('promoteChipOrder', () => {
  it('places the selected category first and keeps up to three previous chips', () => {
    expect(promoteChipOrder(9, [1, 2, 3, 4])).toEqual([9, 1, 2, 3]);
  });
});
