// Main application logic for Kafaball v2
// New flow: Entry → Browser → Lobby → Game (with in-game lobby overlay)
// Admin-only team management with drag-and-drop

(function () {
    // ============ DOM Elements ============
    const screens = {
        entry: document.getElementById('entry-screen'),
        browser: document.getElementById('browser-screen'),
        lobby: document.getElementById('lobby-screen'),
        game: document.getElementById('game-screen')
    };

    const el = {
        nicknameInput: document.getElementById('nickname-input'),
        enterGameBtn: document.getElementById('enter-game-btn'),
        roomList: document.getElementById('room-list'),
        roomNameInput: document.getElementById('room-name-input'),
        roomMaxPlayers: document.getElementById('room-max-players'),
        roomPassword: document.getElementById('room-password'),
        createRoomBtn: document.getElementById('create-room-btn'),
        passwordModal: document.getElementById('password-modal'),
        joinPasswordInput: document.getElementById('join-password-input'),
        passwordJoinBtn: document.getElementById('password-join-btn'),
        passwordCancelBtn: document.getElementById('password-cancel-btn'),
        leaveRoomBtn: document.getElementById('leave-room-btn'),
        lobbyRoomName: document.getElementById('lobby-room-name'),
        startGameBtn: document.getElementById('start-game-btn'),
        stopGameBtn: document.getElementById('stop-game-btn'),
        redPlayers: document.getElementById('red-players'),
        specPlayers: document.getElementById('spec-players'),
        bluePlayers: document.getElementById('blue-players'),
        chatMessages: document.getElementById('chat-messages'),
        chatInput: document.getElementById('chat-input'),
        chatSendBtn: document.getElementById('chat-send-btn'),
        canvas: document.getElementById('game-canvas'),
        hudRedScore: document.getElementById('hud-red-score'),
        hudBlueScore: document.getElementById('hud-blue-score'),
        hudTime: document.getElementById('hud-time'),
        hudState: document.getElementById('hud-state'),
        gameChatMessages: document.getElementById('game-chat-messages'),
        gameChatInput: document.getElementById('game-chat-input'),
        toggleLobbyBtn: document.getElementById('toggle-lobby-btn'),
        ingameLobbyOverlay: document.getElementById('ingame-lobby-overlay'),
        closeIngameLobby: document.getElementById('close-ingame-lobby'),
        ingameRedPlayers: document.getElementById('ingame-red-players'),
        ingameSpecPlayers: document.getElementById('ingame-spec-players'),
        ingameBluePlayers: document.getElementById('ingame-blue-players'),
        ingameStopGameBtn: document.getElementById('ingame-stop-game-btn'),
        ingameLeaveBtn: document.getElementById('ingame-leave-btn'),
    };

    // ============ State ============
    let currentScreen = 'entry';
    let myPlayerId = null;
    let currentRoomId = null;
    let currentRoomState = null;
    let isAdmin = false;
    let pendingJoinRoomId = null;
    let renderer = null;
    let gameActive = false;
    let draggedPlayerId = null;

    // ============ Audio Assets ============
    const sounds = {
        kick: new Audio('audio/kick.mp3'),
        goal: new Audio('audio/goal.mp3')
    };
    sounds.kick.volume = 0.5;
    sounds.goal.volume = 0.6;

    // ============ Screen Management ============
    function showScreen(name) {
        for (const [key, scr] of Object.entries(screens)) {
            scr.classList.toggle('active', key === name);
        }
        currentScreen = name;

        if (name === 'game') {
            if (!renderer) {
                renderer = new Renderer(el.canvas);
            }
            renderer.resize();
            renderer.start();
            inputHandler.enable();
        } else {
            if (renderer) renderer.stop();
            inputHandler.disable();
        }
    }

    // ============ Network Handlers ============
    network.on('welcome', (data) => {
        myPlayerId = data.playerId;
    });

    network.on('room_list', (data) => {
        renderRoomList(data);
    });

    network.on('room_joined', (data) => {
        currentRoomId = data.roomId;
        showScreen('lobby');
    });

    network.on('room_state', (data) => {
        currentRoomState = data;
        isAdmin = data.adminId === myPlayerId;
        renderLobby(data);
        renderIngameLobby(data);

        // Switch to game if running and we're still in lobby
        if (data.state !== 'waiting' && currentScreen === 'lobby') {
            showScreen('game');
            gameActive = true;
        }
    });

    network.on('game_state', (data) => {
        // Decode compact format
        const decoded = {
            state: data.s || data.state,
            score: data.sc || data.score,
            gameTime: data.gt !== undefined ? data.gt : data.gameTime,
            timeLimit: data.tl !== undefined ? data.tl : data.timeLimit,
            discs: (data.d || data.discs || []).map(disc => {
                if (disc.b !== undefined) {
                    return {
                        x: disc.x / 100,
                        y: disc.y / 100,
                        radius: disc.r,
                        color: disc.c,
                        isBall: disc.b === 1,
                        team: disc.t === 1 ? 'red' : disc.t === 2 ? 'blue' : null,
                        isKicking: disc.k === 1
                    };
                }
                return disc;
            }),
            playerMap: {},
            lastGoalTeam: data.lg || data.lastGoalTeam
        };
        // Decode compact playerMap
        const pm = data.pm || data.playerMap || {};
        for (const key of Object.keys(pm)) {
            const p = pm[key];
            decoded.playerMap[key] = {
                name: p.n || p.name,
                team: p.t || p.team,
                id: p.id
            };
        }

        if (currentScreen !== 'game' && decoded.state !== 'waiting') {
            showScreen('game');
            gameActive = true;
        }
        if (renderer) {
            renderer.updateState(decoded);
        }
        // Update HUD
        el.hudRedScore.textContent = decoded.score.red;
        el.hudBlueScore.textContent = decoded.score.blue;
        const totalSeconds = Math.floor(decoded.gameTime / 60);
        const minutes = Math.floor(totalSeconds / 60);
        const seconds = totalSeconds % 60;
        el.hudTime.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
        switch (decoded.state) {
            case 'kickoff': el.hudState.textContent = 'BAŞLANGIÇ VURUŞU'; break;
            case 'goal': el.hudState.textContent = 'GOL!'; break;
            case 'ended': el.hudState.textContent = 'MAÇ SONU'; break;
            default: el.hudState.textContent = '';
        }
    });

    network.on('goal', (data) => {
        playSound('goal');
        showGoalAnimation(data.team);
    });

    network.on('game_start', () => {
        showScreen('game');
        gameActive = true;
    });

    network.on('game_end', (data) => {
        gameActive = false;
        showMatchEndAnimation(data);
        setTimeout(() => {
            if (currentRoomId) {
                showScreen('lobby');
                el.ingameLobbyOverlay.classList.remove('active');
            }
        }, 5000);
    });

    network.on('chat_msg', (data) => {
        appendChatMessage(data);
    });

    network.on('kick', () => {
        playSound('kick');
    });

    network.on('kicked', () => {
        currentRoomId = null;
        currentRoomState = null;
        showScreen('browser');
        network.getRooms();
        alert('Odadan atıldınız!');
    });

    network.on('error', (data) => {
        alert(data.message);
    });

    network.on('disconnected', () => {
        if (currentScreen !== 'entry') {
            showScreen('entry');
            currentRoomId = null;
            currentRoomState = null;
        }
    });

    // ============ Room List ============
    function renderRoomList(rooms) {
        if (!rooms || rooms.length === 0) {
            el.roomList.innerHTML = '<div class="no-rooms">Henüz açık oda yok.</div>';
            return;
        }
        el.roomList.innerHTML = rooms.map(room => {
            const stateClass = room.state === 'waiting' ? 'waiting' : 'playing';
            const stateText = room.state === 'waiting' ? 'Bekliyor' : 'Oyunda';
            const lockIcon = room.hasPassword ? '<span class="room-lock-icon">🔒</span>' : '';
            return `
        <div class="room-item" data-room-id="${room.roomId}" data-has-password="${room.hasPassword}">
          <div class="room-info">
            <div class="room-name">${esc(room.roomName)}${lockIcon}</div>
            <div class="room-meta">
              <span class="room-players">👥 ${room.playerCount}/${room.maxPlayers}</span>
              <span class="room-state-badge ${stateClass}">${stateText}</span>
            </div>
          </div>
          <div class="room-join-section">
            <button class="btn btn-primary btn-small join-room-btn">Katıl</button>
          </div>
        </div>`;
        }).join('');

        el.roomList.querySelectorAll('.join-room-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                const item = btn.closest('.room-item');
                const roomId = item.dataset.roomId;
                const hasPw = item.dataset.hasPassword === 'true';
                if (hasPw) {
                    pendingJoinRoomId = roomId;
                    el.passwordModal.classList.add('active');
                    el.joinPasswordInput.focus();
                } else {
                    network.joinRoom(roomId);
                }
            });
        });
    }

    // ============ Lobby Rendering ============
    function renderLobby(data) {
        el.lobbyRoomName.textContent = data.roomName;
        el.startGameBtn.style.display = (isAdmin && data.state === 'waiting') ? 'inline-flex' : 'none';
        el.stopGameBtn.style.display = (isAdmin && data.state !== 'waiting') ? 'inline-flex' : 'none';

        const redP = data.players.filter(p => p.team === 'red');
        const blueP = data.players.filter(p => p.team === 'blue');
        const specP = data.players.filter(p => p.team === 'spectator');

        el.redPlayers.innerHTML = redP.map(p => renderPlayerItem(p, false)).join('');
        el.bluePlayers.innerHTML = blueP.map(p => renderPlayerItem(p, false)).join('');
        el.specPlayers.innerHTML = specP.map(p => renderPlayerItem(p, false)).join('');

        // Setup drag-and-drop for admin
        if (isAdmin) {
            setupDragDrop('lobby');
            setupKickButtons();
        }
    }

    // ============ In-Game Lobby Overlay ============
    function renderIngameLobby(data) {
        if (!data) return;
        el.ingameStopGameBtn.style.display = (isAdmin && data.state !== 'waiting') ? 'inline-flex' : 'none';

        const redP = data.players.filter(p => p.team === 'red');
        const blueP = data.players.filter(p => p.team === 'blue');
        const specP = data.players.filter(p => p.team === 'spectator');

        el.ingameRedPlayers.innerHTML = redP.map(p => renderPlayerItem(p, true)).join('');
        el.ingameBluePlayers.innerHTML = blueP.map(p => renderPlayerItem(p, true)).join('');
        el.ingameSpecPlayers.innerHTML = specP.map(p => renderPlayerItem(p, true)).join('');

        if (isAdmin) {
            setupDragDrop('ingame');
            setupKickButtons();
        }
    }

    function renderPlayerItem(player, isIngame) {
        const adminBadge = player.isAdmin ? '<span class="admin-badge">ADMIN</span>' : '';
        const isMe = player.id === myPlayerId;
        const meTag = isMe ? ' (sen)' : '';
        const draggableClass = isAdmin ? ' draggable' : '';
        const prefix = isIngame ? 'ingame-' : '';
        let actions = '';
        if (isAdmin && !isMe) {
            actions = `<div class="player-actions">
        <button class="btn btn-small btn-secondary admin-kick-btn" data-player-id="${player.id}" title="At">✕</button>
        <button class="btn btn-small btn-admin-give admin-give-btn" data-player-id="${player.id}" title="Admin Ver">👑</button>
      </div>`;
        }
        return `
      <div class="player-item${draggableClass}" draggable="${isAdmin}" data-player-id="${player.id}" data-prefix="${prefix}">
        <span class="player-name">${adminBadge} ${esc(player.name)}${meTag}</span>
        ${actions}
      </div>`;
    }

    // ============ Drag and Drop ============
    function setupDragDrop(context) {
        const prefix = context === 'ingame' ? 'ingame-' : '';
        const dropZones = context === 'ingame'
            ? [document.getElementById('ingame-drop-red'), document.getElementById('ingame-drop-spec'), document.getElementById('ingame-drop-blue')]
            : [document.getElementById('drop-red'), document.getElementById('drop-spec'), document.getElementById('drop-blue')];

        // Make player items draggable
        const items = (context === 'ingame')
            ? document.querySelectorAll('#ingame-red-players .player-item, #ingame-spec-players .player-item, #ingame-blue-players .player-item')
            : document.querySelectorAll('#red-players .player-item, #spec-players .player-item, #blue-players .player-item');

        items.forEach(item => {
            item.addEventListener('dragstart', (e) => {
                if (!isAdmin) { e.preventDefault(); return; }
                draggedPlayerId = item.dataset.playerId;
                item.classList.add('dragging');
                e.dataTransfer.effectAllowed = 'move';
                e.dataTransfer.setData('text/plain', draggedPlayerId);
            });
            item.addEventListener('dragend', () => {
                item.classList.remove('dragging');
                draggedPlayerId = null;
                dropZones.forEach(z => z && z.classList.remove('drag-over'));
            });
        });

        // Setup drop zones
        dropZones.forEach(zone => {
            if (!zone) return;
            zone.addEventListener('dragover', (e) => {
                if (!isAdmin) return;
                e.preventDefault();
                e.dataTransfer.dropEffect = 'move';
                zone.classList.add('drag-over');
            });
            zone.addEventListener('dragleave', () => {
                zone.classList.remove('drag-over');
            });
            zone.addEventListener('drop', (e) => {
                e.preventDefault();
                zone.classList.remove('drag-over');
                if (!isAdmin) return;
                const pid = e.dataTransfer.getData('text/plain') || draggedPlayerId;
                const team = zone.dataset.team;
                if (pid && team) {
                    network.adminSetTeam(pid, team);
                }
            });
        });
    }

    function setupKickButtons() {
        document.querySelectorAll('.admin-kick-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                const pid = btn.dataset.playerId;
                if (confirm('Bu oyuncuyu atmak istediğinize emin misiniz?')) {
                    network.kickPlayer(pid);
                }
            });
        });
        document.querySelectorAll('.admin-give-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                const pid = btn.dataset.playerId;
                if (confirm('Bu oyuncuya adminlik vermek istediğinize emin misiniz?')) {
                    network.giveAdmin(pid);
                }
            });
        });
    }

    // ============ Chat ============
    function appendChatMessage(data) {
        let senderClass = data.senderTeam || 'spectator';
        if (data.senderName === 'Sistem') senderClass = 'system';

        const html = `<div class="chat-msg">
      <span class="chat-sender ${senderClass}">${esc(data.senderName)}:</span>
      <span class="chat-text">${esc(data.message)}</span>
    </div>`;
        el.chatMessages.insertAdjacentHTML('beforeend', html);
        el.chatMessages.scrollTop = el.chatMessages.scrollHeight;
        el.gameChatMessages.insertAdjacentHTML('beforeend', html);
        el.gameChatMessages.scrollTop = el.gameChatMessages.scrollHeight;
        while (el.gameChatMessages.children.length > 20) {
            el.gameChatMessages.removeChild(el.gameChatMessages.firstChild);
        }
    }

    // ============ Goal Animation ============
    function showGoalAnimation(team) {
        const overlay = document.createElement('div');
        overlay.className = 'goal-overlay';
        overlay.innerHTML = `<div class="goal-text ${team}">GOL!</div>`;
        document.body.appendChild(overlay);
        setTimeout(() => overlay.remove(), 2500);
    }

    function showMatchEndAnimation(data) {
        const overlay = document.createElement('div');
        overlay.className = 'goal-overlay';

        let winnerText = "Berabere!";
        let winnerClass = "";

        if (data.winner === 'red') {
            winnerText = "Kazanan: KIRMIZI TAKIM";
            winnerClass = "red";
        } else if (data.winner === 'blue') {
            winnerText = "Kazanan: MAVİ TAKIM";
            winnerClass = "blue";
        }

        overlay.innerHTML = `
            <div class="match-end-container">
                <div class="match-end-title">MAÇ BİTTİ</div>
                <div class="match-end-winner ${winnerClass}">${winnerText}</div>
                <div class="match-end-score">${data.score.red} - ${data.score.blue}</div>
            </div>
        `;
        document.body.appendChild(overlay);
        setTimeout(() => overlay.remove(), 4800);
    }

    // ============ Utility ============
    function esc(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function playSound(name) {
        if (!sounds[name]) return;
        const sound = sounds[name].cloneNode();
        sound.volume = sounds[name].volume;
        sound.play().catch(e => {
            // Audio play may fail if user hasn't interacted with page yet
            console.debug('Failed to play sound:', e);
        });
    }

    function ensureName() {
        const name = el.nicknameInput.value.trim();
        if (name) {
            network.setName(name);
        } else {
            const defaultName = 'Oyuncu' + Math.floor(Math.random() * 999);
            el.nicknameInput.value = defaultName;
            network.setName(defaultName);
        }
    }

    function sendChat(inputEl) {
        const message = inputEl.value.trim();
        if (message) {
            network.sendChat(message);
            inputEl.value = '';
        }
    }

    // ============ Event Listeners ============

    // Entry screen → Browser screen
    el.enterGameBtn.addEventListener('click', () => {
        ensureName();
        showScreen('browser');
        network.getRooms();
    });
    el.nicknameInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            ensureName();
            showScreen('browser');
            network.getRooms();
        }
    });

    // Create room
    el.createRoomBtn.addEventListener('click', () => {
        ensureName();
        const roomName = el.roomNameInput.value.trim() || 'Yeni Oda';
        const maxPlayers = parseInt(el.roomMaxPlayers.value) || 10;
        const password = el.roomPassword.value.trim() || null;
        network.createRoom(roomName, maxPlayers, password);
        el.roomNameInput.value = '';
        el.roomPassword.value = '';
    });
    el.roomNameInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') el.createRoomBtn.click();
    });

    // Password modal
    el.passwordJoinBtn.addEventListener('click', () => {
        const pw = el.joinPasswordInput.value;
        if (pendingJoinRoomId) network.joinRoom(pendingJoinRoomId, pw);
        el.passwordModal.classList.remove('active');
        el.joinPasswordInput.value = '';
        pendingJoinRoomId = null;
    });
    el.passwordCancelBtn.addEventListener('click', () => {
        el.passwordModal.classList.remove('active');
        el.joinPasswordInput.value = '';
        pendingJoinRoomId = null;
    });
    el.joinPasswordInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') el.passwordJoinBtn.click();
    });
    el.passwordModal.addEventListener('click', (e) => {
        if (e.target === el.passwordModal) {
            el.passwordModal.classList.remove('active');
            pendingJoinRoomId = null;
        }
    });

    // Leave room
    el.leaveRoomBtn.addEventListener('click', () => {
        network.leaveRoom();
        currentRoomId = null;
        currentRoomState = null;
        el.chatMessages.innerHTML = '';
        showScreen('browser');
        network.getRooms();
    });

    // Start / Stop game
    el.startGameBtn.addEventListener('click', () => { network.startGame(); });
    el.stopGameBtn.addEventListener('click', () => { network.stopGame(); });

    // Chat (lobby)
    el.chatSendBtn.addEventListener('click', () => sendChat(el.chatInput));
    el.chatInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') sendChat(el.chatInput); });

    // Chat (game)
    el.gameChatInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') { sendChat(el.gameChatInput); el.gameChatInput.blur(); }
        if (e.key === 'Escape') el.gameChatInput.blur();
    });
    el.gameChatInput.addEventListener('focus', () => inputHandler.setChatFocused(true));
    el.gameChatInput.addEventListener('blur', () => inputHandler.setChatFocused(false));

    // Toggle in-game lobby overlay (game continues running)
    el.toggleLobbyBtn.addEventListener('click', () => {
        const overlay = el.ingameLobbyOverlay;
        const isOpen = overlay.classList.contains('active');
        overlay.classList.toggle('active');
        el.toggleLobbyBtn.textContent = isOpen ? 'Lobiyi Aç' : 'Lobiyi Kapat';
        // Don't disable game - game keeps running
    });

    el.closeIngameLobby.addEventListener('click', () => {
        el.ingameLobbyOverlay.classList.remove('active');
        el.toggleLobbyBtn.textContent = 'Lobiyi Aç';
    });

    // In-game stop game
    el.ingameStopGameBtn.addEventListener('click', () => {
        network.stopGame();
        el.ingameLobbyOverlay.classList.remove('active');
        el.toggleLobbyBtn.textContent = 'Lobiyi Aç';
    });

    // In-game leave room
    el.ingameLeaveBtn.addEventListener('click', () => {
        network.leaveRoom();
        currentRoomId = null;
        currentRoomState = null;
        gameActive = false;
        el.chatMessages.innerHTML = '';
        el.ingameLobbyOverlay.classList.remove('active');
        el.toggleLobbyBtn.textContent = 'Lobiyi Aç';
        showScreen('browser');
        network.getRooms();
    });

    // ============ Initialize ============
    network.connect();

})();
