import React, { memo, useCallback, useState } from "react";

import Spotlight from "@enact/spotlight";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";

import SectionTitle from "../../../components/SectionTitle/SectionTitle";
import { $L } from "../../../utils/helperMethods";
import css from "./TodaysDeals.module.less";
import TodaysDealsCard from "./TodaysDealsCard/TodaysDealsCard";

const STRING_CONF = {
  TODAYS_DEALS: "TODAY'S DEALS",
};

const Container = SpotlightContainerDecorator(
  { leaveFor: { right: "" }, enterTo: "last-focused" },
  "div"
);

const TodaysDeals = ({
  brandTsvInfo,
  handleItemFocus,
  order,
  shelfOrder,
  shelfTitle,
  spotlightId,
}) => {
  const [firstChk, setFirstChk] = useState(0);

  const _handleItemFocus = useCallback(() => {
    if (handleItemFocus) handleItemFocus(spotlightId, shelfOrder);

    const c = Spotlight.getCurrent();

    if (firstChk === 0) {
      if (c) {
        let cAriaLabel = c.getAttribute("aria-label");
        if (cAriaLabel) {
          cAriaLabel = "TODAY DEAL, Heading1," + cAriaLabel;
          c.setAttribute("aria-label", cAriaLabel);
        }
      }
      setFirstChk(1);
    } else if (firstChk === 1) {
      if (c) {
        let cAriaLabel = c.getAttribute("aria-label");
        if (cAriaLabel) {
          const newcAriaLabel = cAriaLabel.replace("TODAY DEAL, Heading1,", "");
          c.setAttribute("aria-label", newcAriaLabel);
        }
      }
    } else {
      return;
    }
  }, [handleItemFocus, firstChk]);

  return (
    <Container
      className={css.container}
      data-wheel-point
      data-shelf-order={order}
      spotlightId={spotlightId}
    >
      <SectionTitle
        title={$L(STRING_CONF.TODAYS_DEALS)}
        data-title="today's-deals"
      />
      <TodaysDealsCard
        brandTsvInfo={brandTsvInfo}
        handleItemFocus={_handleItemFocus}
        spotlightId={spotlightId}
        shelfOrder={shelfOrder}
        shelfTitle={shelfTitle}
      />
    </Container>
  );
};

export default memo(TodaysDeals);
