---
import { AttributeTypes, type EndpointAttribute } from "src/shared/payload/payload-sdk";
import Metadata from "./Metadata.astro";
import { getI18n } from "src/i18n/i18n";
import ErrorMessage from "./ErrorMessage.astro";
import type { Attribute } from "src/utils/attributes";

interface Props {
  attributes: (EndpointAttribute | Attribute)[];
}

const { attributes } = Astro.props;
const { getLocalizedMatch, getLocalizedUrl, formatNumber } = await getI18n(
  Astro.locals.currentLocale
);
---

{/* ------------------------------------------- HTML ------------------------------------------- */}

<div>
  {
    attributes.map((attribute) => {
      if ("title" in attribute) {
        return <Metadata {...attribute} />;
      }
      const { icon, translations, value, type } = attribute;
      const translation = getLocalizedMatch(translations);

      switch (type) {
        case AttributeTypes.Number:
          return (
            <Metadata
              icon={icon}
              title={translation.name}
              lang={translation.language}
              values={[{ name: formatNumber(value) }]}
              withBorder={false}
            />
          );

        case AttributeTypes.Text:
          return (
            <Metadata
              icon={icon}
              title={translation.name}
              lang={translation.language}
              values={[{ name: value }]}
              withBorder={false}
            />
          );

        case AttributeTypes.Tags:
          return (
            <Metadata
              icon={icon}
              title={translation.name}
              lang={translation.language}
              values={value.map(({ translations, page }) => {
                const { name, language } = getLocalizedMatch(translations);
                return {
                  name,
                  lang: language,
                  ...(page ? { href: getLocalizedUrl(`/pages/${page.slug}`) } : {}),
                };
              })}
            />
          );

        default:
          return <ErrorMessage title={`Unknown attribute type: ${type}`} />;
      }
    })
  }
  <slot />
</div>

{/* ------------------------------------------- CSS -------------------------------------------- */}

<style>
  div {
    display: flex;
    flex-direction: column;
    gap: 2em;
  }
</style>