---
import BaseLayout from '../../layouts/BaseLayout.astro';
import { getEvents, resolveDirectusAssetUrl } from '../../lib/directus';
import { getUpcomingEvents } from '../../lib/events';
import { formatDate, formatDateTime } from '../../lib/format';
import { normalizeSlug } from '../../lib/slug';

type EventItem = Awaited<ReturnType<typeof getEvents>>[number];

function resolveEventImageSource(realimage: EventItem['realimage']): string | null {
  if (!realimage) return null;

  const candidate = typeof realimage === 'string' ? realimage : realimage.id;
  if (!candidate) return null;

  if (typeof realimage !== 'string' && realimage.id) {
    return resolveDirectusAssetUrl({
      id: realimage.id,
      filename_download: realimage.filename_download,
    });
  }

  if (candidate.startsWith('/assets/')) {
    return resolveDirectusAssetUrl(candidate.slice('/assets/'.length).split('/')[0]);
  }

  if (candidate.startsWith('http://') || candidate.startsWith('https://')) {
    const candidateUrl = new URL(candidate);
    return candidateUrl.pathname.startsWith('/assets/')
      ? resolveDirectusAssetUrl(candidateUrl.pathname.slice('/assets/'.length).split('/')[0])
      : candidate;
  }

  if (candidate.startsWith('/')) {
    return candidate;
  }

  return resolveDirectusAssetUrl(candidate);
}

export async function getStaticPaths() {
  const events = getUpcomingEvents(await getEvents());
  const paths = new Map<string, { params: { slug: string }; props: { item: EventItem; dates: EventItem[] } }>();

  for (const item of events) {
    const slug = normalizeSlug(item.slug);
    if (!slug) continue;

    const existing = paths.get(slug);
    if (existing) {
      existing.props.dates.push(item);
      continue;
    }

    paths.set(slug, { params: { slug }, props: { item, dates: [item] } });
  }

  return Array.from(paths.values());
}

const { item, dates } = Astro.props as { item: EventItem; dates: EventItem[] };
const imageSrc = resolveEventImageSource(item.realimage);
const imageAlt = item.title;
const hasHtmlDescription = /<[^>]+>/.test(item.description);
---

<BaseLayout title={item.title} description={item.description}>
  <article class="container prose">
    <p class="meta">{dates.length === 1 ? formatDateTime(item.start_datetime) : `${dates.length} upcoming dates`}</p>
    <h1 class="section-title">{item.title}</h1>
    {imageSrc && <p><img src={imageSrc} alt={imageAlt} loading="lazy" /></p>}
    {item.description && hasHtmlDescription && <div class="text-multiline" set:html={item.description} />}
    {item.description && !hasHtmlDescription && <p class="text-multiline">{item.description}</p>}
    {dates.length > 0 && (
      <>
        <h2>Upcoming dates</h2>
        <ul>
          {dates.map((date) => (
            <li>{formatDate(date.start_datetime)}</li>
          ))}
        </ul>
      </>
    )}
    {item.location_text && <p><strong>Location:</strong> {item.location_text}</p>}
    {item.registration_link && <p><a class="button primary" href={item.registration_link}>Register</a></p>}
  </article>
</BaseLayout>
