<template>
  <div class="h-screen flex flex-col items-center justify-center">
    <div id="buttonDiv" class="w-[304px] mt-[20px]"></div>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from "vue";
import { oauthToken } from '@/api/login'
import { useRouter } from 'vue-router'

const router = useRouter()

type GoogleIdentityServices = {
  accounts: {
    id: {
      initialize: (params: Record<string, unknown>) => void;
      renderButton: (el: Element, options: Record<string, unknown>) => void;
    };
  };
};

declare global {
  interface Window {
    google?: GoogleIdentityServices;
  }
}

function loadGoogleIdentityServices(): Promise<void> {
  if (window.google?.accounts?.id) {
    return Promise.resolve();
  }

  return new Promise((resolve, reject) => {
    const src = "https://accounts.google.com/gsi/client";
    const existing = document.querySelector<HTMLScriptElement>(
      `script[src="${src}"]`,
    );

    if (existing) {
      if (window.google?.accounts?.id) {
        resolve();
        return;
      }

      existing.addEventListener("load", () => resolve(), { once: true });
      existing.addEventListener(
        "error",
        () => reject(new Error("GIS load error")),
        { once: true },
      );
      return;
    }

    const script = document.createElement("script");
    script.src = src;
    script.async = true;
    script.defer = true;
    script.onload = () => resolve();
    script.onerror = () => reject(new Error("GIS load error"));
    document.head.appendChild(script);
  });
}

onMounted(() => {
  loadGoogleIdentityServices()
    .then(() => {
      if (!window.google?.accounts?.id) {
        throw new Error("GIS not available");
      }

      window.google.accounts.id.initialize({
        client_id:
          "237078935964-e2pioe5hlfbcd4gaam4m9sn859iihdb9.apps.googleusercontent.com",
        ux_mode: "popup",
        callback: (response: any) => {
          // 登录成功后，谷歌会直接把凭证传进这个函数
          console.log("谷歌登录成功，收到凭证：", response);

          // 这个 credential 就是 JWT (ID Token)
          const idToken = response.credential;

          if (idToken) {
            // 【后续业务】：你可以将这串 idToken 通过 axios 发送给你自己的后端接口
            // 或者是直接利用第三方平台（如 Firebase / Supabase）完成纯前端鉴权
            console.log("拿到的 ID Token 是:", idToken);
            oauthToken({ clientId: import.meta.env.VITE_CLIENT_ID, openIdCode: [idToken], grant_type: 'google' })
              .then((res) => {
                console.log("获取到的 oauth token:", res)

                router.go(-1)
              })
              .catch((e) => {
                console.error(e)
              })
          }
        },
        context: "signin",
      });

      const container = document.getElementById("buttonDiv");
      if (!container) {
        throw new Error("Missing #buttonDiv");
      }

      window.google.accounts.id.renderButton(container, {
        theme: "outline",
        size: "large",
        width: 304,
        shape: "rectangular",
        logo_alignment: "center",
      });
    })
    .catch((e) => {
      console.error(e);
    });
});
</script>
