// screen_login.jsx — VulnerabilityCore authentication with first-login e-mail OTP.
// Step 1 (creds): username + password. If the account is already verified the
// app signs in directly. On first sign-in the backend e-mails a 6-digit code and
// we switch to Step 2 (otp). Once verified, the DB flag is set and future logins
// skip the OTP step.
function LoginScreen({ onLogin, theme }) {
  const [step, setStep] = useState("creds"); // "creds" | "otp"
  const [user, setUser] = useState("");
  const [pw, setPw] = useState("");
  const [show, setShow] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");
  const [otp, setOtp] = useState("");
  const [info, setInfo] = useState(null); // { username, maskedEmail, message }
  const [expired, setExpired] = useState(false); // OTP expired → Verify button becomes "Resend OTP"

  function submit(e) {
    e.preventDefault();
    setErr("");
    if (!user.trim() || !pw.trim()) {
      setErr("Enter your analyst credentials to continue.");
      return;
    }
    setBusy(true);
    window.VCApi.login(user.trim(), pw)
      .then((res) => {
        setBusy(false);
        if (res.otpRequired) {
          setInfo({
            username: res.username || user.trim(),
            maskedEmail: res.maskedEmail,
            message: res.message,
          });
          setOtp("");
          setExpired(false);
          setStep("otp");
        } else {
          onLogin(res.user);
        }
      })
      .catch((error) => {
        setBusy(false);
        setErr(
          error && error.status === 401
            ? "Invalid username or password."
            : error.message || "Sign-in failed.",
        );
      });
  }

  function submitOtp(e) {
    e.preventDefault();
    setErr("");
    if (!otp.trim()) {
      setErr("Enter the 6-digit code from your e-mail.");
      return;
    }
    setBusy(true);
    window.VCApi.verifyOtp(info.username, otp.trim())
      .then((res) => {
        setBusy(false);
        onLogin(res.user);
      })
      .catch((error) => {
        setBusy(false);
        const msg = (error && error.message) || "Verification failed.";
        if (/expired/i.test(msg)) {
          // Code is no longer valid — turn the action button into "Resend OTP".
          setExpired(true);
          setErr("Your OTP has expired. Tap “Resend OTP” to get a new code.");
        } else {
          setErr(msg);
        }
      });
  }

  // Re-run login with the same credentials to mint + e-mail a fresh OTP.
  function resend() {
    setErr("");
    setBusy(true);
    window.VCApi.login(user.trim(), pw)
      .then((res) => {
        setBusy(false);
        if (res.otpRequired) {
          setExpired(false);
          setOtp("");
          setInfo({
            username: res.username || user.trim(),
            maskedEmail: res.maskedEmail,
            message: `A new code was sent to ${res.maskedEmail || "your e-mail"}.`,
          });
        } else {
          // Account got verified in the meantime — just sign in.
          onLogin(res.user);
        }
      })
      .catch((error) => {
        setBusy(false);
        setErr((error && error.message) || "Could not resend the code.");
      });
  }

  function backToCreds() {
    setStep("creds");
    setErr("");
    setOtp("");
    setExpired(false);
  }

  return (
    <div className="login">
      <div className="login-aside">
        <div className="login-aside-grid" />
        <div className="login-aside-scan" />
        {/* <div className="login-aside-top">
          <Logo size={26} />
          <span className="login-poc">PROOF OF CONCEPT · v0.9</span>
        </div> */}
        <div className="login-aside-mid">
          <div className="login-steps">
            {[
              ["Collect", "cybersecurity data from global sources", "bell"],
              ["Correlate", "threats mapped to vehicle components", "browse"],
              ["Act", "prioritize risk, surface what matters", "bolt"],
            ].map(([t, d, ic], i) => (
              <div
                className="login-step"
                key={t}
                style={{ animationDelay: i * 0.12 + 0.2 + "s" }}
              >
                <span className="login-step-num">
                  {String(i + 1).padStart(2, "0")}
                </span>
                <Icon name={ic} size={18} className="login-step-ic" />
                <div className="login-step-tx">
                  <strong>{t}</strong>
                  <span>{d}</span>
                </div>
              </div>
            ))}
          </div>
          <h1 className="login-tag">
            Proactive cybersecurity
            <br />
            visibility.
          </h1>
          <p className="login-sub">
            AI-classified automotive threat &amp; vulnerability intelligence 
            turning the world's CVE noise into clear vehicle risk.
          </p>
        </div>
      </div>

      <div className="login-main">
        <img
          src={
            theme === "light"
              ? (window.__resources && window.__resources.cymoLogoLight) ||
                "VulnerabilityCore/assets/cymobility-logo-light.png"
              : (window.__resources && window.__resources.cymoLogo) ||
                "VulnerabilityCore/assets/cymobility-logo.png"
          }
          alt="CyMobility"
          className="login-main-cymo"
        />
        {step === "creds" ? (
          <form className="login-card" onSubmit={submit}>
            <div className="login-card-head">
              <span className="login-eyebrow">Analyst access</span>
              <h2>Sign in to vulnerability.core</h2>
              {/* <p>
                Single sign-on for CyMobility tenants · verified once by e-mail.
              </p> */}
            </div>

            <label className="field">
              <span className="field-lab">Username</span>
              <div className="field-wrap">
                <Icon name="user" size={16} className="field-ic" />
                <input
                  value={user}
                  onChange={(e) => setUser(e.target.value)}
                  autoComplete="username"
                  placeholder="analyst handle"
                  spellCheck="false"
                />
              </div>
            </label>

            <label className="field">
              <span className="field-lab">Password</span>
              <div className="field-wrap">
                <Icon name="shield" size={16} className="field-ic" />
                <input
                  type={show ? "text" : "password"}
                  value={pw}
                  onChange={(e) => setPw(e.target.value)}
                  autoComplete="current-password"
                  placeholder="••••••••••"
                />
                <button
                  type="button"
                  className="field-toggle"
                  onClick={() => setShow((s) => !s)}
                >
                  {show ? "Hide" : "Show"}
                </button>
              </div>
            </label>

            {err && (
              <div className="login-err">
                <Icon name="bell" size={14} />
                {err}
              </div>
            )}

            <button
              className="btn btn-accent btn-block"
              type="submit"
              disabled={busy}
            >
              {busy ? (
                <span className="btn-spin" />
              ) : (
                <>
                  <Icon
                    name="logout"
                    size={16}
                    style={{ transform: "scaleX(-1)" }}
                  />
                  Sign in
                </>
              )}
            </button>

            <div className="login-card-foot">
              <span className="login-hint">
                Sign in with your vulnerability.core account.
              </span>
              {/* <a className="login-link" href="#">SSO / SAML</a> */}
            </div>
          </form>
        ) : (
          <form className="login-card" onSubmit={submitOtp}>
            <div className="login-card-head">
              <span className="login-eyebrow">Identity verification</span>
              <h2>Enter your code</h2>
              <p>
                {(info && info.message) ||
                  `We e-mailed a 6-digit code to ${(info && info.maskedEmail) || "your e-mail"}.`}
              </p>
            </div>

            <label className="field">
              <span className="field-lab">Verification code</span>
              <div className="field-wrap">
                <Icon name="shield" size={16} className="field-ic" />
                <input
                  value={otp}
                  onChange={(e) =>
                    setOtp(e.target.value.replace(/\D/g, "").slice(0, 6))
                  }
                  inputMode="numeric"
                  autoComplete="one-time-code"
                  autoFocus
                  placeholder="6-digit code"
                  spellCheck="false"
                  style={{ letterSpacing: "0.3em" }}
                />
              </div>
            </label>

            {err && (
              <div className="login-err">
                <Icon name="bell" size={14} />
                {err}
              </div>
            )}

            {expired ? (
              <button
                className="btn btn-accent btn-block"
                type="button"
                disabled={busy}
                onClick={resend}
              >
                {busy ? (
                  <span className="btn-spin" />
                ) : (
                  <>
                    <Icon name="refresh" size={16} />
                    Resend OTP
                  </>
                )}
              </button>
            ) : (
              <button
                className="btn btn-accent btn-block"
                type="submit"
                disabled={busy}
              >
                {busy ? (
                  <span className="btn-spin" />
                ) : (
                  <>
                    <Icon name="check" size={16} />
                    Verify &amp; sign in
                  </>
                )}
              </button>
            )}

            <div className="login-card-foot">
              <button
                type="button"
                className="login-link"
                onClick={backToCreds}
              >
                ← Back
              </button>
              <span className="login-hint">
                First sign-in only — we'll remember this account next time.
              </span>
            </div>
          </form>
        )}
        <p className="login-legal">
          © 2026 CyMobility Private Limited · Bengaluru · Austin
        </p>
      </div>
    </div>
  );
}
window.LoginScreen = LoginScreen;
