// src: views/IntroPanel/IntroPanel.new.jsx

import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import classNames from "classnames";
import { useDispatch, useSelector } from "react-redux";
import BasicIntroPanel from "./IntroPanel.jsx";
import Region from "@enact/sandstone/Region";
import Spotlight from "@enact/spotlight";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";
import {
  setExitApp,
  setHidePopup,
  setShowPopup,
  setDeviceRegistered,
  setOptionalTermsUserDecision,
  setOptionalTermsPopupShown,
  resetOptionalTermsSession,
  updateOptionalTermsAgreement,
  // setTermsAgreeYn,
} from "../../actions/commonActions";
import { registerDevice } from "../../actions/deviceActions";
import { getWelcomeEventInfo } from "../../actions/eventActions";
// import { fetchCurrentUserHomeTermsPromise } from "../../actions/homeActions";
import {
  sendLogGNB,
  sendLogTerms,
  sendLogTotalRecommend,
} from "../../actions/logActions";
import { popPanel, pushPanel } from "../../actions/panelActions";
import TButton, { TYPES } from "../../components/TButton/TButton";
// import TButtonScroller from "../../components/TButtonScroller/TButtonScroller";
// import TButtonTab from "../../components/TButtonTab/TButtonTab";
import TCheckBoxSquare from "../../components/TCheckBox/TCheckBoxSquare";
import TPanel from "../../components/TPanel/TPanel";
import TPopUp from "../../components/TPopUp/TPopUp";
import TNewPopUp from "../../components/TPopUp/TNewPopUp";
import OptionalTermsInfo from "../MyPagePanel/MyPageSub/TermsOfService/OptionalTermsInfo"; // 1단계: 활성화
import useDebugKey from "../../hooks/useDebugKey";
// import useSafeFocusState from "../../hooks/useSafeFocusState"; // 2단계: 제거
import useTermsStateMachine from "../../hooks/useTermsStateMachine";
// import useRightPanelContent from "../../hooks/useRightPanelContent"; // 1단계: 제거
import * as Config from "../../utils/Config";
import { panel_names } from "../../utils/Config";
import { $L } from "../../utils/helperMethods";
import css from "./IntroPanel.new.module.less";
import { types } from "../../actions/actionTypes";
import { focusById } from "../../utils/spotlight-utils";

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

const MAX_RETRY_ATTEMPTS = 5;
const RETRY_DELAY_MS = 1500; // 1.5 seconds

// 조건부 IntroPanel 컴포넌트 (선택약관 존재 여부에 따라 다른 컴포넌트 렌더링)
export default function IntroPanel(props) {
  const optionalTermsAvailable = useSelector(
    (state) => state.home.optionalTermsAvailable,
  );

  // 선택약관이 없으면 기존 IntroPanel.jsx 사용
  if (!optionalTermsAvailable) {
    console.log(
      "[IntroPanel.new] optionalTermsAvailable = false, 기존 IntroPanel 사용",
    );
    return <BasicIntroPanel {...props} />;
  }

  // 선택약관이 있으면 고급 IntroPanel 사용
  console.log(
    "[IntroPanel.new] optionalTermsAvailable = true, 고급 IntroPanel 사용",
  );
  return <IntroPanelWithOptional {...props} />;
}  

// 선택약관 포함 고급 IntroPanel 컴포넌트
function IntroPanelWithOptional({
  // children,
  // isTabActivated,
  // handleCancel,
  spotlightId,
  ...rest
}) {
  delete rest.isTabActivated;
  delete rest.panelInfo;

  useDebugKey({});
  const dispatch = useDispatch();
  // const blurTimeout = useRef(null);
  const termsData = useSelector((state) => state.home.termsData);
  const termsIdMap = useSelector((state) => state.home.termsIdMap);
  const { popupVisible, activePopup, ...popupState } = useSelector(
    (state) => state.common.popup,
  );
  // const eventInfos = useSelector((state) => state.event.eventData);
  const regDeviceData = useSelector((state) => state.device.regDeviceData);
  const deviceRegistered = useSelector(
    (state) => state.common.deviceRegistered,
  );
  // const regDeviceInfoData = useSelector(
  //   (state) => state.device.regDeviceInfoData
  // );

  // registerDevice API 호출 중 여부
  const [isProcessing, setIsProcessing] = useState(false);
  const [showExitMessagePopup, setShowExitMessagePopup] = useState(false);
  // [추가] 재시도 관련 상태
  const [pendingAgree, setPendingAgree] = useState(false);
  // race condition 방지를 위한 안전장치
  const processingTimeoutRef = useRef(null);
  // [추가] 재시도 인터벌 참조
  const retryIntervalRef = useRef(null);
  // 필수약관 팝업 타이머 참조
  const popupTimeoutRef = useRef(null);
  // const [isRequiredFocused, setIsRequiredFocused] = useState(false);

  // const { focusedItem, setFocusAsync, clearFocusAsync } = useSafeFocusState(); // 2단계: 제거
  const { state: termsState, updateStateAsync } = useTermsStateMachine();
  const {
    termsChecked,
    privacyChecked,
    optionalChecked,
    selectAllChecked,
    error: termsError, // 훅의 에러 상태를 가져옴
  } = termsState;

  const introTermsData = useMemo(() => {
    // Chromium68 호환성을 위해 Optional Chaining 제거
    if (termsData && termsData.data && termsData.data.terms) {
      return termsData.data.terms.filter(
        (item) => item.trmsTpCd === "MST00401" || item.trmsTpCd === "MST00402",
      );
    }
    return [];
  }, [termsData]);

  const optionalTermsData = useMemo(() => {
    // Chromium68 호환성을 위해 Optional Chaining 제거
    if (termsData && termsData.data && termsData.data.terms) {
      return termsData.data.terms.filter(
        (item) => item.trmsTpCd === "MST00405" || item.trmsTpCd === "MST00406",
      );
    }
    return [];
  }, [termsData]);

  const webOSVersion = useSelector((state) => {
    // Chromium68 호환성을 위해 Optional Chaining 제거
    if (
      state.common &&
      state.common.appStatus &&
      state.common.appStatus.webOSVersion
    ) {
      return state.common.appStatus.webOSVersion;
    }
    return null;
  });

  // const webOSVersion = 4.5;
  // WebOS 버전별 UI 표시 모드 결정
  // 이미지 표시: 4.0, 5.0, 23, 24
  // 텍스트 표시: 4.5, 6.0, 22
  // 25.07.17 추가
  // 4.0 : 4.4.9 까지
  // 4.5 : 4.5.0 ~
  // 5.0 : 5.0.0~
  // 6.0 : 6.0.0~
  // 22 : 7.0.0~
  // 23 : 8.0.0~
  // 24 : 9.0.0~
  // 25 : 10.0.0~

  const shouldShowBenefitsView = useMemo(() => {
    // if (!webOSVersion) return false;
    // webOSVersion 이 없거나 빈 문자열인 경우 이미지 보기 처리
    if (!webOSVersion || webOSVersion === "") {
      return false;
    }

    const versionNum = Number.parseFloat(String(webOSVersion)); // 기존 로직 유지
    const versionStr = String(webOSVersion);

    // 버전 문자열을 배열로 변환해서 비교
    const parseVersionArray = (version) => {
      return version.split(".").map(Number);
    };

    const currentVersionArray = parseVersionArray(versionStr);

    // 버전 구간별 약관 버전 매핑
    let termsVersion = null;

    if (currentVersionArray[0] >= 10) {
      termsVersion = 25;
    } else if (currentVersionArray[0] >= 9) {
      termsVersion = 24;
    } else if (currentVersionArray[0] >= 8) {
      termsVersion = 23;
    } else if (currentVersionArray[0] >= 7) {
      termsVersion = 22;
    } else if (currentVersionArray[0] >= 6) {
      termsVersion = 6.0;
    } else if (currentVersionArray[0] >= 5) {
      termsVersion = 5.0;
    } else if (currentVersionArray[0] === 4) {
      // 4.x 버전은 세밀한 구분 필요
      const minor = currentVersionArray[1] || 0;
      const patch = currentVersionArray[2] || 0;

      if (minor >= 5) {
        termsVersion = 4.5; // 4.5.0 이상
      } else {
        termsVersion = 4.0; // 4.0.0 ~ 4.4.9
      }
    }

    const textTermsVersions = [4.5, 6.0, 22];
    // const imageTermsVersions = [4.0, 5.0, 23, 24];
    const shouldShowText = textTermsVersions.includes(termsVersion);

    if (process.env.NODE_ENV === "development") {
      console.log("🔍 WebOS 버전별 UI 모드:");
      console.log("  - webOSVersion:", webOSVersion);
      console.log("  - versionNum:", versionNum);
      console.log("  - 파싱된 버전 배열:", currentVersionArray);
      console.log("  - 매핑된 약관 버전:", termsVersion);
      console.log("  - shouldShowText (텍스트 모드):", shouldShowText);
    }

    return shouldShowText;
  }, [webOSVersion]);

  // 상태 관리
  const [currentTerms, setCurrentTerms] = useState(null);
  // 필수약관 체크 해제시 팝업표시용
  const [requiredAgreePopup, setRequiredAgreePopup] = useState(false);
  // const [prevTermsChecked, setPrevTermsChecked] = useState(false); // 제거됨
  // const [prevPrivacyChecked, setPrevPrivacyChecked] = useState(false); // 제거됨

  useEffect(() => {
    dispatch({ type: types.REGISTER_DEVICE_RESET });
    dispatch(sendLogGNB(Config.LOG_MENU.TERMS_CONDITIONS));
  }, [dispatch]);

  // 디버깅용 WebOS 버전 로그
  useEffect(() => {
    if (process.env.NODE_ENV === "development") {
      console.log("[IntroPanel] WebOS 버전 정보:");
      console.log("[IntroPanel] webOSVersion:", webOSVersion);
      console.log(
        "[IntroPanel] shouldShowBenefitsView:",
        shouldShowBenefitsView,
      );
    }
  }, [webOSVersion, shouldShowBenefitsView]);

  useEffect(() => {
    if (showExitMessagePopup) {
      const timer = setTimeout(() => {
        dispatch(setExitApp());
        dispatch(
          sendLogTotalRecommend({
            contextName: Config.LOG_CONTEXT_NAME.SHOPTIME,
            messageId: Config.LOG_MESSAGE_ID.VIEW_CHANGE,
            visible: false,
          }),
        );
      }, 3000);
      return () => clearTimeout(timer);
    }
  }, [showExitMessagePopup, dispatch]);

  // 컴포넌트 마운트 후 0.5초 뒤에 selectAllCheckbox으로 강제 포커스
  useEffect(() => {
    const focusTimer = setTimeout(() => {
      focusById("selectAllCheckbox");
    }, 500);

    return () => {
      clearTimeout(focusTimer);
      // 팝업 타이머도 정리
      if (popupTimeoutRef.current) {
        clearTimeout(popupTimeoutRef.current);
      }
    };
  }, []);

  // [추가] useTermsStateMachine의 에러 상태를 감지하여 팝업으로 표시
  useEffect(() => {
    if (termsError) {
      dispatch(
        setShowPopup(Config.ACTIVE_POPUP.alertPopup, {
          title: $L("Error"),
          text: termsError.message,
          button1Text: $L("OK"),
        }),
      );
    }
  }, [termsError, dispatch]);

  // 필수약관 체크 해제 감지 및 팝업 표시 - 제거됨
  // useEffect(() => {
  //   // 이전 상태가 true이고 현재 상태가 false인 경우 (체크 해제)
  //   if ((prevTermsChecked && !termsChecked) || (prevPrivacyChecked && !privacyChecked)) {
  //     setRequiredAgreePopup(true);
  //
  //     // 3초 후 자동 닫기
  //     popupTimeoutRef.current = setTimeout(() => {
  //       setRequiredAgreePopup(false);
  //     }, 3000);
  //   }
  //
  //   // 현재 상태를 이전 상태로 업데이트
  //   setPrevTermsChecked(termsChecked);
  //   setPrevPrivacyChecked(privacyChecked);
  // }, [termsChecked, privacyChecked, prevTermsChecked, prevPrivacyChecked]);

  useEffect(() => {
    console.log("[IntroPanel] deviceRegistered", deviceRegistered);
    if (deviceRegistered) {
      console.log("[IntroPanel] deviceRegistered 팝업 닫기");
      dispatch(popPanel(panel_names.INTRO_PANEL));
    }
  }, [deviceRegistered, dispatch]);

  // 약관 팝업 동의여부에 따른 이벤트 핸들러
  const handleTermsAgree = useCallback(() => {
    if (!currentTerms) {
      return;
    }
    const termType = currentTerms.trmsTpCd;
    if (termType === "MST00402") {
      updateStateAsync({ termsChecked: true });
    } else if (termType === "MST00401") {
      updateStateAsync({ privacyChecked: true });
    } else if (termType === "MST00405") {
      // Optional Terms
      updateStateAsync({ optionalChecked: true });
    }
    // 팝업 닫기
    dispatch(setHidePopup());
  }, [currentTerms, dispatch, updateStateAsync]);

  const handleTermsClick = useCallback(
    (trmsTpCdList) => {
      if (introTermsData) {
        const selectedTerms = introTermsData.find(
          (term) => term.trmsTpCd === trmsTpCdList,
        );

        setCurrentTerms(selectedTerms);
        dispatch(setShowPopup(Config.ACTIVE_POPUP.termsPopup));

        const logTpNo =
          trmsTpCdList === "MST00402"
            ? Config.LOG_TP_NO.TERMS.TEARMS_CONDITIONS
            : Config.LOG_TP_NO.TERMS.PRIVACY_POLICY;
        dispatch(sendLogTerms({ logTpNo }));
      }
    },
    [introTermsData, dispatch],
  );

  const handleOptionalTermsClick = useCallback(
    (trmsTpCdList) => {
      if (optionalTermsData) {
        const selectedTerms = optionalTermsData.find(
          (term) => term.trmsTpCd === trmsTpCdList,
        );

        setCurrentTerms(selectedTerms);
        dispatch(setShowPopup(Config.ACTIVE_POPUP.termsPopup));

        // const logTpNo =
        //   trmsTpCdList === "MST00402"
        //     ? Config.LOG_TP_NO.TERMS.TEARMS_CONDITIONS
        //     : Config.LOG_TP_NO.TERMS.PRIVACY_POLICY;
        // dispatch(sendLogTerms({ logTpNo }));
      }
    },
    [optionalTermsData, dispatch],
  );

  const onClose = useCallback(() => {
    dispatch(setHidePopup());
  }, [dispatch]);

  // 실패 감지를 위한 useEffect 추가
  useEffect(() => {
    // isProcessing이 true일 때만 실패 체크 (= handleAgree 클릭 후에만)
    if (isProcessing && regDeviceData && regDeviceData.retCode !== 0) {
      if (process.env.NODE_ENV === "development") {
        console.error(
          `[IntroPanel] registerDevice 실패: isProcessing=${isProcessing}, retCode=${regDeviceData.retCode}`,
          regDeviceData,
        );
      }
      dispatch(
        setShowPopup(Config.ACTIVE_POPUP.alertPopup, {
          title: $L("Error"),
          text: $L("Device registration failed. Please try again."),
          button1Text: $L("OK"),
        }),
      );
      setIsProcessing(false);
      clearTimeout(processingTimeoutRef.current); // 타임아웃 정리
    }
  }, [regDeviceData, dispatch, isProcessing]); // isProcessing 의존성 추가

  // [추가] 실제 처리 로직 분리
  const executeAgree = useCallback(
    (retryCount = 0) => {
      console.log(
        `[IntroPanel] executeAgree 실행 시작 (시도: ${retryCount + 1})`,
      );

      // Redux에서 가져온 termsIdMap을 사용하여 동적으로 약관 ID 매핑
      const agreeTerms = [];

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

      if (process.env.NODE_ENV === "development") {
        console.log("[IntroPanel] 현재 termsIdMap:", termsIdMap);
        console.log("[IntroPanel] 최종 전송될 agreeTerms:", agreeTerms);
      }
      console.log("[IntroPanel] agreeTerms!!", agreeTerms);

      dispatch(
        registerDevice(
          { agreeTerms: agreeTerms },
          (newRegDeviceData) => {
            // ================== SUCCESS ==================
            if (newRegDeviceData && newRegDeviceData.retCode === 0) {
              dispatch(setDeviceRegistered(true));

              // ✅ 선택약관 상태를 통합 액션으로 업데이트 (TV 환경 최적화)
              if (optionalChecked) {
                // 선택약관에 동의한 경우
                console.log(
                  "[IntroPanel] 선택약관 동의됨 - 통합 Redux 상태 업데이트",
                );
                dispatch(updateOptionalTermsAgreement(true));
              } else {
                // 선택약관에 동의하지 않은 경우 - HomeBanner에서 팝업이 나올 수 있도록 상태를 초기화
                console.log(
                  "[IntroPanel] 선택약관 미동의 - HomeBanner 팝업 허용을 위해 상태 초기화",
                );
                dispatch(updateOptionalTermsAgreement(false));
                setTimeout(() => {
                  console.log("[IntroPanel] 선택약관 세션 리셋 실행");
                  dispatch(resetOptionalTermsSession());
                }, 1000);
              }

              dispatch(
                getWelcomeEventInfo((eventInfos) => {
                  if (
                    eventInfos &&
                    Object.keys(eventInfos.data).length > 0 &&
                    webOSVersion
                  ) {
                    let displayWelcomeEventPanel = false;

                    if (
                      eventInfos.data?.welcomeEventFlag === "Y" ||
                      (eventInfos.data?.welcomeBillCpnEventFlag === "Y" &&
                        Number(webOSVersion) >= 6)
                    ) {
                      displayWelcomeEventPanel = true;
                    }

                    dispatch(
                      sendLogTerms({ logTpNo: Config.LOG_TP_NO.TERMS.AGREE }),
                    );

                    if (displayWelcomeEventPanel) {
                      dispatch(
                        pushPanel({
                          name: panel_names.WELCOME_EVENT_PANEL,
                          panelInfo: { eventInfos: eventInfos.data },
                        }),
                      );
                    }
                  }
                  setIsProcessing(false);
                }),
              );
            } else {
              // retCode가 0이 아닌 경우도 실패로 간주하고 재시도
              if (retryCount < MAX_RETRY_ATTEMPTS - 1) {
                setTimeout(() => {
                  executeAgree(retryCount + 1);
                }, RETRY_DELAY_MS);
              } else {
                dispatch(
                  setShowPopup(Config.ACTIVE_POPUP.alertPopup, {
                    title: $L("Error"),
                    text: $L(
                      "A temporary network error occurred. Please try again in a moment.",
                    ),
                    button1Text: $L("OK"),
                  }),
                );
                setIsProcessing(false);
              }
            }
          },
          () => {
            // ================== FAIL ==================
            console.error(
              `[IntroPanel] registerDevice 실패 (시도: ${retryCount + 1})`,
            );
            if (retryCount < MAX_RETRY_ATTEMPTS - 1) {
              setTimeout(() => {
                executeAgree(retryCount + 1);
              }, RETRY_DELAY_MS);
            } else {
              console.error("[IntroPanel] 최대 재시도 횟수 초과.");
              dispatch(
                setShowPopup(Config.ACTIVE_POPUP.alertPopup, {
                  title: $L("Error"),
                  text: $L(
                    "A temporary network error occurred. Please try again in a moment.",
                  ),
                  button1Text: $L("OK"),
                }),
              );
              setIsProcessing(false);
            }
          },
        ),
      );
    },
    [
      termsChecked,
      privacyChecked,
      optionalChecked,
      dispatch,
      webOSVersion,
      termsIdMap,
    ],
  );

  // [추가] 재시도 메커니즘 시작
  const startRetryMechanism = useCallback(() => {
    // 기존 재시도가 있다면 정리
    if (retryIntervalRef.current) {
      clearInterval(retryIntervalRef.current);
    }

    console.log("[IntroPanel] 재시도 메커니즘 시작");

    // 500ms마다 isProcessing 상태 체크
    retryIntervalRef.current = setInterval(() => {
      if (!isProcessing && pendingAgree) {
        console.log("[IntroPanel] 처리 가능 상태 감지 - 실행");
        clearInterval(retryIntervalRef.current);
        retryIntervalRef.current = null;
        setPendingAgree(false);
        executeAgree();
      }
    }, 500);

    // 10초 후 자동 포기
    setTimeout(() => {
      if (retryIntervalRef.current) {
        console.warn("[IntroPanel] 재시도 타임아웃");
        clearInterval(retryIntervalRef.current);
        retryIntervalRef.current = null;
        setPendingAgree(false);
      }
    }, 10000);
  }, [isProcessing, pendingAgree, executeAgree]);

  const handleAgree = useCallback(() => {
    console.log("[IntroPanel] handleAgree 호출, isProcessing=", isProcessing);

    // 필수 약관 체크
    if (!termsChecked || !privacyChecked) {
      // 기존 alert 팝업 - 주석 처리됨
      // dispatch(
      //   setShowPopup(Config.ACTIVE_POPUP.alertPopup, {
      //     title: $L("Required Terms"),
      //     text: $L("Please agree to Terms & Conditions and Privacy Policy."),
      //     button1Text: $L("OK"),
      //   }),
      // );

      // 새로운 requiredAgreePopup 사용
      setRequiredAgreePopup(true);

      // 3초 후 자동 닫기
      popupTimeoutRef.current = setTimeout(() => {
        setRequiredAgreePopup(false);
        if (!termsChecked) {
          Spotlight.focus("termsCheckbox");
        } else if (!privacyChecked) {
          Spotlight.focus("privacyCheckbox");
        }
      }, 3000);

      return;
    }

    // 이미 처리 중이면 대기 모드로 전환
    if (isProcessing) {
      console.log("[IntroPanel] 이미 처리 중 - 대기 모드 시작");
      setPendingAgree(true);
      startRetryMechanism();
      return;
    }

    // 실제 처리 실행
    setIsProcessing(true);
    executeAgree();
  }, [
    termsChecked,
    privacyChecked,
    dispatch,
    isProcessing,
    pendingAgree,
    executeAgree,
    startRetryMechanism,
  ]);

  // 컴포넌트 언마운트 시 타임아웃 정리
  useEffect(() => {
    return () => {
      if (processingTimeoutRef.current) {
        clearTimeout(processingTimeoutRef.current);
      }
      // [추가] 재시도 인터벌 정리
      if (retryIntervalRef.current) {
        clearInterval(retryIntervalRef.current);
      }
    };
  }, []);

  const handleDisagree = useCallback(() => {
    dispatch(setShowPopup(Config.ACTIVE_POPUP.exitPopup));
    dispatch(sendLogTerms({ logTpNo: Config.LOG_TP_NO.TERMS.DO_NOT_AGREE }));
  }, [dispatch]);

  const onExit = useCallback(() => {
    dispatch(setHidePopup());
    setShowExitMessagePopup(true);
    dispatch(setExitApp());
    dispatch(
      sendLogTotalRecommend({
        contextName: Config.LOG_CONTEXT_NAME.SHOPTIME,
        messageId: Config.LOG_MESSAGE_ID.VIEW_CHANGE,
        visible: false,
      }),
    );
  }, [dispatch]);

  const onCancel = useCallback(() => {
    if (activePopup === null) {
      dispatch(setShowPopup(Config.ACTIVE_POPUP.exitPopup));
    }
  }, [dispatch, activePopup]);

  // const handleFocus = useCallback(
  //   (item) => {
  //     setFocusAsync(item);
  //   },
  //   [setFocusAsync],
  // ); // 2단계: 제거

  // const handleBlur = useCallback(() => {
  //   clearFocusAsync(0);
  // }, [clearFocusAsync]); // 2단계: 제거

  // 체크박스 핸들러들
  const handleTermsToggle = useCallback(
    async ({ selected }) => {
      try {
        const newState = await updateStateAsync({ termsChecked: selected });
        if (
          newState.termsChecked &&
          newState.privacyChecked &&
          newState.optionalChecked
        ) {
          setTimeout(() => Spotlight.focus("agreeButton"), 100);
        }
      } catch (error) {
        if (process.env.NODE_ENV === "development") {
          console.error("Toggle failed:", error);
        }
      }
    },
    [updateStateAsync],
  );

  const handlePrivacyToggle = useCallback(
    async ({ selected }) => {
      try {
        const newState = await updateStateAsync({ privacyChecked: selected });
        if (
          newState.termsChecked &&
          newState.privacyChecked &&
          newState.optionalChecked
        ) {
          setTimeout(() => Spotlight.focus("agreeButton"), 100);
        }
      } catch (error) {
        if (process.env.NODE_ENV === "development") {
          console.error("Toggle failed:", error);
        }
      }
    },
    [updateStateAsync],
  );

  const handleOptionalToggle = useCallback(
    async ({ selected }) => {
      try {
        const newState = await updateStateAsync({ optionalChecked: selected });
        if (
          newState.termsChecked &&
          newState.privacyChecked &&
          newState.optionalChecked
        ) {
          setTimeout(() => Spotlight.focus("agreeButton"), 100);
        }
      } catch (error) {
        if (process.env.NODE_ENV === "development") {
          console.error("Toggle failed:", error);
        }
      }
    },
    [updateStateAsync],
  );

  const handleSelectAllToggle = useCallback(
    async ({ selected }) => {
      try {
        const newState = await updateStateAsync({ selectAllChecked: selected });
        if (newState.selectAllChecked) {
          setTimeout(() => Spotlight.focus("agreeButton"), 100);
        }
      } catch (error) {
        if (process.env.NODE_ENV === "development") {
          console.error("Toggle failed:", error);
        }
      }
    },
    [updateStateAsync],
  );

  const handleTermsClickMST00402 = useCallback(
    () => handleTermsClick("MST00402"),
    [handleTermsClick],
  );
  const handleTermsClickMST00401 = useCallback(
    () => handleTermsClick("MST00401"),
    [handleTermsClick],
  );
  const handleOptionalTermsClickMST00405 = useCallback(
    () => handleOptionalTermsClick("MST00405"),
    [handleOptionalTermsClick],
  );

  // const handleFocusTermsCheckbox = useCallback(
  //   () => handleFocus("termsCheckbox"),
  //   [handleFocus],
  // ); // 2단계: 제거
  // const handleFocusTermsButton = useCallback(
  //   () => handleFocus("termsButton"),
  //   [handleFocus],
  // ); // 2단계: 제거
  // const handleFocusPrivacyCheckbox = useCallback(
  //   () => handleFocus("privacyCheckbox"),
  //   [handleFocus],
  // ); // 2단계: 제거
  // const handleFocusPrivacyButton = useCallback(
  //   () => handleFocus("privacyButton"),
  //   [handleFocus],
  // ); // 2단계: 제거
  // const handleFocusOptionalCheckbox = useCallback(
  //   () => handleFocus("optionalCheckbox"),
  //   [handleFocus],
  // ); // 2단계: 제거
  // const handleFocusOptionalButton = useCallback(
  //   () => handleFocus("optionalButton"),
  //   [handleFocus],
  // ); // 2단계: 제거
  // const handleFocusSelectAllCheckbox = useCallback(
  //   () => handleFocus("selectAllCheckbox"),
  //   [handleFocus],
  // ); // 2단계: 제거
  // const handleFocusAgreeButton = useCallback(
  //   () => handleFocus("agreeButton"),
  //   [handleFocus],
  // ); // 2단계: 제거
  // const handleFocusDisagreeButton = useCallback(
  //   () => handleFocus("disagreeButton"),
  //   [handleFocus],
  // ); // 2단계: 제거

  // const rightPanelContent = useRightPanelContent(
  //   focusedItem,
  //   termsChecked,
  //   privacyChecked,
  //   shouldShowBenefitsView,
  // ); // 1단계: 제거

  // 1단계: WebOS 버전 기반 고정 콘텐츠로 교체
  const rightPanelContent = useMemo(() => {
    return shouldShowBenefitsView ? (
      <div className={css.optionalDescription}>
        {$L(
          'By checking Optional terms, you allow Shop Time to use your activity (views, purchases, searches, etc.) to show you more relevant content, product recommendations, special offers, and ads. If you do not check, you can still use all basic Shop Time features',
        )}
      </div>
    ) : (
      <OptionalTermsInfo
        displayMode="image"
        imageTitle={$L("Agree and Enjoy Special Benefits")}
        spotlightId="optional-terms-info"
      />
    );
  }, [shouldShowBenefitsView]);

  useEffect(() => {
    Spotlight.focus();
  }, [popupVisible]);

  //20250903 pjh
  //selectAll에서 포커스 올렸을때 처리 변경.
  const onSelectAllSpotlightUp = () => {
    const focusTimer = setTimeout(() => {
      Spotlight.focus("optionalCheckbox");
    }, 100);
    return () => {
      clearTimeout(focusTimer);
    };
  };

  //Optional terms 체크박스가 체크가 되어있을때 아래로 내리면(3개전부 체크기준) agree로 가고, 아닐경우 select all로 포커스이동해야함.
  const onOptionalTermSpotlightDown = () => {
    const focusTimer = setTimeout(() => {
      if (termsChecked && privacyChecked && optionalChecked) {
        Spotlight.focus("agreeButton");
      } else {
        Spotlight.focus("selectAllCheckbox");
      }
    }, 100);
    return () => {
      clearTimeout(focusTimer);
    };
  };

  // useEffect(() => {
  //   if (regDeviceInfoData && regDeviceInfoData.retCode === 0) {
  //     dispatch(setHidePopup());
  //     dispatch(popPanel(panel_names.INTRO_PANEL));
  //   }
  // }, [dispatch, regDeviceInfoData]);

  const description = $L(
    "Check out more LIVE SHOWS now and enjoy shopping at Shop Time's special price on your TV by agreeing to the LG TV Shopping Terms and Conditions.",
  );
  const title = "welcome to shoptime!";
  delete rest.isOnTop;

  const uiMode = shouldShowBenefitsView ? "Text Mode" : "Image Mode";

  // [추가] 약관 종류에 따라 팝업 제목을 반환하는 헬퍼 함수
  const getTermsPopupTitle = (terms) => {
    if (!terms) return "";
    switch (terms.trmsTpCd) {
      case "MST00401":
        return $L("Privacy Policy");
      case "MST00402":
        return $L("Terms & Conditions");
      case "MST00405":
        return $L("Optional Terms");
      default:
        return "";
    }
  };

  return (
    <Region title={title + description}>
      <TPanel
        className={css.panel}
        isTabActivated={false}
        handleCancel={onCancel}
        spotlightId={spotlightId}
      >
        <Container {...rest} className={css.introLayout}>
          {/* 첫 번째 영역: 헤더 섹션 */}
          <div className={css.headerSection}>
            <div className={css.titleContainer}>
              <div className={css.welcomeText}>{$L("Welcome to")}</div>
              <div className={css.brandContainer}>
                <span className={css.shopText}>{$L("Sh")}</span>
                <span className={css.oText}>{$L("o")}</span>
                <span className={css.timeText}>{$L("pTime !")}</span>
              </div>
            </div>
            <div className={css.descriptionContainer}>
              <div className={css.descriptionText}>{description}</div>
            </div>
          </div>

          {/* 두 번째 영역: 약관 섹션 */}
          <div className={css.termsSection}>
            <div className={css.termsLeftPanel}>
              {/* Terms & Conditions */}
              <div className={css.termsItem}>
                <TCheckBoxSquare
                  className={css.customeCheckbox}
                  selected={termsChecked}
                  onToggle={handleTermsToggle}
                  spotlightId="termsCheckbox"
                  ariaLabel={$L("Terms & Conditions checkbox")}
                />
                <TButton
                  className={css.termsButton}
                  onClick={handleTermsClickMST00402}
                  spotlightId="termsButton"
                  type={TYPES.terms}
                  ariaLabel={$L("View Terms & Conditions")}
                >
                  <span className={`${css.termsText} ${css.required}`}>
                    {$L("Terms & Conditions")}
                  </span>
                </TButton>
              </div>

              {/* Privacy Policy */}
              <div className={css.termsItem}>
                <TCheckBoxSquare
                  className={css.customeCheckbox}
                  selected={privacyChecked}
                  onToggle={handlePrivacyToggle}
                  spotlightId="privacyCheckbox"
                  ariaLabel={$L("Privacy Policy checkbox")}
                />
                <TButton
                  className={css.termsButton}
                  onClick={handleTermsClickMST00401}
                  spotlightId="privacyButton"
                  type={TYPES.terms}
                  ariaLabel={$L("View Privacy Policy")}
                >
                  <span className={`${css.termsText} ${css.required}`}>
                    {$L("Privacy Policy")}
                  </span>
                </TButton>
              </div>

              {/* Optional Terms */}
              <div className={css.termsItem}>
                <TCheckBoxSquare
                  className={css.customeCheckbox}
                  selected={optionalChecked}
                  onToggle={handleOptionalToggle}
                  onSpotlightDown={onOptionalTermSpotlightDown}
                  spotlightId="optionalCheckbox"
                  ariaLabel={$L("Optional Terms checkbox")}
                />
                <TButton
                  className={css.termsButton}
                  onClick={handleOptionalTermsClickMST00405}
                  spotlightId="optionalButton"
                  type={TYPES.terms}
                  ariaLabel={$L("View Optional Terms")}
                  style={{ marginBottom: 0 }} // 제일 아래 버튼의 경우 margin-bottom 0
                >
                  <span className={css.termsText}>{$L("Optional Terms")}</span>
                </TButton>
              </div>
            </div>
            <div className={css.termsRightPanel}>{rightPanelContent}</div>
          </div>

          {/* 세 번째 영역: Select All */}
          <div className={css.selectAllSection}>
            <TCheckBoxSquare
              className={css.selectAllCheckbox}
              selected={selectAllChecked}
              onToggle={handleSelectAllToggle}
              onSpotlightUp={onSelectAllSpotlightUp}
              spotlightId="selectAllCheckbox"
              ariaLabel={$L("Select All checkbox")}
            />
            <span className={css.selectAllText}>{$L("Select All")}</span>
          </div>

          {/* 네 번째 영역: 버튼 섹션 */}
          <div className={css.buttonSection}>
            <TButton
              className={classNames(
                css.agreeButton,
                (!termsChecked || !privacyChecked) && css.disabled,
              )}
              onClick={handleAgree}
              spotlightId="agreeButton"
              type={TYPES.agree}
              ariaLabel={$L("Agree to terms")}
            >
              {$L("Agree")}
            </TButton>
            <TButton
              className={css.disagreeButton}
              onClick={handleDisagree}
              spotlightId="disagreeButton"
              type={TYPES.agree}
              ariaLabel={$L("Do not agree to terms")}
            >
              {$L("Do Not Agree")}
            </TButton>
          </div>

          {/* --- DEBUG INFO [START] --- */}
          {/* <div className={css.debugInfo}>
            <div>WebOS: {webOSVersion}</div>
            <div>Mode: {uiMode}</div>
          </div> */}
          {/* --- DEBUG INFO [END] --- */}
        </Container>
      </TPanel>

      {/* 약관 보기 팝업 */}
      {activePopup === Config.ACTIVE_POPUP.termsPopup && (
        <>
          {/*
            <TPopUp
              kind="introTermsPopup"
              contentType={CONTENT_TYPES.TERMS}
              open={popupVisible}
              onClose={onClose}
              onTermsAgree={handleTermsAgree}
              termsData={currentTerms}
              hasButton
              button1Text={$L("Agree")}
              button2Text={$L("Close")}
              spotlightId="tPopupBtn1"
            />
          */}

          {/* TermsPopup 호출은 완전히 삭제 */}

          {/* TNewPopUp을 사용한 새로운 팝업 구현 */}
          <TNewPopUp
            open={popupVisible}
            kind="figmaTermsPopup"
            title={getTermsPopupTitle(currentTerms)}
            showAgreeButton
            onAgreeClick={handleTermsAgree}
            text={currentTerms?.trmsCntt || ""}
            onClose={onClose} // Close 버튼 핸들러 연결
          />
        </>
      )}

      {/* DO NOT AGREE */}
      {activePopup === Config.ACTIVE_POPUP.exitPopup && (
        <TPopUp
          kind="exitPopup"
          open={popupVisible}
          onExit={onExit}
          onClose={onClose}
          hasButton
          button1Text={$L("Exit")}
          button2Text={$L("Cancel")}
          hasText
          title={$L("Exit Shop Time")}
          text={$L("Are you sure you want to exit Shop Time?")}
        />
      )}

      {/* ALERT POPUP (필수 약관 알림) */}
      {activePopup === Config.ACTIVE_POPUP.alertPopup && (
        <TPopUp
          kind="textPopup"
          open={popupVisible}
          onClose={onClose}
          hasButton
          button1Text={popupState.button1Text || $L("OK")}
          hasText
          title={popupState.title || ""}
          text={popupState.text || ""}
        />
      )}

      {/* Final Exit Message Popup */}
      {showExitMessagePopup && (
        <TPopUp
          kind="textPopup"
          open={showExitMessagePopup}
          hasText
          title={$L("Exit Shop Time")}
          text={$L(
            "Thank you for using the Shop Time, and we hope to see you again. The app will close in 3 seconds.",
          )}
        />
      )}

      <TPopUp
        kind="textPopup"
        open={requiredAgreePopup}
        onClose={() => setRequiredAgreePopup(false)}
        hasText
        title={$L("")}
        text={$L(
          "Please check the box to accept the Terms & Conditions and Privacy Policy.",
        )}
      />
    </Region>
  );
}

