'use client';

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useOrgAdmin } from '../_lib/org-admin-context';
import { PortalNav } from '../_components/portal-nav';
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 OrgLayout({ children }: { children: React.ReactNode }) {
  const { orgAdmin, loading, logout } = useOrgAdmin();
  const router = useRouter();

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

  if (loading) {
    return (
      <div className="flex h-screen -m-6">
        <div className="w-56 shrink-0 border-r bg-sidebar animate-pulse" />
        <div className="flex-1" />
      </div>
    );
  }
  if (!orgAdmin) return null;

  return (
    <div className="flex h-screen overflow-hidden -m-6">
      <PortalNav
        portalName="Org"
        navItems={NAV}
        accentClass="text-violet-600"
        user={{ email: orgAdmin.email, name: orgAdmin.name ?? undefined, role: orgAdmin.role }}
        onLogout={() => { void logout(); router.replace('/org/login'); }}
      />
      <main className="flex-1 overflow-auto bg-muted/30 p-6">{children}</main>
    </div>
  );
}
