import './bootstrap';
import '../css/app.css';

import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/vue3';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { ZiggyVue } from '../../vendor/tightenco/ziggy';

/* Font Awesome imports */
import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import {
    faPrint,
    faMagicWandSparkles,
    faXmark,
    faArrowLeft,
    faArrowRight,
    faSun,
    faMoon,
    faArrowsRotate,
    faMinus,
    faPlus,
    faBars,
    faChevronDown,
    faDownload,
} from '@fortawesome/free-solid-svg-icons';

// Add icons to the library
library.add(
    faPrint,
    faMagicWandSparkles,
    faXmark,
    faArrowLeft,
    faArrowRight,
    faSun,
    faMoon,
    faArrowsRotate,
    faMinus,
    faPlus,
    faBars,
    faChevronDown,
    faDownload,
);

const appName = import.meta.env.VITE_APP_NAME || 'Laravel';

const resolveTranslation = (source, path) => {
    if (!source || !path) {
        return undefined;
    }

    return path.split('.').reduce((acc, segment) => {
        if (acc && Object.prototype.hasOwnProperty.call(acc, segment)) {
            return acc[segment];
        }

        return undefined;
    }, source);
};

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
    setup({ el, App, props, plugin }) {
        console.log('Inertia Page Props (app.js):', props.initialPage.props);
        return createApp({ render: () => h(App, props) })
            .use(plugin)
            .use(ZiggyVue)
            .component('font-awesome-icon', FontAwesomeIcon) // Register Font Awesome component
            .mixin({
                methods: {
                    __: function (key, replace = {}) {
                        const sources = [
                            this?.$page?.props?.translations,
                            props.initialPage.props.translations,
                        ];

                        let translation;

                        for (const source of sources) {
                            const value = resolveTranslation(source, key);
                            if (value !== undefined) {
                                translation = value;
                                break;
                            }
                        }

                        let output = translation ?? key;

                        Object.entries(replace).forEach(([placeholder, val]) => {
                            output = output.replace(`:${placeholder}`, val);
                        });

                        return output;
                    },
                },
            })
            .mount(el);
    },
    progress: {
        color: '#4B5563',
    },
});
