---
import SectionHeading from './SectionHeading.astro';
import type { EventItem } from '../lib/fallback-data';
import { formatDate, formatTime, formatWeekday } from '../lib/format';
import { normalizeSlug } from '../lib/slug';

type Props = {
  events: EventItem[];
  title?: string;
  description?: string;
};

const { events, title = 'Upcoming events', } = Astro.props as Props;
---

<section>
  <SectionHeading eyebrow="Events" title={title}  />
  <div class="stack">
    {events.length > 0 ? (
      events.map((event) => {
        const normalizedSlug = normalizeSlug(event.slug);
        const detailHref = normalizedSlug ? `/events/${normalizedSlug}/` : undefined;
        const summary = event.summary?.trim() || event.description;
        const time = formatTime(event.start_datetime);
        const logoSrc = typeof event.logo === 'string' ? event.logo : event.logo?.id;

        return (
          <article class="card event-card">
            {detailHref && <a class="stretched-link" href={detailHref} aria-label={`View ${event.title}`} />}
            <div class="event-layout">
              <div class="event-date-block">
                <p class="event-weekday">{formatWeekday(event.start_datetime)}</p>
                <p class="event-date">{formatDate(event.start_datetime)}</p>
                {time && <p class="event-time">{time}</p>}
                {logoSrc && <img class="event-logo" src={logoSrc} alt={`${event.title} logo`} loading="lazy" />}
              </div>
              <div>
                <h3>{event.title}</h3>
                <p>{summary}</p>
                {event.location_text && <p>{event.location_text}</p>}
                {event.registration_link && (
                  <p class="event-card-actions"><a class="button secondary" href={event.registration_link}>Register</a></p>
                )}
              </div>
            </div>
          </article>
        );
      })
    ) : (
      <article class="card">
        <h3>No events published</h3>
        <p>Directus events will render here when content is available.</p>
      </article>
    )}
  </div>
</section>
