"use client";

import { unmaskFragment } from "@/gql";
import {
  EventFragment,
  EventOrganizerFragmentDefinition,
} from "@/lib/event";
import styles from "./organizerList.module.scss";
import Link from "next/link";
import { Fragment } from "react";

export const OrganizerList = ({ event }: { event: EventFragment }) => {
  const organizers = unmaskFragment(
    EventOrganizerFragmentDefinition,
    event.organizers
  );
  const total = organizers.length;
  return (
    <div className={styles.organizerList}>
      {organizers.map((organizer, index) => {
        const url = organizer.association?.url ?? organizer.externalUrl ?? null;
        const hasValidUrl =
          typeof url === "string" &&
          (url.startsWith("http") || url.startsWith("/"));
        return (
          <Fragment key={organizer.name}>
            {total > 1 && index === total - 1 && <> og </>}
            {hasValidUrl && (
              <span>
                <Link href={url}>{organizer.name}</Link>
              </span>
            )}
            {!hasValidUrl && <span>{organizer.name}</span>}
            {total > 1 && index < total - 2 && <>, </>}
          </Fragment>
        );
      })}
    </div>
  );
};
