import { useEffect, useState } from "react";
import { getLanguage } from "taehui-ts/language";

import { GetTitleAPI } from "src/wwwAPI";
import { wwwAXIOS } from "src/Www";
import Title from "src/Title";

export default function AvatarTitle({ avatarID }: { avatarID: string }) {
  const [avatarTitle, setAvatarTitle] = useState<GetTitleAPI>({
    title: "",
    titleColor: "",
  });

  useEffect(() => {
    (async () => {
      const { data, status } = await wwwAXIOS.get<GetTitleAPI>("/title", {
        params: {
          avatarID,
          language: getLanguage(),
        },
      });
      if (status === 200) {
        if (data.titleColor.startsWith("#")) {
          setAvatarTitle({
            ...data,
            titleColor: `#${data.titleColor.substring(
              3,
            )}${data.titleColor.substring(1, 3)}`,
          });
        } else {
          setAvatarTitle(data);
        }
      }
    })();
  }, [avatarID]);

  return (
    <Title title={avatarTitle.title} titleColor={avatarTitle.titleColor} />
  );
}
