/**
 * 流转心语 · 桌宠条（仅顶部心语轮播，无木鱼交互）
 */

class PetWordsApp {
    constructor() {
        this.state = {
            cloudWords: [],
            rotationPaused: false
        };
        this.motion = {
            cloudTrackSec: 100,
            cloudRefreshMs: 120000
        };
        this._refreshTimer = null;
        this.elements = {};
        this.init();
    }

    assetUrl(path) {
        const base =
            typeof window !== 'undefined' && window.MUYU_ASSET_BASE != null
                ? String(window.MUYU_ASSET_BASE).replace(/\/?$/, '/')
                : '/';
        const p = String(path || '').replace(/^\//, '');
        return base + p;
    }

    async init() {
        this.elements.cloudWordsTrack = document.getElementById('cloudWordsTrack');
        if (typeof WordThemes !== 'undefined' && WordThemes.probeAssets) {
            WordThemes.probeAssets();
        }
        this.bindElectronIpc();
        this.initDesktopSettings();
        await this.loadCloudWords();
        this.renderCloudWords();
        this.startCloudWordsRotation();
    }

    bindElectronIpc() {
        if (!window.petDesktop || typeof window.petDesktop.onCommand !== 'function') {
            return;
        }
        window.petDesktop.onCommand((cmd) => {
            if (cmd === 'pause-rotation') {
                this.setRotationPaused(true);
            } else if (cmd === 'resume-rotation') {
                this.setRotationPaused(false);
            } else if (cmd === 'refresh-words') {
                this.refreshWords();
            } else if (cmd === 'click-through-on') {
                document.body.classList.add('pet-click-through');
                this.showClickThroughBanner();
                this.syncDesktopSettingsUi({ clickThrough: true });
            } else if (cmd === 'click-through-off') {
                document.body.classList.remove('pet-click-through');
                this.removeClickThroughBanner();
                this.syncDesktopSettingsUi({ clickThrough: false });
            } else if (cmd === 'click-through-hint') {
                this.showClickThroughBanner();
            } else if (cmd && cmd.indexOf('opacity-') === 0) {
                const pct = parseInt(cmd.replace('opacity-', ''), 10);
                if (!Number.isNaN(pct)) {
                    this.syncDesktopSettingsUi({ windowOpacity: pct / 100 });
                }
            }
        });
    }

    showClickThroughBanner() {
        this.removeClickThroughBanner();
        const el = document.createElement('div');
        el.className = 'pet-clickthrough-banner';
        el.id = 'petClickThroughBanner';
        el.textContent = '穿透中 · 托盘右键关闭，或按 Ctrl+Shift+M';
        document.body.appendChild(el);
        if (this._clickThroughBannerTimer) clearTimeout(this._clickThroughBannerTimer);
        this._clickThroughBannerTimer = setTimeout(() => this.removeClickThroughBanner(), 8000);
    }

    removeClickThroughBanner() {
        if (this._clickThroughBannerTimer) {
            clearTimeout(this._clickThroughBannerTimer);
            this._clickThroughBannerTimer = null;
        }
        const el = document.getElementById('petClickThroughBanner');
        if (el) el.remove();
    }

    isDesktopEnv() {
        if (window.petDesktop && window.petDesktop.isDesktop) return true;
        return new URLSearchParams(location.search).get('desktop') === '1';
    }

    getDesktopApi() {
        return window.petDesktop && window.petDesktop.isDesktop ? window.petDesktop : null;
    }

    initDesktopSettings() {
        if (!this.isDesktopEnv()) return;

        document.body.classList.add('pet-is-desktop');

        const btn = document.getElementById('petSettingsBtn');
        const popover = document.getElementById('petSettingsPopover');
        const range = document.getElementById('petOpacityRange');
        const valueEl = document.getElementById('petOpacityValue');
        const loginCb = document.getElementById('petOpenAtLogin');
        const loginNote = document.getElementById('petOpenAtLoginNote');
        const throughCb = document.getElementById('petClickThrough');
        const unavailable = document.getElementById('petSettingsUnavailable');

        if (!btn || !popover || !range) return;

        this._desktopSettings = {
            btn,
            popover,
            range,
            valueEl,
            loginCb,
            loginNote,
            throughCb,
            unavailable
        };

        const setPopoverOpen = (open) => {
            popover.hidden = !open;
            btn.classList.toggle('is-open', open);
            btn.setAttribute('aria-expanded', open ? 'true' : 'false');
        };

        btn.addEventListener('click', (e) => {
            e.stopPropagation();
            setPopoverOpen(popover.hidden);
        });

        document.addEventListener('click', (e) => {
            if (popover.hidden) return;
            if (popover.contains(e.target) || btn.contains(e.target)) return;
            setPopoverOpen(false);
        });

        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && !popover.hidden) setPopoverOpen(false);
        });

        range.addEventListener('input', () => {
            const pct = parseInt(range.value, 10);
            if (valueEl) valueEl.textContent = pct + '%';
        });

        range.addEventListener('change', () => {
            const api = this.getDesktopApi();
            const pct = parseInt(range.value, 10);
            if (api && typeof api.setOpacity === 'function') {
                api.setOpacity(pct / 100);
            }
        });

        if (loginCb) {
            loginCb.addEventListener('change', () => {
                const api = this.getDesktopApi();
                if (api && typeof api.setOpenAtLogin === 'function') {
                    api.setOpenAtLogin(loginCb.checked);
                }
            });
        }

        if (throughCb) {
            throughCb.addEventListener('change', () => {
                const api = this.getDesktopApi();
                if (api && typeof api.setClickThrough === 'function') {
                    api.setClickThrough(throughCb.checked);
                }
            });
        }

        const bindApi = () => {
            const api = this.getDesktopApi();
            if (!api) {
                if (popover) popover.classList.add('is-disabled');
                if (unavailable) unavailable.hidden = false;
                return;
            }
            if (popover) popover.classList.remove('is-disabled');
            if (unavailable) unavailable.hidden = true;

            if (typeof api.onSettingsChanged === 'function') {
                api.onSettingsChanged((settings) => this.syncDesktopSettingsUi(settings));
            }
            if (typeof api.getSettings === 'function') {
                api.getSettings().then((s) => this.syncDesktopSettingsUi(s));
            }
        };

        bindApi();
        if (!this.getDesktopApi()) {
            let tries = 0;
            const timer = setInterval(() => {
                tries += 1;
                if (this.getDesktopApi() || tries > 20) {
                    clearInterval(timer);
                    bindApi();
                }
            }, 100);
        }
    }

    syncDesktopSettingsUi(settings) {
        if (!settings || !this._desktopSettings) return;
        const { range, valueEl, loginCb, loginNote, throughCb } = this._desktopSettings;

        if (settings.windowOpacity != null && range) {
            const pct = Math.round(Number(settings.windowOpacity) * 100);
            const min = parseInt(range.min, 10) || 35;
            const max = parseInt(range.max, 10) || 100;
            const clamped = Math.min(max, Math.max(min, pct));
            range.value = String(clamped);
            if (valueEl) valueEl.textContent = clamped + '%';
        }

        if (loginCb) {
            loginCb.checked = !!settings.openAtLogin;
            loginCb.disabled = settings.canOpenAtLogin === false;
            if (loginNote) {
                loginNote.textContent = settings.canOpenAtLogin
                    ? '（关闭后系统将不再自动启动本程序）'
                    : '（安装版可用）';
            }
        }

        if (throughCb && settings.clickThrough != null) {
            throughCb.checked = !!settings.clickThrough;
        }
    }

    setRotationPaused(paused) {
        this.state.rotationPaused = !!paused;
        const track = this.elements.cloudWordsTrack;
        if (track) {
            track.classList.toggle('paused', this.state.rotationPaused);
        }
    }

    async refreshWords() {
        await this.loadCloudWords();
        this.renderCloudWords();
    }

    sleep(ms) {
        return new Promise((resolve) => setTimeout(resolve, ms));
    }

    mapMoodStatusRows(rows) {
        return (rows || [])
            .map((item, idx) => ({
                id: item._id || `status_${idx}`,
                wordsText: String(item.text || '').trim(),
                wordsImg: item.emoji || '',
                tag: '静心平和',
                templateType: (idx % 6) + 1
            }))
            .filter((w) => w.wordsText);
    }

    mapMoodCardRows(rows) {
        return (rows || [])
            .map((item, idx) => ({
                id: item._id || `card_${idx}`,
                wordsText: String(item.text || '').trim(),
                wordsImg: item.photo || item.emoji || '',
                tag: '静心平和',
                templateType: (idx % 6) + 1
            }))
            .filter((w) => w.wordsText);
    }

    async queryCloudCollection(db, name, buildQuery, retries) {
        const times = retries || 2;
        let lastErr;
        for (let i = 0; i < times; i += 1) {
            try {
                if (i > 0) await this.sleep(2000);
                const { data } = await buildQuery(db);
                return data || [];
            } catch (e) {
                lastErr = e;
                console.warn(`[Cloud] ${name} 第 ${i + 1} 次读取失败:`, e.message || e);
            }
        }
        throw lastErr || new Error(name + ' read failed');
    }

    async loadCloudWords() {
        const applyWords = (words, source) => {
            if (!words.length) return false;
            this.state.cloudWords = words;
            console.log('[Pet] 已加载', words.length, '条，来源', source);
            this.mergeWithDefaults();
            return true;
        };

        try {
            if (!window.cloudbase) {
                throw new Error('CloudBase 未初始化');
            }

            const db = window.cloudbase.database();
            const now = Date.now();
            const cmd = db.command;

            try {
                const statuses = await this.queryCloudCollection(db, 'mood_status_pool', (database) =>
                    database
                        .collection('mood_status_pool')
                        .where({ expiresAt: cmd.gt(now) })
                        .orderBy('publishedAt', 'desc')
                        .limit(100)
                        .get()
                );
                if (applyWords(this.mapMoodStatusRows(statuses), 'mood_status_pool')) return;
            } catch (e) {
                console.warn('[Cloud] mood_status_pool 不可用:', e.message || e);
            }

            try {
                const cards = await this.queryCloudCollection(db, 'mood_cards', (database) =>
                    database
                        .collection('mood_cards')
                        .where({ expiresAt: cmd.gt(now) })
                        .orderBy('publishedAt', 'desc')
                        .limit(100)
                        .get()
                );
                if (applyWords(this.mapMoodCardRows(cards), 'mood_cards')) return;
            } catch (e) {
                console.warn('[Cloud] mood_cards 不可用:', e.message || e);
            }

            console.warn('[Pet] 云端无可用心语，使用本地默认');
            this.state.cloudWords = this.getDefaultWords();
        } catch (error) {
            console.warn('[Pet] loadCloudWords 失败:', error.message || error);
            this.state.cloudWords = this.getDefaultWords();
        }
    }

    getDefaultWords() {
        return [
            { id: 1, wordsText: '心静自然凉，万物皆安宁', tag: '静心平和', templateType: 1 },
            { id: 2, wordsText: '今日阳光正好，心情明媚', tag: '轻松愉悦', templateType: 2 },
            { id: 3, wordsText: '深呼吸，让压力随风而去', tag: '舒缓解压', templateType: 3 },
            { id: 4, wordsText: '愿你被世界温柔以待', tag: '温柔寄语', templateType: 4 },
            { id: 5, wordsText: '慢下来，感受生活的美好', tag: '静心平和', templateType: 5 },
            { id: 6, wordsText: '每一个当下都是礼物', tag: '轻松愉悦', templateType: 6 },
            { id: 7, wordsText: '放下烦恼，拥抱宁静', tag: '舒缓解压', templateType: 1 },
            { id: 8, wordsText: '心中有光，前路自明', tag: '温柔寄语', templateType: 2 },
            { id: 9, wordsText: '生活不止眼前的苟且', tag: '静心平和', templateType: 3 },
            { id: 10, wordsText: '你笑起来真好看', tag: '轻松愉悦', templateType: 4 },
            { id: 11, wordsText: '世界很大，幸福很小', tag: '温柔寄语', templateType: 5 },
            { id: 12, wordsText: '今天的你也很棒', tag: '轻松愉悦', templateType: 6 },
            { id: 13, wordsText: '一切都会好起来的', tag: '静心平和', templateType: 1 },
            { id: 14, wordsText: '保持热爱，奔赴山海', tag: '温柔寄语', templateType: 2 },
            { id: 15, wordsText: '岁月静好，现世安稳', tag: '静心平和', templateType: 3 },
            { id: 16, wordsText: '且听风吟，且看花开', tag: '舒缓解压', templateType: 4 },
            { id: 17, wordsText: '做自己的太阳，无需借光', tag: '轻松愉悦', templateType: 5 },
            { id: 18, wordsText: '温柔半两，从容一生', tag: '温柔寄语', templateType: 6 },
            { id: 19, wordsText: '山水万程，皆要好运', tag: '静心平和', templateType: 1 },
            { id: 20, wordsText: '日日是好日，处处是花香', tag: '轻松愉悦', templateType: 2 },
            { id: 21, wordsText: '心之所向，素履以往', tag: '舒缓解压', templateType: 3 },
            { id: 22, wordsText: '繁星不问赶路人', tag: '温柔寄语', templateType: 4 },
            { id: 23, wordsText: '人间值得，未来可期', tag: '静心平和', templateType: 5 },
            { id: 24, wordsText: '所念皆星河，所遇皆温柔', tag: '轻松愉悦', templateType: 6 },
            { id: 25, wordsText: '清风徐来，水波不兴', tag: '舒缓解压', templateType: 1 },
            { id: 26, wordsText: '但愿人长久，千里共婵娟', tag: '温柔寄语', templateType: 2 },
            { id: 27, wordsText: '一花一世界，一叶一菩提', tag: '静心平和', templateType: 3 },
            { id: 28, wordsText: '以欢喜心，慢度日常', tag: '轻松愉悦', templateType: 4 },
            { id: 29, wordsText: '不负韶华，不负自己', tag: '舒缓解压', templateType: 5 },
            { id: 30, wordsText: '万事胜意，喜乐长安', tag: '温柔寄语', templateType: 6 }
        ];
    }

    mergeWithDefaults() {
        const defaults = this.getDefaultWords();
        const existingTexts = new Set(this.state.cloudWords.map((w) => w.wordsText));
        const extra = defaults.filter((d) => !existingTexts.has(d.wordsText));
        if (extra.length > 0) {
            this.state.cloudWords = [...this.state.cloudWords, ...extra];
            console.log('[Pet] Merged', extra.length, 'default words');
        }
    }

    getWordTheme(tag, seed) {
        if (typeof WordThemes !== 'undefined') {
            return WordThemes.resolve(tag, seed);
        }
        return { key: 'neutral', short: '心语', icon: '✨', packType: 'native' };
    }

    moodStickerHtml(theme, extraClass) {
        if (typeof WordThemes !== 'undefined' && WordThemes.stickerMarkup) {
            return WordThemes.stickerMarkup(theme, extraClass || '');
        }
        return (
            '<span class="mood-sticker ' +
            (extraClass || '') +
            '">' +
            (theme.icon || '✨') +
            '</span>'
        );
    }

    getCardVariant(templateType) {
        const n = parseInt(templateType, 10);
        if (n >= 1 && n <= 6) return n;
        return ((n || 1) % 6) + 1;
    }

    escapeHtml(text) {
        return String(text == null ? '' : text)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }

    renderCloudWords() {
        const track = this.elements.cloudWordsTrack;
        if (!track) return;
        track.innerHTML = '';

        const inner = document.createElement('div');
        inner.className = 'cloud-words-track-inner';

        const words = this.state.cloudWords;
        const allWords = [...words, ...words];

        allWords.forEach((word, index) => {
            const text = word.wordsText || word.text;
            const tagLabel = word.tag || '静心平和';
            const seed = word.id != null ? word.id : index;
            const theme = this.getWordTheme(tagLabel, seed);
            const variant = this.getCardVariant(word.templateType);
            const card = document.createElement('div');
            card.className =
                'cloud-word-card cloud-card-v' +
                variant +
                ' mood-' +
                theme.key;
            card.style.animationDelay = (index % 8) * 0.15 + 's';
            card.innerHTML =
                '<div class="cloud-card-glow" aria-hidden="true"></div>' +
                '<div class="cloud-card-quote" aria-hidden="true">“</div>' +
                '<div class="cloud-word-head">' +
                this.moodStickerHtml(theme, 'cloud-sticker') +
                '<span class="cloud-word-variant-dot"></span>' +
                '</div>' +
                '<div class="cloud-word-text">' +
                this.escapeHtml(text) +
                '</div>' +
                '<div class="cloud-word-foot">' +
                '<span class="cloud-word-tag">' +
                this.escapeHtml(theme.short) +
                '</span>' +
                '</div>';
            inner.appendChild(card);
        });

        track.appendChild(inner);
        inner.style.animationDuration = this.motion.cloudTrackSec + 's';
        track.classList.toggle('paused', this.state.rotationPaused);
    }

    startCloudWordsRotation() {
        if (this._refreshTimer) clearInterval(this._refreshTimer);
        this._refreshTimer = setInterval(() => {
            if (this.state.rotationPaused) return;
            this.loadCloudWords().then(() => this.renderCloudWords());
        }, this.motion.cloudRefreshMs);
    }
}

function bootPetApp() {
    window.petWordsApp = new PetWordsApp();
}

document.addEventListener('DOMContentLoaded', () => {
    if (window.cloudbase && !window._cloudReady) {
        window.addEventListener('cloudReady', bootPetApp, { once: true });
        setTimeout(() => {
            if (!window.petWordsApp) {
                console.warn('[Cloud] Auth timeout, init pet with fallback');
                bootPetApp();
            }
        }, 5000);
    } else {
        bootPetApp();
    }
});
