'use client';

import { usePathname, useRouter } from 'next/navigation';
import { useEffect } from 'react';
import { useAuth } from './auth-context';
import { PortalNav } from '../_components/portal-nav';
import {
  Search, Users, MessageSquare, FileText, Settings, Bot,
  LayoutDashboard, Building2, Server, Inbox,
} from 'lucide-react';

// Paths that render their own full-screen layout (no sidebar)
const FULLSCREEN_PATHS = ['/', '/login', '/member-login', '/onboard', '/admin/login', '/org/login', '/org', '/admin', '/my'];

const CHAPTER_NAV = [
  { href: '/search', label: 'Search', icon: <Search /> },
  { href: '/groups', label: 'Groups & Routes', icon: <Users /> },
  { href: '/messages/pending', label: 'Pending', icon: <Inbox /> },
  { href: '/drafts', label: 'AI Drafts', icon: <FileText /> },
  { href: '/settings/rules', label: 'Rules', icon: <Settings /> },
  { href: '/settings/bot', label: 'Bot', icon: <Bot /> },
];

export function Sidebar() {
  const { admin, loading, logout } = useAuth();
  const pathname = usePathname();
  const router = useRouter();

  const isFullscreen = FULLSCREEN_PATHS.some((p) =>
    p === '/' ? pathname === '/' : pathname === p || pathname.startsWith(p + '/'),
  );

  useEffect(() => {
    if (loading || isFullscreen) return;
    if (!admin) router.replace(`/login?next=${encodeURIComponent(pathname)}`);
  }, [loading, admin, pathname, router, isFullscreen]);

  if (isFullscreen) return null;

  if (loading) {
    return (
      <div className="w-56 shrink-0 border-r bg-sidebar animate-pulse" />
    );
  }

  if (!admin) return null;

  return (
    <PortalNav
      portalName="Chapter"
      navItems={CHAPTER_NAV}
      accentClass="text-blue-600"
      user={{ email: admin.email, name: admin.name ?? undefined, role: admin.role }}
      onLogout={() => { void logout(); router.replace('/login'); }}
    />
  );
}
