/**
 * 心语情绪主题 · 双套内置表情 + 自动匹配
 *
 * 说明（版权）：
 * - 微信 / 抖音等平台「专属表情包」为商业授权素材，不存在可随意内置的同款开源库。
 * - 本页使用两套可合规商用的通用表情：
 *   1) native：系统 Unicode 表情（保留原方案，离线可用）
 *   2) twemoji：Twemoji 开源图（CC-BY 4.0，风格接近主流 App 通用 emoji）
 *      https://github.com/twitter/twemoji
 * - 按心语 id/序号自动在两套间分配，同一心语稳定、不同心语可交替展示。
 */
const WordThemes = {
    TWEMOJI_VERSION: '14.0.2',
    /** 本地缺失时回退公网 CDN（自定义域名下本地 404 时自动尝试） */
    TWEMOJI_CDN_FALLBACK: 'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/',

    /**
     * 站点根路径（静态托管 + 自定义域名必须用绝对路径）
     * 若页面在子目录，可在 index.html 设置 window.MUYU_ASSET_BASE = '/子目录/'
     */
    getSiteBase() {
        if (typeof window !== 'undefined' && window.MUYU_ASSET_BASE != null) {
            const b = String(window.MUYU_ASSET_BASE);
            return b.endsWith('/') ? b : b + '/';
        }
        if (typeof window !== 'undefined' && window.location) {
            let p = window.location.pathname || '/';
            if (p.endsWith('/')) return p;
            if (/\.[a-z0-9]+$/i.test(p)) return p.replace(/\/[^/]+$/, '/') || '/';
            return p + '/';
        }
        return '/';
    },

    getTwemojiLocalBase() {
        return this.getSiteBase() + 'assets/twemoji/72x72/';
    },

    meta: {
        '静心平和': { key: 'calm', short: '静心' },
        '轻松愉悦': { key: 'joy', short: '愉悦' },
        '舒缓解压': { key: 'relief', short: '解压' },
        '温柔寄语': { key: 'gentle', short: '温柔' }
    },

    /** 套系 A：Unicode 原生（离线） */
    stickerPacksNative: {
        calm: ['🪷', '🍵', '🕯️', '🌿', '🧘', '☁️', '🍃', '🌙'],
        joy: ['😊', '🌻', '🎐', '🍯', '✨', '🌈', '🐝', '🎈'],
        relief: ['🫧', '💆', '🎋', '🌊', '🍃', '🌤️', '🛁', '🧴'],
        gentle: ['🌸', '💌', '🤍', '🕊️', '💗', '🧸', '🎀', '🫶'],
        neutral: ['☕', '🪵', '📿', '🍂', '🌤️', '🕯️', '🧡', '✨']
    },

    /**
     * 套系 B：Twemoji 图（与 A 同语义序号对齐，渲染为统一扁平 emoji 图）
     * 观感接近微信等 App 的通用 emoji，非平台独家贴纸包。
     */
    stickerPacksTwemoji: {
        calm: ['🪷', '🍵', '🕯️', '🌿', '🧘', '☁️', '🍃', '🌙'],
        joy: ['😊', '🌻', '🎐', '🍯', '✨', '🌈', '🐝', '🎈'],
        relief: ['🫧', '💆', '🎋', '🌊', '🍃', '☁️', '🛁', '✨'],
        gentle: ['🌸', '💌', '🤍', '🕊️', '💗', '🧸', '🎀', '🫶'],
        neutral: ['☕', '🪵', '📿', '🍂', '☀️', '🕯️', '🧡', '✨']
    },

    paradeShapesNative: {
        bird: ['🕊️', '🐦', '🦢'],
        plant: ['🌸', '🌼', '🍀'],
        animal: ['🐱', '🐰', '🦊'],
        car: ['🛶', '🎐', '⛵'],
        cloud: ['☁️', '🌥️', '🌤️']
    },

    paradeShapesTwemoji: {
        bird: ['🕊️', '🐦', '🦆'],
        plant: ['🌸', '🌼', '🌻'],
        animal: ['🐱', '🐰', '🐻'],
        car: ['⛵', '🎐', '🚲'],
        cloud: ['☁️', '🌤️', '⛅']
    },

    pickPackType(seed, moodKey) {
        const n = Math.abs(parseInt(seed, 10) || 0);
        const salt = (moodKey || 'neutral').split('').reduce((a, c) => a + c.charCodeAt(0), 0);
        return (n + salt) % 2 === 0 ? 'native' : 'twemoji';
    },

    getPack(moodKey, packType) {
        const native = this.stickerPacksNative[moodKey] || this.stickerPacksNative.neutral;
        if (packType === 'twemoji') {
            return this.stickerPacksTwemoji[moodKey] || this.stickerPacksTwemoji.neutral;
        }
        return native;
    },

    emojiToTwemojiFile(emoji) {
        const cps = [];
        for (const ch of emoji) {
            const cp = ch.codePointAt(0);
            if (cp === 0xfe0f) continue;
            cps.push(cp.toString(16));
        }
        return cps.join('-');
    },

    twemojiFileName(emoji) {
        const file = this.emojiToTwemojiFile(emoji);
        return file ? file + '.png' : '';
    },

    twemojiUrl(emoji, preferFallback) {
        const name = this.twemojiFileName(emoji);
        if (!name) return '';
        const base = preferFallback ? this.TWEMOJI_CDN_FALLBACK : this.getTwemojiLocalBase();
        return base + name;
    },

    resolve(tag, seed) {
        const label = tag || '静心平和';
        const base = this.meta[label] || { key: 'neutral', short: (label || '心语').slice(0, 4) };
        const n = Math.abs(parseInt(seed, 10) || 0);
        const packType = this.pickPackType(n, base.key);
        const pack = this.getPack(base.key, packType);
        const icon = pack[n % pack.length];
        const variantIcon = pack[(n + 3) % pack.length];
        return {
            key: base.key,
            short: base.short,
            icon,
            variantIcon,
            packType,
            packLabel: packType === 'twemoji' ? 'Twemoji' : 'Unicode',
            packSize: pack.length
        };
    },

    /** 生成心语贴纸 HTML（统一入口） */
    stickerMarkup(theme, extraClass) {
        const cls =
            'mood-sticker ' +
            (extraClass || '') +
            ' mood-sticker-' +
            theme.key +
            ' pack-' +
            theme.packType;
        if (theme.packType === 'twemoji') {
            const url = this.twemojiUrl(theme.icon);
            const safeUrl = url.replace(/"/g, '%22');
            const safeEmoji = theme.icon.replace(/"/g, '');
            const eager =
                extraClass && extraClass.indexOf('cloud-sticker') >= 0 ? ' loading="eager"' : ' loading="lazy"';
            return (
                '<span class="' +
                cls +
                '" data-pack="twemoji" data-emoji="' +
                safeEmoji +
                '" title="' +
                theme.packLabel +
                '" role="img" aria-label="表情">' +
                '<img class="sticker-img" src="' +
                safeUrl +
                '" alt="" decoding="async"' +
                eager +
                ' onerror="WordThemes.onStickerImgError(this)" data-twemoji-file="' +
                this.twemojiFileName(theme.icon) +
                '" />' +
                '<span class="sticker-fallback" aria-hidden="true">' +
                safeEmoji +
                '</span></span>'
            );
        }
        return (
            '<span class="' +
            cls +
            '" data-pack="native" aria-hidden="true" title="' +
            theme.packLabel +
            '">' +
            theme.icon +
            '</span>'
        );
    },

    onStickerImgError(img) {
        const wrap = img && img.parentElement;
        if (!wrap || !img) return;
        const name = img.dataset.twemojiFile || this.twemojiFileName(wrap.dataset.emoji);
        if (img.dataset.fallbackTried !== '1' && this.TWEMOJI_CDN_FALLBACK && name) {
            if (img.src.indexOf('cdn.jsdelivr.net') === -1) {
                img.dataset.fallbackTried = '1';
                img.src = this.TWEMOJI_CDN_FALLBACK + name;
                return;
            }
        }
        img.remove();
        wrap.classList.remove('pack-twemoji');
        wrap.classList.add('pack-native', 'pack-fallback-visible');
        const fb = wrap.querySelector('.sticker-fallback');
        if (fb) fb.style.display = 'inline-flex';
        else if (wrap.dataset.emoji) wrap.textContent = wrap.dataset.emoji;
    },

    /** 部署自检：控制台可查看 Twemoji 是否可从当前域名加载 */
    probeAssets() {
        if (typeof window === 'undefined') return Promise.resolve({ ok: false });
        const sample = this.getTwemojiLocalBase() + '1f375.png';
        return fetch(sample, { method: 'HEAD', cache: 'no-store' })
            .then((res) => {
                const ok = res.ok;
                console.log('[Twemoji] probe', sample, ok ? 'OK' : 'HTTP ' + res.status);
                return { ok, url: sample, status: res.status, base: this.getSiteBase() };
            })
            .catch((e) => {
                console.warn('[Twemoji] probe failed', sample, e.message || e);
                return { ok: false, url: sample, error: String(e.message || e) };
            });
    },

    paradeResolve(shape, groupIndex, tag, wordSeed) {
        const theme = this.resolve(tag, wordSeed != null ? wordSeed : groupIndex);
        const shapes =
            theme.packType === 'twemoji'
                ? this.paradeShapesTwemoji[shape] || this.paradeShapesTwemoji.cloud
                : this.paradeShapesNative[shape] || this.paradeShapesNative.cloud;
        return {
            icon: shapes[groupIndex % shapes.length],
            packType: theme.packType,
            key: theme.key
        };
    },

    paradeMarkup(shape, groupIndex, tag, wordSeed, sizePx) {
        const p = this.paradeResolve(shape, groupIndex, tag, wordSeed);
        const theme = { key: p.key, icon: p.icon, packType: p.packType, packLabel: p.packType === 'twemoji' ? 'Twemoji' : 'Unicode' };
        if (p.packType === 'twemoji') {
            const inner = this.stickerMarkup(theme, 'parade-shape-sticker');
            return { html: inner, isHtml: true, sizePx: sizePx || 48 };
        }
        return { html: p.icon, isHtml: false, sizePx: sizePx || 48 };
    },

    /** @deprecated 使用 paradeMarkup */
    paradeIcon(shape, groupIndex) {
        const pack = this.paradeShapesNative[shape] || this.paradeShapesNative.cloud;
        return pack[groupIndex % pack.length];
    }
};

if (typeof window !== 'undefined') {
    window.WordThemes = WordThemes;
}
