import type {
  SectionData,
  CombinedOptionsType,
  SelectOptionType,
} from './types';

export const isSections = <V, T extends SelectOptionType<V>>(
  options: CombinedOptionsType<V, T>
): options is SectionData<V, T>[] => {
  const firstOption = options[0];

  return (
    firstOption !== undefined &&
    (firstOption as SectionData<V, T>).category !== undefined
  );
};

export const toSections = <V, T extends SelectOptionType<V>>(
  options: CombinedOptionsType<V, T>
): SectionData<V, T>[] => {
  if (isSections(options)) {
    return options;
  }

  return [{ category: '', data: options }];
};

export const toFlatOptions = <V, T extends SelectOptionType<V>>(
  options: CombinedOptionsType<V, T>
): SelectOptionType<V>[] => {
  if (isSections(options)) {
    return options.flatMap((opt) => opt.data);
  }

  return options;
};

type ScrollParams = {
  itemIndex: number;
  sectionIndex: number;
};

export const getScrollParams = <V, T extends SelectOptionType<V>>(
  value: V,
  sections: SectionData<V, T>[]
): ScrollParams => {
  let itemIndex = -1;

  const sectionIndex = sections.findIndex((section) => {
    itemIndex = section.data.findIndex((opt) => opt.value === value);
    return itemIndex !== -1;
  });

  return {
    sectionIndex: sectionIndex < 0 ? 0 : sectionIndex,
    itemIndex: itemIndex < 0 ? 0 : itemIndex,
  };
};
