"use client";

/*
 * Raw `<img>`, as in all four original copies. Left as a plain `<img>` and left
 * *reported* rather than suppressed: `images.unoptimized` is set, so the
 * no-img-element warning is arguably moot here, but suppressing it would drop
 * it from the project's count and hide it from whoever works C7.
 */
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { GoogleLogin, useGoogleOAuth } from "@react-oauth/google";
import AssetIcon from "@/components/ui/AssetIcon";
import { socialProfileFromGoogleCredential } from "@/lib/auth/google";
import type { SocialProfile } from "@/lib/auth/socialSignup";
import { logRequestError } from "@/lib/api/logError";

const FOCUS_RING =
  "rounded-full focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-5";

/**
 * "Or continue with" — the Google button. LinkedIn sign-in was cancelled by the
 * client (answers PDF p.6, item 19: only Google sign-in is needed).
 *
 * Replaces four copies of this block (`LoginForm`,
 * `RegisterVolunteerModalForm`, `IndividualRegistrationForm`,
 * `EntitiesRegistrationForm`). What each does with the result differs — the
 * registration forms stash a prefill first — so the actions are callbacks;
 * only the markup and the missing-client-id guard are shared.
 *
 * That guard is why the copies were worth unifying: three used
 * `t("COMMON.TOAST.GOOGLE_NOT_CONFIGURED")` while
 * `RegisterVolunteerModalForm` hardcoded the English sentence, so an Arabic
 * user of that one modal got an untranslated toast.
 *
 * **Google is GIS's own button (BE-160).** `/social-auth/` verifies a Google
 * *ID token*, which only Google Identity Services' "Sign in with Google"
 * button / One Tap hand out — the `useGoogleLogin` implicit flow this used to
 * call yields an OAuth access token the backend now rejects. GIS draws its
 * button in a cross-origin iframe that cannot be restyled, so the Fursa icon
 * stays as the visible face and the real `<GoogleLogin>` icon button sits
 * over it, scaled to cover it and transparent: the click lands on Google's
 * button, which opens Google's popup and calls back with the `credential`.
 * The iframe is also what takes keyboard focus (with Google's own accessible
 * name), so the ring is drawn on the wrapper through `focus-within`.
 *
 * `onGoogle` receives the decoded profile — email and names read out of the
 * ID token for display/prefill — with the token itself as `social_token`.
 */
export default function SocialAuthButtons({
  onGoogle,
}: {
  onGoogle: (profile: SocialProfile) => void;
}) {
  const { t } = useTranslation();
  const { scriptLoadedSuccessfully } = useGoogleOAuth();
  const googleConfigured = Boolean(
    process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID?.trim()
  );

  const googleIcon = (
    <AssetIcon src="/assets/auth/goggle.svg" width={70} height={60} />
  );

  /*
   * Real `<button>`s, not `<img onClick>`, wherever the click is ours: an
   * image is not focusable and answers neither Enter nor Space. The Google
   * fallback button covers the two states with no GIS button to click — no
   * client id, or the GIS script blocked/still loading — and says which.
   */
  return (
    <div className="flex justify-center gap-[15px]">
      {googleConfigured && scriptLoadedSuccessfully ? (
        <div
          className="relative cursor-pointer rounded-full focus-within:outline focus-within:outline-2 focus-within:outline-offset-2 focus-within:outline-primary-5"
        >
          <span aria-hidden="true" className="block pointer-events-none">
            {googleIcon}
          </span>
          <div className="absolute inset-0 flex items-center justify-center overflow-hidden rounded-full opacity-[0.01]">
            <div className="scale-[1.75]">
              <GoogleLogin
                type="icon"
                shape="circle"
                size="large"
                theme="outline"
                onSuccess={({ credential }) => {
                  const profile = socialProfileFromGoogleCredential(credential);
                  if (!profile) {
                    toast.error(t("COMMON.TOAST.GOOGLE_LOGIN_FAILED"));
                    return;
                  }
                  onGoogle(profile);
                }}
                onError={() => {
                  logRequestError(
                    "Google Login Error:",
                    new Error("No credential from Google Identity Services")
                  );
                  toast.error(t("COMMON.TOAST.GOOGLE_LOGIN_ERROR"));
                }}
              />
            </div>
          </div>
        </div>
      ) : (
        <button
          type="button"
          aria-label={t("COMMON.CONTINUE_WITH_GOOGLE")}
          onClick={() => {
            toast.error(
              googleConfigured
                ? t("COMMON.TOAST.GOOGLE_LOGIN_ERROR")
                : t("COMMON.TOAST.GOOGLE_NOT_CONFIGURED")
            );
          }}
          className={`cursor-pointer ${FOCUS_RING}`}
        >
          {googleIcon}
        </button>
      )}
    </div>
  );
}
