import os
os.environ["OPENCV_VIDEOIO_MSMF_ENABLE_HW_TRANSFORMS"] = "0"  # cegah layar hitam di MSMF

import math
import random
import time

import cv2
import mediapipe as mp
import numpy as np

mp_hands = mp.solutions.hands
mp_draw = mp.solutions.drawing_utils
mp_selfie = mp.solutions.selfie_segmentation

# ------------------------------------------------------------ pengaturan ---
DISPLAY_WIDTH = 700     # ukuran jendela (coba 1280 kalau mau lebih besar)
PROCESS_WIDTH = 640     # lebar gambar untuk deteksi tangan (makin kecil makin ringan)
MODEL_COMPLEXITY = 1    # 1 = lebih akurat untuk 2 tangan, 0 = lebih ringan
HOLD_TIME = 0.10        # efek tetap aktif sebentar setelah gestur hilang
WIN = "Hand Effects"

# --- pengaturan efek love (ubah di sini kalau mau lebih ramai / sepi) ---
HEART_SPAWN_EVERY = 2   # hati muncul tiap N frame (makin besar = makin jarang)
HEART_MAX_PARTICLES = 70  # batas total partikel love di layar

TIPS = [4, 8, 12, 16, 20]
PIPS = [2, 6, 10, 14, 18]
FINGER_NAMES = ["Jempol", "Telunjuk", "Tengah", "Manis", "Kelingking"]

# ---------------------------------------------------------------- kamera ---
BACKENDS = [("MSMF", cv2.CAP_MSMF), ("DSHOW", cv2.CAP_DSHOW), ("AUTO", cv2.CAP_ANY)]
FORMATS = [None, "MJPG", "YUY2"]
SIZES = [(640, 480), (1280, 720), (1920, 1080)]
MAX_INDEX = 6  # cek kamera index 0 sampai 5


def open_cam(index, b, f, s):
    """Buka kamera sesuai pilihan. Return cap atau None."""
    cap = cv2.VideoCapture(index, BACKENDS[b][1])
    if not cap.isOpened():
        cap.release()
        return None
    fourcc = FORMATS[f]
    if fourcc:
        cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*fourcc))
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, SIZES[s][0])
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, SIZES[s][1])
    cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)  # kurangi antrean frame
    return cap


def cfg_text(cfg):
    index, b, f, s = cfg
    fmt = FORMATS[f] or "default"
    return f"Kamera {index} | {BACKENDS[b][0]} | {fmt} | {SIZES[s][0]}x{SIZES[s][1]}"


def select_camera(current=None):
    """
    Jendela pilih kamera dengan preview langsung.
      n / p = kamera berikutnya / sebelumnya
      b     = ganti backend (MSMF / DSHOW / AUTO)
      f     = ganti format (default / MJPG / YUY2)
      r     = ganti resolusi
      ENTER = pakai kamera ini
      q     = keluar
    Return (cap, cfg) atau (None, None).
    """
    index, b, f, s = current if current else (0, 0, 0, 0)
    win = "Pilih Kamera"
    cap = None
    need_open = True

    while True:
        if need_open:
            if cap is not None:
                cap.release()
            cap = open_cam(index, b, f, s)
            need_open = False

        frame = None
        if cap is not None:
            ok, frame = cap.read()
            if not ok:
                frame = None

        if frame is None:
            view = np.zeros((480, 640, 3), np.uint8)
            cv2.putText(view, "Tidak ada gambar dari pengaturan ini",
                        (30, 240), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
        else:
            view = frame.copy()
            if view.shape[1] > 960:
                nh = int(view.shape[0] * 960 / view.shape[1])
                view = cv2.resize(view, (960, nh))

        vh, vw = view.shape[:2]
        cv2.rectangle(view, (0, 0), (vw, 62), (0, 0, 0), -1)
        cv2.putText(view, cfg_text((index, b, f, s)), (10, 22),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
        cv2.putText(view, "n/p=kamera  b=backend  f=format  r=resolusi  ENTER=pakai  q=keluar",
                    (10, 48), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
        cv2.imshow(win, view)

        key = cv2.waitKey(30) & 0xFF
        if cv2.getWindowProperty(win, cv2.WND_PROP_VISIBLE) < 1:
            key = ord("q")

        if key in (13, 32):  # ENTER / SPASI
            if cap is not None and frame is not None:
                cv2.destroyWindow(win)
                cv2.waitKey(1)
                return cap, (index, b, f, s)
        elif key == ord("q"):
            if cap is not None:
                cap.release()
            cv2.destroyAllWindows()
            return None, None
        elif key == ord("n"):
            index = (index + 1) % MAX_INDEX
            need_open = True
        elif key == ord("p"):
            index = (index - 1) % MAX_INDEX
            need_open = True
        elif key == ord("b"):
            b = (b + 1) % len(BACKENDS)
            need_open = True
        elif key == ord("f"):
            f = (f + 1) % len(FORMATS)
            need_open = True
        elif key == ord("r"):
            s = (s + 1) % len(SIZES)
            need_open = True


# ---------------------------------------------------------------- deteksi ---
def dist(a, b):
    return math.hypot(a.x - b.x, a.y - b.y)


def hand_size(lm):
    return dist(lm[0], lm[9]) + 1e-6


def fingers_up(lm):
    """List 5 boolean: [jempol, telunjuk, tengah, manis, kelingking]."""
    up = [dist(lm[4], lm[17]) > dist(lm[3], lm[17])]
    for tip, pip in zip(TIPS[1:], PIPS[1:]):
        up.append(dist(lm[tip], lm[0]) > dist(lm[pip], lm[0]))
    return up


def is_thumb_down(lm, up):
    """Jempol ke bawah, 4 jari lain menekuk, jempol tidak menempel telunjuk."""
    size = hand_size(lm)
    others_folded = not any(up[1:])
    pointing_down = lm[4].y > lm[3].y > lm[2].y
    below_knuckle = lm[4].y > lm[5].y + 0.35 * size
    vertical = abs(lm[4].y - lm[2].y) > 1.0 * abs(lm[4].x - lm[2].x)
    not_touching_index = dist(lm[4], lm[8]) > 0.5 * size
    return (others_folded and pointing_down and below_knuckle
            and vertical and not_touching_index)


def is_finger_heart(lm, up):
    """Jempol & telunjuk saling menyentuh, 3 jari lain menekuk."""
    close = dist(lm[4], lm[8]) < 0.45 * hand_size(lm)
    return close and not (up[2] or up[3] or up[4])


def is_rock(lm, up):
    return up[1] and up[4] and not up[2] and not up[3]


def two_hand_heart(hands):
    """Dua tangan membentuk hati: ujung jempol & telunjuk saling bertemu."""
    if len(hands) < 2:
        return None
    a, b = hands[0], hands[1]
    ref = (hand_size(a) + hand_size(b)) / 2
    if dist(a[4], b[4]) < 0.8 * ref and dist(a[8], b[8]) < 0.8 * ref:
        cx = (a[4].x + b[4].x + a[8].x + b[8].x) / 4
        cy = (a[4].y + b[4].y + a[8].y + b[8].y) / 4
        return cx, cy
    return None


# ------------------------------------------------------- efek: love imut ---
_t = np.linspace(0, 2 * math.pi, 48)
HEART_UNIT = np.stack([
    16 * np.sin(_t) ** 3,
    -(13 * np.cos(_t) - 5 * np.cos(2 * _t) - 2 * np.cos(3 * _t) - np.cos(4 * _t)),
], axis=1) / 16.0

# (warna isi, warna garis tepi) dalam BGR - warna pastel
PALETTE = [
    ((203, 182, 255), (140, 100, 230)),
    ((180, 140, 255), (120, 70, 220)),
    ((230, 190, 255), (170, 110, 230)),
    ((190, 205, 255), (120, 135, 235)),
    ((210, 170, 255), (150, 90, 225)),
]
DARK = (60, 30, 50)


def draw_cute_heart(img, cx, cy, size, fill, outline, face=True):
    if size < 2:
        return
    pts = (HEART_UNIT * size + np.array([cx, cy])).astype(np.int32)
    cv2.fillPoly(img, [pts], fill, cv2.LINE_AA)
    cv2.polylines(img, [pts], True, outline, max(1, int(size / 9)), cv2.LINE_AA)
    # kilau di kiri atas
    cv2.ellipse(img, (int(cx - size * 0.5), int(cy - size * 0.35)),
                (max(1, int(size * 0.2)), max(1, int(size * 0.11))),
                -35, 0, 360, (255, 255, 255), -1, cv2.LINE_AA)
    if face and size >= 15:
        eye_r = max(1, int(size * 0.09))
        ey = int(cy + size * 0.08)
        for sx in (-1, 1):
            # pipi merona
            cv2.circle(img, (int(cx + sx * size * 0.55), int(cy + size * 0.30)),
                       max(1, int(size * 0.11)), (150, 150, 255), -1, cv2.LINE_AA)
            # mata
            ex = int(cx + sx * size * 0.32)
            cv2.circle(img, (ex, ey), eye_r, DARK, -1, cv2.LINE_AA)
            if size >= 24:
                cv2.circle(img, (ex - eye_r // 3, ey - eye_r // 3),
                           max(1, eye_r // 3), (255, 255, 255), -1, cv2.LINE_AA)
        # senyum
        cv2.ellipse(img, (int(cx), int(cy + size * 0.28)),
                    (max(1, int(size * 0.10)), max(1, int(size * 0.07))),
                    0, 0, 180, DARK, max(1, int(size / 18)), cv2.LINE_AA)


def draw_sparkle(img, cx, cy, s, color):
    k = 0.28
    pts = np.array([[cx, cy - s], [cx + s * k, cy - s * k], [cx + s, cy],
                    [cx + s * k, cy + s * k], [cx, cy + s], [cx - s * k, cy + s * k],
                    [cx - s, cy], [cx - s * k, cy - s * k]]).astype(np.int32)
    cv2.fillPoly(img, [pts], color, cv2.LINE_AA)


class Hearts:
    def __init__(self):
        self.particles = []

    def spawn(self, cx, cy, count, scale):
        for _ in range(count):
            fill, outline = random.choice(PALETTE)
            self.particles.append({
                "kind": "heart" if random.random() < 0.7 else "spark",
                "x": cx + random.uniform(-60, 60) * scale,
                "y": cy + random.uniform(-60, 60) * scale,
                "vx": random.uniform(-1.2, 1.2) * scale,
                "vy": random.uniform(-4, -2) * scale,
                "size": random.uniform(8, 20) * scale,   # sedang (awal 9-24)
                "life": random.randint(30, 60),          # sedang (awal 40-80)
                "phase": random.uniform(0, 6.28),
                "fill": fill,
                "outline": outline,
            })

    def update_draw(self, frame, big_points, scale, now):
        alive = []
        for p in self.particles:
            p["x"] += p["vx"] + math.sin(p["phase"]) * 1.2 * scale
            p["y"] += p["vy"]
            p["phase"] += 0.2
            p["life"] -= 1
            if p["life"] > 0:
                s = p["size"] * min(1.0, p["life"] / 20)
                if p["kind"] == "heart":
                    draw_cute_heart(frame, p["x"], p["y"], s, p["fill"], p["outline"])
                else:
                    twinkle = 0.6 + 0.4 * math.sin(p["phase"] * 2)
                    color = (255, 255, 255) if int(p["phase"]) % 2 == 0 else (150, 240, 255)
                    draw_sparkle(frame, p["x"], p["y"], s * 0.9 * twinkle, color)
                alive.append(p)
        self.particles = alive

        # hati besar berdenyut di atas tangan
        for (bx, by) in big_points:
            pulse = 1 + 0.12 * math.sin(now * 9)
            size = 28 * scale * pulse               # sedang (awal 34)
            cy = by - 65 * scale                    # sedang (awal 75)
            draw_cute_heart(frame, bx, cy, size, (203, 182, 255), (140, 100, 230))
            for k in range(2):                      # sebelumnya 3
                a = now * 3 + k * 3.14
                draw_sparkle(frame, bx + math.cos(a) * 55 * scale,
                             cy + math.sin(a) * 45 * scale, 7 * scale, (255, 255, 255))


# ------------------------------------------------- efek: hujan + petir ------
class Rain:
    def __init__(self):
        self.drops = []
        self.intensity = 0.0
        self.next_bolt = 0.0
        self.bolt = None
        self.bolt_time = -10.0
        self.was_active = False

    @staticmethod
    def jagged(x, y, steps, step_h, spread, drift=0):
        pts = [(int(x), int(y))]
        for _ in range(steps):
            x += random.randint(-spread, spread) + drift
            y += random.randint(int(step_h * 0.6), int(step_h * 1.2))
            pts.append((int(x), int(y)))
        return pts

    def make_bolt(self, w, h):
        main = self.jagged(random.randint(int(w * 0.1), int(w * 0.9)), 0,
                           random.randint(6, 9), h / 8, max(2, int(w * 0.05)))
        paths = [main]
        for _ in range(2):
            i = random.randint(2, len(main) - 2)
            bx, by = main[i]
            paths.append(self.jagged(bx, by, random.randint(2, 4), h / 12,
                                     max(2, int(w * 0.04)),
                                     random.choice([-1, 1]) * int(w * 0.03)))
        return paths

    def update_draw(self, frame, active, power, now):
        h, w = frame.shape[:2]
        S = w / 640.0
        self.intensity += ((1.0 if active else 0.0) - self.intensity) * 0.12

        if active:
            if not self.was_active:
                self.next_bolt = now + random.uniform(0.3, 0.8)
            for _ in range(12 * power):
                self.drops.append([random.randint(0, w), -20,
                                   random.uniform(18, 32) * S, random.uniform(15, 35) * S])
            if now >= self.next_bolt:
                self.bolt = self.make_bolt(w, h)
                self.bolt_time = now
                self.next_bolt = now + random.uniform(0.7, 2.0) / power
        self.was_active = active

        # langit menggelap kebiruan
        if self.intensity > 0.02:
            tint = np.full_like(frame, (60, 35, 15))
            frame = cv2.addWeighted(frame, 1 - 0.45 * self.intensity,
                                    tint, 0.45 * self.intensity, 0)

        # tetes hujan
        alive = []
        for d in self.drops:
            x, y, speed, length = d
            cv2.line(frame, (int(x), int(y)), (int(x - 3 * S), int(y + length)),
                     (255, 210, 160), max(1, int(2 * S)))
            d[0] -= 2 * S
            d[1] += speed
            if d[1] < h + 40:
                alive.append(d)
        self.drops = alive

        # petir
        age = now - self.bolt_time
        if self.bolt is not None and age < 0.35:
            if age < 0.2 and not (0.09 < age < 0.12):  # sedikit berkedip
                layer = np.zeros_like(frame)
                for idx, pts in enumerate(self.bolt):
                    k = 1.0 if idx == 0 else 0.6
                    arr = np.array(pts, np.int32).reshape(-1, 1, 2)
                    cv2.polylines(layer, [arr], False, (200, 120, 40),
                                  max(1, int(11 * S * k)), cv2.LINE_AA)
                    cv2.polylines(layer, [arr], False, (255, 200, 130),
                                  max(1, int(5 * S * k)), cv2.LINE_AA)
                    cv2.polylines(layer, [arr], False, (255, 255, 255),
                                  max(1, int(2 * S * k)), cv2.LINE_AA)
                frame = cv2.add(frame, layer)
            flash = (0.55 * max(0.0, 1 - age / 0.35)
                     + 0.25 * max(0.0, 1 - abs(age - 0.13) / 0.06))
            if flash > 0.01:
                frame = cv2.addWeighted(frame, 1 - flash,
                                        np.full_like(frame, (255, 245, 235)), flash, 0)
        return frame


# ----------------------------------------- efek: disko + laser di belakang ---
LASER_COLORS = [(0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255)]


class Disco:
    def __init__(self):
        self.intensity = 0.0

    @staticmethod
    def hue_color(hue):
        bgr = cv2.cvtColor(np.uint8([[[int(hue) % 180, 255, 255]]]),
                           cv2.COLOR_HSV2BGR)[0][0]
        return tuple(int(c) for c in bgr)

    @staticmethod
    def glow(img, sigma):
        h, w = img.shape[:2]
        small = cv2.resize(img, (max(1, w // 4), max(1, h // 4)))
        small = cv2.GaussianBlur(small, (0, 0), sigma)
        return cv2.resize(small, (w, h))

    def draw_lasers(self, img, w, h, t, power, S):
        emitters = [(0.0, 0.0), (1.0, 0.0), (0.5, 0.0)]
        if power >= 2:
            emitters += [(0.25, 0.0), (0.75, 0.0)]  # 2 tangan = laser lebih banyak
        cx, cy = w / 2, h * 0.6
        length = 2 * math.hypot(w, h)
        for ei, (ex, ey) in enumerate(emitters):
            ox, oy = ex * w, ey * h
            color = LASER_COLORS[ei % len(LASER_COLORS)]
            dim = tuple(int(c * 0.35) for c in color)
            base = math.atan2(cy - oy, cx - ox)
            for k in range(5):
                ang = base + math.radians(55) * math.sin(t * 1.7 + k * 0.9 + ei * 1.3)
                p0 = (int(ox), int(oy))
                p1 = (int(ox + math.cos(ang) * length), int(oy + math.sin(ang) * length))
                cv2.line(img, p0, p1, dim, max(1, int(7 * S)), cv2.LINE_AA)
                cv2.line(img, p0, p1, color, max(1, int(2 * S)), cv2.LINE_AA)

    def update_draw(self, frame, active, power, mask, now):
        h, w = frame.shape[:2]
        S = w / 640.0
        self.intensity += ((1.0 if active else 0.0) - self.intensity) * 0.15
        I = self.intensity
        if I < 0.02:
            return frame
        t = now

        # latar belakang digelapkan ala klub
        bg = cv2.convertScaleAbs(frame, alpha=0.38)

        # sorot lampu + bola cahaya
        layer = np.zeros_like(frame)
        n = 7
        for i in range(n):
            color = self.hue_color(t * 80 + i * 25)
            x0 = (i + 0.5) * w / n
            angle = math.sin(t * 2.2 + i * 1.3) * 0.7
            x1 = x0 + math.tan(angle) * h
            pts = np.array([[x0 - 8 * S, 0], [x0 + 8 * S, 0],
                            [x1 + 110 * S, h], [x1 - 110 * S, h]], dtype=np.int32)
            cv2.fillPoly(layer, [pts], color)
        for _ in range(6):
            c = self.hue_color(random.randint(0, 179))
            cv2.circle(layer, (random.randint(0, w - 1), random.randint(0, h - 1)),
                       int(random.randint(25, 70) * S), c, -1)
        layer = cv2.add(layer, self.glow(layer, 5))
        bg = cv2.add(bg, cv2.convertScaleAbs(layer, alpha=0.6))

        # laser (digambar di latar, jadi berada di BELAKANG badan)
        lasers = np.zeros_like(frame)
        self.draw_lasers(lasers, w, h, t, power, S)
        lasers = cv2.add(lasers, self.glow(lasers, 4))
        bg = cv2.add(bg, lasers)

        # strobo mengikuti ketukan
        if (t * 3) % 1.0 < 0.1:
            bg = cv2.addWeighted(bg, 0.8, np.full_like(bg, 255), 0.2, 0)

        # kilauan
        for _ in range(20):
            cv2.circle(bg, (random.randint(0, w - 1), random.randint(0, h - 1)),
                       random.randint(1, 3), (255, 255, 255), -1)

        # badan di depan, kena cahaya warna-warni
        wash = np.full_like(frame, self.hue_color(t * 60))
        person = cv2.addWeighted(frame, 0.82, wash, 0.18, 0)
        if mask is not None:
            m = cv2.resize(mask, (w, h), interpolation=cv2.INTER_LINEAR)
            m = cv2.GaussianBlur(m, (0, 0), 3)
            np.copyto(bg, person, where=(m > 0.5)[..., None])
        out = bg
        return cv2.addWeighted(frame, 1 - I, out, I, 0)


# ----------------------------------------------------------------- main ----
def main():
    cap, cfg = select_camera()
    if cap is None:
        print("Keluar.")
        return

    rain, hearts, disco = Rain(), Hearts(), Disco()
    last_seen = {"rain": 0.0, "heart": 0.0, "disco": 0.0}
    power = {"rain": 1, "heart": 1, "disco": 1}

    display_width = DISPLAY_WIDTH
    need_resize = True
    fullscreen = False
    spawn_tick = 0
    cv2.namedWindow(WIN, cv2.WINDOW_NORMAL)

    with mp_hands.Hands(max_num_hands=2,
                        model_complexity=MODEL_COMPLEXITY,
                        min_detection_confidence=0.5,
                        min_tracking_confidence=0.5) as hands, \
            mp_selfie.SelfieSegmentation(model_selection=1) as selfie:
        while True:
            ok, raw = cap.read()
            if not ok:
                if cv2.waitKey(10) & 0xFF == ord("q"):
                    break
                continue

            raw = cv2.flip(raw, 1)  # mode cermin
            fh, fw = raw.shape[:2]

            # gambar kecil untuk deteksi (ringan), gambar besar untuk ditampilkan
            if fw > PROCESS_WIDTH:
                small = cv2.resize(raw, (PROCESS_WIDTH, int(fh * PROCESS_WIDTH / fw)))
            else:
                small = raw
            if fw != display_width:
                frame = cv2.resize(raw, (display_width, int(fh * display_width / fw)))
            else:
                frame = raw
            h, w = frame.shape[:2]
            S = w / 640.0
            now = time.time()

            rgb = cv2.cvtColor(small, cv2.COLOR_BGR2RGB)
            res = hands.process(rgb)

            counts = {"rain": 0, "heart": 0, "disco": 0}
            heart_pts = []  # (x, y, jumlah hati yang muncul)
            big_pts = []    # posisi hati besar

            if res.multi_hand_landmarks:
                hand_list = [hd.landmark for hd in res.multi_hand_landmarks]
                center = two_hand_heart(hand_list)  # cek love 2 tangan lebih dulu

                for i, hand in enumerate(res.multi_hand_landmarks):
                    lm = hand.landmark
                    mp_draw.draw_landmarks(frame, hand, mp_hands.HAND_CONNECTIONS)

                    side = res.multi_handedness[i].classification[0].label
                    side_id = "Kiri" if side == "Left" else "Kanan"
                    up = fingers_up(lm)

                    gesture = ""
                    if center:
                        counts["heart"] += 1
                        gesture = "Love 2 tangan"
                    elif is_finger_heart(lm, up):
                        counts["heart"] += 1
                        px = (lm[4].x + lm[8].x) / 2 * w
                        py = (lm[4].y + lm[8].y) / 2 * h
                        heart_pts.append((px, py, 2))   # sedang (awal 3)
                        big_pts.append((px, py))
                        gesture = "Love"
                    elif is_thumb_down(lm, up):
                        counts["rain"] += 1
                        gesture = "Jempol bawah"
                    elif is_rock(lm, up):
                        counts["disco"] += 1
                        gesture = "Metal"

                    x, y = int(lm[0].x * w), int(lm[0].y * h)
                    text = f"{side_id}: {sum(up)} jari"
                    if gesture:
                        text += f" | {gesture}"
                    cv2.putText(frame, text, (int(x - 60 * S), int(y + 40 * S)),
                                cv2.FONT_HERSHEY_SIMPLEX, 0.6 * S, (0, 255, 0),
                                max(1, round(1.5 * S)))
                    names = [FINGER_NAMES[k] for k, v in enumerate(up) if v]
                    cv2.putText(frame, ", ".join(names), (int(x - 60 * S), int(y + 65 * S)),
                                cv2.FONT_HERSHEY_SIMPLEX, 0.45 * S, (255, 255, 0), 1)

                if center:
                    cxp, cyp = center[0] * w, center[1] * h
                    heart_pts.append((cxp, cyp, 4))     # sedang (awal 6)
                    big_pts.append((cxp, cyp))

            for k, c in counts.items():
                if c > 0:
                    last_seen[k] = now
                    power[k] = min(2, c)  # 2 tangan = efek lebih heboh

            # segmentasi badan hanya dihitung saat disko aktif (supaya ringan)
            mask = None
            if now - last_seen["disco"] < HOLD_TIME or disco.intensity > 0.05:
                try:
                    mask = selfie.process(rgb).segmentation_mask
                except Exception:
                    mask = None

            # terapkan efek
            frame = rain.update_draw(frame, now - last_seen["rain"] < HOLD_TIME,
                                     power["rain"], now)
            frame = disco.update_draw(frame, now - last_seen["disco"] < HOLD_TIME,
                                      power["disco"], mask, now)

            # hati muncul lebih jarang dan jumlah total dibatasi
            spawn_tick += 1
            if (spawn_tick % HEART_SPAWN_EVERY == 0
                    and len(hearts.particles) < HEART_MAX_PARTICLES):
                for (hx, hy, cnt) in heart_pts:
                    hearts.spawn(hx, hy, cnt, S)
            hearts.update_draw(frame, big_pts, S, now)

            # teks bantuan
            cv2.putText(frame, "Jempol bawah=Hujan+Petir | Love=Spam love | Metal=Disko+Laser",
                        (10, int(h - 38 * S)), cv2.FONT_HERSHEY_SIMPLEX, 0.55 * S,
                        (255, 255, 255), max(1, round(1.5 * S)))
            cv2.putText(frame, "f=layar penuh | +/-=ukuran | c=ganti kamera | q=keluar",
                        (10, int(h - 14 * S)), cv2.FONT_HERSHEY_SIMPLEX, 0.45 * S,
                        (200, 200, 200), 1)

            if need_resize:
                cv2.resizeWindow(WIN, w, h)
                need_resize = False
            cv2.imshow(WIN, frame)

            key = cv2.waitKey(1) & 0xFF
            if cv2.getWindowProperty(WIN, cv2.WND_PROP_VISIBLE) < 1:
                break
            if key == ord("q"):
                break
            elif key == ord("f"):
                fullscreen = not fullscreen
                cv2.setWindowProperty(
                    WIN, cv2.WND_PROP_FULLSCREEN,
                    cv2.WINDOW_FULLSCREEN if fullscreen else cv2.WINDOW_NORMAL)
                if not fullscreen:
                    need_resize = True
            elif key in (ord("+"), ord("=")):
                display_width = min(1600, display_width + 160)
                need_resize = True
            elif key in (ord("-"), ord("_")):
                display_width = max(640, display_width - 160)
                need_resize = True
            elif key == ord("c"):  # buka lagi menu pilih kamera
                cap.release()
                cap, new_cfg = select_camera(cfg)
                if cap is None:
                    return
                cfg = new_cfg

    cap.release()
    cv2.destroyAllWindows()


if __name__ == "__main__":
    main()