'use client';

import { useEffect } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { useAuth } from '@/app/_lib/auth-context';
import { PortalShell } from '@/app/_components/portal-shell';
import { Search, Users, Inbox, FileText, SlidersHorizontal, Bot } from 'lucide-react';

const 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: <SlidersHorizontal /> },
  { href: '/settings/bot', label: 'Bot', icon: <Bot /> },
];

export default function ChapterLayout({ children }: { children: React.ReactNode }) {
  const { admin, loading, logout } = useAuth();
  const router = useRouter();
  const pathname = usePathname();

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

  return (
    <PortalShell
      portalName="Chapter"
      theme="blue"
      navItems={NAV}
      loading={loading}
      authed={!!admin}
      user={admin ? { email: admin.email, name: admin.name, role: admin.role, subtitle: admin.tenantName } : undefined}
      onLogout={() => { void logout(); router.replace('/login'); }}
    >
      {children}
    </PortalShell>
  );
}
