<template>
	<div class="wcc-section wcc-section-policy wcc-zero--padding wcc-zero--margin">
		<div class="wcc-policy-page">
			<div class="wcc-loader-view" v-if="loading">
				<p class="wcc-loading-text">
				<loader />
				{{ $i18n.__("Fetching policy data", "webtoffee-cookie-consent") }}
				</p>
			</div>
			<div class="wcc-row" v-else>
				<div class="wcc-col-12" v-if="getPolicyPage() === '' || !policyPageExist">
					<default-page ref="DefaultPage"></default-page>
				</div>
				<div class="wcc-col-12" v-else>
					<edit-page ref="EditPage"></edit-page>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import defaultPage from "../components/DefaultContentPage.vue";
import editPage from "../components/EditPage.vue";
import { mapState } from "vuex";
import api from "@/modules/policies/helpers/api";
import Loader from "@/components/elements/Loader.vue";

export default {
	name: "Policies",
	components: {
		defaultPage,
		editPage,
		Loader
	},
	data() {
		return {
			defaultContent: false,
			policyPage: null,
			policyPageExist: false,
			loading: true, // Initialize loading to true
		};
	},
	methods: {
		getPolicyPage() {
			this.policyPage = this.info.privacy_policy.page;
			return this.policyPage;
		},
		async checkPageExist() {
			try {
				if (this.policyPage !== '') {
					this.policyPageExist = await api.pageExists(this.policyPage);
					return this.policyPageExist;
				} else {
					this.policyPageExist = false;
				}
			} catch (error) {
				console.error('API Error:', error);
				this.policyPageExist = false;
			} finally {
				this.loading = false; // Set loading to false after checking
			}
		},
		async initializePage() {
			this.getPolicyPage();
			await this.checkPageExist();
		}
	},
	computed: {
		...mapState("settings", ["info"]),
	},
	watch: {
		info: {
			immediate: true,
			handler(newValue) {
				if (newValue) {
					this.initializePage();
				}
			}
		}
	}
}
</script>
