<template>
  <div
    class="tp-texts"
    :class="{
      'tp-inline': props.data.attributes === undefined || props.data.attributes.align === undefined,
      'tp-texts-header1': props.data.attributes && props.data.attributes.header === 1,
      'tp-texts-header2': props.data.attributes && props.data.attributes.header === 2,
      'tp-texts-header3': props.data.attributes && props.data.attributes.header === 3,
      'tp-texts-header4': props.data.attributes && props.data.attributes.header === 4,
      'tp-texts-header5': props.data.attributes && props.data.attributes.header === 5,
      'tp-texts-header6': props.data.attributes && props.data.attributes.header === 6,
    }"
    :title="getTitle()"
    :style="{ textAlign: props.data.attributes?.align }"
  >
    <component
      :is="getComp(text)"
      v-for="(text, index) in props.data.children"
      :data="text"
      :key="index"
    />
  </div>
</template>
<script lang="ts" setup>
import type { Component } from "vue";

import TpImage from "./tp-image.vue";
import TpMention, { type TpMention as TpMentionType } from "./tp-mention.vue";
import TpText, { type TpText as TpTextType } from "./tp-text.vue";

type TpTexts = { children: Array<TpTextType | TpMentionType> } & TpTextType;
type TpTextsProps = { data: TpTexts };

const props = defineProps<TpTextsProps>();

function getComp(text: TpTextType | TpMentionType): Component {
  if (typeof text.insert === "string") return TpText;
  if ("image" in text.insert) return TpImage;
  return TpMention;
}

function getTitle(): string {
  if (!props.data.attributes) return "";
  if (props.data.attributes.link) return props.data.attributes.link;
  if (props.data.attributes.header) return `H${props.data.attributes.header}`;
  return "";
}
</script>
<style lang="scss" scoped>
.tp-texts {
  line-break: anywhere;
  white-space: pre-wrap;
  word-break: break-all;

  &.tp-inline {
    display: inline;
  }
}

@for $i from 1 through 6 {
  .tp-texts-header#{$i} {
    font-family: var(--font-title);
    font-size: calc(26px - $i * 2px);
  }
}
</style>
