#pragma once

#include <QCheckBox>
#include <QDockWidget>
#include <QHash>
#include <QLineEdit>
#include <QPushButton>
#include <QSet>
#include <QTreeWidget>

#include "FlowLayout.h"

#include <memory>

namespace Ui {
class SceneBrowserPanel;
}

namespace fso::fred {

class FredView;
class EditorViewport;

namespace dialogs {
class SceneBrowserModel;
}

/**
 * @brief Dockable scene browser panel.
 *
 * Shows all mission objects organized by layer, then by type within each layer.
 * Layer visibility can be toggled directly via checkboxes on the layer nodes.
 * Selection is bidirectionally synced with the 3D viewport.
 */
class SceneBrowserPanel : public QDockWidget {
	Q_OBJECT

public:
	SceneBrowserPanel(FredView* fredView, EditorViewport* viewport);
	~SceneBrowserPanel() override;

private slots:
	void onModelChanged();
	void onTreeStructureChanged();
	void onItemChanged(QTreeWidgetItem* item, int column);
	void onItemSelectionChanged();
	void onCustomContextMenuRequested(const QPoint& pos);
	void onSearchTextChanged(const QString& text);

private: // NOLINT(readability-redundant-access-specifiers)
	void rebuildTree();
	void updateFloatingMargins(bool floating);
	void rememberExpansionState();
	bool expandedStateOrDefault(const QString& key, bool defaultExpanded) const;
	void syncSelection();
	void syncLayerVisibility();
	void applyFilter(const QString& filter);
	void showAllItems(QTreeWidgetItem* root);

	std::unique_ptr<::Ui::SceneBrowserPanel> ui;  // ::Ui — global scope, generated by uic
	FredView* _fredView = nullptr;
	dialogs::SceneBrowserModel* _model = nullptr;
	QTreeWidget* _tree = nullptr;
	QLineEdit* _searchBar = nullptr;
	QWidget* _iffFilterWidget = nullptr;
	QVector<QCheckBox*> _iffCheckBoxes;
	QPushButton* _selectAllButton = nullptr;
	QPushButton* _clearButton = nullptr;
	QPushButton* _invertButton = nullptr;
	QHash<QString, bool> _expansionState;

	// Item data roles
	enum ItemRole {
		ObjNumRole = Qt::UserRole,
		WingIndexRole = Qt::UserRole + 1,
		WptListIndexRole = Qt::UserRole + 2,
		IsLayerItemRole = Qt::UserRole + 3,
		LayerNameRole = Qt::UserRole + 4,
	};
};

} // namespace fso::fred
