/**
 * HuSNS - 帖子卡片生成模块
 * 生成动态帖子的HTML结构
 */

var HuSNS = window.HuSNS || {};

/**
 * 创建帖子卡片HTML
 * @param {Object} post - 帖子数据
 * @returns {string} HTML字符串
 */
HuSNS.createPostHTML = function(post) {
    var url = HuSNS.url;
    var escape = HuSNS.escape;
    var substr = HuSNS.substr;
    var strip_tags = HuSNS.strip_tags;
    var getDefaultAvatar = HuSNS.getDefaultAvatar;
    
    var isLiked = post.is_liked ? 'liked' : '';
    var userId = post.user_id || 0;
    var username = post.username || post.user_name || '';
    var avatar = post.avatar || post.user_avatar || '';
    var likes = post.likes || 0;
    var comments = post.comments || 0;
    var views = post.views || 0;
    var postId = post.id;
    var isOwner = post.is_owner || false;
    var isPinned = post.is_pinned || false;
    var isFeatured = post.is_featured || false;
    var content = post.content || '';
    var contentShort = escape(substr(strip_tags(content), 0, 50));
    
    // 处理头像HTML
    var avatarHtml = HuSNS.createAvatarHTML(avatar);
    
    // 处理图片HTML
    var imagesHtml = HuSNS.createImagesHTML(post.images);
    
    // 处理视频HTML
    var videoHtml = HuSNS.createVideoHTML(post.videos);
    
    // 处理位置HTML
    var locationHtml = HuSNS.createLocationHTML(post.location);
    
    // 处理转发HTML
    var repostHtml = HuSNS.createRepostHTML(post);
    
    // 处理下拉菜单HTML
    var dropdownHtml = HuSNS.createDropdownHTML(postId, isOwner, post.is_favorited, post.is_pinned, post.is_featured);
    
    // 处理用户头部HTML
    var userHeaderHtml = HuSNS.createUserHeaderHTML(post);
    
    // 处理用户名HTML
    var usernameHtml = HuSNS.createUsernameHTML(post);
    
    // 处理圈子名称HTML
    var circleHtml = HuSNS.createPostCircleBadge(post);
    
    // 处理IP显示
    var ipHtml = post.ip ? '<div class="moment-ip">' + post.ip.replace(/^中国\s*/, '').replace(/^CHINA\s*/i, '') + '</div>' : '';
    
    return '<div class="moment-card" data-id="' + postId + '">' +
        '<div class="moment-header">' +
            userHeaderHtml +
            '<div class="moment-user-info">' +
                usernameHtml +
                '<div class="moment-meta">' +
                    '<div class="moment-time">' + (post.time_ago || '') + '</div>' +
                    ipHtml +
                '</div>' +
            '</div>' +
            '<div class="moment-more-btn" onclick="HuSNS.toggleDropdown(this, event)">' +
                '<span class="moment-more">⋮</span>' +
                '<div class="moment-dropdown">' + dropdownHtml + '</div>' +
            '</div>' +
        '</div>' +
        '<div class="moment-content-link">' +
            '<div class="moment-content">' + circleHtml + content + '</div>' +
            imagesHtml +
            videoHtml +
            locationHtml +
        '</div>' +
        repostHtml +
        '<div class="moment-actions">' +
            '<button class="moment-action like-btn ' + isLiked + '" data-action="like" data-post-id="' + postId + '">' +
                '<span class="moment-action-icon"><span class="iconify" data-icon="' + (isLiked ? 'mdi:heart' : 'mdi:heart-outline') + '"></span></span>' +
                '<span class="moment-action-count">' + (likes || '') + '</span>' +
                '<span class="moment-action-text">赞</span>' +
            '</button>' +
            '<button class="moment-action comment-btn" data-post-id="' + postId + '">' +
                '<span class="moment-action-icon"><span class="iconify" data-icon="mdi:comment-outline"></span></span>' +
                '<span class="moment-action-count">' + (comments || '') + '</span>' +
                '<span class="moment-action-text">评论</span>' +
            '</button>' +
            '<button class="moment-action" onclick="HuSNS.openShareModal(\'' + url('mobile/detail?id=' + postId) + '\', \'' + contentShort + '\')">' +
                '<span class="moment-action-icon"><span class="iconify" data-icon="mdi:share-outline"></span></span>' +
                '<span class="moment-action-text">分享</span>' +
            '</button>' +
            '<button class="moment-action read-btn" onclick="window.location.href=\'' + url('mobile/detail?id=' + postId) + '\'">' +
                '<span class="moment-action-icon"><span class="iconify" data-icon="mdi:eye-outline"></span></span>' +
                '<span class="moment-action-count">' + (views || '') + '</span>' +
                '<span class="moment-action-text">阅读</span>' +
            '</button>' +
        '</div>' +
    '</div>';
};

/**
 * 生成头像HTML
 * @param {string} avatar - 头像数据
 * @returns {string} 头像HTML
 */
HuSNS.createAvatarHTML = function(avatar) {
    var defaultAvatar = HuSNS.getDefaultAvatar();
    
    if (avatar && typeof avatar === 'string' && avatar.trim()) {
        // 如果是HTML格式（包含img标签），提取src属性
        if (avatar.includes('<img')) {
            var match = avatar.match(/<img[^>]+src=["']([^"']+)["']/i);
            if (match && match[1]) {
                return '<img class="moment-avatar" src="' + match[1] + '" alt="" onerror="this.src=\'' + defaultAvatar + '\'">';
            }
        } else if (!avatar.includes('<')) {
            // 纯URL
            return '<img class="moment-avatar" src="' + avatar + '" alt="" onerror="this.src=\'' + defaultAvatar + '\'">';
        }
    }
    // 没有头像或格式异常，使用默认头像
    return '<img class="moment-avatar" src="' + defaultAvatar + '" alt="">';
};

/**
 * 生成图片HTML
 * @param {Array} images - 图片数组
 * @returns {string} 图片HTML
 */
HuSNS.createImagesHTML = function(images) {
    if (!images || images.length === 0) return '';
    
    var gridClass = images.length === 1 ? 'single-image' : '';
    var imgs = images.slice(0, 9).map(function(img) {
        return '<img class="moment-img" src="' + img + '" alt="" loading="lazy">';
    }).join('');
    
    return '<div class="moment-images"><div class="moment-image-grid ' + gridClass + '">' + imgs + '</div></div>';
};

/**
 * 生成视频HTML
 * @param {Array} videos - 视频数组（支持字符串格式和对象格式）
 * @returns {string} 视频HTML
 */
HuSNS.createVideoHTML = function(videos) {
    if (!videos || videos.length === 0) return '';
    
    // 支持多种视频格式：字符串格式、file字段格式、path字段格式
    var videoUrl = '';
    var firstVideo = videos[0];
    if (typeof firstVideo === 'string') {
        videoUrl = firstVideo;
    } else if (typeof firstVideo === 'object' && firstVideo.file) {
        videoUrl = firstVideo.file;
    } else if (typeof firstVideo === 'object' && firstVideo.path) {
        videoUrl = firstVideo.path;
    }
    
    if (!videoUrl) return '';
    
    return '<div class="moment-video-thumbnail" onclick="HuSNS.openVideoPlayer(\'' + videoUrl + '\')" data-video="' + videoUrl + '">' +
        '<img class="moment-video-poster" src="" alt="">' +
        '<div class="moment-video-play-btn">' +
            '<span class="iconify" data-icon="mdi:play" style="color: white; font-size: 24px;"></span>' +
        '</div>' +
        '<div class="moment-video-badge">视频</div>' +
    '</div>';
};

/**
 * 生成位置HTML
 * 只有当有精确坐标时才显示位置信息
 * @param {Object} location - 位置数据
 * @returns {string} 位置HTML
 */
HuSNS.createLocationHTML = function(location) {
    if (!location || !location.name) return '';

    var lat = location.lat || '';
    var lng = location.lng || '';
    var hasCoords = lat && lng && lat !== '0' && lng !== '0';

    // 只有有精确坐标时才显示位置卡片，否则不显示
    if (!hasCoords) return '';

    return '<div class="moment-location-card" onclick="HuSNS.showLocationMap(\'' + HuSNS.escape(location.name) + '\', \'' + lat + '\', \'' + lng + '\')">' +
        '<span class="location-pin">' +
            '<svg viewBox="0 0 24 24">' +
                '<path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>' +
            '</svg>' +
        '</span>' +
        '<span class="location-text">' + HuSNS.escape(location.name) + '</span>' +
    '</div>';
};

/**
 * 生成转发HTML
 * @param {Object} post - 帖子数据
 * @returns {string} 转发HTML
 */
HuSNS.createRepostHTML = function(post) {
    if (!post.is_repost || !post.original_post) return '';
    
    var orig = post.original_post;
    var origContent = orig.content ? orig.content.replace(/<[^>]*>/g, '').substring(0, 80) : '';
    
    return '<div class="moment-repost">' +
        '<a href="' + HuSNS.url('mobile/detail?id=' + orig.id) + '" class="moment-repost-link">' +
            '@' + HuSNS.escape(orig.username || '') + ': ' + HuSNS.escape(origContent) + '...' +
        '</a>' +
    '</div>';
};

/**
 * 生成下拉菜单HTML
 * @param {number} postId - 帖子ID
 * @param {boolean} isOwner - 是否是作者
 * @param {boolean} isFavorited - 是否已收藏
 * @param {boolean} isPinned - 是否已置顶
 * @param {boolean} isFeatured - 是否已加精
 * @returns {string} 菜单HTML
 */
HuSNS.createDropdownHTML = function(postId, isOwner, isFavorited, isPinned, isFeatured) {
    var IS_ADMIN = window.IS_ADMIN || false;
    var isAdmin = IS_ADMIN;
    isFavorited = isFavorited || false;
    isPinned = isPinned || false;
    isFeatured = isFeatured || false;
    
    var html = '';
    
    // 非作者显示收藏
    if (!isOwner) {
        html += '<button class="moment-dropdown-item" onclick="HuSNS.favoritePost(' + postId + ', ' + isFavorited + ')">' +
            '<span class="item-icon"><span class="iconify" data-icon="' + (isFavorited ? 'mdi:star' : 'mdi:star-outline') + '"></span></span>' +
            (isFavorited ? '取消收藏' : '收藏') +
        '</button>';
    }
    
    // 转发按钮
    html += '<button class="moment-dropdown-item" onclick="HuSNS.repostPost(' + postId + ')">' +
        '<span class="item-icon"><span class="iconify" data-icon="mdi:repeat-variant"></span></span>转发' +
    '</button>';
    
    // 作者专属操作
    if (isOwner) {
        html += '<div class="dropdown-divider"></div>';
        html += '<button class="moment-dropdown-item" onclick="HuSNS.editPost(' + postId + ')">' +
            '<span class="item-icon"><span class="iconify" data-icon="mdi:pencil-outline"></span></span>编辑' +
        '</button>';
        html += '<button class="moment-dropdown-item danger" onclick="HuSNS.deletePost(' + postId + ')">' +
            '<span class="item-icon"><span class="iconify" data-icon="mdi:delete-outline"></span></span>删除' +
        '</button>';
    }
    
    // 管理员专属操作
    if (isAdmin) {
        html += '<div class="dropdown-divider"></div>';
        html += '<button class="moment-dropdown-item" onclick="HuSNS.togglePinPost(' + postId + ', ' + (isPinned ? 1 : 0) + ')">' +
            '<span class="item-icon"><span class="iconify" data-icon="mdi:pin"></span></span>' + (isPinned ? '取消置顶' : '置顶') +
        '</button>';
        html += '<button class="moment-dropdown-item" onclick="HuSNS.toggleFeaturePost(' + postId + ', ' + (isFeatured ? 1 : 0) + ')">' +
            '<span class="item-icon"><span class="iconify" data-icon="mdi:trophy-outline"></span></span>' + (isFeatured ? '取消加精' : '加精') +
        '</button>';
    } else if (!isOwner) {
        // 非作者非管理员显示举报
        html += '<div class="dropdown-divider"></div>';
        html += '<button class="moment-dropdown-item" onclick="HuSNS.reportPost(' + postId + ')">' +
            '<span class="item-icon"><span class="iconify" data-icon="mdi:flag-outline"></span></span>举报' +
        '</button>';
    }
    
    return html;
};

/**
 * 生成用户头部HTML
 * @param {Object} post - 帖子数据
 * @returns {string} 用户头部HTML
 */
HuSNS.createUserHeaderHTML = function(post) {
    var url = HuSNS.url;
    var escape = HuSNS.escape;
    var isAnonymous = post.is_anonymous || false;
    
    if (isAnonymous) {
        // 匿名发布
        return '<div style="width: 44px; height: 44px; border-radius: 50%; background: var(--primary-color); display: flex; align-items: center; justify-content: center; margin-right: 12px; flex-shrink: 0;">' +
            '<svg viewBox="0 0 24 24" fill="white" width="24" height="24">' +
                '<path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4zm0 10.99h7c-.53 4.12-3.28 7.79-7 8.94V12H5V6.3l7-3.11v8.8z"/>' +
            '</svg>' +
        '</div>';
    }
    
    var avatar = post.avatar || post.user_avatar || '';
    var avatarHtml = HuSNS.createAvatarHTML(avatar);
    return '<a href="' + url('mobile/user?id=' + (post.user_id || 0)) + '">' + avatarHtml + '</a>';
};

/**
 * 生成用户名HTML
 * @param {Object} post - 帖子数据
 * @returns {string} 用户名HTML
 */
HuSNS.createUsernameHTML = function(post) {
    var url = HuSNS.url;
    var escape = HuSNS.escape;
    var isAnonymous = post.is_anonymous || false;
    var isOnline = post.is_online || false;
    var isPinned = post.is_pinned || false;
    var isFeatured = post.is_featured || false;
    
    var badges = '';
    if (isPinned) badges += '<span class="moment-badge pinned">置顶</span>';
    if (isFeatured) badges += '<span class="moment-badge featured">精华</span>';
    
    var onlineBadgeHtml = isOnline 
        ? '<span class="online-badge" title="在线"></span>' 
        : '<span class="online-badge offline" title="离线"></span>';
    
    var username = post.username || post.user_name || '';
    
    if (isAnonymous) {
        return '<span class="moment-username" style="color: var(--text-secondary-color);">' +
            escape(username) + badges +
        '</span>';
    }
    
    return '<a href="' + url('mobile/user?id=' + (post.user_id || 0)) + '" class="moment-username">' +
        escape(username) +
        onlineBadgeHtml +
        badges +
    '</a>';
};

/**
 * 生成帖子中的圈子名称HTML（仅显示名称，点击跳转）
 * @param {Object} post - 帖子数据
 * @returns {string} 圈子名称HTML
 */
HuSNS.createPostCircleBadge = function(post) {
    if (!post.circle_name) return '';
    
    var url = HuSNS.url;
    var escape = HuSNS.escape;
    
    return '<span class="moment-circle">' +
        '<a href="' + url('mobile/circlePosts?circle_id=' + (post.circle_id || '')) + '" class="circle-name">' +
            escape(post.circle_name) +
        '</a>' +
    '</span>';
};

// 全局暴露
window.HuSNS = HuSNS;