import { createApp } from 'vue';
import DashboardPage from './pages/DashboardPage.vue';
import HrPage from './pages/HrPage.vue';

const VUE_PAGE_REGISTRY = {
    dashboard: DashboardPage,
    hr: HrPage,
};

const parseVueProps = (mountNode) => {
    const scriptNode = mountNode.querySelector('script[data-vue-props]');
    if (!(scriptNode instanceof HTMLScriptElement)) {
        return {};
    }

    const raw = scriptNode.textContent ?? '';
    if (raw.trim() === '') {
        return {};
    }

    try {
        return JSON.parse(raw);
    } catch {
        return {};
    }
};

export const mountVueApps = (scope = document) => {
    const root = scope instanceof Document || scope instanceof Element ? scope : document;
    const mountNodes = root.querySelectorAll('[data-vue-app]:not([data-vue-mounted="1"])');

    mountNodes.forEach((mountNode) => {
        if (!(mountNode instanceof HTMLElement)) {
            return;
        }

        const appKey = String(mountNode.dataset.vueApp || '').trim().toLowerCase();
        const PageComponent = VUE_PAGE_REGISTRY[appKey];

        if (!PageComponent) {
            return;
        }

        const payload = parseVueProps(mountNode);
        mountNode.dataset.vueMounted = '1';

        const app = createApp(PageComponent, {
            payload,
        });

        app.mount(mountNode);
    });
};
