<template>
	<div class="simplestats-app">
		<HeaderSection />
		<div class="simplestats-app-container">
			<RouterView />
		</div>
	</div>
</template>

<script setup>
	import { watch, onMounted } from 'vue';
	import { useRoute, RouterView } from 'vue-router';
	import { useStore } from '@/dashboard/store.js';
	import HeaderSection from './components/HeaderSection.vue';

	const dashboardLink = document.querySelector('#toplevel_page_simplestats ul.wp-submenu [href*="simplestats#/dashboard"]');
	const aboutUsLink   = document.querySelector('#toplevel_page_simplestats ul.wp-submenu [href*="simplestats#/about-us"]');
	const settingsLink  = document.querySelector('#toplevel_page_simplestats ul.wp-submenu [href*="simplestats#/settings"]');

	const submenuLinks = [ dashboardLink, aboutUsLink, settingsLink ];

	const store = useStore();
	const route = useRoute();

	onMounted(() => {
		store.fetchNotifications();
		handleRouteChange();
	});

	watch(
		() => route.path,
		() => {
			handleRouteChange();
		}
	);

	function handleRouteChange() {
		removeClasses();

		const byRouteName = {
			'dashboard': dashboardLink,
			'about-us':  aboutUsLink,
			'settings':  settingsLink,
		};

		const link = byRouteName[ route.name ];

		if ( link ) {
			link.parentElement.classList.add( 'current' );
		}
	}

	function removeClasses() {
		submenuLinks.forEach( ( link ) => {
			if ( link ) {
				link.parentElement.classList.remove( 'current' );
			}
		} );
	}
</script>
