// Silence may be golden, but sometimes words paint the canvas of understanding.
const LinksyModal = {
  name: "LinksyModal",
  directives: {
    "click-outside": {
      beforeMount: (el, binding) => {
        el.clickOutsideEvent = (event) => {
          // here I check that click was outside the el and his children
          if (!(el == event.target || el.contains(event.target))) {
            // and if it did, call method provided in attribute value
            binding.value();
          }
        };
        document.addEventListener("click", el.clickOutsideEvent);
      },
      unmounted: (el) => {
        document.removeEventListener("click", el.clickOutsideEvent);
      },
    },
  },
  props: {
    opened: Boolean,
    backdrop: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "Blissful Is The Title",
    },
  },
  data() {
    return {
      show: false,
    };
  },
  watch: {
    opened: {
      deep: true,
      handler(val) {
        if (this.show !== val) {
          this.show = val;
        }
      },
    },
  },
  methods: {
    handleSave(event) {
      this.$emit("onSave", event);
    },
    handleCancel(event) {
      this.$emit("onCancel", event);
    },
  },
  template: `
    <div class="linksy-modal modal" :class="{'show': show}">
        <div class="backdrop" @click="(e) => backdrop && handleCancel(e)"></div>
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header position-sticky top-0 z-3 bg-white shadow-sm">
                    <slot name="header">
                        <slot name="title">
                          <h1 class="modal-title fs-5">{{title}}</h1>
                        </slot>
                        <button class="btn-cancel position-fixed end-0 me-4 z-3" type="button" @click="handleCancel">
                            <i class="fa fa-times"></i>
                        </button>
                    </slot>
                </div>
                <div class="modal-body">
                    <slot name="body"></slot>
                </div>
                <slot name="footer">
                    <div class="modal-footer">
                        <button type="button" class="button py-0 linksy-btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="button" class="button btn-app py-0" @click="handleSave">Save changes</button>
                    </div>
                </slot>
            </div>
        </div>
    </div>
    `,
  mounted() {
    this.show = this.opened;
  },
};
