#include "albumTile.h"
#include <QPixmap>
#include <QPainter>
#include <QPainterPath>
#include <QMouseEvent>

static QPixmap rounded(const QPixmap& src, int radius); // Used to round album corners

// Box to display album cover and data
AlbumTile::AlbumTile(const AlbumData& item, QWidget* parent)
    : QWidget(parent), item_(item)
{
    auto* layout = new QVBoxLayout(this);
    layout->setAlignment(Qt::AlignCenter);
    layout->setSpacing(6);

    // Cover Image
    QPixmap pix(item.imagePath);
    QPixmap scaled = pix.scaled(200, 200, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    QLabel* cover = new QLabel;
    cover->setPixmap(rounded(scaled, 8));   // ← rounded to 8px
    cover->setAlignment(Qt::AlignCenter);

    // Album Label
    QLabel* albumLabel = new QLabel(item.album);
    albumLabel->setAlignment(Qt::AlignCenter);
    albumLabel->setStyleSheet("font-weight: 650; font-size: 18px; margin-top: 15px;");

    // Artist Label
    QLabel* artistLabel = new QLabel(item.artist);
    artistLabel->setAlignment(Qt::AlignCenter);
    artistLabel->setStyleSheet("color: #888; font-size: 15px;");

    layout->addWidget(cover);
    layout->addWidget(albumLabel);
    layout->addWidget(artistLabel);

    setCursor(Qt::PointingHandCursor);
}

// Simple click handler
void AlbumTile::mousePressEvent(QMouseEvent* event)
{
    emit activated(item_);
    QWidget::mousePressEvent(event);
}

// Round the album corners
static QPixmap rounded(const QPixmap& src, int radius)
{
    QPixmap out(src.size());
    out.fill(Qt::transparent);

    QPainter p(&out);
    p.setRenderHint(QPainter::Antialiasing, true);

    QPainterPath path;
    path.addRoundedRect(src.rect(), radius, radius);
    p.setClipPath(path);
    p.drawPixmap(0, 0, src);

    return out;
}
