<template>
  <div v-if="!consent" class="card text-end bg-secondary text-white border border-1">
    <div class="card-body">
      <form class="mb-1">
        <div class="form-check">
          <input id="essential-cookies" checked class="form-check-input" disabled type="checkbox" value="">
          <label class="form-check-label" for="essential-cookies">
            Essential
          </label>
        </div>
        <div class="form-check">
          <input id="tracking" v-model="tracking" class="form-check-input" type="checkbox">
          <label class="form-check-label" for="tracking">
            Matomo
          </label>
        </div>
      </form>

      <a href="/privacy-policy" class="text-muted">Privacy Policy</a>

      <div class="d-flex justify-content-between mt-2">
        <button class="btn btn-outline-primary" type="button" @click="handleConsentForget">Decline</button>
        <button class="btn btn-info" type="button" @click="handleConsent">Accept</button>
      </div>
    </div>
  </div>
</template>

<script>
import {onMounted, ref} from "vue";
import {useCookies} from 'vue3-cookies'

export default {
  name: "CookieConsentBtn",
  setup() {
    const tracking = ref(true)
    const {cookies} = useCookies()
    const consent = ref(false)

    const handleConsent = () => {
      window._paq.push(['rememberCookieConsentGiven'])
      cookies.set('consent', 'given')

      if (tracking.value){
        window._paq.push(['rememberConsentGiven'])
      }
      consent.value = true
    }
    const handleConsentForget = () => {
      consent.value = true
    }

    onMounted(() => {
      window._paq.push(['requireCookieConsent']);
      window._paq.push(['trackPageView']);

      if (cookies.get('consent') === 'given')
        consent.value = true
    })

    return {handleConsent, handleConsentForget, tracking, consent}
  }
}
</script>

<style scoped>
.card {
  z-index: 10;
}
form {
  display: flex;
  gap: 1rem;
}
</style>
