// src/components/TermsPopup/TermsPopup.jsx
/**
 * ShopTime 애플리케이션의 선택적 약관 동의 팝업 컴포넌트
 * * @component TermsPopup
 * @description 
 * webOS TV 환경에서 개인정보 기반 추천/광고 동의 팝업을 표시합니다.
 * 사용자는 약관 내용을 스크롤하여 확인하고 동의 또는 거부할 수 있습니다.
 * * @param {Object} props
 * @param {boolean} props.visible - 팝업 표시 여부
 * @param {Function} props.onAgree - 동의 버튼 클릭 시 콜백 함수
 * @param {Function} props.onClose - 닫기 버튼 클릭 시 콜백 함수
 * @param {Object} props.termsData - 약관 데이터 객체 (title, content)
 * @param {boolean} props.isAlreadyAgreed - 이미 동의한 약관인지 여부
 */
import React, { useCallback, useEffect, useState } from "react";
import Spotlight from "@enact/spotlight";

import TButton, { TYPES } from "../../../../components/TButton/TButton";
import TButtonScroller from "../../../../components/TButtonScroller/TButtonScroller";
import TPopUp from "../../../../components/TPopUp/TPopUp";
import { $L, scaleH, scaleW } from "../../../../utils/helperMethods";
import css from "./TermsPopup.module.less";

export default function TermsPopup({ visible, onAgree, onClose, termsData, isAlreadyAgreed = false }) {
  const [spotlightDisabled, setSpotlightDisabled] = useState(true);
  const [resetScroll, setResetScroll] = useState(false);

  /**
   * 팝업이 표시될 때 Spotlight 활성화
   */
  useEffect(() => {
    if (visible) {
      setSpotlightDisabled(false);
      // 팝업이 열리면 스크롤을 맨 위로 리셋
      setResetScroll(true);
        // 첫 번째 버튼에 포커스 설정 (약간의 지연을 두어 렌더링 완료 후 포커스)
      setTimeout(() => {
        // 이미 동의된 약관이면 Close 버튼에, 아니면 Agree 버튼에 포커스
        const focusTargetId = isAlreadyAgreed ? "terms-close-button" : "terms-agree-button";
        Spotlight.focus(focusTargetId);
      }, 100);
    } else {
      setSpotlightDisabled(true);
    }
  }, [visible, isAlreadyAgreed]);

  /**
   * 스크롤 리셋 완료 핸들러
   */
  const handleResetScrollComplete = useCallback(() => {
    setResetScroll(false);
  }, []);

  /**
   * 동의 버튼 클릭 핸들러
   */
  const handleAgree = useCallback(() => {
    if (onAgree) {
      onAgree();
    }
  }, [onAgree]);

  /**
   * 닫기 버튼 클릭 핸들러
   */
  const handleClose = useCallback(() => {
    if (onClose) {
      onClose();
    }
  }, [onClose]);

  /**
   * 약관 내용 텍스트 - termsData가 있으면 사용, 없으면 기본값
   */
  const displayTitle = termsData?.title || $L("Optional Terms");
  const displayContent = termsData?.content || `I agree that LG Electronics (LGE) may collect and use Basic Identifier, Commercial Information, Network Activity, Geolocation Data and Inferences, each as defined in the Shop Time Privacy Policy, for personalized and advertising purposes including to display advertisements and offers that are personalized to me or to recommend features, products or contents that might be of interest to me. I understand that I can withdraw my consent at any time by contacting LGE using the contact details [in the Shop Time Privacy Policy] or within [Shop Time application settings] and that any further information that is collected about me will not be used for personalized advertising purposes unless I provide my consent again.`;
  const termsContent = displayContent.length > 0 ? displayContent : $L("No terms content available.");
  console.log('TermsPopup 렌더링:', {
    visible,
    displayTitle,
    contentLength: displayContent.length,
    isAlreadyAgreed
  });

  if (!visible) {
    return null;
  }

  return (
    <TPopUp
      kind="termsPopup"
      open={visible}
      onClose={handleClose}
      hasButton={false}
      className={css.popup}
    >
      <div className={css.container}>
        {/* 약관 카드 */}
        <div className={css.termsCard}>
          {/* 헤더 */}
          {/* 헤더 - 항상 고정 */}
          <div className={css.header}>
            <div className={css.title}>
              {displayTitle}
            </div>
          </div>
          
          {/* 내용 영역 */}
          <div className={css.contentArea}>
            <div className={css.scrollerContainer}>
              <TButtonScroller
                boxHeight={scaleH(460)}
                width={scaleW(980)}
                resetScroll={resetScroll}
                onResetScrollComplete={handleResetScrollComplete}
                className={css.scroller}
              >
                <div className={css.termsContent}>
                  {/* <div className={css.termsTitle}>
                    {$L("Interest Based Recommendation/Advertisement Agreement")}
                  </div> */}
                  <div
                    className={css.termsText}
                    dangerouslySetInnerHTML={{ __html: termsContent }}
                  />
                </div>
              </TButtonScroller>
            </div>
            
            {/* 스크롤바 영역 (시각적 표시용) */}
            <div className={css.scrollbarArea}>
              <div className={css.scrollbarButton}>
                <div className={css.scrollbarIcon} />
              </div>
              <div className={css.scrollbarTrack}>
                <div className={css.scrollbarThumb} />
              </div>
              <div className={css.scrollbarButton}>
                <div className={css.scrollbarIcon} />
              </div>
            </div>
          </div>
        </div>
        
        {/* 버튼 영역 */}
        <div className={css.buttonArea}>
          <div className={css.buttonContainer}>            <TButton
              id="terms-agree-button"
              onClick={handleAgree}
              type={TYPES.primary}
              className={css.agreeButton}
              spotlightDisabled={spotlightDisabled}
              disabled={isAlreadyAgreed}
            >
              {$L("Agree")}
            </TButton>
            <TButton
              id="terms-close-button"  
              onClick={handleClose}
              type={TYPES.secondary}
              className={css.closeButton}
              spotlightDisabled={spotlightDisabled}
            >
              {$L("Close")}
            </TButton>
          </div>
        </div>
      </div>
    </TPopUp>
  );
}