"use client";

import type {
  EventDetailRecord,
  EventSponsorImageRecord,
} from "@/features/events/eventRecord";
import { useTranslation } from "react-i18next";
import "@fancyapps/ui/dist/fancybox/fancybox.css";

export const asset = (path: string) => `/assets/${path}`;

/**
 * `EventDetails`'s shapes and its two small presentational pieces.
 *
 * `localizedError` is here too: it digs a readable message out of whichever
 * error envelope the registration endpoints return, which is logic rather
 * than layout.
 */
/** Re-exported so existing importers keep working off one definition. */
export type { ChoiceDisplay } from "@/lib/choices";
import RemoteImage from "@/components/ui/RemoteImage";

/**
 * The event detail payload.
 *
 * `EventDetailRecord` — the transcription of `WebsiteEventResource` built with
 * `detail: true` — rather than the local shape, which declared `id` as a
 * `string` (it is an integer), the titles and dates as non-null (every one of
 * those columns is nullable), and only a subset of the keys the page reads.
 */
export type EventDetailsData = EventDetailRecord;

export function localizedError(error: unknown, language: string, fallback: string) {
  const response = (
    error as {
      response?: {
        data?: {
          msg?: string;
          message_en?: string;
          message_ar?: string;
          errors?: Record<string, string | Record<string, string> | string[]>;
        };
      };
    }
  )?.response?.data;

  const localizedMessage =
    response?.msg || (language === "ar" ? response?.message_ar : response?.message_en);
  if (localizedMessage) return localizedMessage;

  const firstError = response?.errors && Object.values(response.errors)[0];
  if (typeof firstError === "string") return firstError;
  if (Array.isArray(firstError)) return firstError[0] || fallback;
  if (firstError && typeof firstError === "object") {
    return firstError[language] || fallback;
  }
  return fallback;
}

export function EventSponsors({
  sponsors,
}: {
  sponsors: EventSponsorImageRecord[];
}) {
  const { t } = useTranslation();
  if (!sponsors.length) return null;

  return (
    <section className="my-5 w-full rounded-3xl bg-[#F7F7FB] px-3 py-5">
      <h2 className="mb-4 text-center text-base font-bold text-primary-5">
        {t("COMMON.EVENT_SPONSOR")}
      </h2>
      <div className="grid grid-cols-2 items-center gap-6">
        {[...sponsors]
          .sort((a, b) => a.position - b.position)
          .map((sponsor) => (
            /*
             * One of the two `<img>` elements left in `src/`, and the reason is
             * the same for both (see `OpportunitySponsors`): a sponsor logo is
             * a user upload of unknown aspect ratio, and this element is sized
             * by *its own content* — `max-h-20 max-w-full object-contain`, so a
             * logo shorter than 80px renders at its natural height and the row
             * is as tall as the tallest logo in it.
             *
             * Neither `next/image` mode fits. `width`/`height` would have to be
             * invented, and a wrong pair is worse than none: it sets the
             * reserved aspect ratio, so every logo would be letterboxed to the
             * guess. `fill` needs a parent with a height of its own, which
             * means pinning each cell to 80px — that *is* the layout change
             * this comment exists to refuse, because it stretches a row of
             * short logos.
             *
             * The rule's other two costs do not apply in this project at all:
             * `next.config.ts` sets `images.unoptimized: true`, so `next/image`
             * emits the same `src` with no resizing, no format negotiation and
             * no `srcset`. Nothing about the bytes on the wire or the LCP
             * candidate changes by converting — only the layout behaviour
             * would, and that is the part that cannot be stated honestly here.
             *
             * The cost of leaving it is the reflow the rule warns about: this
             * grid's row heights settle as the logos arrive. Accepted here
             * rather than traded for a wrong aspect ratio on every logo.
             *
             * `next/image`'s own documentation agrees on the alternatives:
             * "If the height and width are unknown, we recommend using the
             * `fill` property", and `fill` "causes the image to expand to the
             * size of the parent element", whose parent "**must** assign
             * position: relative | fixed | absolute" while the image itself is
             * `position: absolute` — i.e. out of flow, so the cell can no
             * longer be sized by the logo.
             */
            <img
              key={sponsor.id}
              src={sponsor.image || asset("profile/org_profile.svg")}
              alt={t("COMMON.EVENT_SPONSOR")}
              className="mx-auto max-h-20 max-w-full rounded-full object-contain"
            />
          ))}
      </div>
    </section>
  );
}

export function DetailRow({
  icon,
  label,
  children,
}: {
  icon: string;
  label?: string;
  children: React.ReactNode;
}) {
  return (
    <div className="flex items-center gap-2 pb-3 text-sm font-bold md:text-base">
      <RemoteImage
  src={icon}
  alt={""}
  width={20}
  height={20}
  className="h-4 w-4 shrink-0 object-contain"
/>
      {label && <span className="text-primary-5">{label} :</span>}
      <span className="text-secondary-102">{children}</span>
    </div>
  );
}

/** The organiser's social links, in the order the card shows them. */
export const socialLinks = [
  ["facebook_link", "profile/facebook.svg", "Facebook"],
  ["twitter_link", "profile/twitter.svg", "Twitter"],
  ["whatsapp_link", "profile/whatsapp.svg", "WhatsApp"],
  ["instagram_link", "profile/instagram.svg", "Instagram"],
  ["linkedin_link", "profile/linkdin.svg", "LinkedIn"],
] as const;
