import store from '@/common/store.js'

import {

	buildNoviceGuidanceSteps,

	isEnterpriseHomeGuideDone,

	NOVICE_GUIDANCE_BASE_CONFIG,

	resolveGuideUserKey,

	setEnterpriseHomeGuideDone

} from '@/utils/home-guide.js'



export default {

	data() {

		return {

			homeGuideBaseConfig: NOVICE_GUIDANCE_BASE_CONFIG,

			homeGuideSteps: buildNoviceGuidanceSteps()

		}

	},

	methods: {

		getEnterpriseHomeContext() {

			const ref = this.$refs.enterpriseHome

			if (Array.isArray(ref)) return ref[0] || null

			return ref || null

		},

		buildGuideRuntimeConfig() {

			const context = this.getEnterpriseHomeContext()

			const steps = buildNoviceGuidanceSteps().map((step) => ({

				...step,

				context: () => context

			}))

			return { steps, baseConfig: this.homeGuideBaseConfig }

		},

		onHomeGuideEnded() {

			const state = store.getState()

			setEnterpriseHomeGuideDone(resolveGuideUserKey(state.user, state.enterprise))

		},

		startHomeGuide() {

			const guide = this.$refs.noviceGuidance

			const context = this.getEnterpriseHomeContext()

			if (!guide || !context || typeof guide.start !== 'function') return false



			const { steps, baseConfig } = this.buildGuideRuntimeConfig()

			if (typeof guide.setConfig === 'function') {

				guide.setConfig(steps, baseConfig)

			}



			setTimeout(() => guide.start(), 80)

			return true

		},

		scheduleHomeGuide() {

			if (this.viewRole !== 'enterprise') return

			const state = store.getState()

			const guideUserKey = resolveGuideUserKey(state.user, state.enterprise)

			if (isEnterpriseHomeGuideDone(guideUserKey)) return



			const tryStart = (attempt = 0) => {

				if (this.viewRole !== 'enterprise' || !this.ready) return

				if (!this.startHomeGuide() && attempt < 15) {

					setTimeout(() => tryStart(attempt + 1), 150)

				}

			}



			this.$nextTick(() => {

				setTimeout(() => tryStart(), 300)

			})

		}

	}

}

