import type { Metadata } from 'next';
import { Event } from '@/lib/api';
import EventsClient from './EventsClient';

const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';

// Listing title lives here (not in the layout) so the root title template still
// applies to the sibling /events/[id] detail route. Picks up "%s – Spanglish".
export const metadata: Metadata = {
  title: 'Upcoming Language Exchange Events in Asunción',
};

// Fetch the public (published) event list on the server so event titles, dates,
// and locations appear in the initial HTML rather than only after JS runs.
async function getEvents(): Promise<Event[]> {
  try {
    const res = await fetch(`${apiUrl}/api/events`, { next: { revalidate: 60 } });
    if (!res.ok) return [];
    const data = await res.json();
    return data.events || [];
  } catch {
    return [];
  }
}

export default async function EventsPage() {
  const events = await getEvents();
  return <EventsClient initialEvents={events} />;
}
