// Atlas · Auth page — Sign in / Sign up
const { useState: useAuthState } = React;

function GoogleLogo() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
      <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
      <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
      <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z" fill="#FBBC05"/>
      <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
    </svg>
  );
}

const TESTIMONIALS = [
  {
    quote: "Atlas cut our technology landscaping time from three weeks to two days. The depth of the literature review is genuinely impressive.",
    attr: "VP of R&D, mid-cap biotech",
  },
  {
    quote: "We use Atlas for every major BD decision now. The structured scope review alone saves hours of back-and-forth with analysts.",
    attr: "Principal, life sciences VC",
  },
  {
    quote: "The citation quality matches what we'd expect from a senior researcher. It's the first AI tool our science team actually trusts.",
    attr: "Chief Scientific Officer, CRO",
  },
];

function AuthPage() {
  const [tab, setTab] = useAuthState(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("mode") === "signup" ? "signup" : "signin";
  });
  const [testimonial] = useAuthState(() => TESTIMONIALS[Math.floor(Math.random() * TESTIMONIALS.length)]);

  const [step, setStep] = useAuthState("email"); // email or code
  const [email, setEmail] = useAuthState("");
  const [code, setCode] = useAuthState("");
  const [loading, setLoading] = useAuthState(false);
  const [error, setError] = useAuthState("");

  const handleSendOtp = async (e) => {
    e.preventDefault();
    if (!email || !email.includes("@")) {
      setError("Please enter a valid email address.");
      return;
    }
    setLoading(true);
    setError("");
    try {
      const resp = await fetch("/api/auth/otp/send", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
      const data = await resp.json();
      if (!resp.ok) throw new Error(data.detail || "Failed to send code.");
      setStep("code");
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyOtp = async (e) => {
    e.preventDefault();
    if (code.length !== 6) {
      setError("Please enter the 6-digit code.");
      return;
    }
    setLoading(true);
    setError("");
    try {
      const resp = await fetch("/api/auth/otp/verify", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, code }),
      });
      const data = await resp.json();
      if (!resp.ok) throw new Error(data.detail || "Invalid code.");
      window.location.href = "/app";
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="auth-page">
      {/* Left panel — brand + testimonial */}
      <div className="auth-left">
        <div>
          <div style={{ fontFamily: "var(--serif)", fontSize: 13, color: "rgba(245,245,247,0.4)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 16 }}>Atlas</div>
          <div style={{ fontFamily: "var(--serif)", fontSize: 28, fontWeight: 500, color: "rgba(245,245,247,0.92)", lineHeight: 1.3, letterSpacing: "-0.015em" }}>
            Research intelligence<br />for science-led teams.
          </div>
          <div style={{ marginTop: 20, display: "flex", flexDirection: "column", gap: 10 }}>
            {["Technology landscapes and company analyses", "Parallel AI research agents", "Literature reviews in hours, not weeks"].map((f) => (
              <div key={f} style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 13, color: "rgba(245,245,247,0.6)" }}>
                <Icon name="check" size={14} style={{ color: "rgba(245,245,247,0.4)", flexShrink: 0 }} />
                {f}
              </div>
            ))}
          </div>
        </div>

        <div>
          <div className="quote">"{testimonial.quote}"</div>
          <div className="quote-attr">{testimonial.attr}</div>
        </div>
      </div>

      {/* Right panel — auth form */}
      <div className="auth-right">
        <div className="auth-card">
          {/* Atlas wordmark */}
          <div style={{ marginBottom: 32, textAlign: "center" }}>
            <div style={{ fontFamily: "var(--serif)", fontSize: 32, fontWeight: 600, letterSpacing: "-0.02em", color: "var(--ink)" }}>Atlas</div>
          </div>

          {/* Sign in / Sign up tabs */}
          <div className="auth-tabs">
            <button className={`auth-tab ${tab === "signin" ? "active" : ""}`} onClick={() => { setTab("signin"); setStep("email"); setError(""); }}>Sign in</button>
            <button className={`auth-tab ${tab === "signup" ? "active" : ""}`} onClick={() => { setTab("signup"); setStep("email"); setError(""); }}>Sign up</button>
          </div>

          {step === "email" ? (
            <>
              {tab === "signin" ? (
                <>
                  <h1 className="auth-title">Welcome back.</h1>
                  <p className="auth-sub">Sign in to your Atlas workspace to continue your reports.</p>
                </>
              ) : (
                <>
                  <h1 className="auth-title">Create your account.</h1>
                  <p className="auth-sub">Get started with Atlas. We'll walk you through setup after you sign in.</p>
                </>
              )}

              <a href="/auth/login" className="auth-google-btn">
                <GoogleLogo />
                {tab === "signin" ? "Continue with Google" : "Sign up with Google"}
              </a>

              <div className="auth-divider">
                <span>or</span>
              </div>

              <form onSubmit={handleSendOtp}>
                <div className="auth-field">
                  <label>Email address</label>
                  <input
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder="name@company.com"
                    disabled={loading}
                    required
                  />
                </div>
                {error && <div className="auth-error">{error}</div>}
                <button type="submit" className="auth-submit-btn" disabled={loading}>
                  {loading ? "Sending..." : "Continue with Email"}
                </button>
              </form>
            </>
          ) : (
            <>
              <h1 className="auth-title">Check your email.</h1>
              <p className="auth-sub">We sent a 6-digit login code to <strong>{email}</strong>.</p>

              <form onSubmit={handleVerifyOtp}>
                <div className="auth-field">
                  <label>Verification code</label>
                  <input
                    type="text"
                    value={code}
                    onChange={(e) => setCode(e.target.value.replace(/\D/g, "").slice(0, 6))}
                    placeholder="000000"
                    pattern="\d{6}"
                    disabled={loading}
                    autoFocus
                    required
                  />
                </div>
                {error && <div className="auth-error">{error}</div>}
                <button type="submit" className="auth-submit-btn" disabled={loading}>
                  {loading ? "Verifying..." : "Verify Code"}
                </button>
                <button
                  type="button"
                  className="auth-back-btn"
                  onClick={() => { setStep("email"); setError(""); }}
                  disabled={loading}
                >
                  Back to email
                </button>
              </form>
            </>
          )}

          {tab === "signin" && step === "email" && (
            <p style={{ marginTop: 20, fontSize: 12, color: "var(--ink-4)", textAlign: "center", lineHeight: 1.6 }}>
              Don't have an account?{" "}
              <button onClick={() => setTab("signup")} style={{ background: "none", border: "none", color: "var(--ink-2)", cursor: "pointer", fontSize: 12, textDecoration: "underline", padding: 0 }}>
                Sign up
              </button>
            </p>
          )}
          {tab === "signup" && step === "email" && (
            <p style={{ marginTop: 20, fontSize: 12, color: "var(--ink-4)", textAlign: "center", lineHeight: 1.6 }}>
              Already have an account?{" "}
              <button onClick={() => setTab("signin")} style={{ background: "none", border: "none", color: "var(--ink-2)", cursor: "pointer", fontSize: 12, textDecoration: "underline", padding: 0 }}>
                Sign in
              </button>
            </p>
          )}

          <p style={{ marginTop: 28, fontSize: 11, color: "var(--ink-4)", textAlign: "center", lineHeight: 1.6 }}>
            By continuing you agree to Atlas's{" "}
            <a href="/terms" style={{ color: "var(--ink-3)" }}>Terms of Service</a>{" "}
            and{" "}
            <a href="/privacy" style={{ color: "var(--ink-3)" }}>Privacy Policy</a>.
          </p>
        </div>
      </div>
    </div>
  );
}

window.AuthPage = AuthPage;
