#pragma once

#include <QWidget>
#include <QLineEdit>
#include <QPushButton>
#include <QCheckBox>
#include <QLabel>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QTextDocument>

class CodeEditor;

// ---------------------------------------------------------------------------
// SearchPanel – Collapsible find/replace bar that operates on a CodeEditor.
//
// Capabilities:
//   • Nächsten / Vorherigen Treffer suchen
//   • Einzeln ersetzen
//   • Alle ersetzen
//   • Nur in Auswahl ersetzen
//   • Optionen: Groß-/Kleinschreibung, Ganzes Wort, Reguläre Ausdrücke
// ---------------------------------------------------------------------------
class SearchPanel : public QWidget
{
    Q_OBJECT

public:
    explicit SearchPanel(QWidget *parent = nullptr);

    // Must be called whenever the active editor changes
    void setEditor(CodeEditor *editor);

    // Toggle visibility and focus the search field
    void activate();

public slots:
    void findNext();
    void findPrevious();
    void replaceCurrent();
    void replaceAll();
    void replaceInSelection();

private slots:
    void onSearchTextChanged(const QString &text);
    void onOptionChanged();   // Für Checkbox-Signale (bool-Parameter wird ignoriert)
    void onCloseClicked();

private:
    void setupUi();

    QTextDocument::FindFlags buildFindFlags(bool backwards = false) const;
    bool                     performFind(bool backwards = false);
    void                     highlightAllMatches();
    void                     clearHighlights();
    void                     updateMatchLabel();

    CodeEditor  *m_editor = nullptr;

    // Search row
    QLineEdit   *m_searchEdit     = nullptr;
    QPushButton *m_btnPrev        = nullptr;
    QPushButton *m_btnNext        = nullptr;
    QLabel      *m_matchLabel     = nullptr;
    QPushButton *m_btnClose       = nullptr;

    // Replace row
    QLineEdit   *m_replaceEdit          = nullptr;
    QPushButton *m_btnReplace           = nullptr;
    QPushButton *m_btnReplaceAll        = nullptr;
    QPushButton *m_btnReplaceSelection  = nullptr;

    // Options row
    QCheckBox   *m_chkCase      = nullptr;
    QCheckBox   *m_chkWord      = nullptr;
    QCheckBox   *m_chkRegex     = nullptr;

    QGridLayout *m_grid = nullptr;
};
