"use client";

import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import Lottie from "lottie-react";

/** Maps pathname to Lottie JSON filename (without .json). Put files in public/lottie/ e.g. home.json, blog.json */
function pathnameToLottieName(pathname: string): string {
  if (!pathname || pathname === "/") return "home";
  const segment = pathname.split("/").filter(Boolean)[0];
  return segment ?? "home";
}

export function HeaderLottie() {
  const pathname = usePathname();
  const [animationData, setAnimationData] = useState<object | null>(null);
  const [loading, setLoading] = useState(true);

  const name = pathnameToLottieName(pathname ?? "");

  useEffect(() => {
    setLoading(true);
    setAnimationData(null);
    fetch(`/lottie/${name}.json`)
      .then((res) => (res.ok ? res.json() : Promise.reject()))
      .then((data) => setAnimationData(data))
      .catch(() => setAnimationData(null))
      .finally(() => setLoading(false));
  }, [name]);

  if (loading || !animationData) return null;

  return (
    <div className="w-full overflow-hidden bg-muted/30 border-t border-border/50">
      <div className="container mx-auto px-4 h-[80px] sm:h-[88px] md:h-[96px] flex items-center justify-center">
        <div className="h-full w-full max-w-2xl flex items-center justify-center">
          <Lottie
            animationData={animationData}
            loop
            className="h-full w-full"
            style={{ maxHeight: "100%", maxWidth: "100%" }}
          />
        </div>
      </div>
    </div>
  );
}
