import React, { useCallback, useEffect, useState } from 'react';
import { isDesktop } from '../utils/platform';
import { getDesktopAppVersion } from '../utils/desktopBridge';
import DesktopUpdateModal from './DesktopUpdateModal';

/** PC(Tauri) 앱 — 버전 표시 및 업데이트 확인 */
const DesktopUpdatePanel: React.FC = () => {
  const [version, setVersion] = useState<string>('—');
  const [modalOpen, setModalOpen] = useState(false);

  useEffect(() => {
    if (!isDesktop()) return;
    void getDesktopAppVersion().then(v => {
      if (v) setVersion(v);
    });
  }, []);

  const handleOpen = useCallback(() => {
    setModalOpen(true);
  }, []);

  if (!isDesktop()) return null;

  return (
    <>
      <div className="stg-section">
        <h3 className="stg-section-title">PC 앱 (GoldenChart Desktop)</h3>
        <div className="stg-row">
          <div className="stg-row-label">
            <strong>현재 버전</strong>
            <p className="stg-row-desc">설치된 데스크톱 클라이언트 버전입니다.</p>
          </div>
          <div className="stg-row-control">
            <span>{version}</span>
          </div>
        </div>
        <div className="stg-row">
          <div className="stg-row-label">
            <strong>업데이트</strong>
            <p className="stg-row-desc">서버에서 새 버전을 확인하고 다운로드합니다.</p>
          </div>
          <div className="stg-row-control">
            <button type="button" className="stg-btn-secondary" onClick={handleOpen}>
              업데이트 확인
            </button>
          </div>
        </div>
      </div>
      <DesktopUpdateModal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        autoStart
      />
    </>
  );
};

export default DesktopUpdatePanel;
