import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/useAuth';
import { getDownloadInfo } from '../api/download';
import './DownloadSection.css';

export default function DownloadSection() {
  const [info, setInfo] = useState(null);
  const [ready, setReady] = useState(false);
  const [launching, setLaunching] = useState(false);
  const { user } = useAuth();
  const navigate = useNavigate();

  useEffect(() => {
    getDownloadInfo()
      .then((data) => { setInfo(data); setReady(true); })
      .catch(() => setReady(true));
  }, []);

  const handlePlay = () => {
    if (!user) {
      navigate('/login');
      return;
    }

    setLaunching(true);

    let launched = false;
    const onBlur = () => { launched = true; };
    window.addEventListener('blur', onBlur);
    window.location.href = 'a301://launch?token=' + user.token;

    setTimeout(() => {
      window.removeEventListener('blur', onBlur);
      setLaunching(false);
      if (!launched && info?.launcherUrl) {
        // 런처 미설치 → launcher.exe 다운로드
        const a = document.createElement('a');
        a.href = info.launcherUrl;
        a.download = 'launcher.exe';
        a.click();
      }
    }, 2000);
  };

  if (!ready) return null;

  return (
    <section className="download-section">
      <div className="download-content">
        <h2 className="download-title">One of the plans</h2>
        {info ? (
          <>
            <p className="download-meta">
              {info.version} &middot; {info.fileSize}
            </p>
            <button onClick={handlePlay} className="btn-play" disabled={launching}>
              {launching ? '실행 중...' : '게임 시작'}
            </button>
            <p className="launch-hint">
              런처 미설치 시 자동으로 다운로드됩니다. 설치 후 다시 클릭하세요.
            </p>
          </>
        ) : (
          <p className="download-preparing">런처 준비 중입니다. 잠시 후 다시 확인해주세요.</p>
        )}
      </div>
    </section>
  );
}
