import {createRoot} from "@wordpress/element";
import {createHooks} from "@wordpress/hooks";
import ChatbotsGroups from "../components/chatbot-groups";
import {ensureNonce} from "../helpers/nonce-manager";

if (!LimbChatbot?.Hooks) {
    LimbChatbot.Hooks = createHooks();
}

/**
 * Initialize the chatbot after nonce is ready
 */
const initChatbot = () => {
    const chatbotEl = document.getElementById('lbaic-chatbot');
    if (chatbotEl) {
        // Render chatbot(s)
        const root = createRoot(chatbotEl);
        root.render(<ChatbotsGroups/>);
    }
};

window.addEventListener('DOMContentLoaded', async () => {
    // Ensure LimbChatbot.rest exists
    if (!LimbChatbot?.rest) {
        console.error('Failed to initialize chatbot: LimbChatbot.rest is not defined');
        return;
    }

    // Get the chatbot element to check for nonce attributes
    const chatbotEl = document.getElementById('lbaic-chatbot');

    // Ensure nonce is available before initializing chatbot
    const nonceReady = await ensureNonce(chatbotEl);

    if (nonceReady) {
        // Initialize chatbot only after nonce is valid
        initChatbot();
    } else {
        console.error('Failed to initialize chatbot: Could not get valid nonce');
    }
});
