import Vue from 'vue';

/**
 * EventHub to listen or broadcast to all components
 *
 * @see https://shopify.dev/tutorials/develop-theme-sections-integration-with-theme-editor
 *
 * Usage: eventHub.$on('shopify:section:select:{my-section-name}', (event) => handleSelect());
 *
 */
const eventHub = new Vue({
  created() {
    const themeEventHandler = (event) => {
      // emit a generic version
      this.$emit(`${event.type}`, event);
      // emit a specific version for the section
      this.$emit(`${event.type}:${event.detail.sectionId}`, event);
    };

    // these are custom events emitted by the Shopify section editor
    // we are hooking them up to our Vue event dispatcher
    document.addEventListener('shopify:section:load', themeEventHandler);
    document.addEventListener('shopify:section:unload', themeEventHandler);
    document.addEventListener('shopify:section:select', themeEventHandler);
    document.addEventListener('shopify:section:deselect', themeEventHandler);
    document.addEventListener('shopify:section:reorder', themeEventHandler);
    document.addEventListener('shopify:block:select', themeEventHandler);
    document.addEventListener('shopify:block:deselect', themeEventHandler);
  }
});

function createApp() {
  return new Vue({
    el: '#app',
  });
}

let instance = createApp();

eventHub.$on('shopify:section:select', ({ detail }) => {
  // recreate the Vue app because the section editor destroyed it
  if (detail.load) {
    instance.$destroy();
    instance = createApp();
  }
});

/**
 * You can also do this in Vue apps
 * Our section would be named "navigation" in this instance
 *
 * import eventHub from 'Functions/event-hub';
 * // this would go in mounted()
 * eventHub.$on('shopify:section:select:navigation', () => {
 *   // do something once the section is opened...
 * });
 * eventHub.$on('shopify:section:deselect:navigation', () => {
 *   // do something once the section is closed...
 * });
 */