import { notFound } from 'next/navigation';
import { TeamDetailPageQuery } from '@/lib/page-queries/TeamDetailPageQuery';
import { TeamDetailPageClient } from '@/client-wrapper/TeamDetailPageClient';
import { Metadata } from 'next';
import { MetadataHelper } from '@/lib/seo/MetadataHelper';
import { JsonLd } from '@/ui/JsonLd';

export async function generateMetadata({ params }: { params: Promise<{ id: string }> }): Promise<Metadata> {
  const { id } = await params;
  const result = await TeamDetailPageQuery.execute(id);

  if (result.isErr()) {
    return MetadataHelper.generate({
      title: 'Team Not Found',
      description: 'The requested team could not be found on GridPilot.',
      path: `/teams/${id}`,
    });
  }

  const viewData = result.unwrap();
  const team = viewData.team;
  
  return MetadataHelper.generate({
    title: team.name,
    description: team.description || `Explore ${team.name} on GridPilot. View team roster, race history, and performance statistics in professional iRacing leagues.`,
    path: `/teams/${id}`,
    // image: team.logoUrl, // If logoUrl exists in viewData
  });
}

export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const result = await TeamDetailPageQuery.execute(id);

  if (result.isErr()) {
    const error = result.getError();
    if (error === 'notFound') {
      notFound();
    }
    // For other errors, treat as not found for now
    notFound();
  }

  const viewData = result.unwrap();
  const team = viewData.team;

  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'SportsTeam',
    name: team.name,
    description: team.description,
    url: `https://gridpilot.com/teams/${team.id}`,
    member: viewData.memberships.map(m => ({
      '@type': 'OrganizationRole',
      member: {
        '@type': 'Person',
        name: m.driverName,
        url: `https://gridpilot.com/drivers/${m.driverId}`,
      },
      roleName: m.role,
    })),
  };

  return (
    <>
      <JsonLd data={jsonLd} />
      <TeamDetailPageClient viewData={viewData} />
    </>
  );
}
