#include <QApplication>
#include <QWidget>
#include <QLabel>
#include <QGridLayout>
#include <QFrame>
#include <QProcess>
#include <QKeyEvent>
#include <QPixmap>
#include <QDir>
#include <QPushButton>
#include <QVBoxLayout>

// --- PART 1: The Custom Square Button Widget ---
class StreamButton : public QFrame {
    Q_OBJECT

public:
    StreamButton(QString serviceName, QString logoFileName, QString url, bool isSystemCmd = false, QWidget *parent = nullptr) 
        : QFrame(parent), target(url), isCmd(isSystemCmd) {
        
        this->setObjectName("StreamButton");
        this->setFrameShape(QFrame::StyledPanel);
        this->setMinimumSize(300, 320); 
        this->setFocusPolicy(Qt::StrongFocus);
        this->setCursor(Qt::PointingHandCursor);

        QString style = 
            "QFrame#StreamButton { "
            "  background-color: #333; "
            "  border: 4px solid #333; "
            "  border-radius: 25px; "
            "}"
            "QFrame#StreamButton:focus { "
            "  background-color: #555; "
            "  border: 4px solid #0078d4; "
            "}";
        this->setStyleSheet(style);

        QVBoxLayout *contentLayout = new QVBoxLayout(this);
        contentLayout->setContentsMargins(20, 20, 20, 15);
        contentLayout->setSpacing(10);

        logoLabel = new QLabel(this);
        logoLabel->setAlignment(Qt::AlignCenter);
        logoLabel->setStyleSheet("border: none; background: transparent;");

        QString appDir = QCoreApplication::applicationDirPath();
        QPixmap logoPix(appDir + QDir::separator() + logoFileName);
        
        if (!logoPix.isNull()) {
            logoLabel->setPixmap(logoPix.scaled(200, 200, Qt::KeepAspectRatio, Qt::SmoothTransformation));
        } else {
            logoLabel->setText("No Logo");
            logoLabel->setStyleSheet("color: #888; font-size: 20px;");
        }

        captionLabel = new QLabel(serviceName, this);
        captionLabel->setAlignment(Qt::AlignCenter);
        captionLabel->setStyleSheet("color: white; font-size: 28px; font-weight: bold; border: none; background: transparent;");
        
        contentLayout->addWidget(logoLabel, 1);
        contentLayout->addWidget(captionLabel, 0);
    }

    void mousePressEvent(QMouseEvent *event) override {
        if (event->button() == Qt::LeftButton) launch();
    }

    void keyPressEvent(QKeyEvent *event) override {
        if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
            launch();
        } else {
            QFrame::keyPressEvent(event);
        }
    }

signals:
    void processFinished();

private:
    void launch() {
        QProcess *proc = new QProcess(this);
        connect(proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), [this, proc]() {
	    QProcess::startDetached("pkill", {"onboard"});
            emit processFinished();
            proc->deleteLater();
        });

        if (isCmd) {
            QProcess::startDetached("onboard");
	    // Run system command (WiFi settings)
            proc->start(target);
        } else {
            // Run browser in Kiosk mode
            proc->start("firefox", {"--kiosk", target});
        }
    }

    QString target;
    bool isCmd;
    QLabel *logoLabel;
    QLabel *captionLabel;
};

#include "main.moc"

// --- PART 2: The Main Fullscreen Launcher window ---
class StreamLauncher : public QWidget {
public:
    StreamLauncher() {
        this->showFullScreen();
        this->setStyleSheet("background-color: #121212;");

        QVBoxLayout *mainLayout = new QVBoxLayout(this);
        mainLayout->setContentsMargins(50, 50, 50, 50);

        gridLayout = new QGridLayout();
        gridLayout->setSpacing(30);
        mainLayout->addLayout(gridLayout, 1);

        int row = 0, col = 0, maxCols = 3;

        // Streaming Tiles
        addGridItem("Netflix", "netflix.jpeg", "https://www.netflix.com", gridLayout, row, col);
        updateGridCoords(row, col, maxCols);
        addGridItem("YouTube", "youtube.jpeg", "https://www.youtube.com", gridLayout, row, col);
        updateGridCoords(row, col, maxCols);
        addGridItem("Twitch", "twitch.jpeg", "https://www.twitch.tv", gridLayout, row, col);
        updateGridCoords(row, col, maxCols);
        addGridItem("Prime Video", "amazon.jpeg", "https://www.amazon.com/gp/video/tv", gridLayout, row, col);
        updateGridCoords(row, col, maxCols);
        addGridItem("Spectrum TV", "spectrum.jpeg", "https://watch.spectrum.net", gridLayout, row, col);
        updateGridCoords(row, col, maxCols);

        // System Tiles
        addGridItem("WiFi Settings", "wifi.jpeg", "nm-connection-editor", gridLayout, row, col, true);

        exitBtn = new QPushButton("Exit Launcher");
        exitBtn->setStyleSheet(
            "QPushButton { color: white; background-color: #cc0000; height: 100px; font-size: 28px; border-radius: 20px; border: 4px solid #cc0000; }"
            "QPushButton:focus { background-color: #ff0000; border: 4px solid white; }"
        );
        mainLayout->addWidget(exitBtn, 0);
        connect(exitBtn, &QPushButton::clicked, qApp, &QApplication::quit);
        
        if (gridLayout->itemAt(0)) {
            gridLayout->itemAt(0)->widget()->setFocus();
        }
    }

protected:
    void keyPressEvent(QKeyEvent *event) override {
        QWidget *current = this->focusWidget();
        if (!current) return;
        int idx = gridLayout->indexOf(current);

        if (current == exitBtn) {
            if (event->key() == Qt::Key_Up) {
                gridLayout->itemAt(gridLayout->count() - 1)->widget()->setFocus();
            }
            return;
        }

        int r, c, rs, cs;
        gridLayout->getItemPosition(idx, &r, &c, &rs, &cs);

        if (event->key() == Qt::Key_Right) focusAt(r, c + 1);
        else if (event->key() == Qt::Key_Left) focusAt(r, c - 1);
        else if (event->key() == Qt::Key_Down) {
            if (!focusAt(r + 1, c)) exitBtn->setFocus();
        }
        else if (event->key() == Qt::Key_Up) focusAt(r - 1, c);
        else QWidget::keyPressEvent(event);
    }

private:
    QGridLayout *gridLayout;
    QPushButton *exitBtn;

    bool focusAt(int r, int c) {
        QLayoutItem *item = gridLayout->itemAtPosition(r, c);
        if (item && item->widget()) {
            item->widget()->setFocus();
            return true;
        }
        return false;
    }

    void addGridItem(QString name, QString logo, QString url, QGridLayout *grid, int r, int c, bool isCmd = false) {
        StreamButton *btn = new StreamButton(name, logo, url, isCmd);
        connect(btn, &StreamButton::processFinished, this, [this]() {
            this->showFullScreen();
            this->activateWindow();
            this->raise();
        });
        grid->addWidget(btn, r, c);
    }

    void updateGridCoords(int &r, int &c, int maxC) {
        c++;
        if (c >= maxC) {
            c = 0;
            r++;
        }
    }
};

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    StreamLauncher launcher;
    launcher.show();
    return app.exec();
}
