from PyQt6.QtCore import QTimer, Qt
from PyQt6.QtGui import QColor, QPainter
from PyQt6.QtWidgets import QWidget


class CRTOverlay(QWidget):
    def __init__(self, parent=None, accent_color: str = "#c06c84"):
        super().__init__(parent)
        self.accent_color = QColor(accent_color)
        self.scanline_offset = 0
        self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
        self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground)
        self.setStyleSheet("background-color: transparent;")
        if parent:
            self.setGeometry(0, 0, parent.width(), parent.height())

        self.timer = QTimer(self)
        self.timer.timeout.connect(self._advance_scanline)
        self.timer.start(50)

    def set_accent_color(self, color: str):
        self.accent_color = QColor(color)
        self.update()

    def _advance_scanline(self):
        self.scanline_offset += 6
        if self.scanline_offset > self.height():
            self.scanline_offset = 0
        self.update()

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setPen(Qt.PenStyle.NoPen)

        r = self.accent_color.red()
        g = self.accent_color.green()
        b = self.accent_color.blue()

        for y in range(0, self.height(), 8):
            painter.setBrush(QColor(r, g, b, 20))
            painter.drawRect(0, y, self.width(), 4)

        painter.setBrush(QColor(r, g, b, 10))
        painter.drawRect(0, self.scanline_offset, self.width(), 6)
