"use client";

import { useEffect, useState, useRef } from "react";
import Fireworks from "fireworks-js";

export default function Home() {
  // ===== STATE =====
  const [phase, setPhase] = useState<
    "typing" | "waiting" | "countdown" | "fireworks"
  >("typing");
  const [typed, setTyped] = useState("");
  const [countdown, setCountdown] = useState(3);
  const [showTitle, setShowTitle] = useState(true); // untuk fade out title

  const containerRef = useRef<HTMLDivElement>(null);
  const fireworksInstance = useRef<Fireworks | null>(null);

  const FULL_TEXT = "Untuk Meigi";

  // ===== 1. TYPEWRITER =====
  useEffect(() => {
    if (phase !== "typing") return;

    let idx = 0;
    const timer = setInterval(() => {
      if (idx < FULL_TEXT.length) {
        setTyped(FULL_TEXT.slice(0, idx + 1));
        idx++;
      } else {
        clearInterval(timer);
        setPhase("waiting");
        // setelah 2 detik, sembunyikan title
        setTimeout(() => {
          setShowTitle(false);
        }, 2000);
        // pindah ke countdown setelah fade (2 detik + 0.8 detik fade)
        setTimeout(() => {
          setPhase("countdown");
          setCountdown(3);
        }, 2800);
      }
    }, 80);

    return () => clearInterval(timer);
  }, [phase]);

  // ===== 2. COUNTDOWN =====
  useEffect(() => {
    if (phase !== "countdown") return;

    if (countdown > 1) {
      const timer = setTimeout(() => {
        setCountdown((prev) => prev - 1);
      }, 1000);
      return () => clearTimeout(timer);
    } else {
      // countdown = 1, tunggu 1 detik lalu luncurkan kembang api
      const timer = setTimeout(() => {
        setPhase("fireworks");
      }, 1000);
      return () => clearTimeout(timer);
    }
  }, [phase, countdown]);

  // ===== 3. FIREWORKS =====
  useEffect(() => {
    if (phase === "fireworks" && containerRef.current) {
      const container = containerRef.current;

      // Konfigurasi kembang api (bisa diatur sesuai selera)
      const options = {
        rocketsPoint: 50, // titik tembak horizontal (50 = tengah)
        hue: { min: 0, max: 360 },
        delay: { min: 15, max: 30 },
        speed: 2,
        acceleration: 1.05,
        friction: 0.97,
        gravity: 1.5,
        particles: 80,
        trace: 3,
        explosion: 6,
        autoresize: true,
        brightness: { min: 50, max: 80 },
        decay: { min: 0.015, max: 0.03 },
      };

      const fw = new Fireworks(container, {
        hue: { min: 0, max: 360 },
        delay: { min: 15, max: 30 },
        acceleration: 1.05,
        friction: 0.97,
        gravity: 1.5,
        particles: 80,
        explosion: 6,
        sound: {
          enabled: true,
          files: ["explosion0.mp3", "explosion1.mp3", "explosion2.mp3"],
        },
        autoresize: true,
        brightness: { min: 50, max: 80 },
        decay: { min: 0.015, max: 0.03 },
      });
      fw.start();
      fireworksInstance.current = fw;

      return () => {
        if (fireworksInstance.current) {
          fireworksInstance.current.stop();
          fireworksInstance.current = null;
        }
      };
    }
  }, [phase]);

  // ===== 4. RENDER =====
  return (
    <div className="relative min-h-screen flex items-center justify-center bg-black overflow-hidden">
      {/* Container untuk kembang api (selalu ada, tapi hanya diisi saat phase fireworks) */}
      <div
        ref={containerRef}
        className="fixed inset-0 pointer-events-none z-0"
      />

      {/* Konten utama di atas lapisan kembang api */}
      <div className="relative z-10 text-white text-center">
        {/* TITLE dengan efek fade */}
        {phase !== "fireworks" && (
          <h1
            className={`
              text-5xl md:text-7xl lg:text-8xl font-bold tracking-wide
              transition-all duration-800 ease-in-out
              ${showTitle ? "opacity-100 scale-100" : "opacity-0 scale-95"}
            `}
          >
            {phase === "typing" ? (
              <>
                {typed}
                <span className="inline-block animate-pulse font-light ml-1">
                  |
                </span>
              </>
            ) : (
              FULL_TEXT // saat waiting / countdown, teks tetap terlihat (kecuali fade)
            )}
          </h1>
        )}

        {/* COUNTDOWN */}
        {phase === "countdown" && (
          <div className="mt-8 text-9xl md:text-[12rem] lg:text-[16rem] font-bold select-none animate-pulse">
            {countdown}
          </div>
        )}
      </div>
    </div>
  );
}
