import React, { useCallback, useMemo } from "react";

import classNames from "classnames";

import { Marquee } from "@enact/sandstone/Marquee";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";
import Spottable from "@enact/spotlight/Spottable";

import { $L } from "../../utils/helperMethods";
import css from "./THeader.module.less";

const Container = SpotlightContainerDecorator(
  { enterTo: "last-focused" },
  "div"
);
const SpottableComponent = Spottable("button");

export default function THeader({
  title,
  className,
  onBackButton,
  onSpotlightUp,
  onSpotlightLeft,
  marqueeDisabled = true,
  onClick,
  ariaLabel,
  children,
  ...rest
}) {
  const convertedTitle = useMemo(() => {
    if (title) {
      const cleanedTitle = title.replace(/(\r\n|\n)/g, "");
      return $L(marqueeDisabled ? title : cleanedTitle);
    }
  }, [marqueeDisabled, title]);

  const _onClick = useCallback(
    (e) => {
      if (onClick) {
        onClick(e);
      }
    },
    [onClick]
  );

  const _onSpotlightUp = (e) => {
    if (onSpotlightUp) {
      onSpotlightUp(e);
    }
  };

  const _onSpotlightLeft = (e) => {
    if (onSpotlightLeft) {
      onSpotlightLeft(e);
    }
  };

  return (
    <Container className={classNames(css.tHeader, className)} {...rest}>
      {onBackButton && (
        <SpottableComponent
          className={css.button}
          onClick={_onClick}
          spotlightId={"spotlightId_backBtn"}
          onSpotlightUp={_onSpotlightUp}
          onSpotlightLeft={_onSpotlightLeft}
          aria-label="Back"
          role="button"
        />
      )}
      <Marquee
        marqueeOn="render"
        className={css.title}
        marqueeDisabled={marqueeDisabled}
        aria-label={ariaLabel}
      >
        {convertedTitle && (
          <span dangerouslySetInnerHTML={{ __html: convertedTitle }} />
        )}
      </Marquee>
      {children}
    </Container>
  );
}
