#pragma once

#include <optional>

#include "ItemTooltipContext.h"
#include "ModalDialog.h"

class BlueprintLibrary;
class ItemIconCache;
class QGridLayout;
class QWidget;

// The blueprint selection dialog (REQ-UI-BLUEPRINT-DIALOG): a modal panel showing every
// saved blueprint as a card in a scrolling two-column grid. The caller pauses the game
// while it is open.
//
// Clicking a card accepts the dialog and reports that blueprint's index; the caller
// enters placement mode afterwards, so the dialog is already closed by then
// (REQ-UI-BLUEPRINT-CARD). Deleting acts on the library immediately and leaves the
// dialog open (REQ-UI-BLUEPRINT-DELETE). Escape, Q, the close button, and a click
// outside dismiss it with no other effect (REQ-UI-DIALOG-DISMISS).
class BlueprintSelectionDialog : public ModalDialog
{
    Q_OBJECT

public:
    // The context's item cache draws the block icon beside each cost, and the rest of it
    // lets that cost explain the item it names (REQ-UI-ITEM-VALUE-TOOLTIP). Neither the
    // library nor anything in the context is owned; both outlive the dialog.
    BlueprintSelectionDialog(BlueprintLibrary* library,
                             const ItemTooltipContext& context,
                             QWidget* parent = nullptr);

    std::optional<int> getChosenIndex() const;

    bool isDismissible() const override;

private:
    void rebuildGrid();
    void onCardClicked(int index);
    void onDeleteClicked(int index);

    BlueprintLibrary*  m_library;
    ItemTooltipContext m_context;
    ItemIconCache*     m_itemIcons;
    QWidget*           m_gridContainer;
    QGridLayout*       m_grid;
    std::optional<int> m_chosenIndex;  // nullopt = dismissed without picking
};
