import './bootstrap';
import * as bootstrap from 'bootstrap';
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Toaster, sileo } from 'sileo';

window.bootstrap = bootstrap;
window.sileo = sileo;

const mountSileoToaster = () => {
    const host = document.getElementById('sileo-root');

    if (!host) {
        return;
    }

    const root = createRoot(host);
    root.render(
        React.createElement(Toaster, {
            position: 'top-center',
            offset: 20,
            theme: 'light',
            options: {
                roundness: 14,
                duration: 6000,
            },
        }),
    );

    const body = document.body;
    const flashStatus = body?.dataset.flashStatus?.trim();
    const flashError = body?.dataset.flashError?.trim();

    window.requestAnimationFrame(() => {
        if (flashStatus) {
            sileo.success({
                title: flashStatus,
            });
        }

        if (flashError) {
            sileo.error({
                title: flashError,
            });
        }
    });
};

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', mountSileoToaster, { once: true });
} else {
    mountSileoToaster();
}
