/**
 * 관리자 설정 패널 — 비밀번호 확인 후 콘텐츠 표시
 */
import React, { useState } from 'react';
import { verifyAdminPassword } from '../utils/backendApi';
import { isAdminUnlocked, setAdminUnlocked } from '../utils/adminUnlock';

interface Props {
  children: React.ReactNode;
}

const AdminPasswordGate: React.FC<Props> = ({ children }) => {
  const [unlocked, setUnlocked] = useState(isAdminUnlocked);
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  if (unlocked) return <>{children}</>;

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      await verifyAdminPassword(password);
      setAdminUnlocked();
      setUnlocked(true);
      setPassword('');
    } catch (err) {
      setError(err instanceof Error ? err.message : '비밀번호 확인에 실패했습니다.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="admin-gate">
      <div className="admin-gate-card">
        <h3 className="admin-gate-title">관리자 인증</h3>
        <p className="admin-gate-desc">
          관리자 설정을 보려면 로그인한 관리자 계정의 비밀번호를 입력하세요.
          (기본: admin / admin)
        </p>
        <form onSubmit={submit} className="admin-gate-form">
          <label className="admin-gate-field">
            <span>관리자 비밀번호</span>
            <input
              type="text"
              autoComplete="off"
              className="admin-gate-field--visible"
              value={password}
              onChange={e => setPassword(e.target.value)}
              disabled={loading}
              placeholder="비밀번호"
            />
          </label>
          {error && <p className="admin-gate-error">{error}</p>}
          <button type="submit" className="admin-gate-btn" disabled={loading || !password}>
            {loading ? '확인 중…' : '확인'}
          </button>
        </form>
      </div>
    </div>
  );
};

export default AdminPasswordGate;
