'use client';

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useOrgAdmin } from '@/app/_lib/org-admin-context';
import { PortalShell } from '@/app/_components/portal-shell';
import { LayoutDashboard, Building2, Shield } from 'lucide-react';

const NAV = [
  { href: '/org', label: 'Dashboard', icon: <LayoutDashboard /> },
  { href: '/org/tenants', label: 'Chapters', icon: <Building2 /> },
  { href: '/org/rules', label: 'Org Rules', icon: <Shield /> },
];

export default function OrgAuthedLayout({ children }: { children: React.ReactNode }) {
  const { orgAdmin, loading, logout } = useOrgAdmin();
  const router = useRouter();

  useEffect(() => {
    if (!loading && !orgAdmin) router.replace('/org/login');
  }, [orgAdmin, loading, router]);

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