/**
 * 快捷入口插件
 * 在 IM 导航栏中添加快捷入口图标，点击后弹出面板可快速打开腾讯文档、腾讯会议等应用
 * 支持粘贴检测：自动识别腾讯文档链接和腾讯会议会议号，轻量弹框引导快捷操作
 */

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

module.exports = {
    name: '快捷入口',
    description: '在导航栏添加快捷入口，支持一键打开腾讯文档、腾讯会议等常用工具',
    version: 'dev',
    author: 'zfeng',
    defaultEnabled: false,

    defaultConfig: {},

    // ---- 快捷入口项配置 ----
    _shortcuts: [
        {
            id: 'tencent-docs',
            name: '腾讯文档',
            icon: `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 384 512" fill="currentColor"><path d="M64 0C28.7 0 0 28.7 0 64V448c0 35.3 28.7 64 64 64H320c35.3 0 64-28.7 64-64V160H256c-17.7 0-32-14.3-32-32V0H64zM256 0V128H384L256 0zM112 256H272c8.8 0 16 7.2 16 16s-7.2 16-16 16H112c-8.8 0-16-7.2-16-16s7.2-16 16-16zm0 64H272c8.8 0 16 7.2 16 16s-7.2 16-16 16H112c-8.8 0-16-7.2-16-16s7.2-16 16-16zm0 64H272c8.8 0 16 7.2 16 16s-7.2 16-16 16H112c-8.8 0-16-7.2-16-16s7.2-16 16-16z"/></svg>`,
            color: '#4E8BF7',
            type: 'url',
            target: 'https://docs.qq.com',
            description: '在线协作文档'
        },
        {
            id: 'tencent-meeting',
            name: '腾讯会议',
            icon: `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4zM14 15H5V9h9v6z"/></svg>`,
            color: '#2B6BFF',
            type: 'protocol',
            target: 'wemeet://',
            fallbackUrl: 'https://meeting.tencent.com',
            description: '视频会议'
        }
    ],

    // ---- 导航栏图标 SVG (网格/方块样式，代表"快捷入口") ----
    _getNavIconSvg(color) {
        return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="${color}"><rect x="3" y="3" width="8" height="8" rx="1.5"/><rect x="13" y="3" width="8" height="8" rx="1.5"/><rect x="3" y="13" width="8" height="8" rx="1.5"/><rect x="13" y="13" width="8" height="8" rx="1.5"/></svg>`;
    },

    _getNavIconBase64(color) {
        return btoa(this._getNavIconSvg(color));
    },

    // ---- 注入样式（从外部 styles.css 文件加载） ----
    _injectStyles() {
        if (document.getElementById('shortcut-entry-styles')) return;
        try {
            const cssPath = path.join(__dirname, 'styles.css');
            const cssContent = fs.readFileSync(cssPath, 'utf-8');
            const style = document.createElement('style');
            style.id = 'shortcut-entry-styles';
            style.textContent = cssContent;
            document.head.appendChild(style);
        } catch (e) {
            console.error('[ShortcutEntry] 加载样式文件失败:', e);
        }
    },

    // ---- 打开目标 ----
    _openTarget(shortcut) {
        try {
            const { shell } = require('electron');
            if (shortcut.type === 'url') {
                shell.openExternal(shortcut.target);
                console.log(`[ShortcutEntry] 🔗 打开链接: ${shortcut.name} -> ${shortcut.target}`);
            } else if (shortcut.type === 'protocol') {
                // 协议唤起（如 wemeet://），跨平台兼容
                shell.openExternal(shortcut.target).catch((err) => {
                    console.warn(`[ShortcutEntry] ⚠️ 协议唤起失败，尝试 fallback:`, err);
                    if (shortcut.fallbackUrl) {
                        shell.openExternal(shortcut.fallbackUrl);
                    }
                });
                console.log(`[ShortcutEntry] 🚀 唤起应用: ${shortcut.name} -> ${shortcut.target}`);
            }
        } catch (e) {
            console.error(`[ShortcutEntry] 打开失败:`, e);
            const url = shortcut.type === 'url' ? shortcut.target : (shortcut.fallbackUrl || shortcut.target);
            window.open(url, '_blank');
        }
    },

    // ---- 剪贴板检测相关正则 ----
    _patterns: {
        // 腾讯文档链接：支持 docs.qq.com 各种子路径
        tencentDocs: /https?:\/\/docs\.qq\.com\/[^\s"'<>]+/i,
        // 腾讯会议入会链接：meeting.tencent.com 的各种路径
        tencentMeetingLink: /https?:\/\/meeting\.tencent\.com\/[^\s"'<>]+/i,
        // 腾讯会议会议号：
        //   格式 A: 3-3-3 或 3-3-4（用 - 或空格分隔），如 852-939-657、852 939 657
        //   格式 B: 连续 9~11 位纯数字，如 852939657
        //   边界采用"非数字"或行首行尾，兼容中文标点（如 ：852-939-657）
        tencentMeetingCode: /(?:^|[^\d])(\d{3}[\s-]\d{3}[\s-]\d{3,4})(?:[^\d]|$)/m,
        tencentMeetingCodePlain: /(?:^|[^\d])(\d{9,11})(?:[^\d]|$)/m,
    },

    /**
     * 分析文本中是否包含腾讯文档链接、腾讯会议链接或会议号
     * 优先级：腾讯会议号 > 腾讯会议入会链接 > 腾讯文档链接
     * @returns {{ type: 'docs'|'meeting'|'meeting-link', url: string, display: string } | null}
     */
    _detectContent(text) {
        if (!text || typeof text !== 'string') return null;

        // 1. 检测腾讯会议会议号（分隔格式，如 852-939-657）—— 优先级最高，schema 直接入会
        const meetingCodeMatch = text.match(this._patterns.tencentMeetingCode);
        if (meetingCodeMatch) {
            const raw = meetingCodeMatch[1].replace(/[\s-]/g, '');
            const formatted = raw.replace(/(\d{3})(\d{3})(\d{3,4})/, '$1-$2-$3');
            return {
                type: 'meeting',
                meetingCode: raw,
                url: `wemeet://page/inmeeting?meeting_code=${raw}`,
                display: formatted,
            };
        }

        // 2. 检测腾讯会议会议号（纯数字格式，如 852939657）
        //    仅在文本包含"会议"关键词时匹配，避免普通数字误触发
        if (/会议|meeting|wemeet/i.test(text)) {
            const plainMatch = text.match(this._patterns.tencentMeetingCodePlain);
            if (plainMatch) {
                const raw = plainMatch[1];
                const formatted = raw.replace(/(\d{3})(\d{3})(\d{3,4})/, '$1-$2-$3');
                return {
                    type: 'meeting',
                    meetingCode: raw,
                    url: `wemeet://page/inmeeting?meeting_code=${raw}`,
                    display: formatted,
                };
            }
        }

        // 3. 检测腾讯会议入会链接（兜底，无会议号时走链接入会）
        const meetingLinkMatch = text.match(this._patterns.tencentMeetingLink);
        if (meetingLinkMatch) {
            return {
                type: 'meeting-link',
                url: meetingLinkMatch[0],
                display: meetingLinkMatch[0].length > 45
                    ? meetingLinkMatch[0].substring(0, 42) + '...'
                    : meetingLinkMatch[0],
            };
        }

        // 4. 检测腾讯文档链接
        const docsMatch = text.match(this._patterns.tencentDocs);
        if (docsMatch) {
            return {
                type: 'docs',
                url: docsMatch[0],
                display: docsMatch[0].length > 50
                    ? docsMatch[0].substring(0, 47) + '...'
                    : docsMatch[0],
            };
        }

        return null;
    },

    /**
     * 创建轻量化 Toast 弹框
     */
    _createToast(detection) {
        // 移除已存在的 toast
        const existing = document.getElementById('shortcut-clipboard-toast');
        if (existing) existing.remove();

        const isDocs = detection.type === 'docs';
        const isMeeting = detection.type === 'meeting' || detection.type === 'meeting-link';
        const toast = document.createElement('div');
        toast.id = 'shortcut-clipboard-toast';
        toast.className = 'shortcut-toast';

        const iconColor = isDocs ? '#4E8BF7' : '#2B6BFF';
        const iconSvg = isDocs
            ? `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 384 512" fill="${iconColor}"><path d="M64 0C28.7 0 0 28.7 0 64V448c0 35.3 28.7 64 64 64H320c35.3 0 64-28.7 64-64V160H256c-17.7 0-32-14.3-32-32V0H64zM256 0V128H384L256 0zM112 256H272c8.8 0 16 7.2 16 16s-7.2 16-16 16H112c-8.8 0-16-7.2-16-16s7.2-16 16-16zm0 64H272c8.8 0 16 7.2 16 16s-7.2 16-16 16H112c-8.8 0-16-7.2-16-16s7.2-16 16-16zm0 64H272c8.8 0 16 7.2 16 16s-7.2 16-16 16H112c-8.8 0-16-7.2-16-16s7.2-16 16-16z"/></svg>`
            : `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="${iconColor}"><path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4zM14 15H5V9h9v6z"/></svg>`;

        const title = isDocs ? '检测到腾讯文档链接'
            : detection.type === 'meeting-link' ? '检测到腾讯会议链接'
            : '检测到腾讯会议号';
        const actionText = isDocs ? '打开' : '入会';

        toast.innerHTML = `
            <div class="shortcut-toast-icon" style="color: ${iconColor}; background: ${iconColor}18;">
                ${iconSvg}
            </div>
            <div class="shortcut-toast-body">
                <div class="shortcut-toast-title">${title}</div>
                <div class="shortcut-toast-detail">${detection.display}</div>
            </div>
            <div class="shortcut-toast-actions">
                <button class="shortcut-toast-btn primary" data-action="open">${actionText}</button>
                <button class="shortcut-toast-btn dismiss" data-action="dismiss">忽略</button>
            </div>
            <div class="shortcut-toast-progress"></div>
        `;

        // 打开操作
        toast.querySelector('[data-action="open"]').addEventListener('click', (e) => {
            e.stopPropagation();
            if (isDocs || detection.type === 'meeting-link') {
                // 文档链接和会议入会链接都用浏览器打开（meeting.tencent.com 会自动唤起客户端）
                this._openTarget({ type: 'url', target: detection.url, name: isDocs ? '腾讯文档' : '腾讯会议' });
            } else {
                // 会议号通过 wemeet:// schema 唤起
                this._openTarget({ type: 'protocol', target: detection.url, name: '腾讯会议', fallbackUrl: 'https://meeting.tencent.com' });
            }
            this._dismissToast(toast);
        });

        // 忽略操作
        toast.querySelector('[data-action="dismiss"]').addEventListener('click', (e) => {
            e.stopPropagation();
            this._dismissToast(toast);
        });

        document.body.appendChild(toast);

        // 动画显示
        requestAnimationFrame(() => {
            toast.classList.add('visible');
        });

        // 8 秒后自动消失
        const autoTimer = setTimeout(() => {
            this._dismissToast(toast);
        }, 8000);
        toast._autoTimer = autoTimer;

        return toast;
    },

    _dismissToast(toast) {
        if (!toast || !toast.parentNode) return;
        if (toast._autoTimer) clearTimeout(toast._autoTimer);
        toast.classList.remove('visible');
        toast.classList.add('hiding');
        setTimeout(() => {
            if (toast.parentNode) toast.remove();
        }, 300);
    },

    /**
     * 注册选中文字检测 —— 用户在消息区域划选文字后自动识别
     */
    _registerSelectionDetection(instance) {
        let lastSelectedText = '';
        let debounceTimer = null;

        const handler = () => {
            // 防抖：用户可能还在调整选区
            if (debounceTimer) clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => {
                try {
                    const sel = window.getSelection();
                    if (!sel || sel.isCollapsed) return;

                    const selectedText = sel.toString().trim();
                    if (!selectedText || selectedText.length < 6) return; // 太短的文本跳过
                    if (selectedText === lastSelectedText) return; // 与上次相同，跳过

                    // 检查选区是否在聊天消息区域内
                    const anchorNode = sel.anchorNode;
                    const msgArea = anchorNode?.parentElement?.closest?.('.rong-conversation-one-message')
                        || anchorNode?.parentElement?.closest?.('.rong-conversation-list');
                    if (!msgArea) return;

                    lastSelectedText = selectedText;

                    const detection = this._detectContent(selectedText);
                    if (detection) {
                        console.log('[ShortcutEntry] ✋ 选中文字检测到内容:', detection);
                        this._createToast(detection);
                    }
                } catch (e) {
                    // 选区访问偶尔可能异常，静默忽略
                }
            }, 500);
        };

        document.addEventListener('mouseup', handler);
        instance._selectionHandler = handler;
        console.log('[ShortcutEntry] ✋ 选中文字检测已启用');
    },

    /**
     * 注册剪贴板轮询检测 —— 复制后即时检测
     */
    _registerClipboardDetection(instance) {
        const { clipboard } = require('electron');
        let lastText = clipboard.readText() || '';  // 记录初始剪贴板内容，避免启动时误触发

        const pollInterval = setInterval(() => {
            try {
                const currentText = clipboard.readText();
                // 剪贴板内容未变化，跳过
                if (!currentText || currentText === lastText) return;

                lastText = currentText;
                const detection = this._detectContent(currentText);
                if (detection) {
                    console.log(`[ShortcutEntry] 📋 剪贴板检测到内容:`, detection);
                    this._createToast(detection);
                }
            } catch (e) {
                // 剪贴板访问偶尔可能异常，静默忽略
            }
        }, 1500);  // 每 1.5 秒检查一次

        instance._clipboardPollInterval = pollInterval;
        console.log('[ShortcutEntry] 📋 剪贴板轮询检测已启用');
    },

    // ---- 创建弹出面板 ----
    _createPanel() {
        const panel = document.createElement('div');
        panel.className = 'shortcut-panel';
        panel.id = 'shortcut-entry-panel';

        // 标题
        const title = document.createElement('div');
        title.className = 'shortcut-panel-title';
        title.textContent = '快捷入口';
        panel.appendChild(title);

        // 各快捷项
        this._shortcuts.forEach(shortcut => {
            const item = document.createElement('div');
            item.className = 'shortcut-item';
            item.dataset.id = shortcut.id;

            const iconWrap = document.createElement('div');
            iconWrap.className = 'shortcut-item-icon';
            iconWrap.style.background = shortcut.color + '18'; // 带透明度的背景
            iconWrap.style.color = shortcut.color;
            iconWrap.innerHTML = shortcut.icon;

            const info = document.createElement('div');
            info.className = 'shortcut-item-info';
            info.innerHTML = `
                <span class="shortcut-item-name">${shortcut.name}</span>
                <span class="shortcut-item-desc">${shortcut.description}</span>
            `;

            item.appendChild(iconWrap);
            item.appendChild(info);

            item.addEventListener('click', (e) => {
                e.stopPropagation();
                this._openTarget(shortcut);
                this._hidePanel(panel);
            });

            panel.appendChild(item);
        });

        document.body.appendChild(panel);
        return panel;
    },

    // ---- 显示面板 ----
    _showPanel(panel, anchorEl) {
        // 计算位置：在图标右侧弹出
        const rect = anchorEl.getBoundingClientRect();
        panel.style.left = (rect.right + 8) + 'px';
        panel.style.top = rect.top + 'px';

        // 确保不超出屏幕底部
        requestAnimationFrame(() => {
            const panelRect = panel.getBoundingClientRect();
            if (panelRect.bottom > window.innerHeight - 10) {
                panel.style.top = (window.innerHeight - panelRect.height - 10) + 'px';
            }
            panel.classList.add('visible');
        });
    },

    _hidePanel(panel) {
        panel.classList.remove('visible');
    },

    // ---- 注册导航栏图标 ----
    _registerNavIcon(instance) {
        const NAV_ICON_ID = 'shortcut-entry-nav-icon';
        const CHECK_INTERVAL = 1000;
        const MAX_ATTEMPTS = 60;
        let attempts = 0;

        const checkAndAddIcon = () => {
            if (document.getElementById(NAV_ICON_ID)) return;

            const navTab = document.querySelector('body > div.rong-im > div > div.rong-nav > ul.rong-nav-tab');

            if (!navTab) {
                attempts++;
                if (attempts < MAX_ATTEMPTS) {
                    setTimeout(checkAndAddIcon, CHECK_INTERVAL);
                }
                return;
            }

            // 创建导航项
            const navItem = document.createElement('li');
            navItem.id = NAV_ICON_ID;
            navItem.className = 'rong-nav-tab-item';
            navItem.style.position = 'relative';
            const iconColor = window.PluginTheme ? window.PluginTheme.getNavIconColor() : '#808CA4';
            navItem.innerHTML = `
                <em class="item-content" style="cursor: pointer;">
                    <span class="rong-nav-icon" style="
                        background-image: url('data:image/svg+xml;base64,${this._getNavIconBase64(iconColor)}');
                    "></span>
                    <span class="rong-nav-icon hover" style="
                        background-image: url('data:image/svg+xml;base64,${this._getNavIconBase64('#3A6EE7')}');
                    "></span>
                    <span class="rong-nav-text">快捷入口</span>
                </em>
            `;

            // 创建弹出面板
            const panel = this._createPanel();
            instance.panel = panel;

            let isOpen = false;
            let hideTimeout = null;

            const showPanel = () => {
                if (hideTimeout) {
                    clearTimeout(hideTimeout);
                    hideTimeout = null;
                }
                if (!isOpen) {
                    this._showPanel(panel, navItem);
                    isOpen = true;
                }
            };

            const hidePanel = () => {
                hideTimeout = setTimeout(() => {
                    if (isOpen) {
                        this._hidePanel(panel);
                        isOpen = false;
                    }
                }, 200);
            };

            // 鼠标悬浮显示/隐藏面板
            navItem.addEventListener('mouseenter', showPanel);
            navItem.addEventListener('mouseleave', hidePanel);

            // 鼠标悬浮面板时保持显示
            panel.addEventListener('mouseenter', showPanel);
            panel.addEventListener('mouseleave', hidePanel);

            // 插入到插件图标的后面
            const pluginNavIcon = document.getElementById('plugin-manager-nav-icon');
            if (pluginNavIcon && pluginNavIcon.nextSibling) {
                navTab.insertBefore(navItem, pluginNavIcon.nextSibling);
            } else if (pluginNavIcon) {
                navTab.appendChild(navItem);
            } else {
                navTab.appendChild(navItem);
            }

            instance.navIcon = navItem;
            console.log('[ShortcutEntry] ✅ 导航图标已添加');
        };

        checkAndAddIcon();
    },

    async init(config, pluginManager) {
        console.log('[ShortcutEntry] 🚀 初始化快捷入口插件...');

        const instance = {
            navIcon: null,
            panel: null,
            _clipboardPollInterval: null,
            _selectionHandler: null,
        };

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

        // 注册导航栏图标
        this._registerNavIcon(instance);

        // 注册选中文字检测
        this._registerSelectionDetection(instance);

        // 注册剪贴板检测（默认启用）
        this._registerClipboardDetection(instance);

        console.log('[ShortcutEntry] ✅ 插件已启动');
        return instance;
    },

    async destroy(instance) {
        console.log('[ShortcutEntry] 🔄 销毁快捷入口插件...');

        if (instance.navIcon) {
            instance.navIcon.remove();
            instance.navIcon = null;
        }
        if (instance.panel) {
            instance.panel.remove();
            instance.panel = null;
        }

        // 移除选中文字检测
        if (instance._selectionHandler) {
            document.removeEventListener('mouseup', instance._selectionHandler);
            instance._selectionHandler = null;
        }

        // 停止剪贴板轮询
        if (instance._clipboardPollInterval) {
            clearInterval(instance._clipboardPollInterval);
            instance._clipboardPollInterval = null;
        }

        // 移除 toast
        const toast = document.getElementById('shortcut-clipboard-toast');
        if (toast) toast.remove();

        const style = document.getElementById('shortcut-entry-styles');
        if (style) style.remove();

        console.log('[ShortcutEntry] ✅ 插件已销毁');
    }
};
