/**
 * AI Icon 通用初始化脚本
 * - 页面加载时随机分配配色
 * - 嵌入 Icon 注入机器人 SVG
 * - 渲染星级评价组件
 */
(function () {
    var ROBOT_SVG = '<svg viewBox="0 0 24 24" fill="none"><rect x="5" y="7" width="14" height="12" rx="4" fill="white"/><path d="M12 7V4" stroke="white" stroke-width="2" stroke-linecap="round"/><circle cx="12" cy="3" r="1.5" fill="white"/><circle cx="9" cy="11.5" r="2" fill="#667eea"/><circle cx="15" cy="11.5" r="2" fill="#667eea"/><circle cx="9.5" cy="11" r="0.7" fill="white"/><circle cx="15.5" cy="11" r="0.7" fill="white"/><path d="M9.5 15C10 16 14 16 14.5 15" stroke="#667eea" stroke-width="1.5" stroke-linecap="round"/><circle cx="7" cy="13.5" r="1" fill="#f5a0c0" opacity="0.6"/><circle cx="17" cy="13.5" r="1" fill="#f5a0c0" opacity="0.6"/><rect x="3" y="10" width="2" height="4" rx="1" fill="white"/><rect x="19" y="10" width="2" height="4" rx="1" fill="white"/></svg>';

    var COLOR_CLASSES = [
        'ai-color-red', 'ai-color-orange', 'ai-color-yellow',
        'ai-color-blue', 'ai-color-indigo', 'ai-color-purple'
    ];

    // 随机选一个配色（同一页面统一）
    var pick = COLOR_CLASSES[Math.floor(Math.random() * COLOR_CLASSES.length)];

    // 给所有嵌入 Icon 和 title badge 加上配色 class
    document.querySelectorAll('.ai-inline-icon, .ai-title-badge').forEach(function (el) {
        el.classList.add(pick);
    });

    // 渲染星级评价
    document.querySelectorAll('.star-rating').forEach(function (container) {
        var score = parseInt(container.getAttribute('data-score') || '0', 10);
        score = Math.max(0, Math.min(10, score));
        var fullStars = Math.floor(score / 2);
        var halfStar = score % 2 === 1;
        var html = '';
        for (var i = 0; i < 5; i++) {
            var fillWidth = '0%';
            if (i < fullStars) fillWidth = '100%';
            else if (i === fullStars && halfStar) fillWidth = '50%';
            html += '<span class="star">'
                + '<svg class="star-empty" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>'
                + '<span class="star-fill" style="width:' + fillWidth + '">'
                + '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>'
                + '</span></span>';
        }
        container.innerHTML = html;
    });
})();
