// Xedap.vn — Popup đăng nhập (dùng lại logic của trang dang-nhap.html).
// Bước SĐT → OTP 4 ô; OTP "1111" = thành công → account.html, khác = báo sai.
const { Button, Input } = window.XedapVnDesignSystem_03b1c0;

function LoginModal({ open, onClose }) {
  const [phone, setPhone] = React.useState("");
  const [step, setStep] = React.useState("phone");
  const [otp, setOtp] = React.useState(["", "", "", ""]);
  const [error, setError] = React.useState(false);
  const valid = /^0\d{8,10}$/.test(phone.trim());
  const inputs = React.useRef([]);

  React.useEffect(() => {
    if (open) { setPhone(""); setStep("phone"); setOtp(["", "", "", ""]); setError(false); }
  }, [open]);

  const setDigit = (i, val) => {
    const d = val.replace(/\D/g, "").slice(-1);
    setOtp((prev) => { const next = [...prev]; next[i] = d; return next; });
    setError(false);
    if (d && i < 3) inputs.current[i + 1] && inputs.current[i + 1].focus();
  };
  const onKeyDown = (i, e) => {
    if (e.key === "Backspace" && !otp[i] && i > 0) inputs.current[i - 1] && inputs.current[i - 1].focus();
  };

  if (!open) return null;
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 200, background: "rgba(15,23,42,.5)", backdropFilter: "blur(2px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ position: "relative", background: "var(--card)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-lg)", padding: "48px 44px", maxWidth: 440, width: "100%" }}>
        <button onClick={onClose} aria-label="Đóng" style={{ position: "absolute", top: 16, right: 16, width: 36, height: 36, borderRadius: "50%", border: "none", background: "var(--secondary)", cursor: "pointer", display: "grid", placeItems: "center", color: "var(--foreground)" }}>
          <i className="ph ph-x" style={{ fontSize: 18 }}></i>
        </button>
        <h1 style={{ margin: "0 0 32px", textAlign: "center", fontSize: 28, fontWeight: 500, color: "var(--foreground)" }}>Đăng nhập</h1>

        {step === "phone" ? (
          <React.Fragment>
            <div style={{ position: "relative", marginBottom: 20 }}>
              <i className="ph ph-device-mobile" style={{ position: "absolute", left: 18, top: "50%", transform: "translateY(-50%)", fontSize: 20, color: "var(--muted-foreground)", pointerEvents: "none" }}></i>
              <Input type="tel" inputMode="numeric" value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="Nhập số điện thoại mua hàng" style={{ height: 52, paddingLeft: 48, borderRadius: "5px", fontSize: 15, boxSizing: "border-box" }} />
            </div>
            <Button variant="default" size="lg" disabled={!valid} onClick={() => { setStep("otp"); setOtp(["", "", "", ""]); setTimeout(() => inputs.current[0] && inputs.current[0].focus(), 60); }} style={{ width: "100%", height: 52, fontSize: 16, letterSpacing: "0.04em", textTransform: "uppercase", boxShadow: "var(--shadow-primary)" }}>
              Tiếp tục
            </Button>
            <p style={{ margin: "22px 0 0", textAlign: "center", fontSize: 13, lineHeight: 1.6, color: "var(--muted-foreground)" }}>
              Nhấn "Tiếp tục" đồng nghĩa với việc bạn cho phép hệ thống gửi tin nhắn xác thực đến số điện thoại trên
            </p>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <p style={{ margin: "0 0 24px", textAlign: "center", fontSize: 14, lineHeight: 1.6, color: "var(--muted-foreground)" }}>
              Nhập mã xác thực gồm 4 số vừa được gửi tới <strong style={{ color: "var(--foreground)" }}>{phone}</strong>
            </p>
            <div style={{ display: "flex", justifyContent: "center", gap: 14, marginBottom: 18 }}>
              {otp.map((d, i) => (
                <input key={i} ref={(el) => (inputs.current[i] = el)} value={d} onChange={(e) => setDigit(i, e.target.value)} onKeyDown={(e) => onKeyDown(i, e)} inputMode="numeric" maxLength={1} style={{ width: 60, height: 68, textAlign: "center", fontSize: 28, fontWeight: 600, color: "var(--foreground)", border: "1.5px solid " + (d ? "var(--primary)" : "var(--border)"), borderRadius: "var(--radius)", outline: "none", fontFamily: "var(--font-sans)", background: "#fff", transition: "border-color .15s" }} />
              ))}
            </div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 8, marginBottom: 24, fontSize: 13.5, color: "var(--muted-foreground)" }}>
              <i className="ph ph-chat-circle-dots" style={{ fontSize: 17, color: "var(--primary)" }}></i>
              <span>Mã OTP đã được gửi qua <strong style={{ color: "var(--foreground)" }}>ZNS</strong> hoặc <strong style={{ color: "var(--foreground)" }}>SMS</strong></span>
            </div>
            {error && (
              <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 7, marginBottom: 20, fontSize: 13.5, color: "var(--destructive)", fontWeight: 500 }}>
                <i className="ph ph-warning-circle" style={{ fontSize: 16 }}></i>
                <span>Mã OTP chưa đúng, vui lòng thử lại</span>
              </div>
            )}
            <Button variant="default" size="lg" disabled={otp.some((d) => !d)} onClick={() => { if (otp.join("") === "1111") { window.location.href = "account.html"; } else { setError(true); } }} style={{ width: "100%", height: 52, fontSize: 16, letterSpacing: "0.04em", textTransform: "uppercase", boxShadow: "var(--shadow-primary)" }}>
              Xác nhận
            </Button>
            <div style={{ margin: "18px 0 0", textAlign: "center" }}>
              <button onClick={() => setStep("phone")} style={{ background: "none", border: "none", padding: 0, cursor: "pointer", color: "var(--primary)", fontFamily: "var(--font-sans)", fontSize: 13.5, fontWeight: 600 }}>Đổi số điện thoại</button>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { LoginModal });
