import { useState } from "react";
import { useDomainflare } from "../context/DomainflareContext";

/** 登录门禁：校验面板 APP_ACCESS_TOKEN */
export function Gate() {
  const { unlockWithToken } = useDomainflare();
  const [token, setToken] = useState("");
  const [error, setError] = useState<string | null>(null);

  async function submit() {
    const t = token.trim();
    setError(null);
    if (!t) {
      setError("请输入令牌");
      return;
    }
    try {
      await unlockWithToken(t);
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    }
  }

  return (
    <div id="overlay" className="overlay" role="dialog" aria-modal="true" aria-labelledby="gate-title">
      <div className="overlay-card">
        <h2 id="gate-title">访问验证</h2>
        <p className="muted small">
          请输入面板访问令牌。令牌由部署时在 Worker 环境变量 <code>APP_ACCESS_TOKEN</code>{" "}
          配置（默认与 wrangler.toml 中一致）。
        </p>
        <label className="field">
          <span>访问令牌</span>
          <input
            id="gate-token"
            type="password"
            autoComplete="off"
            placeholder="输入令牌"
            value={token}
            onChange={(e) => setToken(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && void submit()}
          />
        </label>
        {error ? (
          <p id="gate-error" className="error small">
            {error}
          </p>
        ) : null}
        <button type="button" id="gate-submit" className="btn primary" onClick={() => void submit()}>
          进入
        </button>
      </div>
    </div>
  );
}
