<template>
  <div class="wcc-section wcc-section-consent-banner wcc-zero--padding wcc-zero--margin" v-if="!isLoaded">
    <div class="wcc-section-header wcc-law-select-header">
      <card-loader />
    </div>
    <div class="wcc-customise-section-content">
      <div class="wcc-section-content">
        <div class="wcc-row wcc-banner-selector-section">
        </div>
        <div class="wcc-nav-tab wcc-vertical-tab">
          <div class="wcc-nav-tabs-container">
            <ul class="wcc-vertical-tabs" style="padding: 15px">
              <li><card-loader /></li>
            </ul>
          </div>
          <div class="wcc-nav-tab-content-container">
            <div class="wcc-nav-tab-content">
              <card-loader />
              <card-loader />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div
    class="wcc-section wcc-section-consent-banner wcc-zero--padding wcc-zero--margin"
    v-else
  >
    <GCMNotice/>
    <div class="wcc-section-header wcc-law-select-header">
      <law-selector />
    </div>
    <div class="wcc-customise-section-content">
      <div class="wcc-section-content">
        <div class="wcc-row wcc-banner-selector-section">
          <div class="wcc-col-8 wcc-align-center">
            <div class="wcc-banner-preview-toggler wcc-center">
              <banner-selector />
            </div>
          </div>
          <div class="wcc-col-4 wcc-align-center wcc-justify-end">
            <div class="wcc-banner-preview-toggler wcc-center">
              <label for="wcc-banner-preview" class="wcc-toggle" :data-test-id="'wcc-banner-preview-toggle'">
                <input
                  type="checkbox"
                  id="wcc-banner-preview"
                  v-model="preview"
                  :disabled="noticeDisabled"
                />
                <span class="wcc-toggle-text">{{
                  $i18n.__("Banner Preview", "webtoffee-cookie-consent")
                }}</span>
                <base-popper
                  v-if="noticeDisabled"
                  :content="
                    $i18n.__(
                      'The CCPA banner has been disabled. You can enable it from ‘General’, if needed.',
                      'webtoffee-cookie-consent'
                    )
                  "
                >
                  <span
                    aria-hidden="true"
                    class="wcc-toggle-slider wcc-disabled"
                  >
                  </span>
                </base-popper>
                <span
                  v-else
                  class="wcc-toggle-slider"
                  aria-hidden="true"
                ></span>
              </label>
            </div>
            <base-button
              class="wcc-button wcc-button-blue"
              ref="wccButtonSaveBanner"
              @click.native="saveConfig"
              style="margin-left: 15px"
              :disabled="publishDisabled"
            >
              <template slot="loader">{{ $i18n.__("Update settings", "webtoffee-cookie-consent") }} </template>
              {{ $i18n.__("Update settings", "webtoffee-cookie-consent") }}
            </base-button>
          </div>
        </div>
        <div
          role="navigation"
          class="wcc-nav-tab wcc-vertical-tab wcc-nav-tab-banner-settings"
        >
          <div class="wcc-nav-tabs-container">
            <ul class="wcc-vertical-tabs">
              <li
                v-for="tab in tabs"
                v-bind:key="tab.id"
                v-bind:class="[
                  'wcc-nav-tab-item',
                  { active: currentTab === tab.id },
                ]"
                :data-test-id="'wcc-tab-' + tab.id"
              >
                <button
                  class="wcc-nav-tab-button"
                  v-on:click="currentTab = tab.id"
                >
                  <base-icon
                    class="wcc-nav-tab-button-icon"
                    :icon="tab.icon"
                    v-if="showIcon(tab)"
                  ></base-icon>
                  <span class="wcc-nav-tab-item-title">
                    {{ tab.title }}
                  </span>
                </button>
              </li>
            </ul>
          </div>
          <div class="wcc-nav-tab-content-container">
            <div class="wcc-nav-tab-content">
              <div class="wcc-nav-tab-section">
                <div class="wcc-nav-tab-section-content" v-if="banner.id">
                  <component v-bind:is="currentTabComponent"></component>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { debouncePromise, debounce } from "@/helpers/utils";
import banners from "@/modules/banners/helpers/utils";
import preview from "@/modules/banners/helpers/preview";
import { visibility } from "@/mixins/visibility";

import CardLoader from "@/components/elements/CardLoader.vue";
import Loader from "@/components/elements/Loader.vue";
import BaseIcon from "@/components/icons/BaseIcon.vue";

import Dropdown from "@/components/Dropdown.vue";
import BannerSelector from "@/modules/banners/components/BannerSelector.vue";
import LawSelector from "@/modules/banners/components/LawSelector.vue";
import GCMNotice from "@/components/GCMNotice.vue";

import TabGeneral from "@/modules/banners/tabs/TabGeneral.vue";
import TabLayout from "@/modules/banners/tabs/TabLayout.vue";
import TabContent from "@/modules/banners/tabs/TabContent.vue";
import { saveOptions } from "@/helpers/common";

export default {
  name: "Customize",
  mixins: [visibility],
  components: {
    Loader,
    BaseIcon,
    Dropdown,
    BannerSelector,
    TabGeneral,
    TabLayout,
    TabContent,
    LawSelector,
    CardLoader,
    GCMNotice,
  },
  data() {
    return {
      tabs: [
        { id: "general", icon: "general", title: "General" },
        { id: "layout", icon: "layout", title: "Layout" },
        { id: "content", icon: "note", title: "Content & Colors" },
      ],
      currentTab: "general",
      previewLoader: false,
      loading: true,
      currentLaw: "",
      initialIABStatus: null,
    };
  },
  methods: {
    async loadCookies() {
      try {
        await this.$store.dispatch("cookies/reInit");
      } catch (error) {
        this.showErrors(
          this.$i18n.__(
            "Failed to load cookies please try again later!",
            "webtoffee-cookie-consent"
          )
        );
      }
    },
    showIcon(tab) {
      if (tab.icon) {
        return true;
      }
      return false;
    },
    loadBanner: async function (currentLaw) {
      try {
        await banners.getCurrentActiveBanner(currentLaw);
        await banners.loadPresets();
      } catch (error) {
        console.log(error);
        this.showErrors(
          this.$i18n.__(
            "An unexpected error occurred please try reloading the page or logging in again.",
            "webtoffee-cookie-consent"
          )
        );
      }
    },
    saveConfig: async function () {
      this.$refs.wccButtonSaveBanner.startLoading();
      try {
        /* Check whether IAB status changed */
        let currentIABStatus = this.$store.state.banners.current.properties.settings.iab_enabled === "1";
        if(currentIABStatus !== this.initialIABStatus) {
          this.initialIABStatus = currentIABStatus;
          // Show renew consent warning
          this.updateConsentStatus(true);
          let data = {};
          data.status = true;
          this.setOption("renew_consent_notice", data);
        }
        await saveOptions();
        await banners.bulkUpdate();
        await this.$store.dispatch("cookies/bulkUpdate");
        this.$root.$emit("triggerNotification", {
          type: "success",
          message: this.$i18n.__(
            "Settings updated successfully!",
            "webtoffee-cookie-consent"
          ),
        });
      } catch (error) {
        console.log(error);
        this.showErrors(
          this.$i18n.__(
            "Problem occurred while saving your settings. Please try again later!",
            "webtoffee-cookie-consent"
          )
        );
      }
      this.$refs.wccButtonSaveBanner.stopLoading();
    },
    updateContentPreview: debounce(async function () {
      preview.startLoading();
      await banners.updateContentPreview();
      preview.stopLoading();
    }, 500),
    updateSettingsPreview: debouncePromise(async function () {
      await banners.showPreview();
    }, 500),
    showErrors(message) {
      this.$root.$emit("triggerNotification", {
        type: "error",
        message: message,
      });
    },
  },
  computed: {
    currentTabComponent: function () {
      return "tab-" + this.currentTab.toLowerCase();
    },
    tab() {
      return this.tabs.find((tab) => {
        return tab.id == this.currentTab;
      });
    },
    banner() {
      return this.$store.state.banners.current;
    },
    cookieGroups() {
      return this.$store.state.cookies.items;
    },
    preview: {
      get() {
        return this.$store.state.banners.preview;
      },
      set(value) {
        this.$store.state.banners.preview = value;
      },
    },
    banners() {
      return this.$store.state.banners.items || {};
    },
    appliedLaw() {
      return this.banner.properties.settings.applicableLaw;
    },
    noticeDisabled() {
      return this.banner.properties.config.notice.status === false;
    },
    publishDisabled() {
      return banners.hasErrors();
    },
    isLoaded() {
      return !this.loading && !!this.banner.id;
    },
  },
  watch: {
    "banner.properties.config": {
      async handler() {
        if (this.loading) return;
        await banners.resetTheme();
        preview.startLoading();
        await this.updateSettingsPreview();
        preview.stopLoading();
      },
      deep: true,
    },
    "banner.properties.settings": {
      async handler() {
        if (this.loading) return;
        preview.startLoading();
        await this.updateSettingsPreview();
        preview.stopLoading();
      },
      deep: true,
    },
    "banner.contents": {
      async handler() {
        if (this.loading) return;
        this.updateContentPreview();
      },
      deep: true,
    },
    "banner.properties.config.categoryPreview.status": {
      async handler() {
        preview.startLoading();
        await this.updateSettingsPreview();
        preview.stopLoading();
      },
      deep: true,
    },
    "banner.properties.config.notice.status": {
      handler(value) {
        if (value === false) {
          this.preview = false;
        }
      },
      deep: true,
    },
    '$store.state.settings.options.banners.selected': {
      async handler() {
        if (this.loading) return;
        await banners.resetTheme();
        this.updateContentPreview();
        preview.startLoading();
        await this.updateSettingsPreview();
        preview.stopLoading();
      },
      deep: true,
    },
    cookieGroups: {
      async handler() {
        preview.startLoading();
        await this.updateSettingsPreview();
        preview.stopLoading();
      },
      deep: true,
    },
    preview: {
      async handler() {
        if (this.preview) {
          preview.startLoading();
          await this.updateSettingsPreview();
          preview.stopLoading();
        } else {
          banners.hidePreview();
        }
      },
    },
  },
  async mounted() {
    this.loading = true;
    const selectedLaw = this.$store.state.settings.options.banners.selected;
    if (selectedLaw.length === 1) {
      this.currentLaw = selectedLaw[0]; // Access the selected law correctly
      await this.loadBanner(this.currentLaw);
    } else {
      await this.loadBanner('GDPR');
    }
    this.initialIABStatus = this.$store.state.banners.current.properties.settings.iab_enabled === "1"; // Set the iab status 
    this.loading = false;
    await banners.loadTemplate();
    await this.loadCookies();
  },
  beforeDestroy() {
    banners.closePreview(true);
    banners.reset();
  },
};
</script>
<style lang="scss">
@include wrap-class() {
  .wcc-nav-tab-banner-settings {
    .wcc-nav-tab-content-container {
      background-color: #ffffff;
      width: 85%;
    }
    .wcc-nav-tabs-container {
      width: 15%;
    }
    .wcc-nav-tab-section-content {
      height: auto;
    }
    .wcc-nav-tab-button {
      background-color: transparent;
      text-align: center;
      height: 50px;
      text-align: left;
    }
    .wcc-vertical-tabs {
      .wcc-nav-tab-item {
        border-bottom: none;
        border-radius: 9px;
        height: 50px;
        margin-bottom: 12px;
        margin-right: -1px;
        &.active {
          background: #f1f8fe;
          .wcc-nav-tab-button {
            background: #f1f8fe;
            border-radius: 9px;
            height: 50px;
            margin-bottom: 12px;
            color: #056BE7;
          }
          .wcc-nav-tab-button-icon > svg > path {
            fill: #056BE7;
          }
        }
        &:hover {
          .wcc-nav-tab-button {
            color: #056BE7; 
          }
          .wcc-nav-tab-button-icon > svg > path {
            fill: #056BE7;
          }
        }
      }
    }
    padding-left: 15px;
  }
  h3.wcc-section-title-heading {
    font-weight: 400;
  }
  .wcc-banner-preview-toggler {
    margin-left: 15px;
    .wcc-popper-container {
      display: flex;
      margin-left: 0;
    }
  }
  .wcc-customise-section-content {
    border: 1px solid #eaebed;
    border-radius: 12px;
    margin: 8px 15px 0px 15px;
    &.wcc-nav-tab-content-container {
      padding: 0px 20px 15px 33px;
      border-bottom-right-radius: 16px;
    }
  }
  .wcc-customise-section-content .wcc-tab-content-accordion {
    max-width: 780px;
  }
  .wcc-customise-section-content
    .wcc-tab-content-accordion
    .wcc-app-accordion-title {
    background: #fafbfc;
    height: 53px;
    flex-shrink: 0;
    color: #2a3646;
    font-weight: 500;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
  }
  .wcc-tab-content-accordion
    .wcc-app-accordion.wcc-app-accordion-boxed
    .wcc-app-accordion-title::before {
    content: none;
  }
  .wcc-tab-content-accordion
    .wcc-app-accordion.wcc-app-accordion-boxed
    .wcc-app-accordion-title::after {
    content: "";
  }
  .wcc-tab-content-accordion .wcc-app-accordion-title::after {
    width: 15px;
    height: 12px;
    opacity: 0.8;
    width: 14px;
    height: 14px;
    transition: -webkit-transform 100ms ease;
    transition: transform 100ms ease;
    transition: transform 100ms ease, -webkit-transform 100ms;
    -webkit-mask-image: url("~@/assets/plus-icon.svg");
    mask-image: url("~@/assets/plus-icon.svg");
    background-color: currentColor;
    -webkit-mask-repeat: no-repeat;
    mask-repeat: no-repeat;
    -webkit-mask-size: contain;
    mask-size: contain;
    -webkit-mask-position: center;
    mask-position: center;
    position: absolute;
    right: 20px;
  }
  .wcc-tab-content-accordion
    .wcc-app-accordion-open
    > .wcc-app-accordion-trigger
    .wcc-app-accordion-title::after {
    -webkit-mask-image: url("~@/assets/minus-icon.svg");
    mask-image: url("~@/assets/minus-icon.svg");
  }
  .wcc-content-colors .wcc-row {
    flex-flow: unset;
  }
  .wcc-nav-tab-section-content .wcc-row {
    flex-flow: unset;
  }
  .wcc-customise-section-content .wcc-nav-tab-content-container {
    padding: 0px 20px 15px 33px;
    border-bottom-right-radius: 16px;
  }
  .wcc-customise-section-content .wcc-nav-tab-content-container .wcc-col-3 {
    padding-right: 4px;
    max-width: 29%;
    flex-basis: 29%;
  }
  .wcc-customise-section-content .wcc-nav-tab-content-container .wcc-col-9 {
    padding-right: 10px;
    max-width: 71%;
    flex-basis: 71%;
  }
  .wcc-customise-section-content
    .wcc-nav-tab-content-container
    .wcc-col-9
    .wcc-form-control {
    width: 240px;
  }
  .wcc-customise-section-content
    .wcc-nav-tab-content-container
    .wcc-col-9 .wcc-rich-text-editor-container .wp-editor-container
    .wcc-form-control {
    width: 100%;
  }
  .wcc-customise-section-content
    .wcc-nav-tab-content-container
    .wcc-col-9
    .wcc-input-color {
    width: 100%;
  }
  .wcc-customise-section-content
    .wcc-nav-tab-content-container
    .wcc-row
    .wcc-form-heading {
    color: #3157a6;
  }
  .wcc-customise-section-content .wcc-nav-tab-content-container .wcc-col {
    padding-right: 0%;
  }
  .wcc-customise-section-content
    .wcc-nav-tab-content-container
    .wcc-col
    > label {
    margin-bottom: 5px;
  }
  // Colour Picker Styles
  .wcc-customise-section-content
    .wcc-nav-tab-content-container
    .wcc-col
    .wcc-color-picker {
    width: 107px;
    height: 30px;
    border-radius: 3px;
    & .wcc-color-picker-container {
      height: 100%;
      display: flex;
      width: 25px;
      height: 19px;
      margin-left: 4px;
      align-items: center;
      gap: 6px;
      border-radius: 3px;
      border: 1px solid #eaebed;
      .wcc-current-color {
        border-radius: 3px;
      }
    }
    border: 1px solid $border-color;
    .wcc-color-picker-input {
      box-sizing: border-box;
      background: #fff;
      box-sizing: border-box;
      font-size: 14px;
      border: 0;
      color: #4c5067;
      cursor: pointer;
      .wcc-input-color {
        background: transparent;
        border: none;
        text-transform: uppercase;
        font-size: 12px;
        padding: 0px 0px 0px 6px;
      }
    }
  }
  .wcc-customise-section-content
    .wcc-nav-tab-content-container
    .wcc-col-9
    .wcc-cookie-policy-link {
    width: 360px;
  }
}
</style>