<?php
/**
 * HuSNS Mobile App Layout Footer Scripts
 * 移动端应用布局页脚脚本
 */

$baseUrl = Helper::getBaseUrl();
$userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
?>

<!-- 核心功能脚本 -->
<script src="<?php echo $baseUrl; ?>/templates/mobile/app/js/utils.js"></script>
<script src="<?php echo $baseUrl; ?>/templates/mobile/app/js/post-actions.js"></script>
<script src="<?php echo $baseUrl; ?>/templates/mobile/app/js/post-card.js"></script>
<script src="<?php echo $baseUrl; ?>/templates/mobile/app/js/modal.js"></script>

<!-- 页面特定功能脚本（按需加载） -->
<?php if ($currentPage === 'detail' || $currentPage === 'publish'): ?>
<script src="<?php echo $baseUrl; ?>/templates/mobile/app/js/video-player.js"></script>
<?php endif; ?>

<script>
// ========== 全局变量 ==========
var userId = <?php echo $userId ? $userId : 'null'; ?>;
</script>

<?php if ($currentPage === 'detail' || $currentPage === 'publish' || $currentPage === 'circles'): ?>
<!-- 圈子选择功能 -->
<script>
(function() {
    var circleSelectVisible = false;
    
    window.toggleCircleSelect = function() {
        var modal = document.getElementById('circleSelectModal');
        var btn = document.getElementById('circleToolbarBtn');
        if (!modal) return;
        
        circleSelectVisible = !circleSelectVisible;
        
        if (circleSelectVisible) {
            modal.classList.add('active');
            modal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
            loadUserCircles();
        } else {
            modal.classList.remove('active');
            modal.style.display = 'none';
            document.body.style.overflow = '';
        }
        
        if (btn) btn.classList.toggle('active', circleSelectVisible);
    };
    
    // 点击遮罩关闭
    document.addEventListener('click', function(e) {
        var modal = document.getElementById('circleSelectModal');
        if (modal && circleSelectVisible && e.target === modal) {
            toggleCircleSelect();
        }
    });
    
    function loadUserCircles() {
        var circleList = document.getElementById('circleList');
        if (!circleList) return;
        
        // 保留第一个placeholder
        var items = circleList.querySelectorAll('.circle-item');
        items.forEach(function(item, index) {
            if (index > 0) item.remove();
        });
        
        fetch('<?php echo $baseUrl; ?>/?r=mobileApi/getUserCircles', { credentials: 'include' })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.code === 0 && data.data && data.data.length > 0) {
                    data.data.forEach(function(circle) {
                        var item = document.createElement('div');
                        item.className = 'circle-item';
                        item.dataset.circleId = circle.id;
                        item.dataset.joined = circle.joined ? 'true' : 'false';
                        item.onclick = function() {
                            selectCircle(circle.id, circle.name, circle.joined);
                        };
                        
                        var radio = document.createElement('span');
                        radio.className = 'circle-radio';
                        item.appendChild(radio);
                        
                        if (circle.avatar) {
                            var img = document.createElement('img');
                            img.className = 'circle-avatar-mini';
                            img.src = '<?php echo $baseUrl; ?>/uploads/' + circle.avatar;
                            item.appendChild(img);
                        }
                        
                        var name = document.createElement('span');
                        name.className = 'circle-text';
                        name.textContent = circle.name;
                        item.appendChild(name);
                        
                        if (!circle.joined) {
                            var hint = document.createElement('span');
                            hint.className = 'circle-hint';
                            hint.textContent = '未加入';
                            item.appendChild(hint);
                        }
                        
                        circleList.appendChild(item);
                    });
                }
            });
    }
    
    window.selectCircle = function(circleId, circleName, joined) {
        var circleInput = document.getElementById('selectedCircleId');
        var circleNameDisplay = document.getElementById('selectedCircleName');
        var btn = document.getElementById('circleToolbarBtn');
        
        if (circleInput) circleInput.value = circleId;
        if (circleNameDisplay) circleNameDisplay.textContent = circleName || '全站';
        if (btn) btn.classList.toggle('active', circleId > 0);
        
        toggleCircleSelect();
        
        if (!joined && circleId > 0) {
            var hint = confirm('您还没有加入该圈子，是否前往加入？');
            if (hint) {
                window.location.href = '<?php echo $baseUrl; ?>/?r=mobile/circleInfo&id=' + circleId;
            }
        }
    };
})();
</script>
<?php endif; ?>

<?php if ($currentPage === 'detail' || $currentPage === 'publish'): ?>
<!-- 视频功能 -->
<script>
(function() {
    // 视频缩略图生成
    function generateVideoThumbnails() {
        var videos = document.querySelectorAll('.moment-video-thumbnail[data-video]');
        videos.forEach(function(videoThumb) {
            var videoUrl = videoThumb.dataset.video;
            var posterImg = videoThumb.querySelector('.moment-video-poster');
            
            if (!videoUrl || !posterImg) return;
            
            var video = document.createElement('video');
            video.src = videoUrl;
            video.muted = true;
            video.preload = 'metadata';
            
            video.onloadeddata = function() {
                video.currentTime = 1;
            };
            
            video.onseeked = function() {
                var canvas = document.createElement('canvas');
                canvas.width = video.videoWidth;
                canvas.height = video.videoHeight;
                canvas.getContext('2d').drawImage(video, 0, 0);
                posterImg.src = canvas.toDataURL('image/jpeg');
            };
            
            video.onerror = function() {
                posterImg.style.background = '#f0f0f0';
            };
        });
    }
    
    window.generateVideoThumbnails = generateVideoThumbnails;
    
    // 视频播放器
    window.openVideoPlayer = function(videoUrl) {
        var overlay = document.createElement('div');
        overlay.className = 'video-player-overlay';
        overlay.innerHTML = '<div class="video-player-container">' +
            '<video class="video-player-fullscreen" src="' + videoUrl + '" controls autoplay playsinline></video>' +
            '<div class="video-player-close" onclick="closeVideoPlayer()"><span class="iconify" data-icon="mdi:close" style="color: white; font-size: 24px;"></span></div>' +
        '</div>';
        
        document.body.appendChild(overlay);
        document.body.style.overflow = 'hidden';
        
        var video = overlay.querySelector('.video-player-fullscreen');
        video.addEventListener('click', function() {
            if (document.fullscreenElement) {
                document.exitFullscreen();
            } else {
                video.requestFullscreen().catch(function() {});
            }
        });
        
        document.addEventListener('keydown', function handleEsc(e) {
            if (e.key === 'Escape') {
                closeVideoPlayer();
                document.removeEventListener('keydown', handleEsc);
            }
        });
    };
    
    window.closeVideoPlayer = function() {
        var overlay = document.querySelector('.video-player-overlay');
        if (overlay) {
            var video = overlay.querySelector('.video-player-fullscreen');
            if (video) video.pause();
            overlay.remove();
            document.body.style.overflow = '';
        }
    };
})();
</script>
<?php endif; ?>

<?php if ($currentPage === 'profile' || $currentPage === 'detail'): ?>
<!-- 分享功能 -->
<script>
(function() {
    var currentShareUrl = '', currentShareTitle = '', currentShareContent = '';
    
    window.openShareModal = function(url, title, content) {
        currentShareUrl = url || window.location.href;
        currentShareTitle = title || document.title;
        currentShareContent = content || '';
        
        var shareText = document.getElementById('shareText');
        var shareUrl = document.getElementById('shareUrl');
        if (shareText) shareText.textContent = currentShareContent || currentShareTitle;
        if (shareUrl) shareUrl.textContent = currentShareUrl;
        
        openModal('shareModal');
    };
    
    window.copyShareUrl = function() {
        navigator.clipboard.writeText(currentShareUrl).then(function() {
            showToast('链接已复制');
            closeModal('shareModal');
        });
    };
    
    window.shareToWechat = function() {
        if (navigator.share) {
            navigator.share({ title: currentShareTitle, text: currentShareContent, url: currentShareUrl })
                .then(function() { closeModal('shareModal'); })
                .catch(function() {});
        } else {
            showToast('浏览器不支持分享功能');
        }
    };
    
    window.shareToWeibo = function() {
        var url = 'http://service.weibo.com/share/share.php?url=' + encodeURIComponent(currentShareUrl) + 
                  '&title=' + encodeURIComponent(currentShareTitle + ' ' + currentShareContent);
        window.open(url, '_blank');
    };
    
    window.shareToQQ = function() {
        var url = 'http://connect.qq.com/widget/shareqq/iframe_index.html?url=' + encodeURIComponent(currentShareUrl) + 
                  '&desc=' + encodeURIComponent(currentShareContent);
        window.open(url, '_blank');
    };
})();
</script>
<?php endif; ?>
