<template>
  <li :id="id" :class="{ active: isSelected }">
    <a
      v-if="url"
      @click="onClick"
      :href="url"
      :target="external ? '_blank' : false"
      >{{ title }}</a
    >
    <a v-else @click="onClick">{{ title }}</a>
  </li>
</template>

<script>
  import { str2bool } from "../../util";

  export default {
    name: "bc-menu-link",
    data() {
      return {
        isActive: false,
      };
    },
    props: {
      id: {
        type: String,
        default: null,
      },
      active: {
        type: [Boolean, String],
        default: false,
      },
      title: {
        type: String,
        default: null,
      },
      url: {
        type: String,
        default: null,
      },
      external: {
        type: Boolean,
        default: false,
      },
      selected: {
        type: Object,
        default() {
          return {};
        },
      },
    },
    watch: {
      active: {
        immediate: true,
        handler(newValue) {
          if (newValue) {
            this.isActive = str2bool(newValue);
          }
        },
      },
    },
    computed: {
      isSelected() {
        if (this.id && this.selected && this.selected.id) {
          return this.id === this.selected.id;
        }
        return false;
      },
    },
    methods: {
      onClick() {
        console.log("[MenuLink] click menu item", this.id);
        this.isActive = true;
        if (this.url) {
          console.log("[MenuLink] follow url", this.url);
          this.$parent.$emit("click", {
            url: this.url,
            id: this.id,
            breadcrumb: [this.title],
          });
        } else {
          console.log("[MenuLink] simple click");
          this.$parent.$emit("click", {
            id: this.id,
            breadcrumb: [this.title],
          });
        }
      },
    },
  };
</script>

<style lang="scss" scoped></style>
