// Модальное окно профиля пользователя - Унифицировано с премиум стилем
function showOtherUserProfile(name, avatar, role, isId1, userId, email) {
    let modal = document.getElementById('view-user-modal');

    // Обеспечить соответствие внутренней структуры модального окна нашему премиум стилю
    modal.innerHTML = `
        <div class="profile-card">
            <button onclick="document.getElementById('view-user-modal').style.display='none'" class="close-modal">&times;</button>
            
            <div style="text-align:center; margin-bottom:25px;">
                <div style="position:relative; display:inline-block; margin-bottom:15px;">
                    <img src="${avatar || 'assets/default_avatar.png'}" style="width:120px; height:120px; border-radius:50%; object-fit:cover; border:3px solid var(--primary); box-shadow:0 0 20px rgba(157,78,221,0.2);">
                </div>
                <h2 style="margin:10px 0; font-size:1.6rem; font-weight:700; color:#fff;">${name}</h2>
                <div id="view-user-role-badge">
                    ${(role === 'admin' || isId1) ?
            `<span style="background:rgba(255,183,3,0.1); color:#ffb703; padding:5px 15px; border-radius:30px; font-weight:800; text-transform:uppercase; letter-spacing:1px; font-size:0.7rem; border:1px solid rgba(255,183,3,0.3);">👑 ADMIN</span>` :
            `<span style="color:var(--text-secondary); opacity:0.7; font-size:0.9rem;">${LANG.standard_user || 'User'}</span>`
        }
                </div>
            </div>

            <div style="display:flex; gap:12px; justify-content:center; margin-bottom:25px;">
                ${(typeof USER !== 'undefined' && userId != USER.id) ? `

                    <button id="video-call-user-btn" style="flex:1; background:rgba(0,180,216,0.1); border:1px solid rgba(0,180,216,0.2); color:#00b4d8; padding:12px; border-radius:14px; cursor:pointer; font-size:0.9rem; font-weight:700; display:flex; align-items:center; justify-content:center; gap:8px; transition:all 0.2s;">
                        <span style="font-size:1.2rem;">📹</span> ${LANG.start_video_call || 'Video Call'}
                    </button>
                    <button onclick="document.getElementById('view-user-modal').style.display='none'; if(typeof videoCall !== 'undefined') videoCall.startCall('echo-test', 'Video Test Bot 📹', 'assets/default_avatar.png');" style="flex:1; background:rgba(157,78,221,0.1); border:1px solid rgba(157,78,221,0.2); color:var(--primary); padding:12px; border-radius:14px; cursor:pointer; font-size:0.9rem; font-weight:700; display:flex; align-items:center; justify-content:center; gap:8px; transition:all 0.2s;">
                        <span style="font-size:1.2rem;">🧪</span> Test Call
                    </button>
                ` : ''}
            </div>

            <button onclick="document.getElementById('view-user-modal').style.display='none'" class="btn" style="background:rgba(255,255,255,0.05); color:#fff; border:1px solid rgba(255,255,255,0.1);">
                ${LANG.close || 'Close'}
            </button>
        </div>
    `;

    // Настройка логики кнопки видеозвонка
    const videoCallBtn = document.getElementById('video-call-user-btn');
    if (videoCallBtn) {
        videoCallBtn.addEventListener('mouseenter', () => {
            videoCallBtn.style.background = 'rgba(0,180,216,0.2)';
            videoCallBtn.style.transform = 'translateY(-2px)';
        });
        videoCallBtn.addEventListener('mouseleave', () => {
            videoCallBtn.style.background = 'rgba(0,180,216,0.1)';
            videoCallBtn.style.transform = 'translateY(0)';
        });
        videoCallBtn.onclick = () => {
            if (typeof videoCall !== 'undefined') {
                modal.style.display = 'none';
                videoCall.startCall(userId, name, avatar);
            }
        };
    }

    modal.style.display = 'flex';
}

// Модальное окно участников комнаты - Унифицировано с премиум стилем
async function showRoomMembers(roomId, roomName) {
    try {
        const response = await fetch(`api/room-members.php?room_id=${roomId}`);
        const data = await response.json();
        if (data.status !== 'success') return;

        const members = data.members || [];

        // Добавить бота эхо-теста
        members.unshift({
            id: 'echo-test',
            username: 'Video Test Bot 📹',
            avatar: 'assets/default_avatar.png',
            role: 'bot',
            is_online: 1,
            email: 'bot@chat.local'
        });

        let modal = document.getElementById('room-members-modal');
        if (!modal) {
            modal = document.createElement('div');
            modal.id = 'room-members-modal';
            modal.className = 'modal-overlay';
            document.body.appendChild(modal);
            modal.addEventListener('click', (e) => { if (e.target === modal) modal.style.display = 'none'; });
        }

        let membersHTML = '';
        members.forEach(member => {
            const isOnlineBadge = member.is_online ? `<div style="width:10px; height:10px; background:#4cd137; border-radius:50%; border:2px solid #1e1e1e; position:absolute; bottom:2px; right:2px;"></div>` : '';
            membersHTML += `
                <div class="member-item" data-user-id="${member.id}" style="display:flex; align-items:center; gap:12px; padding:12px; border-radius:16px; cursor:pointer; transition:all 0.2s; background:rgba(255,255,255,0.03); margin-bottom:8px; border:1px solid rgba(255,255,255,0.05);">
                    <div style="position:relative;">
                        <img src="${member.avatar || 'assets/default_avatar.png'}" style="width:48px; height:48px; border-radius:50%; object-fit:cover; border:2px solid rgba(255,255,255,0.1);">
                        ${isOnlineBadge}
                    </div>
                    <div style="flex:1; text-align:left;">
                        <div style="font-weight:700; color:#fff; font-size:1rem;">${member.username}</div>
                        <div style="font-size:0.75rem; color:rgba(255,255,255,0.4); text-transform:uppercase; letter-spacing:0.5px;">${member.role === 'admin' ? '👑 Admin' : 'User'}</div>
                    </div>
                    <div style="color:var(--primary); font-size:1.2rem; opacity:0.6;">→</div>
                </div>
            `;
        });

        modal.innerHTML = `
            <div class="profile-card" style="max-width:450px;">
                <button onclick="document.getElementById('room-members-modal').style.display='none'" class="close-modal">&times;</button>
                <h2 style="margin-bottom:5px;">${roomName}</h2>
                <div style="font-size:0.85rem; color:var(--text-secondary); margin-bottom:20px; text-transform:uppercase; letter-spacing:1px; opacity:0.6;">
                    ${members.length} ${LANG.room_members || 'Members'}
                </div>
                
                <div style="flex:1; overflow-y:auto; max-height:50vh; padding-right:5px;">
                    ${membersHTML}
                </div>
                
                <button onclick="document.getElementById('room-members-modal').style.display='none'" class="btn" style="margin-top:20px; background:rgba(255,255,255,0.05);">
                    ${LANG.close || 'Close'}
                </button>
            </div>
        `;

        // Обработчики кликов
        modal.querySelectorAll('.member-item').forEach(item => {
            item.addEventListener('mouseenter', () => { item.style.background = 'rgba(255,255,255,0.08)'; item.style.transform = 'translateX(5px)'; });
            item.addEventListener('mouseleave', () => { item.style.background = 'rgba(255,255,255,0.03)'; item.style.transform = 'translateX(0)'; });
            item.addEventListener('click', () => {
                const userId = item.dataset.userId;
                const m = members.find(x => x.id == userId);
                if (m) {
                    modal.style.display = 'none';
                    showOtherUserProfile(m.username, m.avatar, m.role, m.id == 1, m.id, m.email);
                }
            });
        });

        modal.style.display = 'flex';
    } catch (e) {
        console.error(e);
    }
}

window.showOtherUserProfile = showOtherUserProfile;
window.showRoomMembers = showRoomMembers;
