import * as React from 'react';
import styled from 'styled-components';

import type { JSX } from 'react';
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
function slicer(str: string, arr: string[]): any[] {
  const markOpenIndex = str.indexOf('<mark>');
  const markCloseIndex = str.indexOf('</mark>');

  if (markOpenIndex !== -1 && markCloseIndex !== -1) {
    const pre = str.slice(0, markOpenIndex);
    const entry = str.slice(markOpenIndex + 6, markCloseIndex);
    const suf = str.slice(markCloseIndex + 7, str.length);
    return (arr = [...arr, pre, { entry }, ...slicer(suf, arr)]);
  } else return [...arr, str];
}

export function searchHighlight(text: string | string[]): JSX.Element | string {
  if (!Array.isArray(text)) {
    const arr = slicer(text, []);
    if (arr.length === 1) return text;

    return (
      <span>
        {arr.map((item, index) => {
          if (typeof item === 'object') {
            return <Highlight key={index}>{item.entry}</Highlight>;
          } else {
            return item;
          }
        })}
      </span>
    );
  }

  const [pre, entry, suf] = text;
  return (
    <span data-component-name="Search/SearchHighlight">
      {pre}
      <Highlight>{entry}</Highlight>
      {suf}
    </span>
  );
}

const Highlight = styled.span`
  background-color: var(--search-highlight-bg-color);
  color: var(--search-highlight-text-color);
`;
