import { RightOutlined } from "@ant-design/icons";
import React from "react";
import { useNavigate } from "react-router-dom";
import { accountStore } from "@/stores";
import { useConfig } from "@/config";

import styles from "./index.module.scss";
import { useSnapshot } from "valtio";

const NeosConfig = useConfig();

export const Component: React.FC = () => {
  const { user } = useSnapshot(accountStore);
  return (
    <>
      <div className={styles.wrapper}>
        {/* <div className={styles["particles-container"]}>
          {Array.from({ length: 100 }).map((_, key) => (
            <div key={key} className={styles["particle-container"]}>
              <div className={styles["particle"]} />
            </div>
          ))}
        </div> */}
        <main className={styles["main"]}>
          <img
            className={styles["neos-logo"]}
            src={`${NeosConfig.assetsPath}/neos-logo.svg`}
            alt="YGO NEOS"
          />
          <img
            className={styles["neos-pic"]}
            src={`${NeosConfig.assetsPath}/neos.png`}
            alt="neos"
          />
        </main>
        <LoginBtn logined={Boolean(user)} />
      </div>
    </>
  );
};
Component.displayName = "Start";

const LoginBtn: React.FC<{ logined: boolean }> = ({ logined }) => {
  const navigate = useNavigate();

  const loginViaSSO = () =>
    // 跳转回match页
    location.replace(getSSOUrl(`${location.origin}/match/}`));

  const goToMatch = () => navigate("/match");

  return (
    <span
      className={styles["start-btn"]}
      onClick={logined ? goToMatch : loginViaSSO}
    >
      {logined ? <span>开始游戏</span> : <span>登录游戏</span>}
      <RightOutlined />
    </span>
  );
};

/** 构建一个单点登录（Single Sign-On，简称SSO）的URL */
function getSSOUrl(callbackUrl: string): string {
  const params = new URLSearchParams({
    sso: btoa(new URLSearchParams({ return_sso_url: callbackUrl }).toString()),
  });

  const url = new URL(NeosConfig.accountUrl);
  url.search = params.toString();

  return url.toString();
}
