import "./index.scss";

import React, { useEffect } from "react";

import { useConfig } from "@/config";
import { accountStore, User } from "@/stores";
const NeosConfig = useConfig();

const Start: React.FC = () => {
  const sso = new URL(location.href).searchParams.get("sso");
  const user: User | undefined = sso ? getSSOUser(new URLSearchParams(atob(sso))) : undefined;
  const onLogin = () => {
    const ssoUrl = getSSOUrl(location.href);
    window.location.href = ssoUrl;
  };

  useEffect(() => {
    if (user) {
      accountStore.login(user);
      // TODO: navigate
    }

  }, [user])

  return (
    <>
      <div className="mycard-header">
        <a className="mycard-logo" href="https://mycard.moe/">
          <img
            src={`${NeosConfig.assetsPath}/mycard_logo.png`}
            alt="MyCard"
            width={130}
            height={40}
          />
        </a>
      </div>
      <div className="wrapper">
        <div role="banner" className="neos-header">
          <div>
            <h1>
              <img
                src={`${NeosConfig.assetsPath}/neos_logo.png`}
                width={540}
                height={250}
                alt="YGO NEOS"
              />
            </h1>
            <button onClick={onLogin}>登陆萌卡进行游玩</button>
          </div>
        </div>
      </div>
    </>
  );
};

function getSSOUrl(callbackUrl: string): string {
  let params = new URLSearchParams();
  params.set("return_sso_url", callbackUrl);
  const payload = btoa(params.toString());

  const url = new URL("https://accounts.moecube.com");
  params = url.searchParams;
  params.set("sso", payload);

  return url.toString();
}

function getSSOUser(searchParams: URLSearchParams): User {
  const sso = {};
  for (const [key, value] of searchParams) {
    // @ts-ignore
    sso[key] = value;
  }

  return sso as any;
}

export default Start;
