"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";

export function Topbar() {
  const pathname = usePathname();
  const [newLeadsCount, setNewLeadsCount] = useState(0);

  useEffect(() => {
    function fetchNewLeads() {
      fetch("/api/leads/stats")
        .then((r) => r.json())
        .then((d: { new?: number }) => setNewLeadsCount(d.new ?? 0))
        .catch(() => {});
    }
    fetchNewLeads();
    const t = setInterval(fetchNewLeads, 30000);
    return () => clearInterval(t);
  }, []);

  const isSearch = pathname === "/suche" || pathname.startsWith("/suche/");
  const isLeadspeicher = pathname === "/leadspeicher" || pathname.startsWith("/leadspeicher/");

  return (
    <header className="sticky top-0 w-full z-50 flex justify-between items-center px-8 h-16"
      style={{
        background: "rgba(13, 20, 25, 0.85)",
        backdropFilter: "blur(20px)",
        WebkitBackdropFilter: "blur(20px)",
        boxShadow: "0 20px 40px rgba(0,0,0,0.4)",
      }}
    >
      {/* Left: Logo + Nav */}
      <div className="flex items-center gap-8">
        <Link href="/suche" style={{ textDecoration: "none" }}>
          <span className="text-xl font-black text-white tracking-tighter" style={{ fontFamily: "Manrope, sans-serif" }}>
            mein-solar | Lead Finder
          </span>
        </Link>
        <nav className="hidden md:flex gap-6 items-center h-full">
          <Link
            href="/suche"
            className={`font-bold tracking-tight transition-all pb-1 text-sm ${
              isSearch
                ? "text-blue-400 border-b-2 border-blue-500"
                : "text-slate-400 hover:text-white"
            }`}
            style={{ fontFamily: "Manrope, sans-serif", textDecoration: "none" }}
          >
            Lead-Suche
          </Link>
          <Link
            href="/leadspeicher"
            className={`font-bold tracking-tight transition-all pb-1 text-sm flex items-center gap-2 ${
              isLeadspeicher
                ? "text-blue-400 border-b-2 border-blue-500"
                : "text-slate-400 hover:text-white"
            }`}
            style={{ fontFamily: "Manrope, sans-serif", textDecoration: "none" }}
          >
            Leadspeicher
            {newLeadsCount > 0 && (
              <span
                className="text-white font-bold rounded-full flex items-center justify-center px-1"
                style={{
                  background: "#1a73e8",
                  fontSize: 10,
                  minWidth: 18,
                  height: 18,
                  lineHeight: 1,
                }}
              >
                {newLeadsCount > 99 ? "99+" : newLeadsCount}
              </span>
            )}
          </Link>
        </nav>
      </div>

    </header>
  );
}
