// Login + Email OTP flow

const ADMIN_EMAILS = ["tsechun@duidui.app", "chu@duidui.app"];

const LoginScreen = ({ onLogin }) => {
  const [step, setStep] = useState("credentials"); // credentials -> otp
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [otp, setOtp] = useState(["", "", "", "", "", ""]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [resendIn, setResendIn] = useState(0);
  const otpRefs = useRef([]);

  useEffect(() => {
    if (resendIn <= 0) return;
    const t = setTimeout(() => setResendIn(r => r - 1), 1000);
    return () => clearTimeout(t);
  }, [resendIn]);

  const submitCred = async () => {
    setError("");
    if (!email || !password) { setError("請輸入帳號與密碼"); return; }
    if (!ADMIN_EMAILS.includes(email)) { setError("帳號或密碼錯誤"); return; }
    setLoading(true);
    try {
      const verifyRes = await fetch("/api/admin/auth/verify", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password }),
      });
      if (!verifyRes.ok) {
        const d = await verifyRes.json().catch(() => ({}));
        setError(d.error || "帳號或密碼錯誤");
        setLoading(false);
        return;
      }
    } catch {
      setError("網路錯誤，請稍後再試");
      setLoading(false);
      return;
    }
    localStorage.setItem("adminEmail", email);
    try {
      const res = await fetch("/api/admin/otp/send", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        setError(data.error || "驗證碼發送失敗，請稍後再試");
        setLoading(false);
        return;
      }
      setStep("otp");
      setResendIn(30);
    } catch {
      setError("網路錯誤，請稍後再試");
    }
    setLoading(false);
  };

  const submitOtp = async () => {
    const code = otp.join("");
    if (code.length < 6) { setError("請輸入完整 6 位驗證碼"); return; }
    setError("");
    setLoading(true);
    try {
      const res = await fetch("/api/admin/otp/verify", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, token: code }),
      });
      if (!res.ok) {
        setError("驗證碼錯誤，請重新輸入");
        setLoading(false);
        setOtp(["","","","","",""]);
        otpRefs.current[0]?.focus();
        return;
      }
      onLogin?.(email);
    } catch {
      setError("網路錯誤，請稍後再試");
      setLoading(false);
    }
  };

  const setOtpDigit = (i, v) => {
    v = v.replace(/\D/g, "").slice(0, 1);
    const next = [...otp]; next[i] = v; setOtp(next);
    if (v && i < 5) otpRefs.current[i + 1]?.focus();
  };
  const onOtpKeyDown = (i, e) => {
    if (e.key === "Backspace" && !otp[i] && i > 0) otpRefs.current[i - 1]?.focus();
    if (e.key === "Enter" && otp.every(d => d)) submitOtp();
  };
  const onOtpPaste = (e) => {
    const digits = e.clipboardData.getData("text").replace(/\D/g,"").slice(0,6);
    if (digits.length) {
      e.preventDefault();
      const next = digits.padEnd(6, "").split("").slice(0,6);
      setOtp(next.map(d => d || ""));
      otpRefs.current[Math.min(digits.length, 5)]?.focus();
    }
  };

  return (
    <div style={{
      minHeight: "100vh", display: "grid", gridTemplateColumns: "1fr 1fr",
      background: "#FBF7F0",
    }}>
      {/* Left: brand */}
      <div style={{
        backgroundColor: "#FBF7F0",
        backgroundImage: "radial-gradient(rgba(148, 184, 247, 0.45) 2px, transparent 2px)",
        backgroundSize: "20px 20px",
        padding: "48px 56px", display: "flex", flexDirection: "column",
        position: "relative", overflow: "hidden",
      }}>
        <div>
          <img src="中文色彩.png" alt="堆堆" style={{ height: 32, objectFit: "contain", display: "block" }}/>
        </div>
        <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center" }}>
          <img src="/emoji2/flower.png" alt="" style={{ width: 576, height: 576, objectFit: "contain" }}/>
        </div>
        <div style={{ fontSize: 12, color: "#A7664B" }}>© 2026 DuiDui Studio</div>
      </div>

      {/* Right: form */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", padding: 40 }}>
        <div style={{ width: "100%", maxWidth: 380 }} className="fade-in" key={step}>
          {step === "credentials" ? (
            <>
              <div style={{ fontSize: 22, fontWeight: 600, marginBottom: 6 }}>登入後台</div>
              <div style={{ fontSize: 13.5, color: "var(--ink-3)", marginBottom: 28 }}>
                僅限獲授權人員使用。所有操作皆會被記錄。
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                <div>
                  <label style={labelStyle}>公司信箱</label>
                  <Input icon="mail" value={email} onChange={e => setEmail(e.target.value)} placeholder="admin@duidui.app"/>
                </div>
                <div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
                    <label style={{ ...labelStyle, marginBottom: 0 }}>密碼</label>
                    <button style={{ fontSize: 12, color: "var(--ink-3)" }}>忘記密碼?</button>
                  </div>
                  <Input icon="lock" type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••"/>
                </div>
                {error && <div style={{ fontSize: 12.5, color: "var(--danger)", display: "flex", alignItems: "center", gap: 6 }}><Icon name="alert" size={14}/>{error}</div>}
                <Button variant="primary" size="lg" onClick={submitCred} disabled={loading} style={{ width: "100%", marginTop: 6 }}>
                  {loading ? "驗證中…" : "繼續"}
                </Button>
              </div>
            </>
          ) : (
            <>
              <button onClick={() => setStep("credentials")} style={{ display: "inline-flex", alignItems: "center", gap: 4, color: "var(--ink-3)", fontSize: 13, marginBottom: 20 }}>
                <Icon name="arrow-left" size={14}/> 返回
              </button>
              <div style={{ fontSize: 22, fontWeight: 600, marginBottom: 6 }}>輸入 Email 驗證碼</div>
              <div style={{ fontSize: 13.5, color: "var(--ink-3)", marginBottom: 28 }}>
                已將 6 位驗證碼發送至 <span style={{ color: "var(--ink-2)", fontWeight: 500 }}>{email.replace(/(.{2}).+(@.+)/, "$1•••$2")}</span>,5 分鐘內有效。
              </div>
              <div style={{ display: "flex", gap: 8, justifyContent: "space-between", marginBottom: 16 }}>
                {otp.map((d, i) => (
                  <input
                    key={i}
                    ref={el => otpRefs.current[i] = el}
                    value={d}
                    onChange={e => setOtpDigit(i, e.target.value)}
                    onKeyDown={e => onOtpKeyDown(i, e)}
                    onPaste={i === 0 ? onOtpPaste : undefined}
                    inputMode="numeric"
                    maxLength={1}
                    style={{
                      width: 48, height: 56, fontSize: 22, textAlign: "center",
                      border: "1.5px solid " + (d ? "var(--ink)" : "var(--border-strong)"),
                      borderRadius: 10, fontFamily: "var(--font-mono)", fontWeight: 600,
                      outline: 0, background: "var(--surface)", transition: "border-color .15s",
                    }}
                  />
                ))}
              </div>
              {error && <div style={{ fontSize: 12.5, color: "var(--danger)", marginBottom: 12, display: "flex", alignItems: "center", gap: 6 }}><Icon name="alert" size={14}/>{error}</div>}
              <Button variant="primary" size="lg" onClick={submitOtp} disabled={loading || otp.some(d => !d)} style={{ width: "100%" }}>
                {loading ? "驗證中…" : "驗證並登入"}
              </Button>
              <div style={{ marginTop: 18, textAlign: "center", fontSize: 13, color: "var(--ink-3)" }}>
                沒收到驗證碼?{" "}
                {resendIn > 0 ? (
                  <span>可於 {resendIn} 秒後重發</span>
                ) : (
                  <button onClick={async () => {
                    setResendIn(30); setError("");
                    await fetch("/api/admin/otp/send", {
                      method: "POST",
                      headers: { "Content-Type": "application/json" },
                      body: JSON.stringify({ email }),
                    });
                  }} style={{ color: "var(--accent-ink)", fontWeight: 500 }}>重新發送</button>
                )}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

const BrandMark = ({ size = 28 }) => (
  <img src="/admin-logo.png" width={size} height={size} style={{ objectFit: "contain" }}/>
);

Object.assign(window, { LoginScreen, BrandMark });
