"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useTranslation } from "react-i18next";

import type { DocsNavGroup } from "@/lib/docs-nav";
import { resolveDocsNavLabel } from "@/lib/docs-nav-labels";
import { cn } from "@/lib/utils";

export function DocsSidebar({ groups }: { groups: readonly DocsNavGroup[] }): React.ReactElement {
  const pathname = usePathname();
  const { t, i18n } = useTranslation("integrationDocs");

  const label = (key: string): string => {
    const translated = t(key);
    if (translated !== key) {
      return translated;
    }
    return resolveDocsNavLabel(key, i18n.resolvedLanguage ?? i18n.language);
  };

  return (
    <aside className="w-full shrink-0 lg:w-44">
      <div className="lg:sticky lg:top-14 lg:max-h-[calc(100dvh-4rem)] lg:overflow-y-auto lg:pr-2">
        <nav className="space-y-4">
          {groups.map((group) => (
            <div key={group.titleKey}>
              <div className="mb-1 px-1.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground/80">
                {label(group.titleKey)}
              </div>
              <ul className="space-y-px">
                {group.items.map((item) => {
                  const active =
                    pathname === item.href ||
                    (item.href !== "/docs/integration" && pathname.startsWith(item.href)) ||
                    (item.href === "/docs/integration" && pathname === "/docs/integration");

                  return (
                    <li key={item.href}>
                      <Link
                        href={item.href}
                        className={cn(
                          "block rounded-md px-2 py-1.5 text-[13px] leading-5 transition-colors",
                          active
                            ? "bg-primary/10 font-medium text-foreground"
                            : "text-muted-foreground hover:bg-muted/40 hover:text-foreground",
                        )}
                      >
                        {label(item.titleKey)}
                      </Link>
                    </li>
                  );
                })}
              </ul>
            </div>
          ))}
        </nav>
      </div>
    </aside>
  );
}
