// Login screen — Google Sign-In + Microsoft Sign-In

function LoginScreen({ onLogin }) {
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const [gsiReady, setGsiReady] = useState(false);
  const buttonRef = useRef(null);
  const callbackRef = useRef(null);

  async function handleAuthResponse(data) {
    localStorage.setItem("ats_token", data.access_token);
    localStorage.setItem("ats_user", JSON.stringify(data.user));
    onLogin(data.user, data.access_token);
  }

  callbackRef.current = async function handleGoogleResponse(response) {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`${API_BASE_URL}/auth/google`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ credential: response.credential }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.detail || `Login failed (${res.status})`);
      }
      await handleAuthResponse(await res.json());
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  async function handleMicrosoftLogin() {
    setLoading(true);
    setError(null);
    try {
      const msalConfig = {
        auth: {
          clientId: window.__MICROSOFT_CLIENT_ID,
          authority: `https://login.microsoftonline.com/${window.__MICROSOFT_TENANT_ID || "common"}`,
          redirectUri: window.location.origin,
        },
      };
      const msalInstance = new msal.PublicClientApplication(msalConfig);
      await msalInstance.initialize();
      const loginResp = await msalInstance.loginPopup({
        scopes: ["User.Read"],
        prompt: "select_account",
      });

      const res = await fetch(`${API_BASE_URL}/auth/microsoft`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ access_token: loginResp.accessToken }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.detail || `Login failed (${res.status})`);
      }
      await handleAuthResponse(await res.json());
    } catch (err) {
      if (err.errorCode === "user_cancelled") {
        setError(null);
      } else {
        setError(err.message || "Microsoft login failed");
      }
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    let cancelled = false;
    let attempts = 0;

    function tryInit() {
      if (cancelled) return;
      attempts++;

      const gsi = window.google && window.google.accounts;
      const clientId = window.__GOOGLE_CLIENT_ID;

      if (!gsi || !clientId) {
        if (attempts < 50) setTimeout(tryInit, 200);
        return;
      }

      gsi.id.initialize({
        client_id: clientId,
        callback: (resp) => callbackRef.current(resp),
      });

      if (buttonRef.current) {
        gsi.id.renderButton(buttonRef.current, {
          theme: "outline",
          size: "large",
          shape: "rectangular",
          text: "signin_with",
          width: 300,
        });
      }
      setGsiReady(true);
    }

    tryInit();
    return () => { cancelled = true; };
  }, []);

  const hasMicrosoft = !!window.__MICROSOFT_CLIENT_ID;
  const [emailMode, setEmailMode] = useState(false);
  const [emailInput, setEmailInput] = useState("");
  const [emailSent, setEmailSent] = useState(false);

  async function handleEmailLogin() {
    if (!emailInput.trim() || !emailInput.includes("@")) { setError("Enter a valid email"); return; }
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`${API_BASE_URL}/auth/email/send-link`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: emailInput.trim() }),
      });
      if (!res.ok) throw new Error("Failed to send login link");
      setEmailSent(true);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div style={{
      width: "100%",
      height: "100%",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      background: "var(--nl-bone, #F5F1EA)",
    }}>
      <div style={{
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        gap: 28,
        padding: 48,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <Mark size={36} />
          <span style={{
            fontFamily: "'arizona-flare', Georgia, serif",
            fontSize: 28,
            fontWeight: 300,
            color: "var(--nl-ink, #1D3140)",
            letterSpacing: "-0.02em",
          }}>
            Nuance ATS
          </span>
        </div>

        {!emailMode && !gsiReady && (
          <div style={{ color: "var(--fg-3)", fontSize: 13 }}>
            Loading sign-in...
          </div>
        )}
        {!emailMode && <div ref={buttonRef} style={{ minHeight: gsiReady ? 44 : 0 }} />}

        {!emailMode && hasMicrosoft && gsiReady && (
          <button
            onClick={handleMicrosoftLogin}
            disabled={loading}
            style={{
              display: "flex", alignItems: "center", justifyContent: "center", gap: 10,
              width: 300, height: 42, border: "1px solid #8c8c8c", borderRadius: 4,
              background: "#fff", cursor: "pointer", fontSize: 14, fontFamily: "'Segoe UI', sans-serif",
              color: "#5e5e5e", fontWeight: 600, padding: "0 12px",
            }}
          >
            <svg width="18" height="18" viewBox="0 0 21 21"><rect x="1" y="1" width="9" height="9" fill="#f25022"/><rect x="11" y="1" width="9" height="9" fill="#7fba00"/><rect x="1" y="11" width="9" height="9" fill="#00a4ef"/><rect x="11" y="11" width="9" height="9" fill="#ffb900"/></svg>
            Sign in with Microsoft
          </button>
        )}

        {!emailMode && gsiReady && (
          <>
            <div style={{ display: "flex", alignItems: "center", gap: 12, width: 300 }}>
              <div style={{ flex: 1, height: 1, background: "var(--border-1)" }} />
              <span style={{ fontSize: 11, color: "var(--fg-4)", textTransform: "uppercase", letterSpacing: "0.05em" }}>or</span>
              <div style={{ flex: 1, height: 1, background: "var(--border-1)" }} />
            </div>
            <button onClick={() => setEmailMode(true)} style={{
              width: 300, height: 42, border: "1px solid var(--border-1)", borderRadius: 4,
              background: "#fff", cursor: "pointer", fontSize: 14, color: "var(--fg-2)", fontWeight: 500,
            }}>
              Sign in with email
            </button>
          </>
        )}

        {emailMode && !emailSent && (
          <div style={{ display: "flex", flexDirection: "column", gap: 12, width: 300 }}>
            <div style={{ fontSize: 13, color: "var(--fg-2)" }}>Enter your email and we'll send a login link.</div>
            <input
              type="email"
              value={emailInput}
              onChange={(e) => setEmailInput(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && handleEmailLogin()}
              placeholder="you@company.com"
              autoFocus
              style={{
                width: "100%", height: 42, border: "1px solid var(--border-1)", borderRadius: 4,
                padding: "0 12px", fontSize: 14, outline: "none",
              }}
            />
            <div style={{ display: "flex", gap: 8 }}>
              <button onClick={() => setEmailMode(false)} style={{
                flex: 1, height: 38, border: "1px solid var(--border-1)", borderRadius: 4,
                background: "#fff", cursor: "pointer", fontSize: 13, color: "var(--fg-3)",
              }}>Back</button>
              <button onClick={handleEmailLogin} disabled={loading} style={{
                flex: 2, height: 38, border: "none", borderRadius: 4,
                background: "var(--nl-ink, #1D3140)", color: "#fff", cursor: "pointer", fontSize: 13, fontWeight: 600,
              }}>{loading ? "Sending..." : "Send login link"}</button>
            </div>
          </div>
        )}

        {emailSent && (
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 12, width: 300 }}>
            <div style={{ fontSize: 36 }}>✉️</div>
            <div style={{ fontSize: 14, color: "var(--fg-1)", fontWeight: 600, textAlign: "center" }}>Check your email</div>
            <div style={{ fontSize: 13, color: "var(--fg-3)", textAlign: "center" }}>
              We sent a login link to <b>{emailInput}</b>. Click the link to sign in. It expires in 15 minutes.
            </div>
            <button onClick={() => { setEmailSent(false); setEmailMode(false); }} style={{
              marginTop: 8, fontSize: 13, color: "var(--fg-3)", background: "none", cursor: "pointer",
              textDecoration: "underline",
            }}>Use a different method</button>
          </div>
        )}

        {loading && !emailMode && (
          <div style={{ fontSize: 13, color: "var(--fg-3)" }}>
            Signing in...
          </div>
        )}

        {error && (
          <div style={{
            fontSize: 13,
            color: "#B4553D",
            background: "rgba(180, 85, 61, 0.08)",
            padding: "10px 16px",
            borderRadius: 6,
            maxWidth: 340,
            textAlign: "center",
          }}>
            {error}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { LoginScreen });
