#pragma once

#include <QPlainTextEdit>
#include <QFont>
#include <QString>
#include <QTextBlock>

class LineNumberArea;
class Settings;
class SyntaxHighlighter;
class ColorIndicator;
class SignatureHelper;

// ---------------------------------------------------------------------------
// CodeEditor – Core editing widget.
// Features:
//   • Line number gutter
//   • Current-line highlight
//   • Auto-indent on Enter
//   • Tab → spaces (configurable)
//   • Syntax highlighting (via pluggable SyntaxHighlighter)
// ---------------------------------------------------------------------------
class CodeEditor : public QPlainTextEdit
{
    Q_OBJECT

public:
    explicit CodeEditor(Settings *settings, QWidget *parent = nullptr);
    ~CodeEditor() override;

    void loadFile(const QString &filePath);
    void applySettings();

    // Speichern
    bool save();
    bool saveAs();

    // Called by LineNumberArea
    int  lineNumberAreaWidth() const;
    void lineNumberAreaPaintEvent(QPaintEvent *event);

    QString filePath()   const;
    bool    isModified() const;

    // Öffentliche Hilfsmethoden für ColorIndicator
    // (die Qt-Originale sind protected und von außen nicht erreichbar)
    QTextBlock firstVisibleBlockPublic() const  { return firstVisibleBlock(); }
    QRectF     blockBoundingGeometryPublic(const QTextBlock &b) const { return blockBoundingGeometry(b); }
    QPointF    contentOffsetPublic() const      { return contentOffset(); }

signals:
    void fileSaved(const QString &filePath);

protected:
    void resizeEvent(QResizeEvent *event) override;
    void keyPressEvent(QKeyEvent *event) override;
    void paintEvent(QPaintEvent *event) override;
    void mousePressEvent(QMouseEvent *event) override;

private slots:
    void updateLineNumberAreaWidth(int newBlockCount);
    void highlightCurrentLine();
    void updateLineNumberArea(const QRect &rect, int dy);

private:
    void setupEditor();
    void installHighlighter(const QString &filePath);
    bool writeToFile(const QString &filePath);

    Settings          *m_settings        = nullptr;
    LineNumberArea    *m_lineNumberArea   = nullptr;
    SyntaxHighlighter *m_highlighter      = nullptr;
    ColorIndicator    *m_colorIndicator   = nullptr;
    SignatureHelper   *m_signatureHelper  = nullptr;
    QString            m_filePath;
};
