"use client";

/**
 * AdminShell — shared admin chrome that wraps every /admin/* page so the
 * site is usable from a phone. Renders:
 *
 *   • Dark top bar (matches existing bg-[#0a0a0a] admin theme) with
 *     hamburger trigger on the right.
 *   • Slide-down drawer listing every admin section. Tap a link, drawer
 *     closes, you're there. Keeps the existing per-page layouts intact
 *     so we can roll it out page-by-page without breaking anything.
 *
 * Usage:
 *   import AdminShell from "@/components/admin/AdminShell";
 *   …
 *   return (
 *     <AdminShell title="Articles">
 *       <YourExistingPageContent />
 *     </AdminShell>
 *   );
 *
 * The shell adds a sticky top bar at min-h-12 so existing content below
 * doesn't overlap.
 */
import React, { useState, useEffect } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";

const SECTIONS = [
  { group: "Content", items: [
    { href: "/admin", label: "Dashboard" },
    { href: "/admin/articles", label: "Articles" },
    { href: "/admin/review-queue", label: "Review Queue" },
    { href: "/admin/import", label: "WP Import" },
    { href: "/admin/audit-log", label: "Audit Log" },
  ]},
  { group: "Editorial", items: [
    { href: "/admin/forum-dashboard", label: "Forum Dashboard" },
    { href: "/admin/forum-moderation", label: "Forum Moderation" },
    { href: "/admin/forum-seed", label: "Forum Seed" },
    { href: "/admin/banned-terms", label: "Banned Terms" },
    { href: "/admin/notifications", label: "Notifications" },
    { href: "/admin/content-status", label: "Content Status" },
  ]},
  { group: "Companies", items: [
    { href: "/admin/company-coverage", label: "Company Coverage" },
    { href: "/admin/company-tracker", label: "Company Tracker" },
  ]},
  { group: "Newsletter", items: [
    { href: "/admin/newsletter", label: "Newsletter" },
    { href: "/admin/newsletter/templates", label: "Templates" },
    { href: "/admin/newsletter/campaign-editor", label: "Campaign Editor" },
    { href: "/admin/newsletter/analytics", label: "Analytics" },
    { href: "/admin/email-analytics", label: "Email Analytics" },
  ]},
  { group: "AdOps", items: [
    { href: "/admin/adops", label: "AdOps" },
    { href: "/admin/adops/products", label: "Products" },
    { href: "/admin/adops/ios", label: "IOs" },
    { href: "/admin/adops/notifications", label: "AdOps Notifs" },
    { href: "/admin/banners", label: "Banners" },
  ]},
  { group: "Accounting", items: [
    { href: "/admin/accounting", label: "Accounting" },
    { href: "/admin/accounting/clients", label: "Clients" },
    { href: "/admin/accounting/invoices", label: "Invoices" },
    { href: "/admin/accounting/expenses", label: "Expenses" },
    { href: "/admin/accounting/reports", label: "Reports" },
  ]},
  { group: "People", items: [
    { href: "/admin/users", label: "Users" },
    { href: "/admin/wp-users", label: "WP Users" },
    { href: "/admin/roles", label: "Roles" },
    { href: "/admin/suspensions", label: "Suspensions" },
  ]},
];

export default function AdminShell({
  title,
  children,
}: {
  title?: string;
  children: React.ReactNode;
}) {
  const [open, setOpen] = useState(false);
  const pathname = usePathname();

  // Close drawer on route change
  useEffect(() => { setOpen(false); }, [pathname]);
  // Close drawer with Escape
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);
  // Lock body scroll while drawer open
  useEffect(() => {
    if (open) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = "hidden";
      return () => { document.body.style.overflow = prev; };
    }
  }, [open]);

  return (
    <>
      {/* Sticky top bar */}
      <header className="sticky top-0 z-40 bg-[#0a0a0a] border-b border-[#222]">
        <div className="max-w-7xl mx-auto px-4 h-12 flex items-center justify-between gap-3">
          <div className="flex items-center gap-3 min-w-0">
            <Link
              href="/admin"
              className="text-[10px] font-mono uppercase tracking-widest text-[#1D4ED8] hover:text-white transition-colors flex-shrink-0"
            >
              AV BEAT · ADMIN
            </Link>
            {title && (
              <>
                <span className="text-[#333]">/</span>
                <span className="font-body font-semibold text-white truncate">{title}</span>
              </>
            )}
          </div>
          <button
            type="button"
            onClick={() => setOpen((o) => !o)}
            aria-label={open ? "Close menu" : "Open menu"}
            aria-expanded={open}
            aria-controls="admin-drawer"
            className="-mr-2 p-2 text-white hover:text-[#1D4ED8] transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-[#1D4ED8] rounded"
          >
            {open ? (
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
                <path strokeLinecap="round" d="M6 6l12 12M6 18L18 6" />
              </svg>
            ) : (
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
                <path strokeLinecap="round" d="M4 7h16M4 12h16M4 17h16" />
              </svg>
            )}
          </button>
        </div>
      </header>

      {/* Drawer overlay */}
      {open && (
        <div
          aria-hidden="true"
          onClick={() => setOpen(false)}
          className="fixed inset-0 z-30 bg-black/60 backdrop-blur-sm"
        />
      )}

      {/* Drawer */}
      <nav
        id="admin-drawer"
        aria-label="Admin sections"
        aria-hidden={!open}
        className={`fixed top-12 right-0 bottom-0 z-40 w-[280px] max-w-[85vw] bg-[#0a0a0a] border-l border-[#222] overflow-y-auto transform transition-transform duration-200 ${
          open ? "translate-x-0" : "translate-x-full pointer-events-none"
        }`}
      >
        <div className="py-3">
          {SECTIONS.map((sec) => (
            <div key={sec.group} className="mb-2">
              <div className="px-4 py-1.5 text-[10px] font-mono font-bold text-[#1D4ED8] uppercase tracking-widest">
                {sec.group}
              </div>
              {sec.items.map((item) => {
                const active = pathname === item.href;
                return (
                  <Link
                    key={item.href}
                    href={item.href}
                    className={`block px-4 py-2.5 text-sm font-body transition-colors ${
                      active
                        ? "bg-[#1D4ED8]/10 text-[#1D4ED8] font-semibold"
                        : "text-[#cbd5e1] hover:bg-[#FFFFFF] hover:text-white"
                    }`}
                  >
                    {item.label}
                  </Link>
                );
              })}
            </div>
          ))}
          <div className="border-t border-[#222] mt-2 pt-2">
            <Link
              href="/"
              className="block px-4 py-2.5 text-sm font-body text-[#888] hover:text-[#1D4ED8] transition-colors"
            >
              ← Back to site
            </Link>
          </div>
        </div>
      </nav>

      {children}
    </>
  );
}
