<template>
  <div id="content-meter-gtm-event" :class="classes.join(', ')"/>
</template>

<script>

const { log } = console;

export default {
  inject: ['EventBus'],

  props: {
    views: {
      type: Number,
      default: 0,
    },
    viewLimit: {
      type: Number,
      default: 3,
    },
    displayGate: {
      type: Boolean,
      default: false,
    },
    displayOverlay: {
      type: Boolean,
      required: false,
    },
  },
  data: () => ({
    classes: [],
  }),
  computed: {
    remaining() {
      const { viewLimit, views } = this;
      return viewLimit - views;
    },
    overlayDisplayed() {
      const { displayGate, displayOverlay } = this;
      return displayGate && displayOverlay;
    },
  },
  created() {
    const { views, remaining, overlayDisplayed } = this;
    this.observer = new IntersectionObserver((event) => {
      if (event[0].isIntersecting) {
        const { dataLayer } = window;
        if (dataLayer) {
          const payload = {
            event: 'identity-x-content-meter-view',
            'identity-x': {
              label: 'content-meter',
              views,
              remaining,
              overlayDisplayed,
            },
          };
          this.emitP1Event({ action: 'View' });
          dataLayer.push(payload);
          const { searchParams } = new URL(window.location.href);
          if (searchParams.has('idxDebugger')) {
            log('identity-x event: identity-x-content-meter-view', payload);
          }
        }
      }
    });
  },
  mounted() {
    this.observer.observe(this.$el);
    this.EventBus.$on('identity-x-login-link-sent', ({ actionSource, entity }) => {
      if (actionSource === 'content_meter_login') {
        // Identify the p1events session at email submit, using the app-user entity
        // the /login route just returned. The p1events identity is otherwise baked
        // anonymously at page render and only set after magic-link auth on a LATER
        // page load, so without this the Submit event (and the rest of this page)
        // tracks anonymously. entity = `identity-x.{appId}.app-user*{userId}`.
        if (window.p1events && entity) window.p1events('setIdentity', entity);
        this.classes.push('login-link-sent');
        this.emitP1Event({ action: 'Submit' });
      }
    });
  },
  methods: {
    emitP1Event({ action }) {
      if (!window.p1events) return;
      const { views, overlayDisplayed } = this;
      window.p1events('track', {
        category: 'Content Meter',
        action,
        ...(overlayDisplayed && { label: 'Gated' }),
        props: { n: views },
      });
    },
  },
};
</script>
