#pragma once

#include <Windows.h>

#include "foundation/input/KeyNames.h"
#include "application/messaging/PresentationState.h"

namespace ta::adapters::windows::input
{
    /// Rising-edge detector for configurable toggle hotkeys.
    /// Key 0 disables the binding. Input is observed while the menu is open so
    /// holding a key while closing the menu cannot produce a delayed toggle.
    class ToggleHotkey final
    {
    public:
        [[nodiscard]] bool poll(const int virtual_key) noexcept
        {
            if (virtual_key == 0 || !ta::foundation::input::is_valid_key_index(virtual_key))
            {
                reset();
                return false;
            }

            const bool down = (GetAsyncKeyState(virtual_key) & 0x8000) != 0;
            if (virtual_key != active_key_)
            {
                active_key_ = virtual_key;
                was_down_ = down;
                return false;
            }

            const bool triggered = down && !was_down_ && !ta::application::presentation_state::menu_visible.acquire();
            was_down_ = down;
            return triggered;
        }

        void reset() noexcept
        {
            active_key_ = 0;
            was_down_ = false;
        }

    private:
        int active_key_ = 0;
        bool was_down_ = false;
    };
}
