<template>
	<fragment>
		<div class="wcc-nav-tab-section wcc-nav-tab-section-cookies">
			<div v-if="!isLoaded" 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>
						<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>
			
			<nav-tabs v-else :onTabChange="loadCookies">
				<nav-tab v-for="category in categories" :key="category.id" :title="category.name[language]"
					:subTitle="getCookiesCountText(category.cookie_list)" :meta="category"
					:class="[{ 'wcc-app-rtl': isRTLLanguage(language) }]"
					:dataTestId="category.slug"
				>
				
					<RenewNotice />
					<div class="wcc-nav-tab-section" v-if="!isEditing" :data-test-id="`wcc-${category.slug}-category-section`">
						<div class="wcc-justify-between wcc-row wcc-cookie-list-title">
							<div class="wcc-col-4 wcc-align-center">
								<h4 class="wcc-cookies-header">
									{{ category.name[language] }}
								</h4>
								<base-popper :content="$i18n.__('Edit category', 'webtoffee-cookie-consent')">
									<button class="wcc-button-no-style" @click="openCookieCategoryModal(category)" :data-test-id="`wcc-edit-${category.slug}-category-button`">
										<base-icon width="14px" icon="edit-alt" color="#000000"></base-icon>
									</button>
								</base-popper>
								<button class="wcc-add-cookie-button wcc-button wcc-button-outline"
									@click="openCookieModal()" :data-test-id="`wcc-add-${category.slug}-cookie-button`">
									{{ $i18n.__(" + Add Cookie", "webtoffee-cookie-consent") }}
								</button>
							</div>
							<div class="wcc-col-8 wcc-align-center wcc-justify-end">
								<h5 class="wcc-cookies-header wcc-language-label">
									{{ $i18n.__("Edit content in: ", "webtoffee-cookie-consent") }}
								</h5>
								<base-select id="wcc-dropdown-languages" :options="selectedLanguages" label="name"
									tag="code" v-model="language"></base-select>
							</div>
						</div>
						<div class="
								wcc-nav-tab-section-header wcc-align-center wcc-justify-between
							">
							<div class="wcc-nav-tab-section-title">
								<div class="wcc-category-description" :data-test-id="`wcc-${category.slug}-category-description`">
									{{ strippedContent(category.description[language]) }}
								</div>
								<div class="wcc-category-prior-consent" v-if="currentCategory.prior_consent">
									{{ $i18n.__("Load prior to consent :", "webtoffee-cookie-consent") }}
									<badge :title="$i18n.__('Enabled', 'webtoffee-cookie-consent')" :type="'success'">
									</badge>
								</div>
							</div>
						</div>
						<div class="wcc-nav-tab-section-content">
							<cookies-table :cookies="category.cookie_list" @createEditCookie="openCookieModal"
								@deleteCookie="deleteCookie" :language="language"></cookies-table>
						</div>
					</div>
					<div class="wcc-nav-tab-section wcc-category-edit" v-else>
						<div class="wcc-justify-between wcc-row wcc-cookie-list-title">
							<div class="wcc-col-4 wcc-align-center">
								<button class="wcc-button-transparent" @click="hideDetails" :data-test-id="`wcc-back-to-${category.slug}-category-button`">
									<span class="wcc-arrow">
										<base-icon icon="arrow"></base-icon>
									</span>
									<span class="wcc-back">
										{{
											$i18n.__("Back to cookie details", "webtoffee-cookie-consent")
										}}
									</span>
								</button>
							</div>
						</div>
						<div class="
								wcc-nav-tab-section-header
							">
							<template v-if="isCategoryLoaded">
								<div class="wcc-row">
									<div class="wcc-col-12">
										<div class="wcc-form-group  wcc-align-center">
											<label class="wcc-label wcc-col-3">{{ $i18n.__("Name",
												"webtoffee-cookie-consent") }}
												<span class="wcc-required"></span>
											</label>
											<div class="wcc-col-6">
												<input type="text" class="wcc-form-control wcc-col-6" required
													v-model="currentCategory.name[language]" :data-test-id="`wcc-edit-${category.slug}-category-name-input`" />
											</div>
										</div>
										<div class="wcc-form-error">
											<label class="wcc-label"></label>
											<div class="wcc-input-error-alert" show v-if="errors.category.name">
												{{ $i18n.__("Name is required", "webtoffee-cookie-consent") }}
											</div>
										</div>
									</div>
								</div>
								<div class="wcc-row">
									<div class="wcc-col-12">
										<div class="wcc-form-group  wcc-align-center">
											<label class="wcc-label wcc-col-3">{{ $i18n.__("Description",
												"webtoffee-cookie-consent") }}
												<span class="wcc-required"></span>
											</label>
											<div class="wcc-col-6">
												<editor v-model="currentCategory.description[language]"
													:language="language" height="100" :data-test-id="`wcc-edit-${category.slug}-category-description`" />
											</div>
										</div>
										<div class="wcc-input-error-alert" show v-if="errors.category.description">
											{{ $i18n.__("Description is required", "webtoffee-cookie-consent") }}
										</div>
									</div>
								</div>
								<div class="wcc-row" v-if="'necessary' !== currentCategory.slug">
									<div class="wcc-col-12">
										<div class="wcc-form-group wcc-align-center">
											<label class="wcc-col-3 wcc-col-label" for="wcc-prior-consent-checkbox">
												{{
													$i18n.__(
														"Load cookies prior to user consent",
														"webtoffee-cookie-consent"
													)
												}}
												<base-popper :content="$i18n.__(
													'If this category contains cookies and you choose to load it prior to receiving user consent, your website will be non-compliant with the GDPR','webtoffee-cookie-consent' )" 
												/>
											</label>
											<div class="wcc-col-9">
												<input type="checkbox" id="wcc-prior-consent-checkbox"
													v-model="currentCategory.prior_consent" :data-test-id="`wcc-edit-${category.slug}-category-prior-consent-checkbox`" />
												<span id="wcc-prior-consent-checkbox" aria-hidden="true"> </span>
											</div>
										</div>
									</div>
								</div>
								<div class="wcc-row" v-if="'necessary' !== currentCategory.slug">
									<div class="wcc-col-12">
										<div class="wcc-form-group wcc-align-center">
											<label class="wcc-col-3 wcc-col-label" for="wcc-opt-out-checkbox">
												{{
													$i18n.__(
														"Sells or shares personal data",
														"webtoffee-cookie-consent"
													)
												}}
												<base-popper :content="$i18n.__(
													'Enable this option if this category contains cookies that sell and share personal data. Once enabled, all cookies under this category will be blocked if the user opts out by clicking the “Do Not Sell or Share My Personal Information” link. Applicable only for US State Law users',
													'webtoffee-cookie-consent'
												)
													" />
											</label>
											<div class="wcc-col-9">
												<input type="checkbox" id="wcc-opt-out-checkbox"
													v-model="currentCategory.sell_personal_data" :data-test-id="`wcc-edit-${category.slug}-category-sell-personal-data-checkbox`" />
												<span id="wcc-opt-out-checkbox" aria-hidden="true"> </span>
											</div>
										</div>
									</div>
								</div>
								<div class="wcc-row" v-if="'necessary' !== currentCategory.slug">
									<div class="wcc-col-12">
										<div class="wcc-form-group wcc-align-center">
											<label class="wcc-col-3 wcc-col-label" for="wcc-hide-empty-cat-checkbox">
												{{
													$i18n.__(
														"Show category on cookie banner",
														"webtoffee-cookie-consent"
													)
												}}
												<base-popper :content="$i18n.__(
													'If this category contains cookies and you choose to hide it, your website will be non-compliant with the GDPR.','webtoffee-cookie-consent' )" 
												/>
											</label>
											<div class="wcc-col-9">
												<input type="checkbox" id="wcc-hide-empty-cat-checkbox"
													v-model="currentCategory.visibility" :data-test-id="`wcc-edit-${category.slug}-category-visibility-checkbox`" />
												<span id="wcc-hide-empty-cat-checkbox" aria-hidden="true"> </span>
											</div>
										</div>
									</div>
								</div>
								<div class="wcc-row" v-if="'necessary' !== currentCategory.slug">
									<div class="wcc-accordion-advanced">
										<div class="wcc-col-12">
											<accordion name="cookies">
												<accordion-item>
													<template slot="accordion-trigger">
														<label
															class="wcc-app-accordion-title wcc-cookie-avdanced-options wcc-label">
															{{ $i18n.__("Advanced Options", "webtoffee-cookie-consent")
															}}</label>
													</template>
													<template slot="accordion-content">
														<label for="" class="wcc-label">
															{{ $i18n.__("Script URL Pattern",
																"webtoffee-cookie-consent") }}

														</label>
														<notice type="warning" class="wcc-col-10" style="max-width: 948px;">
															<p>
																If the third-party script setting this cookie is
																&lt;script async
																src='https://www.google-analytics.com/analytics.js'&gt;&lt;/script&gt;
																then you can specify its "Script URL Pattern" as
																<b>google-analytics.com</b>
															</p>
														</notice>
														<div class="wcc-no-cookie-scripts">
															<div class="wcc-no-cookie-scripts">
																<div class="wcc-row wcc-align-center">
																	<label class="wcc-col-3 wcc-col-label"
																		for="wcc-no-cookie-scripts">
																		{{
																			$i18n.__(
																				"Insert script URL pattern to block",
																				"webtoffee-cookie-consent"
																			)
																		}}
																	</label>
																	<div class="wcc-col-9">
																		<MultiSelectInput
																			:placeholderText="placeholderText"
																			:initialItems="urlsToBlock[currentCategory.slug] || []"
																			@update:selectedItems="updateScriptsToBlock" :data-test-id="`wcc-edit-${category.slug}-category-scripts-to-block-input`" />
																	</div>
																</div>
															</div>
															<div class="wcc-row">
																<div class="wcc-col-3"></div>
																<div class="wcc-col-9">
																	<label
																		class="wcc-form-check-label wcc-urls-to-block-help"
																		for="wcc-urls-to-block">
																		{{
																			$i18n.__(
																				"Use ( | ) to separate script sources.",
																				"webtoffee-cookie-consent"
																			)
																		}}
																	</label>
																</div>
															</div>
														</div>
													</template>
												</accordion-item>
											</accordion>
										</div>
									</div>
								</div>
								<div class="wcc-app-modal-actions wcc-col-12">
									<base-button class="wcc-button-primary" ref="wccButtonCreateEditCookieCategory"
										@click.native="addOrEditCookieCategory" :disabled="isSaving" :data-test-id="`wcc-edit-${category.slug}-category-save-button`">
										{{ $i18n.__("Save Changes", "webtoffee-cookie-consent") }}
									</base-button>
									<button class="wcc-button wcc-button-outline-secondary" @click="hideDetails">
										{{ $i18n.__("Cancel", "webtoffee-cookie-consent") }}
									</button>
								</div>
							</template>
						</div>
					</div>
				</nav-tab>
			</nav-tabs>
		</div>
		<modal ref="wccCookieModal" :class="[
			'wcc-app-modal-cookies',
			{ 'wcc-app-rtl': isRTLLanguage(language) },
		]" @close="clearCookieModal">
			<template v-slot:header>
				<h4 v-if="cookie.id">
					{{ $i18n.__("Edit Cookie", "webtoffee-cookie-consent") }}
				</h4>
				<h4 v-else>
					{{ $i18n.__("Add new cookie", "webtoffee-cookie-consent") }}
				</h4>
			</template>
			<template v-slot:body>
				<div class="wcc-row">
					<div class="wcc-col-12">
						<div class="wcc-form-group">
							<label class="wcc-label">{{ $i18n.__("Cookie Name", "webtoffee-cookie-consent") }}
								<span class="wcc-required"></span>
							</label>
							<input type="text" class="wcc-form-control" v-model="currentCookie.name" :data-test-id="`wcc-edit-${category.slug}-${currentCookie?.slug || 'new-cookie'}-cookie-name-input`" />
						</div>
						<div class="wcc-form-error">
							<label class="wcc-label"></label>
							<div class="wcc-input-error-alert" show v-if="errors.cookie.name">
								{{ $i18n.__("Cookie name is required", "webtoffee-cookie-consent") }}
							</div>
						</div>
					</div>
				</div>
				<div class="wcc-row">
					<div class="wcc-col-12">
						<div class="wcc-form-group">
							<label class="wcc-label">
								{{ $i18n.__("Domain", "webtoffee-cookie-consent") }}
								<span class="wcc-required"></span>
							</label>
							<input type="text" class="wcc-form-control" v-model="currentCookie.domain" :data-test-id="`wcc-edit-${category.slug}-${currentCookie?.slug || 'new-cookie'}-cookie-domain-input`" />
						</div>
						<div class="wcc-form-error">
							<label class="wcc-label"></label>
							<div class="wcc-input-error-alert" show v-if="errors.cookie.domain">
								{{ $i18n.__("Domain is required", "webtoffee-cookie-consent") }}
							</div>
						</div>
					</div>
				</div>
				<div class="wcc-row" v-if="cookie.id">
					<div class="wcc-col-12">
						<div class="wcc-form-group">
							<label class="wcc-label">
								{{ $i18n.__("Category", "webtoffee-cookie-consent") }}
								<span class="wcc-required"></span>
							</label>
							<select
								class="wcc-category-select"
								v-model="currentCategory.name[language]"
								@change="updateCurrentCookieCategory"
								:data-test-id="`wcc-edit-${category.slug}-${currentCookie?.slug || 'new-cookie'}-cookie-category-select`"
							>
								<option
									v-for="category in categories"
									:key="category.id"
									:value="category.name[language]"
								>
									{{ category.name[language] }}
								</option>
							</select>
						</div>
						<div class="wcc-form-error">
							<label class="wcc-label"></label>
							<div class="wcc-input-error-alert" show v-if="errors.cookie.category">
								{{ $i18n.__("Category is required", "webtoffee-cookie-consent") }}
							</div>
						</div>
					</div>
				</div>
				<div class="wcc-row">
					<div class="wcc-col-12">
						<div class="wcc-form-group">
							<label class="wcc-label">
								{{ $i18n.__("Duration", "webtoffee-cookie-consent") }}
								<span class="wcc-required"></span>
							</label>
							<input type="text" class="wcc-form-control" required
								v-model="currentCookie.duration[language]" :data-test-id="`wcc-edit-${category.slug}-${currentCookie?.slug || 'new-cookie'}-cookie-duration-input`" />
						</div>
						<div class="wcc-form-error">
							<label class="wcc-label"></label>
							<div class="wcc-input-error-alert" show v-if="errors.cookie.duration">
								{{ $i18n.__("Duration is required", "webtoffee-cookie-consent") }}
							</div>
						</div>
					</div>
				</div>
				<div class="wcc-row">
					<div class="wcc-col-12">
						<div class="wcc-form-group">
							<label class="wcc-label">{{ $i18n.__("Description", "webtoffee-cookie-consent") }}
								<span class="wcc-required"></span>
							</label>
							<editor v-model="currentCookie.description[language]" :language="language" height="100" :data-test-id="`wcc-edit-${category.slug}-${currentCookie?.slug || 'new-cookie'}-cookie-description-input`">
							</editor>
						</div>
						<div class="wcc-form-error">
							<label class="wcc-label"></label>
							<div class="wcc-input-error-alert" show v-if="errors.cookie.description">
								{{ $i18n.__("Description is required", "webtoffee-cookie-consent") }}
							</div>
						</div>
					</div>
				</div>
				<div class="wcc-row">
					<div class="wcc-col-12">
						<accordion name="cookies">
							<accordion-item>
								<template slot="accordion-trigger">
									<label class="wcc-app-accordion-title wcc-cookie-avdanced-options">Advanced
										Options</label>
								</template>
								<template slot="accordion-content">
									<label for="" class="wcc-label">
										{{ $i18n.__("Script URL Pattern", "webtoffee-cookie-consent") }}
										<base-popper :content="$i18n.__(
											'Our auto-blocking mechanism will use the Script URL Pattern to identify the third-party script (setting a cookie) by purpose category, and consequently, the associated cookie will be automatically blocked prior to receiving user consent for the respective category.',
											'webtoffee-cookie-consent'
										)
											" position="right" />
									</label>
									<div class="wcc-help-text">
										<p>
											{{
												$i18n.__(
													"URL pattern for blocking the third-party script settings of this cookie",
													"webtoffee-cookie-consent"
												)
											}}
										</p>
									</div>
									<notice type="warning">
										<p>
											If the third-party script setting this cookie is
											&lt;script async
											src='https://www.google-analytics.com/analytics.js'&gt;&lt;/script&gt;
											then you can specify its "Script URL Pattern" as
											<b>google-analytics.com</b>
										</p>
									</notice>
									<input type="text" class="wcc-form-control" v-model="currentCookie.url_pattern"
										placeholder="Please enter a valid Script URL Pattern. Eg:- google-analytics.com" :data-test-id="`wcc-edit-${category.slug}-${currentCookie?.slug || 'new-cookie'}-cookie-url-pattern-input`" />
								</template>
							</accordion-item>
						</accordion>
					</div>
				</div>
			</template>
			<template v-slot:footer>
				<div class="wcc-app-modal-actions wcc-app-cookie-edit wcc-justify-end">
					<button class="wcc-button wcc-button-outline-secondary" @click="closeCookieModal" :data-test-id="`wcc-edit-${category.slug}-${currentCookie.slug}-cookie-cancel-button`">
						{{ $i18n.__("Cancel", "webtoffee-cookie-consent") }}
					</button>
					<base-button class="wcc-button-primary" ref="wccButtonCreateEditCookie"
						@click.native="addOrEditCookie" :data-test-id="`wcc-edit-${category.slug}-${currentCookie.slug}-cookie-save-button`">
						{{ $i18n.__("Save Changes", "webtoffee-cookie-consent") }}
					</base-button>
				</div>
			</template>
		</modal>
		<modal ref="wccCookieCategoryModal" :class="[
			'wcc-app-modal-cookies-categories',
			{ 'wcc-app-rtl': isRTLLanguage(language) },
		]" @close="clearCategoryModal">
			>
			<template v-slot:header>
				<h4>
					{{ $i18n.__("Edit Category", "webtoffee-cookie-consent") }}
				</h4>
			</template>
			<template v-slot:body v-if="isCategoryLoaded">
				<div class="wcc-row">
					<div class="wcc-col-12">
						<div class="wcc-form-group">
							<label class="wcc-label">{{ $i18n.__("Name", "webtoffee-cookie-consent") }}
								<span class="wcc-required"></span>
							</label>
							<input type="text" class="wcc-form-control" required
								v-model="currentCategory.name[language]" :data-test-id="`wcc-edit-${category.slug}-category-name-input`" />
						</div>
						<div class="wcc-form-error">
							<label class="wcc-label"></label>
							<div class="wcc-input-error-alert" show v-if="errors.category.name">
								{{ $i18n.__("Name is required", "webtoffee-cookie-consent") }}
							</div>
						</div>
					</div>
					<div class="wcc-col-6"></div>
				</div>
				<div class="wcc-row">
					<div class="wcc-col-12">
						<div class="wcc-form-group">
							<label class="wcc-label">{{ $i18n.__("Description", "webtoffee-cookie-consent") }}
								<span class="wcc-required"></span>
							</label>
							<editor v-model="currentCategory.description[language]" :language="language" height="100" :data-test-id="`wcc-edit-${category.slug}-category-description-input`" />
							<div class="wcc-input-error-alert" show v-if="errors.category.description">
								{{ $i18n.__("Description is required", "webtoffee-cookie-consent") }}
							</div>
						</div>
					</div>
				</div>
			</template>
			<template v-slot:footer>
				<div class="wcc-app-modal-actions wcc-justify-end">
					<button class="wcc-button wcc-button-outline-secondary" @click="closeCookieCategoryModal" :data-test-id="`wcc-edit-${category.slug}-category-cancel-button`">
						{{ $i18n.__("Cancel", "webtoffee-cookie-consent") }}
					</button>
					<base-button class="wcc-button-primary" ref="wccButtonCreateEditCookieCategory"
						@click.native="addOrEditCookieCategory" :disabled="isSaving" :data-test-id="`wcc-edit-${category.slug}-category-save-button`">
						{{ $i18n.__("Save Changes", "webtoffee-cookie-consent") }}
					</base-button>
				</div>
			</template>
		</modal>
	</fragment>
</template>

<script>
import { cloneDeep } from "@/helpers/utils";
import BaseIcon from "@/components/icons/BaseIcon.vue";
import NavTabs from "@/components/tabs/NavTabs.vue";
import NavTab from "@/components/tabs/NavTab.vue";
import CookiesTable from "@/modules/cookies/components/CookiesTable.vue";
import api from "@/modules/cookies/helpers/api";
import Modal from "@/components/Modal.vue";
import Accordion from "@/components/accordion/Accordion.vue";
import AccordionItem from "@/components/accordion/AccordionItem.vue";
import Notice from "@/components/elements/Notice.vue";
import BaseSelect from "@/components/elements/BaseSelect.vue";
import CardLoader from "@/components/elements/CardLoader.vue";
import Editor from "@/components/elements/Editor.vue";
import { Fragment } from "vue-frag";
import Badge from "@/components/elements/Badge.vue";
import RenewNotice from "@/components/ConsentRenewNotice.vue";
import MultiSelectInput from "@/modules/banners/components/MultiSelectInput.vue";
import { mapState } from "vuex";

export default {
	name: "TabCookies",
	components: {
		BaseIcon,
		NavTab,
		NavTabs,
		CookiesTable,
		Modal,
		Accordion,
		AccordionItem,
		Notice,
		BaseSelect,
		CardLoader,
		Editor,
		Fragment,
		Badge,
		RenewNotice,
		MultiSelectInput,
	},
	data() {
		return {
			cookie: {},
			category: {},
			categoryCookies: [],
			cookies: [],
			currentTab: "layout",
			cookieCategories: [],
			loading: false,
			isSaving: false,
			currentLanguage: "",
			errors: {
				cookie: {
					id: false,
					name: false,
					domain: false,
					duration: false,
					description: false,
				},
				category: {
					name: false,
					description: false,
				},
			},
			isEditing: false,
			urlsToBlock: [],
			initialCategory: null,
		};
	},
	async mounted() {
		this.loadItems(true);
	},
	methods: {
		async loadItems(force = false) {
			try {
				this.loading = force;
				await this.$store.dispatch("cookies/reInit");
				this.urlsToBlock = this.$store.state.settings.info.no_cookie_scripts_to_block.selected;
				this.loading = false;
			} catch (error) {
				console.error(error);
				this.$root.$emit("triggerNotification", {
					type: "error",
					message: this.$i18n.__(
						"An unexpected error occurred please try reloading the page or logging in again.",
						"webtoffee-cookie-consent"
					),
				});
			}
		},
		async addOrEditCookie() {
			this.$refs.wccButtonCreateEditCookie.startLoading();
			try {
				let response = {};
				const cookie = this.currentCookie;
				let updatedCategory = cookie.category;
				this.resetErrors("cookie");
				const validated = this.validateCookieFields(cookie);
				if (validated) {
					if (cookie.id > 0) {
						response = await api.updateCookie(cookie.id, cookie);
						if (response) {
							await this.loadItems();
							if (updatedCategory !== this.initialCategory) {
								this.updateConsentStatus(true);
								let data = {};
								data.status = true;
								this.setOption("renew_consent_notice", data);
								this.saveOptions();
							}
							this.closeCookieModal();
							this.$root.$emit("triggerNotification", {
								type: "success",
								message: this.$i18n.__("Cookie updated successfully!", "webtoffee-cookie-consent"),
							});
						}
					} else {
						response = await api.createCookie(cookie);
						if (response) {
							await this.loadItems();
							/* Show renew consent warning  */
							this.updateConsentStatus(true);
							let data = {};
							data.status = true;
							this.setOption("renew_consent_notice", data);
							this.saveOptions();
							this.closeCookieModal();
							this.$root.$emit("triggerNotification", {
								type: "success",
								message: this.$i18n.__("Cookie saved successfully!", "webtoffee-cookie-consent"),
							});
						}
					}
				}
			} catch (error) {
				this.$root.$emit("triggerNotification", {
					type: "error",
					message: this.$i18n.__(
						"Problem occurred while saving your cookie. Please try again later!",
						"webtoffee-cookie-consent"
					),
				});
			}
			this.$refs.wccButtonCreateEditCookie.stopLoading();
		},
		async addOrEditCookieCategory() {
			this.isSaving = true;  // Start loading
			try {
				let response = {};
				const category = this.currentCategory;
				this.resetErrors("category");
				const validated = this.validateCategoryFields(category);
				if (validated) {
					if (category.id) {
						response = await api.updateCookieCategory(category.id, category);
						/* Save no cookie script list  */
						// Create a clean copy of `urlsToBlock` without Vue's reactivity
						const urlsToBlockData = {};

						for (const [category, urls] of Object.entries(this.urlsToBlock)) {
							// Convert each category array to a plain array, removing Vue’s reactivity
							urlsToBlockData[category] = JSON.parse(JSON.stringify(urls));
						}
						await api.updateNoCookieScripts(urlsToBlockData);
					} else {
						response = await api.createCookieCategory(category);
					}
					if (response) {
						await this.loadItems();
					}
					this.$refs.wccCookieCategoryModal.close();
					this.$root.$emit("triggerNotification", {
						type: "success",
						message: this.$i18n.__("Changes saved successfully!", "webtoffee-cookie-consent"),
					});
				}
			} catch (error) {
				this.$root.$emit("triggerNotification", {
					type: "error",
					message: this.$i18n.__(
						"Problem occurred while saving your settings. Please try again later!",
						"webtoffee-cookie-consent"
					),
				});
			}
			finally {
				this.isSaving = false;  // Stop loading
			}
		},
		loadCookies(tab) {
			this.category = cloneDeep(tab.meta);
		},
		openCookieModal(cookie = {}) {
			this.cookie = cloneDeep(cookie);
			this.$refs.wccCookieModal.show();
		},
		openCookieCategoryModal(category) {
			this.category = cloneDeep(category);
			this.isEditing = true;
		},
		closeCookieModal() {
			this.$refs.wccCookieModal.close();
			this.clearCookieModal();
		},
		clearCookieModal() {
			this.cookie = {};
			this.resetErrors("cookie");
		},
		closeCookieCategoryModal() {
			this.$refs.wccCookieCategoryModal.close();
			this.clearCategoryModal();
		},
		clearCategoryModal() {
			this.resetErrors("category");
		},
		async deleteCookie(cookie) {
			if (
				confirm(
					this.$i18n.__(
						"Are you sure you want to delete this cookie?",
						"webtoffee-cookie-consent"
					)
				)
			) {
				if (cookie.id) {
					let response = await api.deleteCookie(cookie.id);
					if (response.id > 0) {
						this.$root.$emit("triggerNotification", {
							type: "success",
							message: this.$i18n.__(
								"Cookie deletion successful",
								"webtoffee-cookie-consent"
							),
						});
						/* Show renew consent warning  */
						this.updateConsentStatus(true);
						let data = {};
						data.status = true;
						this.setOption("renew_consent_notice", data);
						this.saveOptions();
						await this.loadItems();
					} else {
						this.$root.$emit("triggerNotification", {
							type: "error",
							message: this.$i18n.__("Failed", "webtoffee-cookie-consent"),
						});
					}
				}
			}
		},
		getCookiesCountText(cookies) {
			let count = cookies.length;
			return "(" + count + ")";
		},
		getLanguageContents(item) {
			let data = {};
			this.selectedLanguages.forEach((language) => {
				let code = language.code;
				data[code] =
					item && Object.prototype.hasOwnProperty.call(item, code)
						? item[code]
						: "";
			});
			return data;
		},
		strippedContent(description) {
			if (!description) {
				return "";
			}
			return description.replace(/(<([^>]+)>)/gi, "");
		},
		resetErrors(type) {
			Object.keys(this.errors[type]).forEach((key) => {
				this.errors[type][key] = false;
			});
		},
		validateCookieFields(cookie) {
			this.errors.cookie.name = !(cookie.name && cookie.name.trim());
			this.errors.cookie.domain = !(cookie.domain && cookie.domain.trim());
			this.errors.cookie.duration = !(
				cookie.duration[this.language] && cookie.duration[this.language].trim()
			);
			this.errors.cookie.description = !(
				cookie.description[this.language] &&
				cookie.description[this.language].trim()
			);

			return (
				!this.errors.cookie.name &&
				!this.errors.cookie.domain &&
				!this.errors.cookie.duration &&
				!this.errors.cookie.description
			);
		},
		validateCategoryFields(category) {
			this.errors.category.name = !(
				category.name[this.language] && category.name[this.language].trim()
			);
			this.errors.category.description = !(
				category.description[this.language] &&
				category.description[this.language].trim()
			);

			return !this.errors.category.name && !this.errors.category.description;
		},
		hideDetails() {
			this.isEditing = false;
		},
		updateScriptsToBlock(newItems) {
			// Ensure the nested path exists in the store
			if (!this.$store.state.settings?.options?.no_cookie_scripts_to_block) {
				this.$store.state.settings.options.no_cookie_scripts_to_block = { selected: [] };
			}
			// Update urlsToBlock based on Category slug
			this.urlsToBlock[this.currentCategory.slug] = Array.isArray(newItems) ? newItems : [newItems];
			// Update the Vuex store with the new value
			this.$store.state.settings.options.no_cookie_scripts_to_block.selected = this.urlsToBlock;
		},
		updateCurrentCookieCategory() {
			// Find the selected category based on the name
			const selectedCategory = this.categories.find(
				(category) => category.name[this.language] === this.currentCategory.name[this.language]
			);
			
			if (selectedCategory) {
				this.currentCookie.category = selectedCategory.id;
			} else {
				this.currentCookie.category = null; // Clear if no match found
			}
		},
	},
	computed: {
		cookieGroups() {
			const items = this.$store.state.cookies.items;
			if (!Array.isArray(items)) {
				return [];
			}
			return items.map(category => {
				const filteredCategory = { ...category };
				if (filteredCategory.cookie_list) {
					filteredCategory.cookie_list = filteredCategory.cookie_list.filter(cookie => cookie.cookie_status === true);
				}
				return filteredCategory;
			});
		},
		currentCookie: {
			get() {
				const cookie = cloneDeep(this.cookie);
				cookie.description = this.getLanguageContents(this.cookie.description);
				cookie.category = this.cookie.category
					? this.cookie.category
					: this.category.id;
				cookie.duration = this.getLanguageContents(this.cookie.duration);
				this.initialCategory = cookie.category;
				return cookie;
			},
			set(cookie) {
				this.cookie = cloneDeep(cookie);
			},
		},
		currentCategory: {
			get() {
				const category = cloneDeep(this.category);
				category.name = this.getLanguageContents(this.category.name);
				category.description = this.getLanguageContents(
					this.category.description
				);
				category.prior_consent = this.category.prior_consent;
				category.sell_personal_data = this.category.sell_personal_data;
				category.visibility = this.category.visibility;
				return category;
			},
			set(category) {
				this.category = cloneDeep(category);
			},
		},
		disabled: function () {
			return !this.cookie.id;
		},
		categories: function () {
			return this.cookieGroups;
		},
		selectedLanguages() {
			const selected = this.$store.state.languages.selected;
			const available = this.$store.state.languages.available;

			const filtered = available.filter(function (item) {
				return selected.indexOf(item.code) > -1;
			});
			return filtered;
		},
		language: {
			get() {
				return (
					(this.currentLanguage && this.currentLanguage) ||
					this.$store.state.languages.default
				);
			},
			set(value) {
				this.currentLanguage = value;
			},
		},
		isLoaded() {
			return !this.loading && !!this.categories.length;
		},
		isCategoryLoaded() {
			return !!this.category.id;
		},
		placeholderText() {
			// Check if the array for the current category slug is empty
			const currentCategoryArray = this.urlsToBlock[this.currentCategory.slug] || [];

			return currentCategoryArray.length === 0 
				? "Enter a valid Script URL Pattern. Eg:- google-analytics.com and press Enter" 
				: ""; // Show placeholder only when empty
		},
		...mapState("settings", ["info"]),
	},
};
</script>
<style lang="scss" scoped>
.wcc-cookie-list-title {
	margin-bottom: 20px;

	.wcc-add-cookie-button {
		margin-left: 16px;
	}
}

.wcc-nav-tab-section-cookies {
	background: transparent;
}

.wcc-app-modal-cookies {
	.wcc-admin-notice-message p {
		font-size: 12px;
	}
}

.wcc-cookies-title,
.wcc-category-prior-consent {
	display: flex;
	align-items: center;
	padding: 10px 0;
}

.wcc-cookies-title .wcc-button-no-style {
	margin-left: 11px;
}

.wcc-nav-tab-section-header {
	border: none;
}

.wcc-nav-tab-section-cookies {
	padding: 15px 15px;

	.wcc-nav-tab-section-header {
		h5 {
			font-weight: $font--medium;
			// border-bottom: 1px solid;
			padding-bottom: 2px;
			margin: 0;
		}
	}
}

.wcc-app-cookie-edit {
	width: 100%;
	box-sizing: border-box;
}

.wcc-app-cookie-edit button {
	width: 50%;
}

.wcc-app-wrap .wcc-app-modal-footer .wcc-app-cookie-edit button:first-child {
	margin-right: 10px;
}

.wcc-app-modal .wcc-app-modal-footer .wcc-app-modal-actions button {
	margin-left: 0px;
}

.wcc-app-modal-footer .wcc-app-modal-actions .wcc-action-languages button:first-child {
	margin-right: 10px;
}

.wcc-app-wrap .wcc-app-accordion-title {
	font-size: 14px;
	font-weight: normal;
	margin-bottom: 6px;
	cursor: pointer;
	margin: 0;
	color: #1863dc;
	display: flex;
	align-items: center;
	font-weight: 500;
	background-color: transparent;
}
</style>
<style lang="scss">
@include wrap-class() {
	.wcc-table {
		&.wcc-table-cookies {
			margin-top: 15px;
			border: none;

			tbody tr {
				border-top: none;

				td {
					font-size: 13px;
				}
			}

			tbody td,
			th {
				padding: 15px 10px;
			}
		}
	}

	.wcc-cookie-list-title {
		select {
			margin-left: 10px;
			min-width: 150px; // auto
			height: auto;
			width: auto;
		}
	}

	.wcc-nav-tab-manage-cookies {
		&>.wcc-nav-tab-content-container>.wcc-nav-tab-section>.wcc-nav-tab-section-header {
			padding: 15px 0 15px 0;
		}

		.wcc-nav-tab-button {
			padding: 15px 10px;
		}

		.wcc-nav-tab-content-container {
			border-bottom-left-radius: 15px;
			border-bottom-right-radius: 15px;
		}
	}

	.wcc-nav-tab-manage-cookies {
		.wcc-horizontal-tabs {
			.wcc-nav-tab-item {
				.wcc-nav-tab-button {
					.wcc-icon-base {
						margin-right: 8px;

						svg>path {
							fill: #6E7681;
						}
					}
				}

				&.active,
				&:hover {
					.wcc-nav-tab-button {
						color: #3157a6;
						font-weight: 600;

						.wcc-icon-base {
							margin-right: 8px;
						}

						&.active,
						&:hover {
							.wcc-icon-base>svg>path {
								fill: #1863dc;
							}
						}
					}
				}
			}
		}
	}
}

.wcc-app-rtl {

	input,
	.wcc-cookies-title,
	.wcc-category-description,
	.wcc-rich-text-editor * {
		direction: rtl;
		text-align: right;
	}
}

.wcc-input-error-alert {
	color: #dc3545;
	padding: 5px 0px;
}

.wcc-app-wrap .wcc-app-modal-cookies-categories .wcc-app-modal .wcc-app-modal-footer .wcc-app-modal-actions button {
	margin-left: 10px;
}

.wcc-section-cookies {
	.wcc-rich-text-editor-container {
		margin-top: -30px;
	}

	.wcc-nav-tab-item.active .wcc-nav-tab-has-subtitle .wcc-nav-tab-item-title::before {
		content: url("~@/assets/active-cookie.svg");
		margin-right: 10px;
		width: 20px;
		height: 20px;
		vertical-align: middle;
	}

	.wcc-nav-tab-item .wcc-nav-tab-has-subtitle .wcc-nav-tab-item-title::before {
		content: url("~@/assets/inactive-cookie.svg");
		margin-right: 10px;
		width: 20px;
		height: 20px;
		vertical-align: middle;
	}

	.wcc-nav-tab-item .wcc-nav-tab-has-subtitle .wcc-nav-tab-item-title {
		display: inline-block;
		/* Set the title to display as an inline-block element */
		vertical-align: middle;
		/* Align the title text vertically to the middle */
	}

	.wcc-app-modal .wcc-form-group,
	.wcc-app-modal .wcc-form-error {
		width: 100%;
		display: inline-flex;
		margin-bottom: 16px;
	}

	.wcc-app-modal .wcc-form-group .wcc-label,
	.wcc-app-modal .wcc-form-error .wcc-label {
		width: 30%;
	}
	.wcc-app-modal-cookies .wcc-app-modal .wcc-app-modal-body .wcc-form-group {
		margin-bottom: 4px;
	}
	.wcc-app-modal .wcc-form-error .wcc-input-error-alert,
	.wcc-app-modal .wcc-form-group .wcc-form-control {
		width: 50%;
	}
	.wcc-app-modal .wcc-form-group .wcc-rich-text-editor-container .wcc-rich-text-editor {
		width: 100%;
	}
	.wcc-app-modal .wcc-form-group .wcc-rich-text-editor-container {
		width: 70%;
	}
	.wcc-category-edit .wcc-app-modal-actions button:first-child {
		margin-right: 10px;
	}

	.wcc-urls-to-block-help {
		font-family: Inter;
		font-size: 12px;
		font-weight: 400;
		line-height: 14.52px;
		text-align: left;
		padding-top: 10px
	}
	.wcc-accordion-advanced {
		background: #fff;
		padding: 12px 20px 12px 16px;
		margin-bottom: 15px;
		border-radius: 3px;
	}
	.wcc-category-select {
		width: 50%;
		height: 40px;
		margin: 0;
		padding: 9px 14px;
		border: 1px solid #d1d5db;
		border-radius: 3px;
		font-size: 14px;
		font-weight: 400;
		transition: 0.1s ease-in-out;
		line-height: 1.6;
	}
}
</style>