# ui/hazard_stripes.py

from PySide6.QtWidgets import QPushButton, QStyleOptionButton, QStyle
from PySide6.QtGui import QPainter, QColor, QPainterPath, QPen, QPolygon
from PySide6.QtCore import Qt, QPoint


class HazardButton(QPushButton):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._hazard = False

    def set_hazard(self, enabled: bool):
        self._hazard = enabled
        self.update()

    def paintEvent(self, event):
        if not hasattr(self, '_hazard'):
            self.__dict__['_hazard'] = False

        p = QPainter(self)
        p.setRenderHint(QPainter.RenderHint.Antialiasing)

        r = self.rect()
        radius = 4

        path = QPainterPath()
        path.addRoundedRect(r, radius, radius)
        p.setClipPath(path)

        if self._hazard:
            p.fillRect(r, QColor("#FFD700"))

            p.setPen(Qt.PenStyle.NoPen)
            p.setBrush(QColor("#000000"))

            stripe_width = 20
            stripe_gap = 30
            period = stripe_width + stripe_gap
            diag = r.width() + r.height()

            for x in range(-diag, diag * 2, period):
                stripe = QPolygon([
                    QPoint(x, r.bottom() + 10),
                    QPoint(x + stripe_width, r.bottom() + 10),
                    QPoint(x + stripe_width + r.height() + 10, r.top() - 10),
                    QPoint(x + r.height() + 10, r.top() - 10),
                ])
                p.drawPolygon(stripe)

            # ↓ Fond semi-transparent derrière le texte
            text_bg = QColor(255, 215, 0, 230)  # noir à 63% d'opacité
            p.setPen(Qt.PenStyle.NoPen)
            p.setBrush(text_bg)
            bg_rect = r.adjusted(60, 8, -60, -8)  # marges internes
            p.drawRoundedRect(bg_rect, 4, 4)

        else:
            p.fillRect(r, QColor("#FFD700"))

        p.setClipping(False)
        p.setPen(QPen(QColor("#000000"), 2))
        p.setBrush(Qt.BrushStyle.NoBrush)
        p.drawRoundedRect(r.adjusted(1, 1, -1, -1), radius, radius)

        p.setClipping(False)
        opt = QStyleOptionButton()
        self.initStyleOption(opt)
        opt.palette.setColor(
            opt.palette.ColorRole.ButtonText,
            self.palette().color(self.palette().ColorRole.ButtonText)
        )
        self.style().drawControl(
            QStyle.ControlElement.CE_PushButtonLabel, opt, p, self
        )
