<template>
	<div
		v-if="openMessageBox"
		class="fixed inset-0 bg-gray-600 overflow-y-auto h-full w-full z-80 dark:bg-gray-900 opacity-97"
	>
	<message-box-view
		:messageType="message_type"
		:openMessageBox="openMessageBox"
		:show_input="show_input"
		:input_placeholder="input_placeholder"
		:input_btns="input_btns"
		:select_ops="select_ops"
		:data_url_encoded="data_url_encoded"
		:inpType="oneInputType"
		@onInput="onInput"
		@onMessageBox="onMessageBox"
		@onLoadModel="onLoadModel"
	/>
	</div>
	<div v-if="show_content" class="font-sans antialiased h-screen">
		<div class="container mx-auto max-w-screen-2xl main-container">
			<nav-menu
			  class="bg-light-300 dark:bg-gray-900"
				:position="NavPosition.header"
				:openMessageBox="openMessageBox"
				:fixMenu="fixMenu"
				:show_infopanel="show_infopanel"
				:dataAuth="false"
				:useInfoPanel="false"
				:useLogin="true"
				:showinfo="show_info"
				:authinfo="auth_info"
				:needSave="needSave"
				:prefix="prefix"
				@onNavMenu="onNavMenu"
			/>
			<main
				id="cv-wrapper"
				class="rounded flex flex-col sm:flex-row-reverse shadow-2xl"
				:class="{ 'mt-11': fixMenu }"
			>
				<div
					v-if="show_infopanel"
					id="sidebar"
					class="rounded-r w-full lg:w-80 sm:max-w-sm p-8 border-l-1 border-indigo-200 bg-gradient-to-b from-indigo-300 via-indigo-200 to-indigo-100 dark:bg-gray-600 dark:from-indigo-500 dark:via-indigo-400 dark:to-indigo-800"
				>
				</div>
				<div class="content w-full p-5">
					<div class="prose flex lg:items-center lg:justify-center p-4 border-1 rounded-md border-gray-300 dark:border-gray-600 lg:w-full sm:w-full sm:max-w-sm shadow-xl bg-light-300 dark:bg-gray-900">
						<img v-if="isDark"
							class="m-auto m-5"
							width="500"
							:src="`${assetsPath}/images/genadmin_b.svg`"
						/>
						<img v-else
							class="m-auto mt-5"
							width="500"
							:src="`${assetsPath}/images/genadmin_w.svg`"
						/>	
					</div>
					<div class="prose my-4">
					   CVgen admin ...
					</div>
				</div>
				<hr class="hr-sep" />
			</main>
		</div>
	</div>
	<div v-else class="text-center m-auto">
		<img v-if="isDark"
			class="m-auto mt-5"
			width="250"
			:src="`${assetsPath}/images/genadmin_b.svg`"
		/>
		<img v-else
			class="m-auto mt-5"
			width="250"
			:src="`${assetsPath}/images/genadmin_w.svg`"
		/>
		<h2 class="mt-8 text-2xl text-gray-700 dark:text-gray-400">{{ t('message.loading', 'Loading') }}...</h2>
		<h3> </h3>
		<h4>{{useState().connection.value.state}}</h4>
	</div>
	<div
		v-if="show_content" 
		class="flex-1 lg:mx-11 sm:mx-0 -mt-10 text-center text-sm text-gray-600 border-gray-300 border-1 border-b-0 rounded-t-lg"
	>
		<nav-menu
			class="shadow-xl bg-light-300 dark:bg-gray-900"
			:position="NavPosition.footer"
			:fixMenu="fixMenu"
			:show_infopanel="show_infopanel"
			:dataAuth="false"
			:useInfoPanel="false"
			:useLogin="true"
			:showinfo="show_info"
			:authinfo="auth_info"
			:needSave="needSave"
			prefix="sec"
			:openMessageBox="openMessageBox"
			@onNavMenu="onNavMenu"
		/>
	</div>
</template>
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
const i18n = useI18n()
const { t } = useI18n()
const router = useRouter()

import MessageBoxView from '~/components/MessageBoxView.vue'
import NavMenu from '@/NavMenu.vue'
import { isDark } from '~/composables'
// import Modal from '@/Modal.vue'
import useState from '~/hooks/useState'
import { parseJwt,checkUserAuth } from '~/hooks/utilsAuth'
import { send_data,show_message} from '~/hooks/utils'
import { MessageType} from '~/typs'
import { MessageBoxType, NavPosition, InputBtnsType, ModelType, ShowInfoType} from '~/typs/cv'
import { load_currentRoute } from '~/hooks/loads'
import { track_action } from '~/hooks/tracking'

const prefix = 'home'

const assetsPath = useState().ASSETS_PATH
// const routeKy = router.currentRoute.value.params.ky || router.currentRoute.value.query.k || ''
const message_type = ref(MessageBoxType.NotSet)
const fixMenu = ref(false)
const show_content = ref(true)
const show_infopanel = ref(false)
const openMessageBox = ref(false)
const needSave = ref(false)
const show_input = ref(false)
const data_url_encoded = ref('')
const input_btns = ref([] as InputBtnsType[])
const input_placeholder = ref('')
const oneInputType = ref('')

const onInput = (btn: InputBtnsType) => {
	switch (btn.id) {
		case 'ok':
			break
		case 'cancel':
			break
	}
	show_input.value = false
}
const select_ops = ref({} as ModelType)
const show_info = ref({} as ShowInfoType)
const auth_info = useState().authinfo

const refresh = () => {
	show_content.value = false
	setTimeout(() => show_content.value = true, 1)
}

const onNavMenu = (item: { src: string, target: string }) => {
	switch (item.src) {
		case 'locale':
	    track_action(null, { ref: 'locale',text: i18n.locale.value})
			refresh()
			break
		case 'infopanel':
	    track_action(null, { ref: 'onNavMenu',text: 'item.src'})
			show_infopanel.value = !show_infopanel.value
			break
		case 'fixmenu':
	    track_action(null, { ref: 'onNavMenu',text: 'item.src'})
			fixMenu.value = !fixMenu.value
			break
		case 'endinput':
			show_input.value = false
			break
		case 'select':
	    track_action(null, { ref: 'onNavMenu',text: 'item.src'})
			message_type.value = MessageBoxType.Select
			openMessageBox.value = true
			break
		case 'save':
	    track_action(null, { ref: 'onNavMenu',text: 'item.src'})
			input_placeholder.value = `${t('name', 'Name')} o 'data'`
			show_input.value = true
			message_type.value = MessageBoxType.Save
			data_url_encoded.value = ''
			openMessageBox.value = true
			break
	    track_action(null, { ref: 'onNavMenu',text: 'item.src'})
			useState().authinfo.value.editable = !useState().authinfo.value.editable
			const state = useState().authinfo.value.editable ? 'on' : 'off'
			const msgTyp = state === 'on' ? MessageType.Warning :  MessageType.Info
      show_message(msgTyp, `${t('saveload.editMode','Edit Mode')} ${t('cv.'+state,'')}`)
			break
		case 'viewchange':
	    track_action(null, { ref: 'onNavMenu',text: 'item.src'})
			useState().authinfo.value.viewchange = !useState().authinfo.value.viewchange
			break
		case 'goto':
			const dom_id = document.getElementById(item.target)
			if (dom_id) {
	      track_action(null, { ref: 'gotp',text: item.target})
				dom_id.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' })
				setTimeout(() => window.scrollBy(0, -40), 4000)
			}
			break
	}
}
const saveData = async(mode: string,val: string) => {
	const showinfo: ShowInfoType[] = useState().cvdata.value.showinfo 
  message_type.value = MessageBoxType.Save
	const payload = parseJwt(localStorage.getItem(useState().AUTHKEY.value))
	const cv: any = {
		u: payload.id ? payload.id : '',
		data: {}
	} 
	cv.data[val]={}
	Object.keys(useState().datalang.value).forEach(lng => 
	  cv.data[val][lng] = useState().datalang.value[lng]
	)
	cv.data[val].main = useState().cvdata.value 
	showinfo.forEach((it,idx) => {
		if (it.ky === useState().showinfo.value.ky) {
		  cv.data[val].main[idx] = useState().showinfo.value	
		}
	})
	const url = useState().CONFURLS.value.send || ''
	if (mode == 'send' && url !== '') {
		onMessageBox({src: 'done', val: ''})
		const res = await send_data(url, cv, true, true, () => {
	    track_action(null, { ref: 'saveData',text: `${url} -> ${val}`})
		  show_message(MessageType.Success, `${t('saveload.dataSaved','Data saved')}`,2000,() => { 
		  })
		})
		console.log(res)
	} else {
	  track_action(null, { ref: 'saveData',text: `local_json -> ${val}`})
		show_message(MessageType.Warning, `${t('saveload.saveData','Save data')}`,2000,() => { 
		  data_url_encoded.value = `text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(cv))}`
		})
	}
}
const onMessageBox = (item: { src: string, val: string }) => {
	switch (item.src) {
		case 'savedata':
			show_input.value = false
			saveData('local', item.val)
			break
		case 'sendata':
			show_input.value = false
			saveData('send', item.val)
			break
		case 'oneinput':
			const r = async() => {
				if (await checkUserAuth(item.val)) {
					oneInputType.value='text'
			    openMessageBox.value = false
				  if (!await load_currentRoute(router.currentRoute.value)) {
					   show_message(MessageType.Error, `${t('saveload.loaderror','Load error')}`,2000)
					}
				} else {
					show_message(MessageType.Error, `${t('saveload.autherror','Auth error')}`,2000)
				}
			}
			r()
		  break
		case 'endinput':
			show_input.value = false
			break
		case 'done':
			openMessageBox.value = false
			break
		case 'open':
			openMessageBox.value = true
			break
	}
}
// const onHome = () => {
// 	const dom_body = document.getElementsByTagName('body')[0]
// 	if (dom_body) {
// 		dom_body.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' })
// 	}
// }
const onLoadModel = (model: { id: string}) => {
	// if (useState().selectOps.value[model.id]) {
	// 	load_data_model(model.id, useState().DATA_URL.value, routeKy as string,true,() => {
	//     show_content.value = false
	// 	  show_message(MessageType.Success, `${t('saveload.dataLoaded','Data loaded')}`,2000,() => { 
	//       show_content.value = true
	// 		})
	// 	})
  // }
}
onBeforeMount(async() => {
	useState().dataSections.value = ['Config','Tracking','Users']
	// if (!useState().allowView.value && useState().userID.value === "?") {
	// 	oneInputType.value='password'
	// 	message_type.value=MessageBoxType.OneInput
	// 	openMessageBox.value=true
	// 	show_input.value=false
	// 	input_placeholder.value='Enter password'
	// }
})
</script>