import { auth } from '../../auth';
import Navigation from '../Navigation';
import ProfileTabs from './ProfileTabs';
import MinProfilTab from './tabs/MinProfilTab';

export const metadata = { title: 'Min profil' };

type Props = {
  searchParams: Promise<{ tab?: string }>;
};

export default async function ProfilPage({ searchParams }: Props) {
  const { tab = 'profil' } = await searchParams;
  const session = await auth();
  const isAdmin = (session?.user as any)?.role === 'admin';

  // DatabsTab och AnvandareTab laddas dynamiskt för att hålla page.tsx tunn
  let TabContent: React.ComponentType;
  if (tab === 'databas') {
    const { default: DatabsTab } = await import('./tabs/DatabsTab');
    TabContent = DatabsTab;
  } else if (tab === 'anvandare' && isAdmin) {
    const { default: AnvandareTab } = await import('./tabs/AnvandareTab');
    TabContent = AnvandareTab;
  } else if (tab === 'forslag' && isAdmin) {
    const { default: ForslagTab } = await import('./tabs/ForslagTab');
    TabContent = ForslagTab;
  } else if (tab === 'ai' && isAdmin) {
    const { default: AiTab } = await import('./tabs/AiTab');
    TabContent = AiTab;
  } else {
    TabContent = MinProfilTab;
  }

  const adminTabs = ['anvandare', 'forslag', 'ai'];
  const userTabs = ['databas'];
  const activeTab =
    (isAdmin && (adminTabs.includes(tab) || userTabs.includes(tab))) ||
    userTabs.includes(tab)
      ? tab
      : 'profil';

  return (
    <>
      <Navigation />
      <main style={{ padding: '1rem', maxWidth: '1200px', margin: '0 auto' }}>
        <h1 style={{ marginBottom: '1.5rem' }}>Min profil</h1>
        <ProfileTabs activeTab={activeTab} isAdmin={isAdmin} />
        <TabContent />
      </main>
    </>
  );
}

