#pragma once
#include <Windows.h>
#include <shellapi.h>
#include <functional>
#include <vector>
#include <string>

// ============================================================================
// SysTray — 独立的 Windows 系统托盘模块
//
// 用法:
//   SysTray tray(hwnd, hIcon, L"MyApp");
//   tray.AddMenuItem(1001, L"设置", [](UINT id) { ... });
//   tray.AddMenuItem(1002, L"退出", [](UINT id) { ... });
//   tray.AddIcon();
//   tray.StartAutoRefresh(30);
//   // 在消息循环中调用 tray.HandleMessage(msg, wParam, lParam);
// ============================================================================

class SysTray {
public:
    using MenuCallback = std::function<void(UINT menuId)>;
    using SimpleCallback = std::function<void()>;

    SysTray(HWND hwnd, HICON hIcon, const wchar_t* tooltip);
    ~SysTray();

    // 生命周期
    bool AddIcon();
    bool RemoveIcon();
    bool RefreshIcon();

    // 自动刷新（防 Explorer 崩溃后图标丢失）
    void StartAutoRefresh(UINT intervalMinutes = 30);
    void StopAutoRefresh();

    // 菜单项
    void AddMenuItem(UINT id, const wchar_t* text, MenuCallback onSelect = nullptr);
    void SetMenuItemChecked(UINT id, bool checked);
    void ClearMenuItems();

    // 回调设置
    void SetOnLeftClick(SimpleCallback cb) { m_onLeftClick = std::move(cb); }
    void SetOnDoubleClick(SimpleCallback cb) { m_onDoubleClick = std::move(cb); }
    void SetMenuCallback(MenuCallback cb) { m_menuCallback = std::move(cb); }

    // 消息处理 —— 在主消息循环中调用
    void HandleMessage(UINT msg, WPARAM wParam, LPARAM lParam);

    // 获取托盘窗口句柄
    HWND GetTrayWindow() const { return m_trayHwnd; }

    // 窗口过程（供子类化使用）
    static LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);

private:
    void ShowContextMenu();
    void ReaddIcon();
    bool RegisterWindowClass();
    void UnregisterWindowClass();

    HWND m_hwnd;           // 主窗口
    HWND m_trayHwnd;       // 托盘消息窗口
    HICON m_hIcon;
    NOTIFYICONDATA m_nid;
    UINT_PTR m_timerId;
    std::wstring m_className;

    struct MenuItem {
        UINT id;
        std::wstring text;
        MenuCallback callback;
        bool checked = false;
    };
    std::vector<MenuItem> m_menuItems;

    MenuCallback m_menuCallback;
    SimpleCallback m_onLeftClick;
    SimpleCallback m_onDoubleClick;

    static const UINT WM_TRAYICON = WM_USER + 1;
    static UINT WM_TASKBARCREATED;
};

// ============================================================================
// 便捷函数：为任意 HWND 创建简单托盘
// ============================================================================
namespace SysTrayUtil {
    // 注册并显示一个最简托盘（左键恢复窗口，右键退出菜单）
    SysTray* CreateSimple(HWND hwnd, HICON hIcon, const wchar_t* tooltip);
}
