"use client";

import { useEffect, useRef, useState } from "react";
import { usePathname } from "next/navigation";
import "./logo-intro.css";

const BRAND = "pirajin";

export function LogoIntro() {
  const pathname = usePathname();
  const isHome = pathname === "/";
  const [visible, setVisible] = useState(false);
  const [hiding, setHiding] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);
  const started = useRef(false);

  useEffect(() => {
    if (!isHome) {
      document.documentElement.classList.remove("logo-intro-pending");
      setVisible(false);
      setHiding(false);
      started.current = false;
      return;
    }
    setHiding(false);
    setVisible(true);
    document.documentElement.classList.add("logo-intro-pending");
  }, [isHome]);

  useEffect(() => {
    if (!isHome || !visible || hiding || started.current) return;
    if (!rootRef.current) return;
    started.current = true;

    let cancelled = false;
    let safety = 0;

    const finish = () => {
      if (cancelled) return;
      cancelled = true;
      window.clearTimeout(safety);
      document.documentElement.classList.remove("logo-intro-pending");
      setHiding(true);
      window.setTimeout(() => setVisible(false), 600);
    };

    safety = window.setTimeout(finish, 5200);

    const loadAnime = (): Promise<AnimeStatic> =>
      new Promise((resolve, reject) => {
        if (window.anime) {
          resolve(window.anime);
          return;
        }
        const existing = document.querySelector<HTMLScriptElement>("script[data-anime-logo]");
        if (existing) {
          existing.addEventListener("load", () => resolve(window.anime));
          existing.addEventListener("error", () => reject(new Error("anime load failed")));
          return;
        }
        const script = document.createElement("script");
        script.src = "/vendor/anime.min.js";
        script.async = true;
        script.dataset.animeLogo = "1";
        script.onload = () => resolve(window.anime);
        script.onerror = () => reject(new Error("anime load failed"));
        document.head.appendChild(script);
      });

    (async () => {
      let anime: AnimeStatic;
      try {
        anime = await loadAnime();
      } catch {
        finish();
        return;
      }
      if (cancelled || !rootRef.current || !anime) return;

      const root = rootRef.current;
      const draws = root.querySelectorAll(".brand-svg .draw");
      const dots = root.querySelectorAll(".brand-svg .dot");
      const iconLine = root.querySelector(".icon-line") as SVGPathElement | null;

      draws.forEach((el) => {
        const path = el as SVGPathElement;
        const len = anime.setDashoffset(path);
        path.setAttribute("stroke-dasharray", String(Math.abs(len)));
        path.setAttribute("stroke-dashoffset", String(Math.abs(len)));
      });

      if (iconLine) {
        iconLine.setAttribute("stroke-dashoffset", String(anime.setDashoffset(iconLine)));
      }

      anime
        .timeline({ complete: finish })
        .add({
          targets: draws,
          strokeDashoffset: [anime.setDashoffset, 0],
          delay: (_el: unknown, i: number) => 200 + i * 100,
          duration: 700,
          easing: "easeOutQuad",
        })
        .add({
          targets: dots,
          opacity: [0, 1],
          scale: [0, 1],
          delay: (_el: unknown, i: number) => i * 80,
          duration: 400,
          easing: "easeOutBack",
          offset: "-=400",
        })
        .add({
          targets: root.querySelectorAll(".brand-svg"),
          opacity: [1, 0],
          scale: [1, 0.9],
          duration: 450,
          easing: "easeInQuart",
          delay: 400,
        })
        .add({
          targets: root.querySelectorAll(".logo-icon"),
          opacity: [0, 1],
          scale: [0.75, 1],
          duration: 500,
          easing: "easeOutBack",
          offset: "-=150",
        })
        .add({
          targets: root.querySelectorAll(".icon-line"),
          strokeDashoffset: [anime.setDashoffset, 0],
          strokeWidth: [8, 2],
          stroke: ["#FFF", "#5E89FB"],
          duration: 700,
          easing: "easeInOutQuart",
          offset: "-=200",
        })
        .add({
          targets: root.querySelectorAll(".icon-text text"),
          translateY: [36, 0],
          opacity: [0, 1],
          delay: (_el: unknown, i: number) => i * 30,
          duration: 320,
          easing: "easeOutQuart",
          offset: "-=350",
        });
    })();

    return () => {
      cancelled = true;
      window.clearTimeout(safety);
    };
  }, [isHome, visible, hiding]);

  if (!isHome || !visible) return null;

  return (
    <div
      ref={rootRef}
      className={`logo-intro-overlay${hiding ? " is-hiding" : ""}`}
      aria-hidden="true"
    >
      <div className="logo-animation">
        {/* pirajin. — حروف هندسی واضح */}
        <svg className="brand-svg" viewBox="0 0 700 160" fill="none">
          {/* p — کاسه بالا + پایه پایین تا b نشود */}
          <path className="draw" stroke="#5E89FB" strokeWidth="28" d="M40 8v136" />
          <path className="draw" stroke="#5E89FB" strokeWidth="28" d="M40 20a36 36 0 0 1 0 72" />
          {/* i */}
          <path className="draw" stroke="#FB155A" strokeWidth="28" d="M140 68v72" />
          <circle className="dot" cx="140" cy="34" r="14" fill="#FB155A" />
          {/* r */}
          <path className="draw" stroke="#18FF92" strokeWidth="28" d="M200 16v124" />
          <path className="draw" stroke="#18FF92" strokeWidth="28" d="M200 68c12-36 48-44 68-28" />
          {/* a */}
          <circle className="draw" cx="340" cy="96" r="40" stroke="#5E89FB" strokeWidth="28" />
          <path className="draw" stroke="#5E89FB" strokeWidth="28" d="M380 70v70" />
          {/* j */}
          <path className="draw" stroke="#FB155A" strokeWidth="28" d="M460 68v36c0 26-20 40-40 40" />
          <circle className="dot" cx="460" cy="34" r="14" fill="#FB155A" />
          {/* i */}
          <path className="draw" stroke="#18FF92" strokeWidth="28" d="M520 68v72" />
          <circle className="dot" cx="520" cy="34" r="14" fill="#18FF92" />
          {/* n */}
          <path className="draw" stroke="#5E89FB" strokeWidth="28" d="M580 140V68c0-28 22-44 44-44" />
          <path className="draw" stroke="#5E89FB" strokeWidth="28" d="M624 68v72" />
          {/* . */}
          <circle className="dot" cx="670" cy="128" r="12" fill="#FFFFFF" />
        </svg>

        <div className="logo-icon">
          <div className="icon">
            <svg viewBox="0 0 62 62">
              <g fill="none" fillRule="evenodd" strokeWidth="2" transform="translate(1 1)">
                <path className="icon-curve" stroke="#FF1554" d="M0 16a80.88 80.88 0 0 1 44 44" />
                <path
                  className="icon-line"
                  stroke="#5E89FB"
                  d="M4 0h54a2 2 0 0 1 2 2.01V58A2 2 0 0 1 58 60H2a2 2 0 0 1-2-2.01V2A2 2 0 0 1 2 0h2z"
                />
                <rect width="40" height="40" x="10" y="10" stroke="#18FF92" rx="20" />
              </g>
            </svg>
          </div>
          <div className="icon-text" aria-label="pirajin">
            <svg viewBox="0 0 200 62" width="200" height="62">
              <g
                fill="#FBF3FB"
                fontFamily="Arial, Helvetica, sans-serif"
                fontSize="22"
                fontWeight="700"
              >
                {BRAND.split("").map((ch, i) => (
                  <text key={`${ch}-${i}`} x={4 + i * 22} y="38">
                    {ch}
                  </text>
                ))}
              </g>
            </svg>
          </div>
        </div>
      </div>
    </div>
  );
}
