<template>
  <div class="wcc-section wcc-zero--padding wcc-zero--margin">
    <div class="wcc-section-header wcc-align-center wcc-justify-between">
      <div class="wcc-section-title wcc-edit-content-wrapper">
        <div class="wcc-button-transparent">
          <span class="wcc-back-button-label">
            <router-link to="/languages">
              <span class="wcc-arrow">
            <base-icon icon="arrow"></base-icon>
          </span>
              {{
                $i18n.__(
                  "Back to Language List",
                  "webtoffee-cookie-consent"
                )
              }}
            </router-link>
          </span>
        </div>
      </div>
      <div class="wcc-section-header-actions wcc-align-center">
        <div class="wcc-align-center wcc-justify-end">
          <label for="wcc-banner-preview" class="wcc-toggle">
            <input type="checkbox" id="wcc-banner-preview" v-model="preview" :data-test-id="'wcc-banner-preview-toggle'" />
            <span class="wcc-toggle-text">{{
              $i18n.__("Banner Preview", "webtoffee-cookie-consent")
            }}</span>
            <span class="wcc-toggle-slider" aria-hidden="true"></span>
          </label>
          <base-button
            class="wcc-button"
            ref="wccButtonSaveLanguage"
            @click.native="saveConfig"
            style="margin-left: 15px"
            :data-test-id="'wcc-save-translation-button'"
          >
            {{ $i18n.__("Save translation", "webtoffee-cookie-consent") }}
          </base-button>
        </div>
      </div>
    </div>
    <div class="wcc-section-content">
      <div class="wcc-edit-content">
        <div class="wcc-row wcc-justify-between wcc-button-section">
          <div class="wcc-col-6">
            <div class="wcc-loader-languages" v-if="loading">
              <card-loader />
            </div>
          </div>
          <div class="wcc-col-6">
            <div class="wcc-loader-languages" v-if="loading">
              <card-loader />
            </div>
          </div>
        </div>
        <div class="wcc-row">
          <div class="wcc-col" v-if="defaultLanguage !== currentLanguage">
            <div class="wcc-loader-languages" v-if="loading">
              <card-loader />
              <card-loader />
              <card-loader />
            </div>

            <div class="wcc-edit-content-lists" v-else>
              <div class="wcc-choosen-law">
                <div class="wcc-default-language">
                  <div class="wcc-choosen-banner-label">
                    <h5>
                      {{ $i18n.__("Banner:", "webtoffee-cookie-consent") }}
                    </h5>
                    <select v-model="currentLaw" class="wcc-select">
                      <option
                        v-for="law in selectedLaws"
                        v-bind:value="law"
                        :key="law"
                      >
                        {{ law }}
                      </option>
                    </select>
                  </div>
                  <h5>
                    {{
                      $i18n.__(
                        "Default language:",
                        "webtoffee-cookie-consent"
                      )
                    }}
                    <b>{{ getLanguageName(defaultLanguage) }}</b>
                  </h5>
                  <accordion-tab-content
                    :language="defaultLanguage"
                    :translate="true"
                    :disabled="true"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="wcc-col">
            <div class="wcc-loader-languages" v-if="loading">
              <card-loader />
              <card-loader />
              <card-loader />
            </div>
            <div class="wcc-edit-content-lists" v-else>
              <div class="wcc-align-center wcc-edit-language">
                <div class="wcc-choosen-law" v-if="defaultLanguage === currentLanguage">
                  <div class="wcc-align-center">
                    <h5>
                      {{ $i18n.__("Banner:", "webtoffee-cookie-consent") }}
                    </h5>
                    <select v-model="currentLaw" class="wcc-select" :data-test-id="'wcc-edit-content-banner-select'">
                      <option
                        v-for="law in selectedLaws"
                        v-bind:value="law"
                        :key="law"
                        :data-test-id="`wcc-edit-banner-content-${law}`"
                      >
                        {{ law }}
                      </option>
                    </select>
                  </div>
                </div>
                <h5>
                  {{
                    $i18n.__(
                      "Edit content in:",
                      "webtoffee-cookie-consent"
                    )
                  }}
                </h5>
                <select v-model="currentLanguage" class="wcc-select" :data-test-id="'wcc-edit-content-language-select'">
                  <option
                    v-for="language in selectedLanguages"
                    v-bind:value="language"
                    v-bind:key="language"
                    :data-test-id="`wcc-edit-content-language-${language}`"
                  >
                    {{ getLanguageName(language) }}
                  </option>
                </select>
              </div>
              <accordion-tab-content
                :language="currentLanguage"
                :translate="true"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <translation-update-modal
      ref="TranslationUpdateModal"
      :code="currentLanguage"
    ></translation-update-modal>
  </div>
</template>
<script>
import { debounce } from "@/helpers/utils";
import banners from "@/modules/banners/helpers/utils";
import preview from "@/modules/banners/helpers/preview";
import languages from "@/modules/languages/helpers/utils";
import { mapState } from "vuex";
import BaseIcon from "@/components/icons/BaseIcon.vue";
import AccordionTabContent from "@/modules/banners/tabs/content/AccordionTabContent";
import CardLoader from "@/components/elements/CardLoader.vue";
import TranslationUpdateModal from "../components/TranslationUpdateModal.vue";
export default {
  name: "Customize",
  components: {
    AccordionTabContent,
    CardLoader,
    BaseIcon,
    TranslationUpdateModal,
  },
  data() {
    return {
      bannerPreview: false,
      loading: true,
      currentLaw: "",
    };
  },
  methods: {
    async loadCookies() {
      try {
        await this.$store.dispatch("cookies/reInit");
      } catch (error) {
        console.error(error);
      }
    },
    showIcon(tab) {
      return !!tab.icon;
    },
    loadBanner: async function (currentLaw) {
      await banners.getCurrentActiveBanner(currentLaw);
    },
    saveConfig: async function () {
      this.$refs.wccButtonSaveLanguage.startLoading();
      await banners.save();
      this.$root.$emit("triggerNotification", {
        type: "success",
        message: "Successfully saved",
      });
      this.$refs.TranslationUpdateModal.open();
      this.$refs.wccButtonSaveLanguage.stopLoading();
    },
    async loadLanguage() {
      const code = this.$route.params.language || "en";
      this.$store.state.languages.current = code;
    },
    async changeLanguage(code) {
      this.$store.state.languages.current = code;
    },
    updateBannerContents: debounce(async function () {
      preview.startLoading();
      await banners.updateContentPreview();
      preview.stopLoading();
    }, 500),
    getLanguageName(code) {
      return languages.getName(code);
    },
  },
  computed: {
    ...mapState("languages", ["default", "selected", "available"]),
    currentTabComponent: function () {
      return `tab-${this.currentTab.toLowerCase()}`;
    },
    banner() {
      return this.$store.state.banners.current;
    },
    banners() {
      return this.$store.state.banners.items || {};
    },
    preview: {
      get() {
        return this.$store.state.banners.preview;
      },
      set(value) {
        this.$store.state.banners.preview = value;
      },
    },
    defaultLanguage() {
      return this.default;
    },
    currentLanguage: {
      get() {
        return this.$store.state.languages.current;
      },
      set(value) {
        this.$store.state.languages.current = value;
      },
    },
    selectedLanguages: function () {
      return this.$store.state.languages.selected;
    },
    selectedLaws() {
      return this.$store.state.settings.options.banners.selected;
    },
  },
  async created() {
    this.loading = true;
    await this.loadLanguage();
    this.currentLaw = this.selectedLaws[0];
    await this.loadBanner(this.currentLaw);
    await banners.loadTemplate();
    this.loading = false;
    await this.loadCookies();
  },
  watch: {
    currentLanguage: {
      async handler() {
        await banners.showPreview(true);
      },
      deep: true,
    },
    "banner.contents": {
      handler() {
        this.updateBannerContents();
      },
      deep: true,
    },
    preview: {
      handler() {
        banners.showPreview();
      },
    },
    currentLaw: {
      immediate: true, // This option will make the watcher trigger immediately when the component is created.
      handler(newLaw, oldLaw) {
        if (newLaw !== oldLaw) {
          this.loadBanner(newLaw);
        }
      },
    },
  },
  beforeDestroy() {
    banners.closePreview(true);
    this.$store.state.languages.current = this.$store.state.languages.default;
  },
};
</script>
<style lang="scss">
@include wrap-class() {
  h3.wcc-section-title-heading {
    font-weight: 400;
  }
  .wcc-edit-content {
    padding: 15px;
    background-color: color(mono, white);
    h4 {
      font-weight: 500;
    }
    .wcc-select {
      min-width: 180px;
      max-height: 35px;
      margin-left: 10px;
      width: auto;
    }
    .wcc-rich-text-editor .ql-editor {
      min-height: 200px;
      max-height: 200px;
      overflow: scroll;
    }
    .wcc-app-accordion {
      .wcc-form-section:not(.wcc-form-section-group) {
        .wcc-col-3.wcc-col-label {
          display: none;
        }
        .wcc-col-9 {
          width: 100%;
          max-width: 100%;
          flex-basis: 100%;
        }
      }
    }
    .wcc-form-heading {
      margin-bottom: 10px;
    }
    .wcc-app-accordion-boxed {
      .wcc-app-accordion-title {
        background-color: #f6f7f7;
      }
    }
    .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-back-button-label a {
    color: #555e6b;
    font-size: 14px;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
  }
  .wcc-back-button-label a:hover:not(.wcc-button) {
    text-decoration: none;
  }
  .wcc-edit-content-lists {
    padding: 0px 15px 0px 15px;
    background-color: color(mono, white);
  }

  .wcc-edit-content-lists button {
    margin-left: 10px;
  }

  .wcc-button-section button {
    margin-left: 10px;
  }

  .wcc-select-label {
    margin-top: 10px;
  }
  .wcc-loader-languages .wcc-card-loader-container:not(:first-child) {
    margin-top: 15px;
  }
  .wcc-default-language {
    display: block;
  }
  .wcc-default-language h5,
  .wcc-default-language .wcc-choosen-banner-label {
    display: inline-block;
  }
  .wcc-default-language .wcc-choosen-banner-label, .wcc-edit-language .wcc-choosen-law {
    margin-right: 10px;
  }
  .wcc-edit-content-wrapper .wcc-button-transparent .wcc-back-button-label .router-link-active{
    display: flex;
    align-items: center;
  }
  .wcc-edit-content-wrapper .wcc-button-transparent .wcc-back-button-label .router-link-active .wcc-arrow {
    line-height: 10px;
  }
}
</style>