// Pre-app sign-in: the Magic Auth / SSO screen shown when the backend says
// nobody is signed in, plus the provider marks it renders. This is the only UI
// that runs before the app has an identity.

const GoogleMark = () => (
  <svg className="auth-google-mark" viewBox="0 0 18 18" aria-hidden="true" focusable="false">
    <path fill="#4285F4" d="M17.64 9.205c0-.638-.057-1.252-.164-1.841H9v3.482h4.844c-.209 1.125-.843 2.078-1.796 2.716v2.258h2.908c1.702-1.567 2.684-3.874 2.684-6.615z"/>
    <path fill="#34A853" d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.258c-.806.54-1.837.859-3.048.859-2.344 0-4.328-1.583-5.036-3.71H.957v2.331C2.438 15.983 5.482 18 9 18z"/>
    <path fill="#FBBC05" d="M3.965 10.711A5.41 5.41 0 0 1 3.682 9c0-.594.102-1.171.283-1.711V4.958H.957A8.995 8.995 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.008-2.331z"/>
    <path fill="#EA4335" d="M9 3.58c1.321 0 2.508.454 3.441 1.346l2.581-2.582C13.463.892 11.426 0 9 0 5.482 0 2.438 2.017.957 4.958l3.008 2.331C4.672 5.162 6.656 3.58 9 3.58z"/>
  </svg>
);

const AuthBootstrap = () => {
  const params = new URLSearchParams(window.location.search || "");
  const initialEmail = params.get("email") || (window.Flow && window.Flow.CURRENT_USER && window.Flow.CURRENT_USER.email) || "";
  const [email, setEmail] = React.useState(initialEmail);
  const [code, setCode] = React.useState("");
  const [sent, setSent] = React.useState(params.get("sent") === "1");
  const [showCode, setShowCode] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [cooldownUntil, setCooldownUntil] = React.useState(0);
  const [now, setNow] = React.useState(Date.now());
  const [error, setError] = React.useState(() => {
    const e = params.get("error");
    if (e === "bad_state") return "That sign-in session expired or opened in a different browser. Start sign-in again from here.";
    if (e === "expired_magic_link") return "That sign-in link expired or was already used. Send yourself a new one.";
    if (e === "magic_link_failed") return "That sign-in link could not be verified. Send a new link and try again.";
    if (e) return "Sign-in could not be completed. Send a new link and try again.";
    return "";
  });
  const returnTo = authReturnTo();
  const api = window.PreambleAPI || {};
  const track = (name, props) => {
    if (window.PreambleObservability && window.PreambleObservability.track) {
      window.PreambleObservability.track(name, props || {});
    }
  };

  React.useEffect(() => {
    const t = window.setInterval(() => setNow(Date.now()), 1000);
    return () => window.clearInterval(t);
  }, []);

  const submitEmail = (e) => {
    e.preventDefault();
    if (!api.startMagicAuth || !email.trim()) return;
    setBusy(true); setError("");
    track("auth.magic_start", { type: "auth", metadata: { returnTo } });
    api.startMagicAuth(email.trim(), returnTo).then((res) => {
      setBusy(false);
      setSent(true);
      setShowCode(false);
      setCooldownUntil(Date.now() + 30000);
      if (res && res.email) setEmail(res.email);
    }).catch((err) => {
      setBusy(false);
      setError((err && err.message) || "Could not send a sign-in code.");
    });
  };
  const submitCode = (e) => {
    e.preventDefault();
    if (!api.verifyMagicAuth || !code.trim()) return;
    setBusy(true); setError("");
    track("auth.magic_verify", { type: "auth", metadata: { returnTo } });
    api.verifyMagicAuth(email.trim(), code.trim(), returnTo).then((res) => {
      const next = res && res.needsWorkspace ? "/app/setup" : ((res && res.returnTo) || returnTo || "/app");
      window.location.href = next;
    }).catch((err) => {
      setBusy(false);
      setError((err && err.message) || "Could not verify that code.");
    });
  };
  const googleHref = "/api/v1/auth/login?provider=GoogleOAuth&returnTo=" + encodeURIComponent(returnTo);
  const ssoHref = "/api/v1/auth/login?returnTo=" + encodeURIComponent(returnTo);
  const remaining = Math.max(0, Math.ceil((cooldownUntil - now) / 1000));

  return (
    <div className="auth-screen" data-observe-component="auth">
      <div className="auth-shell">
        <div className="auth-brand-wrap">
          <span className="auth-brand brand-word" aria-label="Preamble">
            <span className="bw-pr">Pr</span><span className="bw-tail">eamble</span>
          </span>
        </div>
        {error && <div className="auth-error">{error}</div>}
        {!sent ? (
          <div className="auth-stage">
            <h1>Start with your work email.</h1>
            <p>We’ll send a private sign-in link. New customer admins can create their company workspace after email verification.</p>
            <form className="auth-form" onSubmit={submitEmail}>
              <label>
                <span>Work email</span>
                <input type="email" value={email} autoFocus placeholder="you@company.com" onChange={(e) => setEmail(e.target.value)} />
              </label>
              <button className="auth-primary" type="submit" disabled={busy || !email.trim()}>{busy ? "Sending..." : "Continue"}</button>
            </form>
            <div className="auth-divider"><span>or</span></div>
            <div className="auth-alt-grid">
              <a className="auth-alt" href={googleHref}><GoogleMark/> Continue with Google</a>
              <a className="auth-alt" href={ssoHref}><Icon name="lock" size={15}/> Enterprise SSO</a>
            </div>
          </div>
        ) : (
          <div className="auth-stage inbox">
            <h1>Check your inbox</h1>
            <p>We sent a magic link to <b>{email}</b>. Open it in this browser to finish signing in.</p>
            {!showCode && (
              <button className="auth-link" type="button" onClick={() => { setShowCode(true); setError(""); }}>
                Enter code instead
              </button>
            )}
            {showCode && (
              <form className="auth-form code" onSubmit={submitCode}>
                <label>
                  <span>Verification code</span>
                  <input value={code} inputMode="numeric" autoFocus placeholder="123456" onChange={(e) => setCode(e.target.value)} />
                </label>
                <button className="auth-primary" type="submit" disabled={busy || !code.trim()}>{busy ? "Verifying..." : "Continue"}</button>
              </form>
            )}
            <div className="auth-inbox-foot">
              <a className="auth-foot-act" href="https://mail.google.com/mail/u/0/#search/Preamble" target="_blank" rel="noreferrer">Open Gmail</a>
              <span className="auth-dot" aria-hidden="true">·</span>
              <button className="auth-foot-act" type="button" disabled={busy || remaining > 0} onClick={submitEmail}>
                {remaining > 0 ? `Resend in ${remaining}s` : "Resend email"}
              </button>
              <span className="auth-dot" aria-hidden="true">·</span>
              <button className="auth-foot-act" type="button" onClick={() => { setSent(false); setShowCode(false); setCode(""); setError(""); }}>
                Change email
              </button>
            </div>
          </div>
        )}
      </div>
      <style>{`
        .auth-screen {
          min-height: 100vh; display: grid; place-items: center; padding: 28px;
          background: var(--bg-0);
          color: var(--text); position: relative;
        }
        .auth-shell {
          width: min(452px, 100%); padding: 40px 40px 36px; position: relative;
          border: 0; border-radius: var(--radius-lg);
          background: var(--bg-1);
          box-shadow: var(--shadow-md);
          animation: fadeIn 150ms var(--ease) both;
        }
        .auth-brand-wrap { display: flex; justify-content: center; min-height: 34px; margin-bottom: 30px; }
        .auth-brand { font-size: var(--fs-display); cursor: default; }
        .auth-stage { display: grid; }
        .auth-stage h1 { margin: 0 0 12px; font-size: var(--fs-display); line-height: var(--lh-tight); font-weight: 600; letter-spacing: -0.01em; text-align: center; }
        .auth-stage p { margin: 0 auto 26px; color: var(--text-dim); font-size: var(--fs-body); line-height: var(--lh-body); text-align: center; max-width: 360px; }
        .auth-stage p b { color: var(--text); font-weight: 600; }
        .auth-form { display: grid; gap: 12px; }
        .auth-form label { display: grid; gap: 7px; font-size: var(--fs-caption); font-weight: 500; color: var(--text-dim); }
        .auth-form input {
          width: 100%; box-sizing: border-box; border: 0;
          border-radius: var(--radius-sm); background: var(--surface-2); color: var(--text);
          padding: 14px 15px; font-size: var(--fs-ui); transition: box-shadow var(--dur) var(--ease);
        }
        .auth-form input::placeholder { color: var(--text-muted); }
        .auth-form input:focus { outline: 0; box-shadow: inset 0 0 0 1px var(--accent); }
        .auth-primary {
          border: 0; border-radius: var(--radius-sm); min-height: 48px; font-size: var(--fs-ui); font-weight: 600; cursor: pointer;
          color: var(--on-accent); background: var(--accent);
          transition: background var(--dur) var(--ease);
        }
        .auth-primary:hover { background: var(--accent-2); }
        .auth-primary:disabled { opacity: .5; cursor: default; }
        .auth-divider { display: flex; align-items: center; gap: 12px; margin: 18px 0; color: var(--text-muted); font-size: var(--fs-caption); }
        .auth-divider::before, .auth-divider::after { content: ""; height: 1px; flex: 1; background: var(--divider); }
        .auth-alt-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
        .auth-alt {
          display: flex; align-items: center; justify-content: center; gap: 9px; min-height: 46px;
          border: 0; border-radius: var(--radius-sm); background: var(--surface-2);
          color: var(--text); text-decoration: none; font-size: var(--fs-ui); font-weight: 500;
          transition: background var(--dur) var(--ease);
        }
        .auth-alt:hover { background: var(--surface-3); }
        .auth-google-mark { width: 18px; height: 18px; flex: 0 0 18px; display: block; }
        .auth-link {
          border: 0; background: transparent; color: var(--accent); padding: 4px; min-height: 30px;
          font-size: var(--fs-ui); font-weight: 500; cursor: pointer; border-radius: var(--radius-sm);
          justify-self: center;
          transition: color var(--dur) var(--ease);
        }
        .auth-link:hover:not(:disabled) { color: var(--accent-2); text-decoration: underline; text-underline-offset: 3px; }
        .auth-inbox-foot {
          display: flex; align-items: center; justify-content: center; flex-wrap: wrap; gap: 4px 8px;
          margin-top: 18px;
        }
        .auth-foot-act {
          border: 0; background: transparent; color: var(--text-muted); padding: 4px; min-height: 28px;
          display: inline-flex; align-items: center;
          font-size: var(--fs-caption); font-weight: 500; cursor: pointer; border-radius: var(--radius-sm);
          text-decoration: none;
          transition: color var(--dur) var(--ease);
        }
        .auth-foot-act:hover:not(:disabled) { color: var(--text); }
        .auth-foot-act:disabled { color: var(--text-muted); opacity: .6; cursor: default; }
        .auth-dot { color: var(--text-muted); font-size: var(--fs-caption); user-select: none; }
        .auth-form.code { margin-top: 6px; }
        .auth-error { margin-bottom: 18px; padding: 11px 13px; border-radius: var(--radius-sm); background: var(--rose-soft); color: var(--rose); font-size: var(--fs-ui); border: 0; text-align: center; }
        @media (max-width: 620px) {
          .auth-shell { padding: 30px 22px; }
          .auth-alt-grid { grid-template-columns: 1fr; }
        }
      `}</style>
    </div>
  );
};
