export const BI_ELEMENT_TYPE_ATTRIBUTE = 'data-element_type';
export const BI_SUB_ELEMENT_TYPE_ATTRIBUTE = 'data-sub_element_type';
export const BI_ACTION_DETAIL_ATTRIBUTE = 'data-action_detail';

export const BI_CONTAINER_ELEMENT_NAME = 'Navigation Menu';

export const getElementAttributes = (type: string, id: string | undefined, name: string) => ({
  [BI_ELEMENT_TYPE_ATTRIBUTE]: type,
  'data-element_id': id,
  'data-element_name': name,
});

export const getSubElementAttributes = (
  name: string,
  type: 'slide' | 'card' | 'tab contents' | 'main tile',
  index: number | undefined,
) => ({
  [BI_SUB_ELEMENT_TYPE_ATTRIBUTE]: type,
  'data-sub_element_name': name,
  'data-sub_element_index': index,
});

export const getItemAttributes = (
  name: string,
  format: 'image' | 'link' | 'button',
  actionDetail:
    | 'navigation'
    | 'scroll'
    | 'filter'
    | 'see more'
    | 'popup screen'
    | 'close'
    | 'play'
    | 'pause'
    | 'retry'
    | undefined,
  targetUrl: string | undefined,
  index: number | undefined,
) => ({
  [BI_ACTION_DETAIL_ATTRIBUTE]: actionDetail,
  'data-item_name': name,
  'data-item_format': format,
  'data-target_url': targetUrl,
  'data-item_index': index,
});

export type BIItemAttributes = ReturnType<typeof getItemAttributes>;

export const getElementAttributeValues = (containerElement: HTMLElement) => ({
  elementName: containerElement.dataset.element_name,
  elementType: containerElement.dataset.element_type,
  elementId: containerElement.dataset.element_id,
});

export const getSubElementAttributeValues = (subElement: HTMLElement) => ({
  subElementName: subElement.dataset.sub_element_name,
  subElementType: subElement.dataset.sub_element_type,
  subElementIndex: subElement.dataset.sub_element_index,
});

export const getItemAttributeValues = (actionItem: HTMLElement) => {
  const validLinkHref = (actionItem.tagName === 'A' && actionItem.getAttribute('href')) || undefined;

  return {
    itemName: actionItem.dataset.item_name ?? actionItem.textContent ?? undefined,
    itemIndex: actionItem.dataset.item_index,
    itemFormat: actionItem.dataset.item_format ?? (validLinkHref && 'link'),
    actionDetail: actionItem.dataset.action_detail ?? (validLinkHref && 'navigation'),
    targetUrl: actionItem.dataset.target_url ?? validLinkHref,
  };
};
