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

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

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

  const handleCheck = useCallback(async () => {
    setBusy(true);
    setStatus('업데이트 확인 중…');
    try {
      const res = await checkDesktopUpdates();
      setStatus(res.message ?? (res.available ? `새 버전 ${res.version}` : '최신 버전입니다.'));
    } finally {
      setBusy(false);
    }
  }, []);

  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" disabled={busy} onClick={() => { void handleCheck(); }}>
            {busy ? '확인 중…' : '업데이트 확인'}
          </button>
          {status && <span className="stg-hint" style={{ marginLeft: 8 }}>{status}</span>}
        </div>
      </div>
    </div>
  );
};

export default DesktopUpdatePanel;
