/* AdminGate — 관리자 사이트/README 진입 시 비밀번호 프롬프트.
 * - 세션: sessionStorage (탭 닫히면 자동 락)
 * - 30분 무동작 idle timeout (CIS.touchAdmin() 으로 활동 갱신)
 * - 비밀번호는 SHA-256 해시로 shared-data.js 에 저장돼 있음
 */
function AdminGate({ children }) {
  const [unlocked, setUnlocked] = useState(() => CIS.isAdminUnlocked());
  const [pw, setPw] = useState('');
  const [err, setErr] = useState(null);
  const [busy, setBusy] = useState(false);
  const [showPw, setShowPw] = useState(false);
  const [remaining, setRemaining] = useState(null);
  const inputRef = useRef(null);

  // idle timeout tracker: 활동을 감지하면 touch, 5초마다 남은 시간 계산
  useEffect(() => {
    if (!unlocked) return;
    const events = ['click', 'keydown', 'mousemove'];
    let last = Date.now();
    const onAct = () => {
      const now = Date.now();
      if (now - last > 5000) { CIS.touchAdmin(); last = now; }
    };
    events.forEach(e => document.addEventListener(e, onAct, { passive: true }));

    const check = setInterval(() => {
      if (!CIS.isAdminUnlocked()) {
        setUnlocked(false); setPw(''); setErr('세션이 만료됐어요. 다시 로그인해주세요.');
      } else {
        try {
          const t = JSON.parse(sessionStorage.getItem(CIS.K.adminGate));
          const left = Math.max(0, 30 * 60 * 1000 - (Date.now() - t.last));
          setRemaining(Math.ceil(left / 60000));
        } catch (e) {}
      }
    }, 5000);

    return () => {
      events.forEach(e => document.removeEventListener(e, onAct));
      clearInterval(check);
    };
  }, [unlocked]);

  useEffect(() => {
    if (!unlocked && inputRef.current) inputRef.current.focus();
  }, [unlocked]);

  async function submit(e) {
    e && e.preventDefault && e.preventDefault();
    if (busy) return;
    setBusy(true); setErr(null);
    const res = await CIS.unlockAdmin(pw);
    if (res.ok) { setUnlocked(true); setPw(''); }
    else { setErr(res.msg); setPw(''); if (inputRef.current) inputRef.current.focus(); }
    setBusy(false);
  }

  function logout() {
    if (!confirm('관리자 로그아웃하시겠어요? · Sign out as admin?')) return;
    CIS.lockAdmin();
    setUnlocked(false); setPw(''); setErr(null);
  }

  if (unlocked) {
    return (
      <>
        {children}
        <AdminBadge remaining={remaining} onLogout={logout}/>
      </>
    );
  }

  return (
    <div style={gateBg}>
      <div style={gateCard}>
        {/* Brand */}
        <div style={{ display:'flex', alignItems:'center', gap: 10, marginBottom: 20 }}>
          <img src="../../assets/logo-mark.svg" width="34" height="34" alt="" style={{ borderRadius: 8, flexShrink: 0 }}/>
          <div style={{ lineHeight: 1.25, minWidth: 0 }}>
            <div style={{ fontSize: 14, fontWeight: 700, letterSpacing: '-0.01em' }}>Career Intelligence Suite</div>
            <div style={{ fontSize: 10.5, color: 'var(--fg-3)', letterSpacing:'0.14em', fontWeight: 500, marginTop: 2 }}>ADMIN CONSOLE</div>
          </div>
        </div>

        <div style={{
          width: 56, height: 56, borderRadius: 14, margin: '0 auto',
          background: 'linear-gradient(135deg, var(--brand-500), var(--violet-500, #7C55F2))',
          color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 12px 30px rgba(31, 95, 255, 0.24)',
        }}>
          <Icon name="shield-check" size={22}/>
        </div>

        <div style={{ textAlign: 'center', marginTop: 16 }}>
          <h1 style={{ fontSize: 22, fontWeight: 700, letterSpacing:'-0.02em', margin: 0 }}>
            관리자 인증
          </h1>
          <div style={{ fontSize: 13, color: 'var(--fg-3)', marginTop: 4 }}>
            Restricted area · Enter admin password to continue
          </div>
        </div>

        <form onSubmit={submit} style={{ marginTop: 20, display: 'grid', gap: 12 }}>
          <div>
            <label style={{ fontSize: 12, fontWeight: 600, color: 'var(--fg-2)', display: 'block', marginBottom: 6 }}>
              비밀번호 (Password)
            </label>
            <div style={{ position: 'relative' }}>
              <input ref={inputRef}
                type={showPw ? 'text' : 'password'}
                value={pw}
                onChange={e => { setPw(e.target.value); setErr(null); }}
                placeholder="••••••••••"
                autoComplete="current-password"
                style={pwInput}/>
              <button type="button" onClick={() => setShowPw(v => !v)} style={eyeBtn} aria-label={showPw ? '숨기기' : '표시'}>
                <Icon name={showPw ? 'eye-off' : 'eye'} size={15}/>
              </button>
            </div>
          </div>

          {err && (
            <div style={{
              padding: '9px 12px', borderRadius: 8, fontSize: 12.5,
              background: '#FDECEC', color: '#8F1515',
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              <Icon name="alert-circle" size={14}/>
              {err}
            </div>
          )}

          <button type="submit" disabled={busy || !pw} style={{
            ...submitBtn,
            background: busy ? 'var(--brand-300)' : (!pw ? 'var(--neutral-200, #D5D9E0)' : submitBtn.background),
            cursor: busy || !pw ? 'not-allowed' : 'pointer',
          }}>
            {busy ? (<><Icon name="loader-2" size={14}/> 인증 중… (Verifying…)</>) : (<>인증 후 진입 · Unlock <Icon name="arrow-right" size={14}/></>)}
          </button>
        </form>

        <div style={{
          marginTop: 20, padding: 12, background: 'var(--neutral-50)',
          borderRadius: 8, fontSize: 11.5, color: 'var(--fg-3)', lineHeight: 1.55,
        }}>
          <b style={{ color: 'var(--fg-2)' }}>🔒 보안 안내 · Security notice</b><br/>
          • 이 화면은 관리자 전용이에요. 지원자는 사용할 수 없어요.<br/>
          • 30분 무동작 시 자동 로그아웃돼요. Idle for 30 min → auto sign-out.<br/>
          • 브라우저 탭을 닫으면 세션이 초기화돼요.<br/>
          <a href="../applicant/index.html" style={{
            color: 'var(--brand-600)', fontWeight: 600, textDecoration: 'none',
            display: 'inline-flex', alignItems: 'center', gap: 4, marginTop: 8,
          }}>
            <Icon name="arrow-left" size={11}/>
            지원자 사이트로 돌아가기 · Back to applicant site
          </a>
        </div>
      </div>
    </div>
  );
}

function AdminBadge({ remaining, onLogout }) {
  return (
    <div style={{
      position: 'fixed', bottom: 16, right: 16, zIndex: 50,
      background: 'var(--neutral-0)',
      border: '1px solid var(--border-strong)',
      borderRadius: 999, padding: '6px 8px 6px 12px',
      display: 'inline-flex', alignItems: 'center', gap: 8,
      fontSize: 11.5, fontWeight: 500,
      boxShadow: 'var(--shadow-md)',
    }}>
      <span style={{
        width: 6, height: 6, borderRadius: 999, background: 'var(--success-500, #17A34A)',
      }}/>
      <span style={{ color: 'var(--fg-2)' }}>관리자 세션</span>
      {remaining != null && (
        <span style={{ color: 'var(--fg-3)', fontFamily: 'var(--font-latin)', fontVariantNumeric: 'tabular-nums' }}>
          {remaining}분 남음
        </span>
      )}
      <button onClick={onLogout} style={{
        marginLeft: 4, padding: '3px 8px', background: 'var(--neutral-100)',
        border: 'none', borderRadius: 999, cursor: 'pointer',
        fontSize: 10.5, fontWeight: 600, color: 'var(--fg-1)', fontFamily: 'var(--font-sans)',
      }}>로그아웃</button>
    </div>
  );
}

const gateBg = {
  minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
  background: 'radial-gradient(120% 90% at 15% 0%, #E9EEFB 0%, var(--neutral-50) 55%)',
  padding: '48px 20px',
};
const gateCard = {
  width: '100%', maxWidth: 420,
  background: 'var(--neutral-0)', borderRadius: 18,
  padding: 32,
  border: '1px solid var(--border-default)',
  boxShadow: '0 20px 60px rgba(6, 19, 63, 0.14)',
};
const pwInput = {
  width: '100%', padding: '12px 42px 12px 12px',
  border: '1px solid var(--border-default)', borderRadius: 8,
  fontSize: 14, fontFamily: 'var(--font-sans)', outline: 'none',
  background: 'var(--neutral-0)', color: 'var(--fg-1)',
  boxSizing: 'border-box',
};
const eyeBtn = {
  position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)',
  background: 'transparent', border: 'none', cursor: 'pointer',
  padding: 6, color: 'var(--fg-3)',
  display: 'inline-flex',
};
const submitBtn = {
  padding: '12px 16px',
  background: 'var(--brand-500)', color: '#fff', border: 'none', borderRadius: 10,
  fontSize: 14, fontWeight: 700, fontFamily: 'var(--font-sans)',
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
};

window.AdminGate = AdminGate;
