import React, { useCallback, useMemo } from "react";
import styles from "../styles/Header.module.css";
import bgStyles from "../styles/Background.module.css";
import { usePlayer } from "../providers/PlayerProvider";
import { useAccount } from "wagmi";
import dynamic from "next/dynamic";
import Counter, { toReadable } from "./Counter";
import { useModal } from "../providers/ModalProvider";

const Header = () => {
  const { isConnected } = useAccount();
  const { isRegistered, player, army } = usePlayer();
  const { openRegistrationModal } = useModal();

  const title = useMemo(() => {
    return isRegistered && !player?.has_active_session
      ? `You died 😇 Click here to start again and ...`
      : isRegistered
      ? `SLAY THE MOLOCH`
      : !isConnected
      ? "Connect your wallet traveler ☝️  and then ..."
      : "Click here to start 😈";
  }, [isConnected, isRegistered, player?.has_active_session]);

  const subtitle = useMemo(() => {
    if (isRegistered && player?.has_active_session) {
      return <Counter />;
    } else {
      return (
        <p
          className={`${styles.counter} ${
            isConnected && !player?.has_active_session ? bgStyles.excited : ""
          }`}
        >
          SLAY THE MOLOCH
        </p>
      );
    }
  }, [isRegistered, player?.has_active_session, isConnected]);

  const perSecondParagraph = useMemo(() => {
    const perSecond = toReadable(army?.profit_per_second ?? BigInt(0));
    return isRegistered && player?.has_active_session ? (
      <p className={styles.counter_per_seconds}>per second: {perSecond}</p>
    ) : null;
  }, [isRegistered, army?.profit_per_second, player?.has_active_session]);

  const onRegister = useCallback(() => {
    if (player?.has_active_session) return;
    openRegistrationModal();
  }, [player?.has_active_session, openRegistrationModal]);

  return (
    <header
      onClick={onRegister}
      className={`${styles.header} ${
        isConnected && !player?.has_active_session ? styles.clickable : ""
      }`}
    >
      <h1 className={`${styles.title}`}>{title}</h1>
      {subtitle}
      {perSecondParagraph}
    </header>
  );
};

// export default Header

export default dynamic(() => Promise.resolve(Header), {
  ssr: false,
});
