#include "SignatureTooltip.h"

#include <QApplication>
#include <QScreen>

SignatureTooltip::SignatureTooltip(QWidget *parent)
    : QFrame(parent, Qt::ToolTip | Qt::FramelessWindowHint)
{
    setFrameShape(QFrame::StyledPanel);
    setFrameShadow(QFrame::Raised);
    setAttribute(Qt::WA_ShowWithoutActivating);

    // Dezentes Styling passend zu Hell- und Dunkeltheme
    setStyleSheet(
        "SignatureTooltip {"
        "  background: palette(toolTipBase);"
        "  border: 1px solid palette(mid);"
        "  border-radius: 4px;"
        "  padding: 4px;"
        "}"
    );

    m_layout = new QVBoxLayout(this);
    m_layout->setContentsMargins(8, 6, 8, 6);
    m_layout->setSpacing(3);

    // Signatur — Monospace, deutlich hervorgehoben
    m_sigLabel = new QLabel(this);
    m_sigLabel->setTextFormat(Qt::PlainText);
    m_sigLabel->setWordWrap(false);
    QFont sigFont = m_sigLabel->font();
    sigFont.setFamily("Monospace");
    sigFont.setStyleHint(QFont::Monospace);
    sigFont.setPointSize(sigFont.pointSize());
    m_sigLabel->setFont(sigFont);
    m_sigLabel->setStyleSheet("color: palette(toolTipText); font-weight: bold;");
    m_layout->addWidget(m_sigLabel);

    // Beschreibung — kleiner, gedimmt
    m_descLabel = new QLabel(this);
    m_descLabel->setTextFormat(Qt::PlainText);
    m_descLabel->setWordWrap(false);
    m_descLabel->setStyleSheet("color: palette(mid);");
    QFont descFont = m_descLabel->font();
    descFont.setPointSize(qMax(descFont.pointSize() - 1, 8));
    m_descLabel->setFont(descFont);
    m_layout->addWidget(m_descLabel);

    hide();
}

void SignatureTooltip::showSignature(const QString &signature,
                                     const QString &description,
                                     const QPoint  &globalPos)
{
    m_sigLabel->setText(signature);

    if (description.isEmpty())
    {
        m_descLabel->hide();
    }
    else
    {
        m_descLabel->setText(description);
        m_descLabel->show();
    }

    adjustSize();

    // Position so wählen dass das Popup nicht aus dem Bildschirm ragt
    QPoint pos = globalPos;
    const QRect screen = QApplication::primaryScreen()->availableGeometry();

    if (pos.x() + width() > screen.right())
    {
        pos.setX(screen.right() - width() - 4);
    }
    if (pos.y() + height() > screen.bottom())
    {
        pos.setY(globalPos.y() - height() - 24);
    }

    move(pos);
    show();
    raise();
}

void SignatureTooltip::hide()
{
    QFrame::hide();
}
