"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { NavLinks } from "@/components/layout/nav-links";
import { SidebarUtilities } from "@/components/layout/sidebar-utilities";
import { useJobs } from "@/components/layout/jobs-provider";
import { BrandLogo, BrandMark } from "@/components/brand/logo";
import { NAV_GROUPS } from "@/lib/nav";
import { useNotifications } from "@/lib/notifications/use-notifications";
import { setNotificationScope } from "@/lib/notifications/store";

export function Sidebar() {
  const router = useRouter();
  const { unreadCount } = useNotifications();
  const { activeJobs } = useJobs();
  const badgeCount = unreadCount + activeJobs.length;
  const [userEmail, setUserEmail] = useState<string | null>(null);

  useEffect(() => {
    fetch("/api/auth/me")
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => {
        if (data?.user?.id) setNotificationScope(data.user.id);
        setUserEmail(data?.user?.email ?? null);
      })
      .catch(() => undefined);
  }, []);

  async function logout() {
    await fetch("/api/auth/logout", { method: "POST" });
    router.replace("/login");
  }

  return (
    <aside className="app-sidebar hidden w-[236px] shrink-0 flex-col lg:sticky lg:top-0 lg:flex lg:h-dvh lg:min-h-dvh">
      <div className="flex h-[72px] shrink-0 items-center gap-2 border-b border-border px-5">
        <BrandLogo size="sm" />
        <BrandMark />
      </div>

      <div className="min-h-0 flex-1 overflow-y-auto px-3 py-5">
        <NavLinks groups={NAV_GROUPS} badgeCount={badgeCount} />
        <SidebarUtilities userEmail={userEmail} onLogout={logout} />
      </div>
    </aside>
  );
}
