// screens/login.jsx — vulnerabilitycore authentication with one-time account activation.
// Step 1 (creds): username + password. An activated account signs in directly. An
// account that is not activated yet goes to Step 2 (activate): the 24-character
// activation token the administrator was shown when they created the account. It
// works once; after it, every sign-in is Step 1 alone.
const ACTIVATION_TOKEN_LENGTH = 24;

function LoginScreen({ onLogin, theme }) {
  const [step, setStep] = useState("creds"); // "creds" | "activate"
  const [user, setUser] = useState("");
  const [pw, setPw] = useState("");
  const [show, setShow] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");
  const [activationToken, setActivationToken] = useState("");
  const [info, setInfo] = useState(null); // { username, message }
  // Why the last session ended, when the server said: the account signed in on another device.
  const [notice, setNotice] = useState(() => window.VCApi.takeSignOutNotice());

  function submit(e) {
    e.preventDefault();
    setErr("");
    setNotice(null);
    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.activationRequired) {
          setInfo({ username: res.username || user.trim(), message: res.message });
          setActivationToken("");
          setStep("activate");
        } else {
          onLogin(res.user);
        }
      })
      .catch((error) => {
        setBusy(false);
        setErr(
          error && error.status === 401
            ? "Invalid username or password."
            : error.message || "Sign-in failed.",
        );
      });
  }

  // Spaces and dashes a paste picks up are dropped, as the server drops them too.
  const typedToken = activationToken.replace(/[\s-]/g, "");

  function submitActivation(e) {
    e.preventDefault();
    setErr("");
    if (typedToken.length !== ACTIVATION_TOKEN_LENGTH || !/^[A-Za-z0-9]+$/.test(typedToken)) {
      setErr(`An activation token is ${ACTIVATION_TOKEN_LENGTH} letters and digits.`);
      return;
    }
    setBusy(true);
    window.VCApi.activate(info.username, pw, typedToken)
      .then((res) => {
        setBusy(false);
        onLogin(res.user);
      })
      .catch((error) => {
        setBusy(false);
        // A 401 here is the password (the client calls every 401 an expired session).
        setErr(error && error.status === 401
          ? "Invalid username or password. Go back and sign in again."
          : (error && error.message) || "Activation failed.");
      });
  }

  function backToCreds() {
    setStep("creds");
    setErr("");
    setActivationToken("");
  }

  return (
    <div className="login">
      <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-brand"
      />
      <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
          className="login-wordmark"
          src={
            (theme === "light"
              ? "VulnerabilityCore/assets/vulnerabilitycore-logo-light.svg"
              : "VulnerabilityCore/assets/vulnerabilitycore-logo-dark.svg") +
            // Cache-bust: keep in step with the sidebar wordmark in app.jsx.
            "?v=1"
          }
          alt="vulnerability.core"
        />
        {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>

            {notice && (
              <div className="login-note" role="status">
                <Icon name="logout" size={14} />
                {notice}
              </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={submitActivation}>
            <div className="login-card-head">
              <span className="login-eyebrow">Account activation</span>
              <h2>Activate your account</h2>
              <p>
                {(info && info.message) ||
                  `Enter the ${ACTIVATION_TOKEN_LENGTH}-character activation token your administrator gave you.`}
              </p>
            </div>

            <label className="field">
              <span className="field-lab">Activation token</span>
              <div className="field-wrap">
                <Icon name="shield" size={16} className="field-ic" />
                <input
                  value={activationToken}
                  onChange={(e) => setActivationToken(e.target.value.slice(0, 40))}
                  autoComplete="off"
                  autoCapitalize="off"
                  autoFocus
                  placeholder={`${ACTIVATION_TOKEN_LENGTH} letters and digits`}
                  spellCheck="false"
                  className="mono"
                  aria-describedby="activation-count"
                />
              </div>
              <span id="activation-count" className="field-note">
                {typedToken.length} of {ACTIVATION_TOKEN_LENGTH} characters
              </span>
            </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="check" size={16} />
                  Activate &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. The token works once.
              </span>
            </div>
          </form>
        )}
        <p className="login-legal">
          © 2026 CyMobility Private Limited · Bengaluru · Austin
        </p>
      </div>
    </div>
  );
}
window.LoginScreen = LoginScreen;
