"use client";

import React, { useCallback, useEffect, useRef, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  AlertTriangle,
  ArrowRight,
  Check,
  Loader2,
  Lock,
  Mail,
  MailCheck,
  User,
} from "lucide-react";
import { useI18n } from "@/lib/i18n/context";
import { validateEmail, validateName, validatePassword } from "@/lib/auth/validation";
import { authErrorMessage } from "@/lib/auth/errors";
import { AuthField } from "./AuthField";
import { PasswordStrengthMeter } from "./PasswordStrengthMeter";
import { apiFetch } from "@/lib/csrf/client";

type Mode = "login" | "signup";
type Status = "idle" | "submitting" | "success";
type View = "form" | "verification_sent";

interface FieldErrors {
  name?: string | null;
  email?: string | null;
  password?: string | null;
}

interface Providers {
  google: boolean;
  smtp: boolean;
  devMailFallback: boolean;
}

interface AuthFormProps {
  mode: Mode;
  /** Modal variant tightens spacing and swaps the mode link for a callback. */
  compact?: boolean;
  /** Called right before navigating away — the modal uses it to close itself. */
  onBeforeNavigate?: () => void;
  /** When provided, the "switch mode" affordance becomes a button, not a link. */
  onSwitchMode?: () => void;
}

interface ApiResult {
  ok: boolean;
  status: number;
  data: Record<string, unknown>;
}

async function postJson(url: string, body: unknown): Promise<ApiResult> {
  const response = await apiFetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });

  let data: Record<string, unknown> = {};
  try {
    data = (await response.json()) as Record<string, unknown>;
  } catch {
    // Non-JSON body (proxy error page, empty 500) — the status still tells us enough.
  }

  return { ok: response.ok, status: response.status, data };
}

/**
 * Credential form shared by the login page, the signup page and the landing
 * modal, so all three stay in lockstep on validation, states and copy.
 *
 * Talks to the real endpoints under `/api/auth`. Signup deliberately does not
 * sign anyone in — it hands over to the "confirm your email" view, and the
 * account stays inert until the emailed link is opened.
 */
export function AuthForm({ mode, compact = false, onBeforeNavigate, onSwitchMode }: AuthFormProps) {
  const router = useRouter();
  const { language } = useI18n();
  const isDe = language === "de";
  const isSignup = mode === "signup";

  const formRef = useRef<HTMLFormElement>(null);

  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [remember, setRemember] = useState(true);
  const [errors, setErrors] = useState<FieldErrors>({});
  const [formError, setFormError] = useState<string | null>(null);
  /** Positive one-off message, e.g. after returning from a password reset. */
  const [notice, setNotice] = useState<string | null>(null);
  const [status, setStatus] = useState<Status>("idle");

  const [googlePending, setGooglePending] = useState(false);
  const [view, setView] = useState<View>("form");
  const [providers, setProviders] = useState<Providers | null>(null);

  /** Set when correct credentials belong to an account that was never confirmed. */
  const [unverifiedEmail, setUnverifiedEmail] = useState<string | null>(null);
  const [resendState, setResendState] = useState<"idle" | "sending" | "sent">("idle");
  /** Development convenience: the link the server would have emailed. */
  const [devLink, setDevLink] = useState<string | null>(null);

  const busy = status !== "idle" || googlePending;

  // Which sign-in paths this deployment actually has wired up.
  useEffect(() => {
    let active = true;
    apiFetch("/api/auth/providers")
      .then((response) => (response.ok ? response.json() : null))
      .then((data: Providers | null) => {
        if (active && data) setProviders(data);
      })
      .catch(() => undefined);
    return () => {
      active = false;
    };
  }, []);

  // Other flows report back through the query string: the OAuth callback uses
  // ?error=…, a finished password reset uses ?reset=success. Read them from the
  // URL directly so this component needs no Suspense boundary, then strip them
  // so a reload doesn't replay the message.
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const code = params.get("error");
    const reset = params.get("reset");
    if (!code && !reset) return;

    if (code) setFormError(authErrorMessage(code, isDe));
    if (reset === "success") {
      setNotice(
        isDe
          ? "Passwort geändert. Melde dich mit dem neuen Passwort an."
          : "Password changed. Sign in with your new password."
      );
    }

    params.delete("error");
    params.delete("reset");
    const query = params.toString();
    window.history.replaceState(
      null,
      "",
      `${window.location.pathname}${query ? `?${query}` : ""}`
    );
    // Runs once on mount: the language at that moment is the one the user sees.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Messages are localised when produced, so a language switch would leave
  // stale-language text on screen. Drop them; the next attempt re-creates them.
  useEffect(() => {
    setErrors({});
    setFormError(null);
  }, [isDe]);

  const goToDashboard = useCallback(
    (onboardingCompletedAt?: string | null) => {
      onBeforeNavigate?.();
      router.push(onboardingCompletedAt ? "/dashboard" : "/dashboard/onboarding");
    },
    [onBeforeNavigate, router]
  );

  const handleGoogle = () => {
    if (busy) return;
    setGooglePending(true);
    // Full navigation: the OAuth handshake is a server-side redirect chain.
    window.location.href = "/api/auth/google";
  };

  const runValidation = (): FieldErrors => ({
    name: isSignup ? validateName(name, isDe) : null,
    email: validateEmail(email, isDe),
    password: validatePassword(password, isDe, { requireStrength: isSignup }),
  });

  const handleBlur = (field: keyof FieldErrors) => () => {
    // Only surface a blur error once the user has actually typed something,
    // so tabbing through an empty form doesn't turn it red.
    const value = field === "name" ? name : field === "email" ? email : password;
    if (!value) return;
    setErrors((current) => ({ ...current, [field]: runValidation()[field] }));
  };

  const resendVerification = async (target: string) => {
    setResendState("sending");
    const result = await postJson("/api/auth/resend-verification", {
      email: target,
      lang: isDe ? "de" : "en",
    });

    if (!result.ok) {
      setResendState("idle");
      setFormError(
        authErrorMessage(
          result.data.error as string,
          isDe,
          result.data.retryAfter as number | undefined
        )
      );
      return;
    }

    if (typeof result.data.devLink === "string") setDevLink(result.data.devLink);
    setResendState("sent");
  };

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    if (busy) return;

    const nextErrors = runValidation();
    setErrors(nextErrors);
    setFormError(null);
    setUnverifiedEmail(null);

    if (nextErrors.name || nextErrors.email || nextErrors.password) {
      requestAnimationFrame(() => {
        formRef.current?.querySelector<HTMLInputElement>('[aria-invalid="true"]')?.focus();
      });
      return;
    }

    setStatus("submitting");

    try {
      const result = isSignup
        ? await postJson("/api/auth/signup", {
            name,
            email,
            password,
            lang: isDe ? "de" : "en",
          })
        : await postJson("/api/auth/login", { email, password, remember });

      if (!result.ok) {
        setStatus("idle");
        const code = result.data.error as string | undefined;

        // Right password, unconfirmed address: offer a new link in place.
        // The server no longer echoes the email — the submitted value is what
        // the user typed, and that is exactly what the resend uses.
        if (code === "email_not_verified") {
          setUnverifiedEmail(email);
          setResendState("idle");
          return;
        }

        // Point the user at the field that is actually wrong where we can.
        if (code === "invalid_email" || code === "disposable_email") {
          setErrors((current) => ({ ...current, email: authErrorMessage(code, isDe) }));
          return;
        }
        if (code === "weak_password") {
          setErrors((current) => ({ ...current, password: authErrorMessage(code, isDe) }));
          return;
        }

        setFormError(
          authErrorMessage(code, isDe, result.data.retryAfter as number | undefined)
        );
        return;
      }

      if (isSignup) {
        if (typeof result.data.devLink === "string") setDevLink(result.data.devLink);
        setStatus("idle");
        setView("verification_sent");
        return;
      }

      setStatus("success");
      const loggedInUser = result.data.user as { onboardingCompletedAt?: string | null } | undefined;
      setTimeout(() => goToDashboard(loggedInUser?.onboardingCompletedAt), 400);
    } catch {
      setStatus("idle");
      setFormError(authErrorMessage("server_error", isDe));
    }
  };

  const capsLockHint = isDe ? "Feststelltaste ist aktiv" : "Caps lock is on";

  if (view === "verification_sent") {
    return (
      <VerificationSentPanel
        email={email}
        isDe={isDe}
        compact={compact}
        devLink={devLink}
        resendState={resendState}
        onResend={() => resendVerification(email)}
        onBack={() => {
          setView("form");
          setPassword("");
          setResendState("idle");
          setDevLink(null);
          onSwitchMode?.();
        }}
        backIsSwitch={Boolean(onSwitchMode)}
      />
    );
  }

  return (
    <div>
      {/* Heading */}
      <div className={compact ? "mb-5" : "mb-7"}>
        <div className="flex items-center gap-2 mb-3">
          <span className="w-2 h-2 bg-black" aria-hidden="true" />
          <span className="font-mono text-[11px] uppercase tracking-caps text-[#475569] font-bold">
            {isSignup
              ? isDe
                ? "Konto anlegen"
                : "Create account"
              : isDe
              ? "Anmeldung"
              : "Sign in"}
          </span>
        </div>
        <h1
          className={`font-display font-bold tracking-tighter text-black leading-[1.1] ${
            compact ? "text-[26px]" : "text-[30px] sm:text-[36px]"
          }`}
        >
          {isSignup
            ? isDe
              ? "Konto erstellen"
              : "Create your account"
            : isDe
            ? "Willkommen zurück"
            : "Welcome back"}
        </h1>
        <p className="text-[14px] text-[#64748B] mt-2 leading-relaxed">
          {isSignup
            ? isDe
              ? "In 30 Sekunden startklar — Belege scannen und direkt nach Excel exportieren."
              : "Ready in 30 seconds — scan receipts and export straight to Excel."
            : isDe
            ? "Weiter zu deinen Belegen, Auswertungen und Exporten."
            : "Continue to your receipts, analytics and exports."}
        </p>
      </div>

      {providers?.google && (
        <div className="space-y-2.5">
          <button
            type="button"
            onClick={handleGoogle}
            disabled={busy}
            className="w-full h-12 flex items-center justify-center gap-2.5 bg-white border border-[#C4C7C9] text-[14px] font-medium text-[#161C22] hover:border-black hover:bg-[#F8FAFC] transition-colors disabled:opacity-50 disabled:pointer-events-none"
          >
            {googlePending ? (
              <Loader2 className="w-4 h-4 animate-spin" aria-hidden="true" />
            ) : (
              <GoogleIcon />
            )}
            <span>{isDe ? "Mit Google fortfahren" : "Continue with Google"}</span>
          </button>
        </div>
      )}

      {/* Divider */}
      <div className="relative flex items-center justify-center my-6">
        <div className="w-full border-t border-[#E2E8F0]" />
        <span
          className={`absolute px-3 font-mono text-[10px] uppercase tracking-wider text-[#94A3B8] ${
            compact ? "bg-white" : "bg-[#F6F9FF]"
          }`}
        >
          {isSignup
            ? isDe
              ? "oder mit E-Mail registrieren"
              : "or register with email"
            : isDe
            ? "oder mit E-Mail"
            : "or continue with email"}
        </span>
      </div>

      {notice && (
        <div className="flex items-start gap-2.5 border border-emerald-600 bg-[#ECFDF5] px-3.5 py-3 mb-5 text-[13px] text-[#065F46] leading-snug">
          <Check className="w-4 h-4 shrink-0 mt-px" aria-hidden="true" />
          <span>{notice}</span>
        </div>
      )}

      {formError && (
        <div
          role="alert"
          className="flex items-start gap-2.5 border border-[#BA1A1A] bg-[#FFDAD6] px-3.5 py-3 mb-5 text-[13px] text-[#93000A] leading-snug"
        >
          <AlertTriangle className="w-4 h-4 shrink-0 mt-px" aria-hidden="true" />
          <span>{formError}</span>
        </div>
      )}

      {unverifiedEmail && (
        <UnverifiedNotice
          email={unverifiedEmail}
          isDe={isDe}
          devLink={devLink}
          resendState={resendState}
          onResend={() => resendVerification(unverifiedEmail)}
        />
      )}

      <form ref={formRef} onSubmit={handleSubmit} noValidate className="space-y-4">
        {isSignup && (
          <AuthField
            label={isDe ? "Name oder Firma" : "Name or company"}
            icon={User}
            type="text"
            name="name"
            autoComplete="name"
            placeholder={isDe ? "Max Mustermann" : "Alex Morgan"}
            value={name}
            onChange={(event) => setName(event.target.value)}
            onBlur={handleBlur("name")}
            error={errors.name}
            disabled={busy}
          />
        )}

        <AuthField
          label={isDe ? "E-Mail-Adresse" : "Email address"}
          icon={Mail}
          type="email"
          name="email"
          autoComplete="email"
          inputMode="email"
          autoCapitalize="none"
          spellCheck={false}
          placeholder="name@unternehmen.de"
          value={email}
          onChange={(event) => setEmail(event.target.value)}
          onBlur={handleBlur("email")}
          error={errors.email}
          disabled={busy}
        />

        <div>
          <AuthField
            label={isDe ? "Passwort" : "Password"}
            icon={Lock}
            type="password"
            name="password"
            autoComplete={isSignup ? "new-password" : "current-password"}
            placeholder={
              isSignup
                ? isDe
                  ? "Mindestens 8 Zeichen"
                  : "At least 8 characters"
                : "••••••••••••"
            }
            value={password}
            onChange={(event) => setPassword(event.target.value)}
            onBlur={handleBlur("password")}
            error={errors.password}
            disabled={busy}
            capsLockHint={capsLockHint}
            trailingLabel={
              !isSignup ? (
                <Link
                  href="/auth/forgot-password"
                  className="font-mono text-[11px] text-[#475569] hover:text-black underline underline-offset-2 transition-colors"
                >
                  {isDe ? "Passwort vergessen?" : "Forgot password?"}
                </Link>
              ) : null
            }
          />
          {isSignup && password.length > 0 && (
            <PasswordStrengthMeter value={password} isDe={isDe} />
          )}
        </div>

        {!isSignup && (
          <label className="flex items-center gap-2.5 cursor-pointer select-none w-fit">
            <input
              type="checkbox"
              checked={remember}
              onChange={(event) => setRemember(event.target.checked)}
              disabled={busy}
              className="w-4 h-4 appearance-none border border-[#C4C7C9] bg-white checked:bg-black checked:border-black bg-[length:11px] bg-center bg-no-repeat transition-colors cursor-pointer"
              style={{
                backgroundImage: remember
                  ? "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='4' stroke-linecap='square'%3E%3Cpath d='M4 12l6 6L20 6'/%3E%3C/svg%3E\")"
                  : undefined,
              }}
            />
            <span className="text-[13px] text-[#475569]">
              {isDe ? "Angemeldet bleiben" : "Keep me signed in"}
            </span>
          </label>
        )}

        {isSignup && (
          <p className="text-[11.5px] text-[#64748B] leading-relaxed">
            {isDe ? "Mit der Registrierung akzeptierst du unsere " : "By creating an account you agree to our "}
            <Link href="/terms" className="text-black underline underline-offset-2 font-medium">
              {isDe ? "AGB" : "Terms"}
            </Link>
            {isDe ? " und " : " and "}
            <Link href="/privacy" className="text-black underline underline-offset-2 font-medium">
              {isDe ? "Datenschutzerklärung" : "Privacy Policy"}
            </Link>
            .
          </p>
        )}

        <button
          type="submit"
          disabled={busy}
          className="w-full h-12 flex items-center justify-center gap-2 bg-black text-white font-mono text-[12px] uppercase tracking-caps font-medium hover:bg-[#334155] transition-colors disabled:pointer-events-none disabled:bg-[#475569]"
        >
          {status === "submitting" && (
            <>
              <Loader2 className="w-4 h-4 animate-spin" aria-hidden="true" />
              <span>{isDe ? "Einen Moment…" : "One moment…"}</span>
            </>
          )}
          {status === "success" && (
            <>
              <Check className="w-4 h-4" aria-hidden="true" />
              <span>{isDe ? "Weiterleitung…" : "Redirecting…"}</span>
            </>
          )}
          {status === "idle" && (
            <>
              <span>
                {isSignup
                  ? isDe
                    ? "Konto erstellen"
                    : "Create account"
                  : isDe
                  ? "Anmelden"
                  : "Sign in"}
              </span>
              <ArrowRight className="w-3.5 h-3.5" aria-hidden="true" />
            </>
          )}
        </button>
      </form>

      {/* Mode switch */}
      <div className="mt-6 pt-5 border-t border-[#E2E8F0] flex items-center justify-between gap-3 text-[13px] text-[#64748B]">
        <span>
          {isSignup
            ? isDe
              ? "Bereits registriert?"
              : "Already have an account?"
            : isDe
            ? "Noch kein Konto?"
            : "No account yet?"}
        </span>
        {onSwitchMode ? (
          <button
            type="button"
            onClick={onSwitchMode}
            className="font-mono text-[11px] uppercase tracking-caps text-black font-medium hover:underline underline-offset-4"
          >
            {isSignup
              ? isDe
                ? "Anmelden →"
                : "Sign in →"
              : isDe
              ? "Registrieren →"
              : "Sign up →"}
          </button>
        ) : (
          <Link
            href={isSignup ? "/auth/login" : "/auth/signup"}
            className="font-mono text-[11px] uppercase tracking-caps text-black font-medium hover:underline underline-offset-4"
          >
            {isSignup
              ? isDe
                ? "Anmelden →"
                : "Sign in →"
              : isDe
              ? "Registrieren →"
              : "Sign up →"}
          </Link>
        )}
      </div>
    </div>
  );
}

/** Post-signup state: the account exists but stays inert until the link is opened. */
function VerificationSentPanel({
  email,
  isDe,
  compact,
  devLink,
  resendState,
  onResend,
  onBack,
  backIsSwitch,
}: {
  email: string;
  isDe: boolean;
  compact: boolean;
  devLink: string | null;
  resendState: "idle" | "sending" | "sent";
  onResend: () => void;
  onBack: () => void;
  backIsSwitch: boolean;
}) {
  return (
    <div>
      <div className="w-12 h-12 border border-black flex items-center justify-center mb-5">
        <MailCheck className="w-6 h-6 text-black" aria-hidden="true" />
      </div>

      <div className="flex items-center gap-2 mb-3">
        <span className="w-2 h-2 bg-black" aria-hidden="true" />
        <span className="font-mono text-[11px] uppercase tracking-caps text-[#475569] font-bold">
          {isDe ? "Fast fertig" : "Almost there"}
        </span>
      </div>

      <h1
        className={`font-display font-bold tracking-tighter text-black leading-[1.1] ${
          compact ? "text-[24px]" : "text-[28px] sm:text-[32px]"
        }`}
      >
        {isDe ? "Bestätige deine E-Mail" : "Confirm your email"}
      </h1>

      <p className="text-[14px] text-[#64748B] mt-2.5 leading-relaxed">
        {isDe ? "Wir haben einen Bestätigungslink an " : "We've sent a confirmation link to "}
        <span className="text-black font-medium break-all">{email}</span>
        {isDe
          ? " gesendet. Öffne den Link, um dein Konto zu aktivieren."
          : ". Open it to activate your account."}
      </p>

      <div className="mt-5 border border-[#E2E8F0] bg-[#F8FAFC] p-4 space-y-2 font-mono text-[11px] uppercase tracking-wider text-[#64748B]">
        <p>{isDe ? "· Link ist 24 Stunden gültig" : "· Link is valid for 24 hours"}</p>
        <p>{isDe ? "· Prüfe auch den Spam-Ordner" : "· Check your spam folder too"}</p>
        <p>
          {isDe
            ? "· Login erst nach Bestätigung möglich"
            : "· Sign-in works only after confirming"}
        </p>
      </div>

      {devLink && (
        <div className="mt-4 border border-dashed border-[#C4C7C9] bg-white p-3.5">
          <p className="font-mono text-[10px] uppercase tracking-wider text-[#B45309] mb-1.5">
            {isDe ? "Dev-Modus · kein SMTP konfiguriert" : "Dev mode · SMTP not configured"}
          </p>
          <a
            href={devLink}
            className="text-[12px] text-[#475569] underline break-all hover:text-black"
          >
            {devLink}
          </a>
        </div>
      )}

      <div className="mt-6 flex flex-col sm:flex-row gap-2.5">
        <button
          type="button"
          onClick={onResend}
          disabled={resendState !== "idle"}
          className="flex-1 h-11 flex items-center justify-center gap-2 border border-black bg-white text-black font-mono text-[11px] uppercase tracking-caps font-medium hover:bg-black hover:text-white transition-colors disabled:opacity-50 disabled:pointer-events-none"
        >
          {resendState === "sending" && (
            <Loader2 className="w-3.5 h-3.5 animate-spin" aria-hidden="true" />
          )}
          {resendState === "sent" && <Check className="w-3.5 h-3.5" aria-hidden="true" />}
          <span>
            {resendState === "sent"
              ? isDe
                ? "Erneut gesendet"
                : "Sent again"
              : isDe
              ? "Link erneut senden"
              : "Resend link"}
          </span>
        </button>

        {backIsSwitch ? (
          <button
            type="button"
            onClick={onBack}
            className="flex-1 h-11 flex items-center justify-center border border-[#E2E8F0] bg-white text-[#475569] font-mono text-[11px] uppercase tracking-caps hover:border-black hover:text-black transition-colors"
          >
            {isDe ? "Zur Anmeldung" : "To sign in"}
          </button>
        ) : (
          <Link
            href="/auth/login"
            className="flex-1 h-11 flex items-center justify-center border border-[#E2E8F0] bg-white text-[#475569] font-mono text-[11px] uppercase tracking-caps hover:border-black hover:text-black transition-colors"
          >
            {isDe ? "Zur Anmeldung" : "To sign in"}
          </Link>
        )}
      </div>
    </div>
  );
}

/** Shown on login when the credentials are right but the address is unconfirmed. */
function UnverifiedNotice({
  email,
  isDe,
  devLink,
  resendState,
  onResend,
}: {
  email: string;
  isDe: boolean;
  devLink: string | null;
  resendState: "idle" | "sending" | "sent";
  onResend: () => void;
}) {
  return (
    <div
      role="alert"
      className="border border-[#F59E0B] bg-[#FFFBEB] px-3.5 py-3 mb-5 text-[13px] text-[#78350F] leading-snug"
    >
      <p className="flex items-start gap-2.5">
        <AlertTriangle className="w-4 h-4 shrink-0 mt-px" aria-hidden="true" />
        <span>
          {isDe
            ? "Diese E-Mail-Adresse ist noch nicht bestätigt. Öffne den Link, den wir an "
            : "This email address isn't confirmed yet. Open the link we sent to "}
          <span className="font-medium break-all">{email}</span>
          {isDe ? " gesendet haben." : "."}
        </span>
      </p>

      {devLink && (
        <a
          href={devLink}
          className="block mt-2 ml-6 text-[12px] underline break-all hover:text-black"
        >
          {devLink}
        </a>
      )}

      <button
        type="button"
        onClick={onResend}
        disabled={resendState !== "idle"}
        className="mt-2.5 ml-6 inline-flex items-center gap-1.5 font-mono text-[11px] uppercase tracking-caps underline underline-offset-2 hover:text-black disabled:opacity-60 disabled:pointer-events-none"
      >
        {resendState === "sending" && (
          <Loader2 className="w-3 h-3 animate-spin" aria-hidden="true" />
        )}
        {resendState === "sent" && <Check className="w-3 h-3" aria-hidden="true" />}
        {resendState === "sent"
          ? isDe
            ? "Link erneut gesendet"
            : "Link sent again"
          : isDe
          ? "Link erneut senden"
          : "Resend link"}
      </button>
    </div>
  );
}

/** Google's four-colour mark, inlined so the CSP-free page needs no external asset. */
function GoogleIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true" focusable="false">
      <path
        fill="#4285F4"
        d="M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.48h4.84a4.14 4.14 0 0 1-1.8 2.72v2.26h2.92c1.71-1.57 2.68-3.89 2.68-6.62z"
      />
      <path
        fill="#34A853"
        d="M9 18c2.43 0 4.47-.8 5.96-2.18l-2.92-2.26c-.81.54-1.84.86-3.04.86-2.34 0-4.32-1.58-5.03-3.7H.96v2.34A8.99 8.99 0 0 0 9 18z"
      />
      <path fill="#FBBC05" d="M3.97 10.72a5.41 5.41 0 0 1 0-3.44V4.94H.96a9 9 0 0 0 0 8.12l3.01-2.34z" />
      <path
        fill="#EA4335"
        d="M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.59A8.99 8.99 0 0 0 .96 4.94l3.01 2.34C4.68 5.16 6.66 3.58 9 3.58z"
      />
    </svg>
  );
}
