<script>
import { defineComponent, computed, toRefs } from "vue";
import { isExternal, isMailto, isTel, ensureExt } from "../helpers/utils";
import { RecoIcon } from "@vuepress-reco/core/lib/components";
import { useInstance } from "../helpers/composable";

export default defineComponent({
  components: { RecoIcon },

  props: {
    item: {
      required: true,
    },
  },

  render(h) {
    const { link, exact, isExternal, isMailto, isTel } = this;

    let WBCNavItemObj;

    if (!link) {
      WBCNavItemObj = {
        comp: "span",
        dive: true,
        options: {
          class: ["nav-link"],
          html: {
            dive: true,
            options: {
              class: "mx-1",
            },
            html: (that) => this.item.text,
          },
        },
      };
    } else {
      WBCNavItemObj = {
        comp: isExternal(link, this.$store) ? "a" : "router-link",
        // dive: true,
        options: {
          // key: (that) => that.item.text + -"-" + that.lg.lang,
          props: {
            to: isExternal(link, this.$store) ? null : link,
            href: isExternal(link, this.$store) ? link : null,
            exact: exact,
            target:
              isMailto(link, this.$store) || isTel(link, this.$store) ? null : "_blank",
            rel:
              isMailto(link, this.$store) || isTel(link, this.$store)
                ? null
                : "noopener noreferrer",
          },
          class: ["nav-link", { external: isExternal(link, this.$store) }],
          html: {
            dive: true,
            options: {
              class: "mx-1",
            },
            html: (that) => this.item.text,
          },
        },
      };
    }

    return h("WBC", {
      key: `${this.item.text}-${this.$store.state.lg}`,
      props: { item: WBCNavItemObj },
    });
  },
  setup(props, ctx) {
    const instance = useInstance();

    const { item } = toRefs(props);

    const link = computed(() => ensureExt(item.value.link, instance.$store));

    const exact = computed(() => {
      if (instance.$site.locales) {
        return Object.keys(instance.$site.locales).some(
          (rootLink) => rootLink === link.value
        );
      }
      return link.value === "/";
    });

    return { link, exact, isExternal, isMailto, isTel };
  },
});
</script>
