import { useEffect, useRef, useState } from 'react'
import { verifyToken, tokenStore } from '../api/client.js'

/** 未携带有效密钥时全屏展示, 校验通过后写入 localStorage 并刷新应用状态 */
export default function AccessGate() {
  const [key, setKey] = useState('')
  const [err, setErr] = useState('')
  const [loading, setLoading] = useState(false)
  const inputRef = useRef(null)

  useEffect(() => {
    inputRef.current?.focus()
  }, [])

  const submit = async () => {
    const v = key.trim()
    if (!v) return
    setLoading(true)
    setErr('')
    try {
      const r = await verifyToken(v)
      if (r && r.ok) {
        tokenStore.set(v)
      } else {
        setErr('密钥不正确')
      }
    } catch (e) {
      setErr(e.message || '验证失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="access-gate">
      <div className="card" style={{ width: '100%', maxWidth: 360 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <img src="/logo.png" alt="" width={36} height={36} style={{ borderRadius: 8 }} />
          <h1 style={{ fontSize: 18, margin: 0 }}>萌邮 MengPost</h1>
        </div>
        <p className="muted" style={{ marginBottom: 16, fontSize: 14 }}>
          请输入访问密钥（与后端 <code>MP_TOKEN</code> 一致）
        </p>
        <input
          ref={inputRef}
          type="password"
          autoComplete="off"
          placeholder="访问密钥"
          value={key}
          onChange={(e) => setKey(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && submit()}
        />
        {err && (
          <div style={{ color: 'var(--danger)', fontSize: 13, marginTop: 10 }}>{err}</div>
        )}
        <div style={{ marginTop: 14 }}>
          <button type="button" className="btn-primary" disabled={loading} onClick={submit}>
            {loading ? '验证中…' : '进入'}
          </button>
        </div>
      </div>
    </div>
  )
}
