import { Rpc } from '@entityseven/rage-fw-rpc';

const rpc = new Rpc();
let browser: BrowserMp | null = null;

// Initialize CEF via standard RAGE MP event to bootstrap the browser for RPC
mp.events.add('client:initCef', (cefUrl: string, isDebug: boolean) => {
    if (isDebug) {
        mp.gui.chat.push(`[Client] Initializing CEF: ${cefUrl}`);
    }

    if (browser) {
        browser.destroy();
        browser = null;
    }
    
    browser = mp.browsers.new(cefUrl);
    rpc.browser = browser; // Link immediately
    
    mp.gui.chat.push(`[Client] Browser created and linked to RPC`);
    mp.gui.cursor.show(true, true);
});

// Fallback: auto-link any newly created browser if current is null
mp.events.add('browserCreated', (b: BrowserMp) => {
    if (!rpc.browser) {
        rpc.browser = b;
        mp.gui.chat.push(`[Client] RPC Browser auto-linked via browserCreated`);
    }
    mp.gui.chat.show(false);
});

// Custom Chat Handlers via RPC
rpc.register('chat:toggleInput', (state: boolean) => {
    // This allows you to freeze other inputs while typing if you build a UI manager later
});

rpc.register('chat:sendMessage', (msg: string) => {
    // Send the message natively to the server via our RPC
    rpc.callServer('server:chat:receive', [msg]);
});

// Listen for structured chat broadcasts from the server (Player chat)
rpc.register('chat:push:custom', (chatData: any) => {
    rpc.callBrowser('chat:addMessage', [chatData]);
});

// Listen for incoming native string messages from the server (System prints/announcements)
mp.events.add('chat:push', (text: string) => {
    rpc.callBrowser('chat:addMessage', [{ type: 'system', text: text }]);
});

export { rpc };
