"use client";

import { useEffect, useState } from "react";
import { GraduationCap } from '@/lib/icons';
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
import { ACADEMY_MODULES } from "@/lib/academy/tours";
import { getCompletedModules } from "@/lib/academy/progress";

export function AcademySidebarBadge() {
  const [percent, setPercent] = useState(0);
  const pathname = usePathname();
  const isActive = pathname === "/academy";

  useEffect(() => {
    function update() {
      const completed = getCompletedModules();
      setPercent(Math.round((completed.length / ACADEMY_MODULES.length) * 100));
    }
    update();
    window.addEventListener("focus", update);
    return () => window.removeEventListener("focus", update);
  }, []);

  if (percent === 100) return null;

  return (
    <Link
      href="/academy"
      className={cn(
        "flex items-center gap-2.5 px-3 py-2 rounded-lg text-sm transition-colors mx-2",
        isActive
          ? "bg-primary/10 text-primary"
          : "text-muted-foreground hover:bg-accent hover:text-accent-foreground"
      )}
    >
      <GraduationCap className="size-4 shrink-0" />
      <span className="flex-1 text-xs font-medium">Akademi</span>
      <span className={cn(
        "text-[10px] font-semibold px-1.5 py-0.5 rounded-full",
        percent === 0
          ? "bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300"
          : "bg-primary/15 text-primary"
      )}>
        %{percent}
      </span>
    </Link>
  );
}
