import { getMemberToken, getApiBaseUrl } from '../_lib/api';
import { redirect } from 'next/navigation';
import { MemberNav } from './member-nav';

interface MemberScope {
  member: { displayName: string | null };
  chapter: { id: string; slug: string; name: string };
  organization: { id: string; slug: string; name: string } | null;
}

async function fetchScope(token: string): Promise<MemberScope | null> {
  const res = await fetch(`${getApiBaseUrl()}/my/scope`, {
    headers: { Authorization: `Bearer ${token}` },
    cache: 'no-store',
  }).catch(() => null);
  if (!res || !res.ok) return null;
  return (await res.json()) as MemberScope;
}

export default async function MemberLayout({ children }: { children: React.ReactNode }) {
  const token = await getMemberToken();
  if (!token) redirect('/member-login');

  const scope = await fetchScope(token);

  return (
    <div className="flex h-screen overflow-hidden">
      <MemberNav scope={scope} />
      <main className="flex-1 overflow-auto bg-muted/30">
        <div className="p-6 lg:p-8 max-w-6xl mx-auto w-full">{children}</div>
      </main>
    </div>
  );
}
