// src/views/HomePanel/HomeBanner/HomeBanner.jsx

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

import { useDispatch, useSelector } from "react-redux";
import Spotlight from "@enact/spotlight";
import { SpotlightContainerDecorator } from "@enact/spotlight/SpotlightContainerDecorator";
import Spottable from "@enact/spotlight/Spottable";
import { $L } from "../../../utils/helperMethods";
import {
  setDefaultFocus,
  // setShowPopup,
  fetchCurrentUserHomeTerms,
} from "../../../actions/homeActions";
import {
  changeAppStatus,
  setOptionalTermsPopupShown,
  setOptionalTermsUserDecision,
  handleOptionalTermsAgree as handleOptionalTermsAgreeAction,
  handleOptionalTermsDecline,
  updateOptionalTermsAgreement,
} from "../../../actions/commonActions";
import { setMyPageTermsAgree } from "../../../actions/myPageActions";
import { pushPanel, popPanel } from "../../../actions/panelActions";
import { panel_names } from "../../../utils/Config";
import {
  startVideoPlayer,
  requestPlayControl,
  releasePlayControl,
} from "../../../actions/playActions";
import CustomImage from "../../../components/CustomImage/CustomImage";
import css from "./HomeBanner.module.less";
import Random from "./RandomUnit";
import Rolling from "./RollingUnit";
import TNewPopUp from "../../../components/TPopUp/TNewPopUp";
// import TButtonScroller from "../../../components/TButtonScroller/TButtonScroller";
import OptionalConfirm from "../../../components/Optional/OptionalConfirm";
// import * as Config from "../../../utils/Config";

// 새로운 비디오 유닛 컴포넌트 임포트
import PersistentVideoUnit from "./PersistentVideoUnit";
import RandomUnitNew from "./RandomUnit.new";
import SimpleVideoContainer from "./SimpleVideoContainer";

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

export default function HomeBanner({
  firstSpot,
  spotlightId,
  handleItemFocus,
  handleShelfFocus,
}) {
  const dispatch = useDispatch();
  const homeTopDisplayInfo = useSelector(
    (state) => state.home.homeTopDisplayInfo
  );

  const bannerDataList = useSelector(
    (state) => state.home.bannerData?.bannerInfos
  );

  const popupVisible = useSelector((state) => state.common.popup.popupVisible);

  const selectTemplate = useMemo(() => {
    return homeTopDisplayInfo.shptmTmplCd;
  }, [homeTopDisplayInfo]);

  const _handleItemFocus = useCallback(() => {
    if (handleItemFocus) {
      handleItemFocus();
    }
  }, [handleItemFocus]);

  // 🔽 [추가] 0번째 배너에 대한 영구 비디오 재생을 처리하는 useEffect
  // useEffect(() => {
  //   if (
  //     bannerDataList &&
  //     bannerDataList.length > 0 &&
  //     selectTemplate === "DSP00201"
  //   ) {
  //     const banner0Data = bannerDataList[0]?.bannerDetailInfos?.[0];

  //     if (banner0Data && banner0Data.showUrl) {
  //       // DOM 요소가 존재하는지 확인 후 실행
  //       console.log("[HomeBanner] banner0Data", banner0Data);
  //       const checkAndPlay = () => {
  //         const targetElement = document.querySelector(
  //           '[data-spotlight-id="banner0"]',
  //         );
  //         console.log("[HomeBanner] targetElement", targetElement);
  //         if (targetElement) {
  //           console.log("[HomeBanner] targetElement 존재");
  //           dispatch(
  //             startVideoPlayer({
  //               showUrl: banner0Data.showUrl,
  //               patnrId: banner0Data.patnrId,
  //               showId: banner0Data.showId,
  //               shptmBanrTpNm: "MEDIA",
  //               modal: true,
  //               modalContainerId: "banner0",
  //               spotlightDisable: true,
  //             }),
  //           );
  //           console.log("[HomeBanner] startVideoPlayer 호출");
  //         } else {
  //           // 요소가 없으면 잠시 후 재시도
  //           console.log("[HomeBanner] targetElement 없음");
  //           setTimeout(checkAndPlay, 100);
  //         }
  //       };

  //       // 다음 tick에서 실행하여 렌더링 완료 보장
  //       setTimeout(checkAndPlay, 0);
  //     }
  //   }
  // }, [dispatch, bannerDataList, selectTemplate]);

  // 🔽 [수정] 새로운 1번 배너 포커스/블러 핸들러
  const handleSecondBannerFocus = useCallback(() => {
    const secondBannerData = bannerDataList?.[1];
    if (secondBannerData) {
      const randomData =
        secondBannerData.bannerDetailInfos[secondBannerData.randomIndex];
      const videoInfo = {
        showUrl: randomData.showUrl,
        patnrId: randomData.patnrId,
        showId: randomData.showId,
        shptmBanrTpNm: randomData.showId ? randomData.shptmBanrTpNm : "MEDIA",
        lgCatCd: randomData.lgCatCd,
        chanId: randomData.brdcChnlId,
        modal: true,
        modalContainerId: "banner1",
        modalClassName: css.videoModal,
        isVerticalModal: true, // Assuming second banner is horizontal, so modal is vertical
      };

      // 중앙 제어 시스템에 '미리보기' 재생을 요청
      dispatch(requestPlayControl("banner1_preview", videoInfo));
    }

    if (handleItemFocus) {
      handleItemFocus();
    }
  }, [dispatch, bannerDataList, handleItemFocus]);

  const handleSecondBannerBlur = useCallback(() => {
    // 중앙 제어 시스템에 '미리보기' 제어권 해제를 요청
    dispatch(releasePlayControl("banner1_preview"));
  }, [dispatch]);

  const termsData = useSelector((state) => state.home.termsData);
  const termsIdMap = useSelector((state) => state.home.termsIdMap);
  const optionalTermsAvailable = useSelector(
    (state) => state.home.optionalTermsAvailable
  );
  const optionalTermsData = useSelector((state) => {
    // Chromium68 호환성을 위해 Optional Chaining 제거
    if (
      state.home.termsData &&
      state.home.termsData.data &&
      state.home.termsData.data.terms
    ) {
      return state.home.termsData.data.terms.find(
        (term) => term.trmsTpCd === "MST00405"
      );
    }
    return null;
  });
  const termsLoading = useSelector((state) => state.common.termsLoading);
  const isGnbOpened = useSelector((state) => state.common.isGnbOpened);
  // 선택약관 동의여부
  const introTermsAgree = useSelector((state) => state.common.introTermsAgree);

  // 새로운 Redux 상태: 선택약관 팝업 플로우 관리
  const optionalTermsPopupFlow = useSelector(
    (state) => state.common.optionalTermsPopupFlow
  );

  //------------------------------------------------------------------------------
  // 팝업표시 상태
  const [isOptionalConfirmVisible, setIsOptionalConfirmVisible] =
    useState(false);
  const [isOptionalTermsVisible, setIsOptionalTermsVisible] = useState(false);

  const [optionalTermsAgreed, setOptionalTermsAgreed] = useState(false);

  // 선택약관 팝업 표시 여부 ===================================================
  const shouldShowOptionalTermsPopup = useMemo(() => {
    console.log("[HomeBanner] Step 1: 상태 확인", {
      termsLoading,
      isGnbOpened,
      optionalTermsAvailable,
      optionalTermsPopupFlow,
    });

    // 1. 기본 조건 확인
    if (termsLoading || isGnbOpened || !optionalTermsAvailable) {
      console.log("[HomeBanner] Early return: 기본 조건 불만족");
      return false;
    }

    // 2. 새로운 Redux 상태 확인 (TV 환경 최적화)
    if (
      optionalTermsPopupFlow.popupShown ||
      optionalTermsPopupFlow.userDecision ||
      optionalTermsPopupFlow.agreedInSession
    ) {
      console.log(
        "[HomeBanner] Early return: 이미 처리됨",
        optionalTermsPopupFlow
      );
      return false;
    }

    // 3. 서버 데이터 확인
    const terms = termsData && termsData.data && termsData.data.terms;
    console.log("[HomeBanner] Step 2: termsData 확인", terms);
    if (!terms) {
      console.log("[HomeBanner] Early return: terms가 존재하지 않음");
      return false;
    }

    const optionalTerm = terms.find((term) => term.trmsTpCd === "MST00405");
    console.log("[HomeBanner] Step 3: optionalTerm 검색 결과", optionalTerm);

    const result = optionalTerm
      ? optionalTerm.trmsPopFlag === "Y" && optionalTerm.trmsAgrFlag === "N"
      : false;

    console.log("[HomeBanner] Step 4: 최종 결과", result);
    return result;
  }, [
    termsData,
    termsLoading,
    isGnbOpened,
    optionalTermsAvailable,
    optionalTermsPopupFlow,
  ]);

  // 선택약관 팝업 표시 여부 ===================================================

  const handleOptionalAgree = useCallback(() => {
    if (process.env.NODE_ENV === "development") {
      console.log("[HomeBanner] handleAgree Click");
    }

    if (!termsIdMap || Object.keys(termsIdMap).length === 0) {
      if (process.env.NODE_ENV === "development") {
        console.error("[HomeBanner] termsIdMap이 없습니다:", termsIdMap);
      }
      return;
    }

    const requiredTermTypes = ["MST00401", "MST00402", "MST00405"];
    const missingTerms = requiredTermTypes.filter((type) => !termsIdMap[type]);

    if (missingTerms.length > 0) {
      if (process.env.NODE_ENV === "development") {
        console.error("[HomeBanner] 누락된 약관 타입:", missingTerms);
      }
      return;
    }

    const termsList = [];

    if (termsIdMap["MST00401"]) {
      termsList.push(termsIdMap["MST00401"]); // 개인정보처리방침
    }
    if (termsIdMap["MST00402"]) {
      termsList.push(termsIdMap["MST00402"]); // 이용약관
    }
    if (termsIdMap["MST00405"]) {
      termsList.push(termsIdMap["MST00405"]); // 선택약관
    }

    const notTermsList = [];

    if (process.env.NODE_ENV === "development") {
      console.log("[HomeBanner] 현재 termsIdMap:", termsIdMap);
      console.log("[HomeBanner] 약관 동의 API 호출 파라미터:", {
        termsList,
        notTermsList,
      });
    }

    const callback = (response) => {
      if (response.retCode === "000" || response.retCode === 0) {
        if (process.env.NODE_ENV === "development") {
          console.log("[HomeBanner] 약관 동의 성공:", response);
        }
        // ✅ IntroPanel과 동일한 방식으로 Redux 상태 직접 업데이트 (API 호출 없이)
        dispatch(updateOptionalTermsAgreement(true));
        // 로컬 상태도 업데이트 (기존 로직 유지)
        setOptionalTermsAgreed(true);
      } else {
        if (process.env.NODE_ENV === "development") {
          console.error("[HomeBanner] 약관 동의 실패:", response);
        }
      }
    };

    if (process.env.NODE_ENV === "development") {
      console.log("[HomeBanner] 약관 동의 API 호출 payload:", {
        termsList,
        notTermsList,
      });
    }

    dispatch(setMyPageTermsAgree({ termsList, notTermsList }, callback));
  }, [dispatch, termsIdMap]);

  const handleOptionalTermsClick = useCallback(() => {
    console.log("[HomeBanner] 약관 자세히 보기 클릭");
    setIsOptionalConfirmVisible(false);
    setIsOptionalTermsVisible(true);
    // 약관 상세 팝업을 띄우는 로직 추가
  }, []);

  const handleOptionalAgreeClick = useCallback(() => {
    handleOptionalAgree();
    setIsOptionalConfirmVisible(false);
  }, [handleOptionalAgree]);

  const handleOptionalDeclineClick = useCallback(() => {
    console.log("[HomeBanner] 거절/다음에 하기 버튼 클릭");
    // ✅ 거절 상태 업데이트
    dispatch(updateOptionalTermsAgreement(false));
    setIsOptionalConfirmVisible(false);
  }, [dispatch]);

  // 선택약관 팝업 Close
  const handleTermsPopupClosed = useCallback(() => {
    setIsOptionalTermsVisible(false);
    setIsOptionalConfirmVisible(true);
    Spotlight.focus("optional-confirm-popup");
  }, []);

  // 선택약관 팝업 Agree
  const handleTermsPopupAgree = useCallback(() => {
    console.log("[HomeBanner] handleTermsPopupAgree");
    handleOptionalAgree();
    setIsOptionalTermsVisible(false);
  }, [handleOptionalAgree]);

  //------------------------------------------------------------------------------
  const _handleShelfFocus = useCallback(() => {
    if (handleShelfFocus) {
      handleShelfFocus();
    }
  }, [handleShelfFocus]);

  const defaultFocus = useMemo(() => {
    if (bannerDataList) {
      let targetIndex = 0;
      for (let i = 0; i < bannerDataList.length; i++) {
        const data = bannerDataList[i];
        let bannerDetailInfos = data.bannerDetailInfos;

        if (data.shptmDspyTpNm === "Random") {
          if (
            bannerDetailInfos[data.randomIndex].shptmBanrTpNm === "LIVE" ||
            bannerDetailInfos[data.randomIndex].shptmBanrTpNm === "VOD"
          ) {
            targetIndex = i;
            break;
          }
        } else if (
          bannerDetailInfos.find(
            (el) => el.shptmBanrTpNm === "LIVE" || el.shptmBanrTpNm === "VOD"
          )
        ) {
          targetIndex = i;
          break;
        }
      }
      return "banner" + targetIndex;
    }

    return null;
  }, [bannerDataList]);

  // useEffect(() => {
  //   if (firstSpot && defaultFocus && popupVisible === false) {
  //     setTimeout(() => {
  //       Spotlight.focus(defaultFocus);
  //     }, 0);
  //   }

  //   if (defaultFocus) {
  //     dispatch(setDefaultFocus(defaultFocus));
  //   }
  // }, [defaultFocus, dispatch, popupVisible]);

  // 테스트용 팝업 표시
  // useEffect(() => {
  //   setTimeout(() => {
  //     console.log("App.js optionalTermsTest 팝업 표시");
  //     setIsOptionalConfirmVisible(true);
  //     // setIsOptionalTermsVisible(true);
  //   }, 1000);
  // }, []);

  // 약관 동의 및 선택 약관 팝업 처리 (TV 환경 최적화)
  useEffect(() => {
    if (termsLoading) {
      // 약관 데이터 로딩 중에는 아무것도 하지 않음
      return;
    }

    // 선택 약관 팝업을 띄워야 하는 경우
    if (shouldShowOptionalTermsPopup && !isOptionalConfirmVisible) {
      console.log("shouldShowOptionalTermsPopup", shouldShowOptionalTermsPopup);
      console.log("App.js optionalTermsConfirm 팝업 표시");

      const timer = setTimeout(() => {
        setIsOptionalConfirmVisible(true);
        // 팝업이 실제로 표시된 후에 Redux 상태 업데이트
        dispatch(setOptionalTermsPopupShown(true));
      }, 1000);

      // 컴포넌트 언마운트 시 타이머 클리어
      return () => clearTimeout(timer);
    }
  }, [
    shouldShowOptionalTermsPopup,
    termsLoading,
    isOptionalConfirmVisible,
    dispatch,
  ]);

  // const renderItem = useCallback(
  //   (index, isHorizontal) => {
  //     const data = bannerDataList?.[index] ?? {};

  //     if (index === 1) {
  //       return (
  //         <div className={!isHorizontal ? css.imgBox : undefined}>
  //           <RandomUnitNew
  //             bannerData={data}
  //             isHorizontal={isHorizontal}
  //             key={"banner" + index}
  //             spotlightId={"banner" + index}
  //             handleShelfFocus={_handleShelfFocus}
  //             onFocus={handleSecondBannerFocus}
  //             onBlur={handleSecondBannerBlur}
  //             randomNumber={data.randomIndex}
  //           />
  //         </div>
  //       );
  //     }

  //     return (
  //       <div className={!isHorizontal ? css.imgBox : undefined}>
  //         {data.shptmDspyTpNm === "Rolling" ? (
  //           <Rolling
  //             bannerData={data}
  //             isHorizontal={isHorizontal}
  //             key={"banner" + index}
  //             spotlightId={"banner" + index}
  //             handleShelfFocus={_handleShelfFocus}
  //             handleItemFocus={_handleItemFocus}
  //           />
  //         ) : data.shptmDspyTpNm === "Random" ? (
  //           <Random
  //             bannerData={data}
  //             isHorizontal={isHorizontal}
  //             key={"banner" + index}
  //             spotlightId={"banner" + index}
  //             handleShelfFocus={_handleShelfFocus}
  //             handleItemFocus={_handleItemFocus}
  //             randomNumber={data.randomIndex}
  //           />
  //         ) : (
  //           <SpottableComponent spotlightId={"banner" + index}>
  //             <CustomImage
  //               delay={0}
  //               src={
  //                 isHorizontal
  //                   ? homeTopDisplayInfo.wdthtpImgPath1
  //                   : homeTopDisplayInfo.vtctpImgPath1
  //               }
  //               aria-label={
  //                 isHorizontal
  //                   ? homeTopDisplayInfo.wdthtpImgNm1
  //                   : homeTopDisplayInfo.vtctpImgNm1
  //               }
  //             />
  //           </SpottableComponent>
  //         )}
  //       </div>
  //     );
  //   },
  //   [
  //     bannerDataList,
  //     _handleItemFocus,
  //     _handleShelfFocus,
  //     handleSecondBannerFocus,
  //     handleSecondBannerBlur,
  //   ],
  // );

  const renderItem = useCallback(
    (index, isHorizontal) => {
      const data = bannerDataList?.[index] ?? {};
      return (
        <div className={!isHorizontal ? css.imgBox : undefined}>
          {data.shptmDspyTpNm === "Rolling" ? (
            <Rolling
              bannerData={data}
              isHorizontal={isHorizontal}
              key={"banner" + index}
              spotlightId={"banner" + index}
              handleShelfFocus={_handleShelfFocus}
              handleItemFocus={_handleItemFocus}
            />
          ) : data.shptmDspyTpNm === "Random" ? (
            <Random
              bannerData={data}
              isHorizontal={isHorizontal}
              key={"banner" + index}
              spotlightId={"banner" + index}
              handleShelfFocus={_handleShelfFocus}
              handleItemFocus={_handleItemFocus}
              randomNumber={data.randomIndex}
            />
          ) : (
            <SpottableComponent spotlightId={"banner" + index}>
              <CustomImage
                delay={0}
                src={
                  isHorizontal
                    ? homeTopDisplayInfo.wdthtpImgPath1
                    : homeTopDisplayInfo.vtctpImgPath1
                }
                aria-label={
                  isHorizontal
                    ? homeTopDisplayInfo.wdthtpImgNm1
                    : homeTopDisplayInfo.vtctpImgNm1
                }
              />
            </SpottableComponent>
          )}
        </div>
      );
    },
    [_handleItemFocus, _handleShelfFocus, bannerDataList]
  );

  // 1번째 배너(포커스 재생) 및 기타 배너를 위한 렌더링 함수
  const renderItemNew = useCallback(
    (index, isHorizontal) => {
      const data = bannerDataList?.[index] ?? {};

      // DSP00201 레이아웃의 두 번째 배너는 새로운 RandomUnitNew를 사용
      if (selectTemplate === "DSP00201" && index === 1) {
        return (
          <div className={!isHorizontal ? css.imgBox : undefined}>
            <RandomUnitNew
              bannerData={data}
              isHorizontal={isHorizontal}
              key={"banner" + index}
              spotlightId={"banner" + index}
              handleShelfFocus={_handleShelfFocus}
              handleItemFocus={_handleItemFocus}
              randomNumber={data.randomIndex}
            />
          </div>
        );
      }

      // 다른 타입의 유닛 렌더링 (예: RollingUnit)
      if (data.shptmDspyTpNm === "Rolling") {
        return (
          <div className={!isHorizontal ? css.imgBox : undefined}>
            <RollingUnit
              bannerData={data}
              isHorizontal={isHorizontal}
              key={"banner" + index}
              spotlightId={"banner" + index}
              handleShelfFocus={_handleShelfFocus}
              handleItemFocus={_handleItemFocus}
            />
          </div>
        );
      }
      // 기본 이미지만 있는 배너 등 다른 케이스 처리
      return (
        <div
          className={!isHorizontal ? css.imgBox : undefined}
          key={"banner" + index}
        >
          <SpottableComponent spotlightId={"banner" + index}>
            {/* ... 정적 이미지 렌더링 로직 ... */}
          </SpottableComponent>
        </div>
      );
    },
    [_handleItemFocus, _handleShelfFocus, bannerDataList, selectTemplate]
  );

  // 0번째 배너(영구 재생)를 위한 렌더링 함수
  const renderItemPersistentVideo = useCallback(
    (index, isHorizontal) => {
      return (
        <div className={!isHorizontal ? css.imgBox : undefined}>
          <SimpleVideoContainer
            spotlightId={"banner" + index} // "banner0"
            isHorizontal={isHorizontal}
            handleShelfFocus={_handleShelfFocus}
          />
        </div>
      );
    },
    [_handleShelfFocus]
  );

  const renderSimpleVideoContainer = useCallback(
    (index, isHorizontal) => {
      return (
        <div className={!isHorizontal ? css.imgBox : undefined}>
          <SimpleVideoContainer
            spotlightId={"banner" + index}
            isHorizontal={isHorizontal}
            handleShelfFocus={_handleShelfFocus}
          />
        </div>
      );
    },
    [_handleShelfFocus]
  );

  const renderLayout = useCallback(() => {
    switch (selectTemplate) {
      case "DSP00201": {
        return (
          <>
            <ContainerBasic className={css.smallBox}>
              {renderItem(0, true)}
              {renderItem(1, true)}
            </ContainerBasic>
            {renderItem(2, false)}
            {renderItem(3, false)}
          </>
        );
      }
      case "DSP00202": {
        return (
          <>
            {renderItem(0, false)}
            <ContainerBasic className={css.smallBox}>
              {renderItem(1, true)}
              {renderItem(2, true)}
            </ContainerBasic>
            {renderItem(3, false)}
          </>
        );
      }
      case "DSP00203": {
        return (
          <>
            {renderItem(0, false)}
            {renderItem(1, false)}
            <ContainerBasic className={css.smallBox}>
              {renderItem(2, true)}
              {renderItem(3, true)}
            </ContainerBasic>
          </>
        );
      }
    }
    return null;
  }, [selectTemplate, renderItem, renderSimpleVideoContainer]);

  return (
    <>
      <Container
        className={css.container}
        spotlightId={spotlightId}
        data-wheel-point={true}
      >
        <div className={css.homeTemplateBox}>{renderLayout()}</div>
      </Container>
      {/* 선택약관 동의 팝업 */}
      <OptionalConfirm
        open={isOptionalConfirmVisible}
        spotlightId="optional-confirm-popup"
        onClose={handleOptionalDeclineClick}
        onOptionalTermsClick={handleOptionalTermsClick}
        onOptionalAgreeClick={handleOptionalAgreeClick}
        onOptionalDeclineClick={handleOptionalDeclineClick}
        customPosition={true}
        position={{
          position: "absolute",
          top: "342px", // 가운데를 기준으로 한 좌표 (1080/2) - 198
          left: "0px",
          bottom: "unset",
          transform: "none",
        }}
      />
      {/* 선택약관 자세히 보기 팝업 */}
      <TNewPopUp
        kind="figmaTermsPopup"
        open={isOptionalTermsVisible}
        title={$L("Optional Terms")}
        text={optionalTermsData?.trmsCntt || ""}
        onClose={handleTermsPopupClosed}
        onAgreeClick={handleTermsPopupAgree}
        showAgreeButton={true}
      />
    </>
  );
}
