// bindings.js : tous les listeners DOM du menu et du lobby

import { send } from './network.js';


export function bindEvents(callbacks) {
    const $ = id => document.getElementById(id);

    // pseudo
    $('username-btn').addEventListener('click', () => {
        const v = $('username-input').value.trim();
        if (v) {
            callbacks.setUsername(v);
            send('set_username', { username: v });
        }
    });

    $('username-input').addEventListener('keydown', e => {
        if (e.key === 'Enter') $('username-btn').click();
    });

    // creer une partie
    $('create-game-btn').addEventListener('click', () => send('create_lobby'));

    // rejoindre une partie
    $('join-game-btn').addEventListener('click', () => {
        $('home-buttons').classList.add('hidden');
        $('join-row').classList.remove('hidden');
        $('code-input').focus();
    });

    $('join-confirm-btn').addEventListener('click', () => {
        const code = $('code-input').value.trim().toUpperCase();
        if (code) send('join_lobby', { code });
    });

    $('code-input').addEventListener('keydown', e => {
        if (e.key === 'Enter') $('join-confirm-btn').click();
    });

    $('join-cancel-btn').addEventListener('click', () => {
        $('join-row').classList.add('hidden');
        $('home-buttons').classList.remove('hidden');
    });

    // retour au menu
    $('lobby-back-btn').addEventListener('click', () => {
        send('leave_lobby');
        callbacks.switchToHome();
    });

    // selection de classe
    document.querySelectorAll('.class-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            document.querySelectorAll('.class-btn').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            send('select_class', { class: btn.dataset.class });
            $('ready-btn').disabled = false;
        });
    });

    // pret
    $('ready-btn').addEventListener('click', () => {
        send('ready');
        $('ready-btn').disabled = true;
    });

    // demarrer (host)
    $('start-btn').addEventListener('click', () => send('start_game'));

    // plein ecran
    $('fullscreen-btn')?.addEventListener('click', () => {
        if (!document.fullscreenElement) {
            document.documentElement.requestFullscreen();
        } else {
            document.exitFullscreen();
        }
    });

    // settings (todo)
    $('settings-btn').addEventListener('click', () => {
        callbacks.notify('Settings coming soon');
    });

    // leaderboard
    $('leaderboard-btn').addEventListener('click', () => callbacks.showLeaderboard?.());
    $('lb-back-btn').addEventListener('click', () => callbacks.hideLeaderboard?.());
}
