import * as GTM from '@assets/filters/common/utils/gtm';

import type { FiltersState } from '@assets/filters/state';
import type { Label } from '@assets/filters/common/state-parsers/filterValuesCache';

export function trackLabelsChange(
   config: FiltersState['config']['labels'],
   oldState: number[],
   newState: number[],
) {
   let active: boolean;
   let changedLabel: Label | null = null;

   if (oldState.length > newState.length) {
      changedLabel = config.find(label => !newState.includes(label.id)) ?? null;
      active = false;
   } else if (oldState.length < newState.length) {
      changedLabel = config.find(label => !oldState.includes(label.id)) ?? null;
      active = true;
   }

   if (changedLabel === null) {
      // no change

      return;
   }

   GTM.dataCollector.applyFilterLabels(changedLabel, active);
}
