/**
 * 自动锁屏插件
 * 在设定时间内无操作时自动锁屏，需输入自定义密码解锁
 * 遮罩覆盖整个聊天区域，保护隐私
 */

const fs = require('fs');
const path = require('path');

module.exports = {
    name: '自动锁屏',
    description: '设定时间内无操作自动锁屏，需输入密码解锁，保护聊天隐私',
    version: 'dev',
    author: 'zfeng',
    defaultEnabled: false,

    defaultConfig: {
        timeout: '5',           // 锁屏超时时间（分钟）
        password: '123456',           // 自定义密码（为空则首次锁屏时引导设置）
    },

    configMeta: {
        timeout: {
            label: '⏰ 自动锁屏时间',
            options: [
                { value: '0.5', label: '30 秒无操作（调试）' },
                { value: '5',   label: '5 分钟无操作' },
                { value: '10',  label: '10 分钟无操作' },
                { value: '30',  label: '30 分钟无操作' },
            ]
        },
        password: {
            label: '🔑 解锁密码'
        }
    },

    STYLE_ID: 'plugin-auto-lock-screen-styles',
    OVERLAY_ID: 'plugin-lock-screen-overlay',

    // 系统空闲检测轮询间隔（毫秒）
    IDLE_POLL_INTERVAL: 2000,

    /**
     * 获取 @electron/remote 模块（复用 water-reminder 的兼容逻辑）
     */
    _getElectronRemote() {
        try { return require('@electron/remote'); } catch (e) { /* ignore */ }

        let parentModule = module.parent;
        while (parentModule) {
            try { return parentModule.require('@electron/remote'); } catch (e) { parentModule = parentModule.parent; }
        }

        if (process.mainModule) {
            try { return process.mainModule.require('@electron/remote'); } catch (e) { /* ignore */ }
        }

        return null;
    },

    /**
     * 读取外部 CSS 样式文件
     */
    _loadCSS() {
        try {
            const cssPath = path.join(__dirname, 'styles.css');
            return fs.readFileSync(cssPath, 'utf-8');
        } catch (e) {
            window.PluginManager.log('auto-lock-screen', `[AutoLockScreen] 加载样式文件失败: ${e.message || e}`);
            return '';
        }
    },

    /**
     * 注入样式到页面
     */
    _injectStyles() {
        if (document.getElementById(this.STYLE_ID)) return;
        const style = document.createElement('style');
        style.id = this.STYLE_ID;
        style.textContent = this._loadCSS();
        document.head.appendChild(style);
    },

    /**
     * 直接保存密码到插件配置文件（不触发 destroy → init 重启周期）
     */
    _savePasswordDirect(pluginManager, password) {
        try {
            const config = pluginManager.pluginConfigs.get('auto-lock-screen');
            if (config) {
                config.config.password = password;
                pluginManager.saveConfig();
                window.PluginManager.log('auto-lock-screen', '[AutoLockScreen] ✅ 密码已直接保存到配置文件');
            }
        } catch (error) {
            window.PluginManager.log('auto-lock-screen', `[AutoLockScreen] ❌ 保存密码失败: ${error.message || error}`);
        }
    },

    /**
     * 获取当前时间字符串
     */
    _getTimeStr() {
        const now = new Date();
        return now.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit',
            hour12: false
        });
    },

    /**
     * 获取当前日期字符串
     */
    _getDateStr() {
        const now = new Date();
        const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        const month = now.getMonth() + 1;
        const day = now.getDate();
        const weekDay = weekDays[now.getDay()];
        return `${month}月${day}日 ${weekDay}`;
    },

    /**
     * 构建锁屏界面 HTML
     * @param {boolean} isSetup - 是否为首次设置密码模式
     */
    _buildLockHTML(isSetup) {
        const timeStr = this._getTimeStr();
        const dateStr = this._getDateStr();

        const setupHint = isSetup ? `
            <div class="als-setup-hint">
                <span class="als-setup-hint-icon">💡</span>
                <span class="als-setup-hint-text">首次使用锁屏，请设置一个解锁密码。<br>密码将自动保存到插件配置中。</span>
            </div>
        ` : '';

        const confirmField = isSetup ? `
            <div class="als-confirm-group">
                <div class="als-password-group">
                    <label class="als-password-label">确认密码</label>
                    <div class="als-password-wrapper" id="als-confirm-wrapper">
                        <span class="als-password-icon">🔐</span>
                        <input type="password" class="als-password-input" id="als-confirm-input"
                               placeholder="请再次输入密码" autocomplete="off" />
                        <button class="als-password-toggle" id="als-confirm-toggle" tabindex="-1" title="显示/隐藏密码">👁️</button>
                    </div>
                </div>
            </div>
        ` : '';

        const passwordLabel = isSetup ? '设置密码' : '请输入密码';
        const passwordPlaceholder = isSetup ? '请输入新密码 (至少4位)' : '请输入解锁密码';
        const btnText = isSetup ? '🔐 设置密码并解锁' : '🔓 解锁';

        return `
            <div class="als-card">
                <div class="als-header">
                    <div class="als-lock-icon">🔒</div>
                    <p class="als-title">屏幕已锁定</p>
                    <p class="als-subtitle">${isSetup ? '请设置密码以保护您的隐私' : '请输入密码以解锁'}</p>
                </div>
                <div class="als-body">
                    <div class="als-clock">
                        <div class="als-clock-time" id="als-clock-time">${timeStr}</div>
                        <div class="als-clock-date" id="als-clock-date">${dateStr}</div>
                    </div>
                    ${setupHint}
                    <div class="als-password-group">
                        <label class="als-password-label">${passwordLabel}</label>
                        <div class="als-password-wrapper" id="als-password-wrapper">
                            <span class="als-password-icon">🔑</span>
                            <input type="password" class="als-password-input" id="als-password-input"
                                   placeholder="${passwordPlaceholder}" autocomplete="off" />
                            <button class="als-password-toggle" id="als-password-toggle" tabindex="-1" title="显示/隐藏密码">👁️</button>
                        </div>
                    </div>
                    ${confirmField}
                    <div class="als-error-msg" id="als-error-msg"></div>
                    <button class="als-unlock-btn" id="als-unlock-btn">${btnText}</button>
                </div>
                <div class="als-footer">
                    <p class="als-footer-hint">自动锁屏插件 · 保护您的隐私安全</p>
                </div>
            </div>
        `;
    },

    /**
     * 显示锁屏遮罩
     */
    _showLockScreen(instance) {
        if (instance._locked) return;
        instance._locked = true;

        const isSetup = !instance.config.password;

        const overlay = document.createElement('div');
        overlay.id = this.OVERLAY_ID;
        overlay.innerHTML = this._buildLockHTML(isSetup);
        document.body.appendChild(overlay);
        instance._overlay = overlay;

        // 启动时钟刷新
        instance._clockTimer = setInterval(() => {
            const timeEl = overlay.querySelector('#als-clock-time');
            const dateEl = overlay.querySelector('#als-clock-date');
            if (timeEl) timeEl.textContent = this._getTimeStr();
            if (dateEl) dateEl.textContent = this._getDateStr();
        }, 1000);

        // 绑定事件
        this._bindLockEvents(instance, isSetup);

        // 自动聚焦密码输入框
        setTimeout(() => {
            const input = overlay.querySelector('#als-password-input');
            if (input) input.focus();
        }, 500);

        window.PluginManager.log('auto-lock-screen', `[AutoLockScreen] 🔒 屏幕已锁定 (${isSetup ? '首次设置密码模式' : '密码验证模式'})`);
    },

    /**
     * 绑定锁屏界面事件
     */
    _bindLockEvents(instance, isSetup) {
        const overlay = instance._overlay;
        if (!overlay) return;

        const self = this;
        const passwordInput = overlay.querySelector('#als-password-input');
        const passwordToggle = overlay.querySelector('#als-password-toggle');
        const unlockBtn = overlay.querySelector('#als-unlock-btn');
        const errorMsg = overlay.querySelector('#als-error-msg');
        const passwordWrapper = overlay.querySelector('#als-password-wrapper');

        let confirmInput, confirmToggle, confirmWrapper;
        if (isSetup) {
            confirmInput = overlay.querySelector('#als-confirm-input');
            confirmToggle = overlay.querySelector('#als-confirm-toggle');
            confirmWrapper = overlay.querySelector('#als-confirm-wrapper');
        }

        // 密码显示/隐藏切换
        const togglePassword = (input, toggle) => {
            if (input.type === 'password') {
                input.type = 'text';
                toggle.textContent = '🙈';
            } else {
                input.type = 'password';
                toggle.textContent = '👁️';
            }
        };

        passwordToggle.addEventListener('click', () => togglePassword(passwordInput, passwordToggle));
        if (confirmToggle && confirmInput) {
            confirmToggle.addEventListener('click', () => togglePassword(confirmInput, confirmToggle));
        }

        // 显示错误
        const showError = (msg) => {
            errorMsg.textContent = msg;
            errorMsg.classList.add('als-visible');
            passwordWrapper.classList.add('als-error');
            if (confirmWrapper) confirmWrapper.classList.add('als-error');
            setTimeout(() => {
                passwordWrapper.classList.remove('als-error');
                if (confirmWrapper) confirmWrapper.classList.remove('als-error');
            }, 400);
        };

        // 清除错误
        const clearError = () => {
            errorMsg.textContent = '';
            errorMsg.classList.remove('als-visible');
        };

        // 输入时清除错误
        passwordInput.addEventListener('input', clearError);
        if (confirmInput) confirmInput.addEventListener('input', clearError);

        // 解锁逻辑
        const attemptUnlock = () => {
            const pwd = passwordInput.value.trim();

            if (isSetup) {
                // 设置密码模式
                if (pwd.length < 4) {
                    showError('密码至少需要 4 位字符');
                    passwordInput.focus();
                    return;
                }
                const confirmPwd = confirmInput ? confirmInput.value.trim() : '';
                if (pwd !== confirmPwd) {
                    showError('两次输入的密码不一致');
                    confirmInput.focus();
                    return;
                }
                // 保存密码到配置（直接修改配置并持久化，避免 updatePluginConfig 触发 destroy → init 重启）
                instance.config.password = pwd;
                self._savePasswordDirect(instance._pluginManager, pwd);
                self._hideLockScreen(instance);
            } else {
                // 验证密码模式
                if (!pwd) {
                    showError('请输入密码');
                    passwordInput.focus();
                    return;
                }
                if (pwd !== instance.config.password) {
                    showError('密码错误，请重试');
                    passwordInput.value = '';
                    passwordInput.focus();
                    return;
                }
                self._hideLockScreen(instance);
            }
        };

        unlockBtn.addEventListener('click', attemptUnlock);

        // 支持回车键解锁
        const onEnter = (e) => {
            if (e.key === 'Enter') {
                attemptUnlock();
            }
        };
        passwordInput.addEventListener('keydown', onEnter);
        if (confirmInput) confirmInput.addEventListener('keydown', onEnter);

        // 阻止遮罩层上的所有键盘事件传播到底层
        overlay.addEventListener('keydown', (e) => {
            // 只允许在输入框内操作，阻止 Tab 逃逸到遮罩外
            const allowedTargets = [passwordInput, confirmInput, unlockBtn, passwordToggle, confirmToggle].filter(Boolean);
            if (!allowedTargets.includes(e.target)) {
                e.preventDefault();
                e.stopPropagation();
                passwordInput.focus();
            }
        });

        // 阻止鼠标点击穿透
        overlay.addEventListener('mousedown', (e) => {
            e.stopPropagation();
        });
    },

    /**
     * 隐藏锁屏遮罩
     */
    _hideLockScreen(instance) {
        if (!instance._locked) return;

        const overlay = instance._overlay;
        if (overlay) {
            // 播放解锁动画
            overlay.classList.add('als-unlocking');
            setTimeout(() => {
                overlay.remove();
            }, 400);
        }

        if (instance._clockTimer) {
            clearInterval(instance._clockTimer);
            instance._clockTimer = null;
        }

        instance._overlay = null;
        instance._locked = false;

        window.PluginManager.log('auto-lock-screen', '[AutoLockScreen] 🔓 屏幕已解锁');
    },

    /**
     * 启动系统级空闲检测轮询
     * 使用 Electron powerMonitor.getSystemIdleTime() 获取 OS 级空闲秒数
     * 检测全局鼠标、键盘活动，不局限于 IM 窗口
     */
    _startIdlePolling(instance) {
        const self = this;
        const timeoutSec = (parseFloat(instance.config.timeout) || 5) * 60;

        window.PluginManager.log('auto-lock-screen', `[AutoLockScreen] 🔍 启动系统空闲检测，阈值: ${timeoutSec} 秒`);

        instance._idlePollTimer = setInterval(() => {
            if (instance._locked) return; // 已锁屏，跳过检测

            try {
                const idleSeconds = instance._powerMonitor.getSystemIdleTime();
                if (idleSeconds >= timeoutSec) {
                    window.PluginManager.log('auto-lock-screen', `[AutoLockScreen] ⏰ 系统空闲 ${idleSeconds} 秒，超过阈值 ${timeoutSec} 秒，自动锁屏`);
                    self._showLockScreen(instance);
                }
            } catch (error) {
                window.PluginManager.log('auto-lock-screen', `[AutoLockScreen] 获取系统空闲时间失败: ${error.message || error}`);
            }
        }, this.IDLE_POLL_INTERVAL);
    },

    /**
     * 停止空闲检测轮询
     */
    _stopIdlePolling(instance) {
        if (instance._idlePollTimer) {
            clearInterval(instance._idlePollTimer);
            instance._idlePollTimer = null;
        }
    },

    // ========== 生命周期 ==========

    async init(config, pluginManager) {
        window.PluginManager.log('auto-lock-screen', '[AutoLockScreen] 🚀 初始化自动锁屏插件...');

        // 预检查 powerMonitor 是否可用
        const remote = this._getElectronRemote();
        if (!remote || !remote.powerMonitor || typeof remote.powerMonitor.getSystemIdleTime !== 'function') {
            const msg = 'powerMonitor.getSystemIdleTime 不可用，无法检测系统空闲时间';
            window.PluginManager.log('auto-lock-screen', `[AutoLockScreen] ❌ ${msg}`);
            return { success: false, message: msg };
        }

        const instance = {
            config,
            _pluginManager: pluginManager,
            _powerMonitor: remote.powerMonitor,
            _locked: false,
            _overlay: null,
            _idlePollTimer: null,
            _clockTimer: null,
        };

        // 注入样式
        this._injectStyles();

        // 启动系统级空闲检测轮询
        this._startIdlePolling(instance);

        const timeoutMin = parseFloat(config.timeout) || 5;
        window.PluginManager.log('auto-lock-screen', `[AutoLockScreen] ✅ 插件已启动，系统空闲 ${timeoutMin} 分钟后自动锁屏（检测全局鼠标/键盘活动）`);
        if (!config.password) {
            window.PluginManager.log('auto-lock-screen', '[AutoLockScreen] ⚠️ 尚未设置密码，首次锁屏时将引导设置');
        }

        return instance;
    },

    async destroy(instance) {
        window.PluginManager.log('auto-lock-screen', '[AutoLockScreen] 🔄 销毁自动锁屏插件...');

        // 停止空闲检测轮询
        this._stopIdlePolling(instance);

        // 移除锁屏遮罩
        if (instance._overlay) {
            instance._overlay.remove();
            instance._overlay = null;
        }
        if (instance._clockTimer) {
            clearInterval(instance._clockTimer);
            instance._clockTimer = null;
        }
        instance._locked = false;

        // 移除注入的样式
        const style = document.getElementById(this.STYLE_ID);
        if (style) style.remove();

        window.PluginManager.log('auto-lock-screen', '[AutoLockScreen] ✅ 插件已销毁');
    }
};
