// =============================================================================
// HeadlineSift.com — Admin Sidebar
// =============================================================================
"use client";

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

interface NavItem {
  label: string;
  href: string;
  icon: string;
}

const NAV_ITEMS: NavItem[] = [
  { label: "Dashboard",       href: "/admin",               icon: "📊" },
  { label: "Countries",       href: "/admin/countries",      icon: "🌍" },
  { label: "Categories",      href: "/admin/categories",     icon: "🏷️" },
  { label: "Sources",         href: "/admin/sources",        icon: "📡" },
  { label: "Source Mappings", href: "/admin/source-mappings", icon: "🔗" },
  { label: "Raw Articles",    href: "/admin/articles",       icon: "📄" },
  { label: "Story Clusters",  href: "/admin/stories",        icon: "📰" },
  { label: "Review Queue",    href: "/admin/review",         icon: "✅" },
  { label: "AI Analysis",     href: "/admin/ai-analysis",    icon: "🤖" },
  { label: "Fetch Logs",      href: "/admin/fetch-logs",     icon: "📋" },
  { label: "Jobs",            href: "/admin/jobs",           icon: "⚙️" },
  { label: "Ranking Rules",   href: "/admin/ranking-rules",  icon: "📈" },
  { label: "Settings",        href: "/admin/settings",       icon: "🔧" },
  { label: "Backups",         href: "/admin/backups",        icon: "💾" },
  { label: "System Logs",     href: "/admin/system-logs",    icon: "🪵" },
];

interface AdminSidebarProps {
  /** Whether the mobile sidebar is open. */
  open: boolean;
  /** Called to close the sidebar (mobile overlay tap / nav link click). */
  onClose: () => void;
}

export function AdminSidebar({ open, onClose }: AdminSidebarProps) {
  const pathname = usePathname();

  // Close sidebar on route change (mobile)
  useEffect(() => {
    onClose();
  }, [pathname, onClose]);

  // Close on Escape key
  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        onClose();
      }
    },
    [onClose],
  );

  useEffect(() => {
    if (open) {
      document.addEventListener("keydown", handleKeyDown);
      return () => {
        document.removeEventListener("keydown", handleKeyDown);
      };
    }
    // No cleanup needed when sidebar is closed.
    return undefined;
  }, [open, handleKeyDown]);

  const sidebarContent = (
    <>
      {/* Logo */}
      <div className="flex h-16 items-center gap-2 border-b border-border px-6 shrink-0">
        <span className="text-brand-600">▲</span>
        <Link
          href="/admin"
          className="text-lg font-bold text-heading no-underline"
        >
          HeadlineSift
        </Link>
        <span className="ml-auto rounded bg-surface-tertiary px-1.5 py-0.5 text-2xs font-medium text-body-muted">
          Admin
        </span>
      </div>

      {/* Navigation */}
      <nav
        className="flex-1 overflow-y-auto p-4"
        aria-label="Admin navigation"
      >
        <ul className="space-y-1">
          {NAV_ITEMS.map((item) => {
            const isActive =
              item.href === "/admin"
                ? pathname === "/admin"
                : pathname.startsWith(item.href);

            return (
              <li key={item.href}>
                <Link
                  href={item.href}
                  className={`flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors no-underline ${
                    isActive
                      ? "bg-brand-50 text-brand-700"
                      : "text-body hover:bg-surface-secondary hover:text-heading"
                  }`}
                >
                  <span className="text-base" aria-hidden="true">
                    {item.icon}
                  </span>
                  {item.label}
                </Link>
              </li>
            );
          })}
        </ul>
      </nav>

      {/* Footer */}
      <div className="border-t border-border p-4 shrink-0">
        <Link
          href="/"
          className="flex items-center gap-2 text-xs text-body-muted no-underline hover:text-body"
        >
          ← Back to site
        </Link>
      </div>
    </>
  );

  return (
    <>
      {/* ---- Desktop sidebar (always visible on lg+) ---- */}
      <aside className="fixed inset-y-0 left-0 z-40 hidden w-64 flex-col border-r border-border bg-white lg:flex">
        {sidebarContent}
      </aside>

      {/* ---- Mobile overlay ---- */}
      {open && (
        <div className="fixed inset-0 z-50 lg:hidden">
          {/* Backdrop */}
          <div
            className="fixed inset-0 bg-black/40 transition-opacity"
            onClick={onClose}
            aria-hidden="true"
          />

          {/* Drawer */}
          <aside className="fixed inset-y-0 left-0 z-50 flex w-64 flex-col bg-white shadow-xl transition-transform">
            {sidebarContent}
          </aside>
        </div>
      )}
    </>
  );
}
