import Title from "@/components/Title";
import styles from "./styles.module.css";
import { useCallback, useEffect, useRef, useState } from "react";
import { onboardingTitles } from "@/data/onboarding";
import routes from "@/routes";
import { useNavigate } from "react-router-dom";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys } from "@/api/resources/Paywall";

function OnboardingPage() {
  const navigate = useNavigate();
  const [activeIndexTitle, setIndexTitle] = useState(0);
  const [periodClassName, setPeriodClassName] = useState("");
  const titleInterval = useRef<NodeJS.Timeout>();
  const classNameTimeOut = useRef<NodeJS.Timeout>();
  usePaywall({ placementKey: EPlacementKeys["aura.placement.main"] });

  const handleNext = useCallback(() => {
    navigate(routes.client.trialChoice());
  }, [navigate]);

  useEffect(() => {
    setPeriodClassName("to-nontransparent");
    classNameTimeOut.current = setTimeout(() => {
      setPeriodClassName("to-transparent");
    }, 4000);
    titleInterval.current = setTimeout(() => {
      if (activeIndexTitle < onboardingTitles.length - 1) {
        setIndexTitle((prev) => prev + 1);
      } else {
        handleNext();
      }
    }, 5000);
    return () => {
      if (titleInterval.current) clearTimeout(titleInterval.current);
      if (classNameTimeOut.current) clearTimeout(classNameTimeOut.current);
    };
  }, [activeIndexTitle, handleNext]);

  return (
    <section className={`${styles.page} page`}>
      {onboardingTitles[activeIndexTitle] && (
        <Title className={`${styles.title} ${styles[periodClassName]}`}>
          {onboardingTitles[activeIndexTitle]}
        </Title>
      )}
    </section>
  );
}

export default OnboardingPage;
