<template>
  <teleport to="body">
    <transition
      enter-active-class="l-transition l-ease-out l-duration-50"
      enter-from-class="l-opacity-0"
      enter-to-class="l-opacity-100"
      leave-active-class="l-transition l-ease-in l-duration-50"
      leave-from-class="l-opacity-100"
      leave-to-class="l-opacity-0"
    >
      <div
        v-if="openModal"
        class="
          l-w-full
          l-h-screen
          l-absolute
          l-top-0
          l-flex
          l-justify-center
          l-items-center
          l-p-4
        "
      >
        <div
          class="
            l-bg-white l-rounded l-w-full
            sm:l-w-1/2
            l-h-4/5 l-z-40 l-justify-center l-items-center l-flex l-relative
          "
        >
          <CloseIcon
            class="
              l-text-black
              l-fill-current
              l-cursor-pointer
              l-absolute
              l-right-2
              l-top-2
            "
            @click="hide"
          />
          <p v-if="errorMessage">{{ errorMessage }}</p>

          <div
            v-if="loading"
            class="l-w-full l-h-full l-flex l-items-center l-justify-center"
          >
            <svg
              class="l-animate-spin -l-ml-1 l-mr-3 l-h-10 l-w-10 l-text-red-800"
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
            >
              <circle
                class="l-opacity-25"
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                stroke-width="4"
              ></circle>
              <path
                class="l-opacity-75"
                fill="currentColor"
                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
              ></path>
            </svg>
          </div>

          <iframe
            v-show="!loading && reviewData"
            :src="reviewData.url"
            title="lauded page review"
            class="l-h-full l-w-full l-rounded"
            :onload="onLoad"
          ></iframe>
        </div>

        <div
          class="
            l-absolute
            l-top-0
            l-left-0
            l-w-full
            l-h-full
            l-bg-gray-900
            l-bg-opacity-50
            l-z-20
          "
        ></div>
      </div>
    </transition>
  </teleport>
</template>


<script setup="{ emit }">
import { computed, onMounted, onBeforeUnmount, ref } from "vue";
import useReviews from "@/api/reviews";
import CloseIcon from "../../assets/close.svg";

const props = defineProps({
  apiUrl: {
    type: String,
  },
});

console.log("Initialised");

const emit = defineEmits(["close"]);

const { reviewData, errorMessage, getReviewRequest } = useReviews();

const loading = ref(false);
const openModal = ref(false);
const internalParams = ref(null);
const environment = ref("test");

const baseApiUrl = computed(() =>
  environment.value === "live"
    ? import.meta.env.VITE_PROD_URL
    : import.meta.env.VITE_DEV_URL
);

const getAPIKeyEnv = (key) => {
  const keyArray = key.split("_");
  const env = keyArray[0];
  const api_key = keyArray.length === 2 ? keyArray[1] : keyArray[0];

  return { env, api_key };
};

const fireEvent = async (event, params) => {
  loading.value = true;
  errorMessage.value = null;

  if (params) {
    internalParams.value = params;
  }

  if (!internalParams.value && !params) {
    console.error(
      "Use mount() function or set the second argument of fireEvent() to set the params before firing any events"
    );
  }

  let formattedParams = internalParams.value;

  let { env, api_key } = getAPIKeyEnv(formattedParams.api_key);

  formattedParams.api_key = api_key;
  environment.value = env;

  try {
    await getReviewRequest(baseApiUrl.value, {
      customer: formattedParams.customer,
      api_key: formattedParams.api_key,
      event,
    });

    if (reviewData.value?.show_widget) {
      show();
    }
  } catch (error) {
    console.log("e", error);
  }
};

const show = () => {
  openModal.value = true;
};

const onLoad = () => {
  loading.value = false;
};

const setParameters = (params) => {
  internalParams.value = params;
};

const hide = () => {
  openModal.value = false;
  emit("close");
};

Element.prototype.fireEvent = (event, params) => fireEvent(event, params);
Element.prototype.mount = (params) => setParameters(params);
Element.prototype.hide = () => hide();

defineExpose({
  show,
  setParameters,
  hide,
  fireEvent,
});

onBeforeUnmount(() => {
  window.removeEventListener("message", hide());
});

onMounted(async () => {
  window.addEventListener(
    "message",
    (event) => {
      if (event.data === "POPUP_CLOSE") {
        hide();
      }
    },
    false
  );
});
</script>
