#!/usr/bin/env python3
"""Neon Pong - a fast, chaotic local 2-player Pong with falling power-ups.

Run interactively:
    python3 pong.py

Render a verification frame (headless-safe, exits after saving) and quit:
    python3 pong.py --screenshot out.png

Controls (local two-player):
    W / S               Player 1 (left paddle)  up / down
    Arrow Up / Down     Player 2 (right paddle) up / down
    Enter / Space       start / serve
    P                   pause / resume
    R                   restart the round (or reset after game over)
    Esc / Q             quit

Power-ups collect as they fall; colour-coded capsules. Match the ball at
3x base speed, so collect the TURBO / SHIELD / GROW drops to keep up.
"""

import sys
import math
import random
import array

import pygame

# ------------------------------------------------------------------ config --
WIDTH, HEIGHT = 960, 600
FPS = 120
SAMPLE_RATE = 44100

BG       = (14, 16, 24)
GRID_C   = (34, 40, 56)
PANEL    = (22, 26, 38)
FG       = (238, 242, 255)
MUTED    = (150, 158, 180)
PLAYER_C = (64, 216, 255)   # neon cyan  -> player 1 (left)
AI_C     = (255, 92, 148)   # neon magenta -> player 2 (right)
BALL_C   = (240, 246, 255)
FIRE_C   = (255, 150, 40)

PADDLE_W, PADDLE_H = 14, 110
PADDLE_SPEED = 940.0

BALL_RADIUS   = 9
BALL_BASE_SPEED = 1290.0     # 3x faster than the original 430
BALL_SERVE_SPEED = BALL_BASE_SPEED * 0.5   # slower opening serve; ramps to full speed on first paddle hit
BALL_MAX_BOUNCE = math.radians(62)
BALL_CAP = 5                 # max simultaneous balls

WIN_SCORE = 7

# Power-up tuning
POWERUP_FALL_SPEED = 150.0
POWERUP_SPAWN_MIN, POWERUP_SPAWN_MAX = 3.0, 5.5
POWERUP_W, POWERUP_H = 120, 80
POWERUP_TIMER_TURBO = 6.0
POWERUP_TIMER_GROW = 6.0
POWERUP_TIMER_SHRINK = 6.0
POWERUP_TIMER_SHIELD = 6.0
POWERUP_TIMER_FIRE = 5.0
POWERUP_FIRE_MULT = 1.5

POWERUP_TYPES = ["multi", "turbo", "grow", "shrink", "fire", "shield", "switch"]
POWERUP_COLORS = {
    "multi":  (120, 220, 255),
    "turbo":  (255, 214, 90),
    "grow":   (120, 255, 170),
    "shrink": (255, 130, 100),
    "fire":   (255, 120, 40),
    "shield": (170, 150, 255),
    "switch": (255, 80, 110),
}
POWERUP_LETTERS = {
    "multi": "M", "turbo": "S", "grow": "G",
    "shrink": "K", "fire": "F", "shield": "H", "switch": "X",
}

MENU, PLAYING, PAUSED, GAME_OVER = "menu", "playing", "paused", "game_over"


# ----------------------------------------------------------------- helpers --
def clamp(v, lo, hi):
    return lo if v < lo else hi if v > hi else v


def synth_sound(freq_start, freq_end, ms, volume=0.42, wave="square"):
    """Build a mono pygame.mixer.Sound from a swept waveform, no numpy needed."""
    n = max(1, int(SAMPLE_RATE * ms / 1000))
    buf = array.array("h")
    fade_in = SAMPLE_RATE * 0.004
    fade_out = SAMPLE_RATE * 0.008
    for i in range(n):
        frac = i / n
        freq = freq_start + (freq_end - freq_start) * frac
        phase = 2.0 * math.pi * freq * (i / SAMPLE_RATE)
        if wave == "square":
            v = 1.0 if math.sin(phase) >= 0 else -1.0
        elif wave == "sine":
            v = math.sin(phase)
        else:  # triangle
            v = 2.0 / math.pi * math.asin(math.sin(phase))
        env = min(1.0, i / fade_in, (n - i) / fade_out)
        env = max(0.0, env)
        sample = int(max(-32768, min(32767, v * volume * env * 32767)))
        buf.append(sample)
    return pygame.mixer.Sound(buffer=buf.tobytes())


# ------------------------------------------------------------------- actors --
class Paddle:
    def __init__(self, x, y):
        self.x = float(x)
        self.y = float(y)
        self.w, self.h = PADDLE_W, PADDLE_H
        self.boost_timer = 0.0
        self.grow_timer = 0.0
        self.shrink_timer = 0.0
        self.shield_timer = 0.0

    @property
    def center(self):
        return self.y + self.h / 2.0

    @property
    def rect(self):
        return pygame.Rect(int(self.x), int(self.y), self.w, self.h)

    @property
    def speed(self):
        return PADDLE_SPEED * (2.0 if self.boost_timer > 0 else 1.0)

    @property
    def shield_active(self):
        return self.shield_timer > 0

    def _eff_h(self):
        if self.grow_timer > 0:
            return PADDLE_H * 2.0
        if self.shrink_timer > 0:
            return PADDLE_H * 0.5
        return PADDLE_H

    def move(self, dt, direction):
        self.y += direction * self.speed * dt
        self.y = clamp(self.y, 0, HEIGHT - self.h)

    def tick(self, dt):
        if self.boost_timer > 0:
            self.boost_timer -= dt
        if self.grow_timer > 0:
            self.grow_timer -= dt
        if self.shrink_timer > 0:
            self.shrink_timer -= dt
        if self.shield_timer > 0:
            self.shield_timer -= dt
        new_h = self._eff_h()
        if new_h != self.h:
            self.y += (self.h - new_h) / 2.0   # keep the paddle centred
            self.h = new_h
        self.y = clamp(self.y, 0, HEIGHT - self.h)


class Ball:
    def __init__(self):
        self.x = WIDTH / 2.0
        self.y = HEIGHT / 2.0
        self.speed = BALL_BASE_SPEED
        self.vx = 0.0
        self.vy = 0.0
        self.trail = []
        self.serve_delay = 0.0
        self.serve_dir = 1
        self.on_fire = False
        self.fire_left = 0.0
        self.accelerated = False   # becomes True after the first paddle bounce
        self.last_hitter = None    # 1 = left paddle, 2 = right paddle; owns the next power-up

    @property
    def rect(self):
        return pygame.Rect(int(self.x - BALL_RADIUS), int(self.y - BALL_RADIUS),
                           BALL_RADIUS * 2, BALL_RADIUS * 2)

    def halt(self):
        self.vx = self.vy = 0.0
        self.trail.clear()

    def set_serve(self, direction, delay):
        self.x = WIDTH / 2.0
        self.y = HEIGHT / 2.0
        self.speed = BALL_SERVE_SPEED
        self.on_fire = False
        self.fire_left = 0.0
        self.accelerated = False
        self.serve_dir = direction
        self.serve_delay = delay
        self.halt()

    def serve(self, direction):
        self.x = WIDTH / 2.0
        self.y = HEIGHT / 2.0
        self.speed = BALL_SERVE_SPEED
        self.serve_delay = 0.0
        angle = random.uniform(-0.42, 0.42)
        self.vx = self.speed * math.cos(angle) * direction
        self.vy = self.speed * math.sin(angle)

    def apply_fire(self, duration):
        if not self.on_fire:
            self.vx *= POWERUP_FIRE_MULT
            self.vy *= POWERUP_FIRE_MULT
            self.speed *= POWERUP_FIRE_MULT
            self.on_fire = True
        self.fire_left = max(self.fire_left, duration)

    def _tick_fire(self, dt):
        if not self.on_fire:
            return
        self.fire_left -= dt
        if self.fire_left <= 0:
            self.vx /= POWERUP_FIRE_MULT
            self.vy /= POWERUP_FIRE_MULT
            self.speed /= POWERUP_FIRE_MULT
            self.on_fire = False

    def update(self, dt, left, right):
        self._tick_fire(dt)
        if self.serve_delay > 0:
            self.serve_delay -= dt
            if self.serve_delay <= 0:
                self.serve(self.serve_dir)
                return "serve"
            return ""

        self.trail.append((self.x, self.y))
        if len(self.trail) > 14:
            self.trail.pop(0)

        dist = math.hypot(self.vx, self.vy) * dt
        steps = max(1, int(dist / (BALL_RADIUS * 0.6)) + 1)
        sub = dt / steps
        for _ in range(steps):
            self.x += self.vx * sub
            self.y += self.vy * sub
            ev = self._collide(left, right)
            if ev:
                return ev
        return ""

    def _collide(self, left, right):
        # top / bottom walls
        if self.y - BALL_RADIUS <= 0:
            self.y = BALL_RADIUS
            self.vy = abs(self.vy)
            return "wall"
        if self.y + BALL_RADIUS >= HEIGHT:
            self.y = HEIGHT - BALL_RADIUS
            self.vy = -abs(self.vy)
            return "wall"

        # right paddle (player 2)
        if self.vx > 0 and self.x + BALL_RADIUS >= right.x and self.x <= right.x + right.w:
            if right.y - BALL_RADIUS <= self.y <= right.y + right.h + BALL_RADIUS:
                self.x = right.x - BALL_RADIUS
                self._bounce(right, -1, 2)
                return "paddle"
        # fully off the right edge -> player 1 scores
        if self.x - BALL_RADIUS > WIDTH:
            return "score_left"

        # left paddle (player 1)
        if self.vx < 0 and self.x - BALL_RADIUS <= left.x + left.w and self.x >= left.x:
            if left.y - BALL_RADIUS <= self.y <= left.y + left.h + BALL_RADIUS:
                self.x = left.x + left.w + BALL_RADIUS
                self._bounce(left, 1, 1)
                return "paddle"
        # fully off the left edge -> player 2 scores
        if self.x + BALL_RADIUS < 0:
            return "score_right"

        return ""

    def _bounce(self, paddle, direction, hitter=None):
        if hitter is not None:
            self.last_hitter = hitter
        # Elastic reflection off the flat paddle face: reverse the horizontal
        # component and keep the vertical one, conserving the ball's momentum
        # (total speed is unchanged by a bounce after the ramp-up).
        speed = math.hypot(self.vx, self.vy)
        if speed < 1e-6:
            speed = BALL_SERVE_SPEED
            self.vy = 0.0
            self.vx = speed * direction
            self.speed = speed
            return
        self.vx = abs(self.vx) * direction
        if not self.accelerated:
            # first paddle hit: ramp the opening serve up to the normal speed
            self.accelerated = True
            target = BALL_BASE_SPEED * (POWERUP_FIRE_MULT if self.on_fire else 1.0)
            self.speed = target
            mag = math.hypot(self.vx, self.vy)
            if mag < 1e-6:
                self.vx = target * direction
                self.vy = 0.0
            else:
                self.vx = self.vx / mag * target
                self.vy = self.vy / mag * target
        else:
            self.speed = speed


class Particle:
    __slots__ = ("x", "y", "vx", "vy", "life", "max_life", "color", "size")

    def __init__(self, x, y, vx, vy, life, color, size):
        self.x, self.y = x, y
        self.vx, self.vy = vx, vy
        self.life = self.max_life = life
        self.color = color
        self.size = size

    def update(self, dt):
        self.x += self.vx * dt
        self.y += self.vy * dt
        self.vx *= 0.94
        self.vy *= 0.94
        self.life -= dt

    def draw(self, surf):
        if self.life <= 0:
            return
        alpha = max(0, int(255 * self.life / self.max_life))
        r = max(1, int(self.size * self.life / self.max_life))
        pygame.draw.circle(surf, (*self.color, alpha), (int(self.x), int(self.y)), r)


class PowerUp:
    def __init__(self, kind, x):
        self.kind = kind
        self.rect = pygame.Rect(0, 0, POWERUP_W, POWERUP_H)
        self.rect.centerx = int(x)
        self.rect.top = -POWERUP_H

    @property
    def color(self):
        return POWERUP_COLORS[self.kind]

    def update(self, dt):
        self.rect.y += POWERUP_FALL_SPEED * dt

    def off_screen(self):
        return self.rect.top > HEIGHT

    def draw(self, glow, world, font):
        c = self.color
        rect = self.rect
        pygame.draw.rect(glow, (*c, 46), rect.inflate(14, 14), border_radius=9)
        pygame.draw.rect(glow, (*c, 90), rect.inflate(4, 4), border_radius=7)
        pygame.draw.rect(world, c, rect, border_radius=6)
        pygame.draw.rect(world, FG, rect, width=1, border_radius=6)
        img = font.render(POWERUP_LETTERS[self.kind], True, FG)
        r = img.get_rect()
        r.center = rect.center
        world.blit(img, r)


# --------------------------------------------------------------------- game --
class Game:
    def __init__(self, demo=False):
        pygame.init()
        try:
            pygame.mixer.pre_init(SAMPLE_RATE, -16, 1, 512)
            pygame.mixer.init()
            self.sounds = {
                "paddle": synth_sound(320, 320, 55, 0.40, "square"),
                "wall":   synth_sound(190, 160, 42, 0.34, "triangle"),
                "score":  synth_sound(420, 120, 330, 0.40, "square"),
                "win":    synth_sound(330, 660, 320, 0.45, "sine"),
                "power":  synth_sound(500, 900, 70, 0.42, "sine"),
                "shield": synth_sound(200, 620, 140, 0.42, "triangle"),
            }
        except Exception:
            self.sounds = {}

        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption("Neon Pong")
        self.clock = pygame.time.Clock()
        self.glow = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        self.world = pygame.Surface((WIDTH, HEIGHT), depth=24)
        self.flash_surf = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        self.overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        self.background = self._build_background()

        self.font_big = self._font(96, bold=True)
        self.font_med = self._font(42, bold=True)
        self.font_power = self._font(56, bold=True)
        self.font_sm = self._font(24)
        self.font_tiny = self._font(18)

        self.demo = demo
        self.state = MENU
        self.match_mode = "infinite"   # "infinite" or "scratch" (first to WIN_SCORE)
        self.control = {"left": 1, "right": 2}   # which player controls each side
        self.shake = 0.0
        self.flash = 0.0

        self.left_paddle = Paddle(28, HEIGHT / 2 - PADDLE_H / 2)
        self.right_paddle = Paddle(WIDTH - 28 - PADDLE_W, HEIGHT / 2 - PADDLE_H / 2)
        self.balls = [Ball()]
        self.particles = []
        self.popups = []
        self.powerups = []
        self.powerup_timer = random.uniform(POWERUP_SPAWN_MIN, POWERUP_SPAWN_MAX)
        self.score_p = 0
        self.score_a = 0

        if demo:
            self._enter_playing(serve_delay=0.25)

    # ------------------------------------------------------------- helpers --
    def _font(self, size, bold=False):
        try:
            return pygame.font.SysFont("menlo, monaco, couriernew, arial", size, bold=bold)
        except Exception:
            return pygame.font.Font(None, size)

    def _build_background(self):
        bg = pygame.Surface((WIDTH, HEIGHT))
        bg.fill(BG)
        for x in range(0, WIDTH, 48):
            pygame.draw.line(bg, GRID_C, (x, 0), (x, HEIGHT), 1)
        for y in range(0, HEIGHT, 48):
            pygame.draw.line(bg, GRID_C, (0, y), (WIDTH, y), 1)
        return bg

    def _sound(self, name):
        s = self.sounds.get(name)
        if s:
            s.play()

    def _spawn(self, x, y, color, count, speed=170.0, life=0.5):
        for _ in range(count):
            ang = random.uniform(0, math.tau)
            spd = random.uniform(speed * 0.3, speed)
            self.particles.append(
                Particle(x, y, math.cos(ang) * spd, math.sin(ang) * spd,
                         random.uniform(life * 0.5, life), color,
                         random.uniform(2.5, 5.5)))

    def _popup(self, text, x, y, color):
        self.popups.append([text, x, y, 1.0, color])

    def _enter_playing(self, serve_delay=0.9):
        self.state = PLAYING
        self.balls = [Ball()]
        self.balls[0].set_serve(random.choice([-1, 1]), serve_delay)

    def _clear_buffs(self):
        for p in (self.left_paddle, self.right_paddle):
            p.boost_timer = p.grow_timer = 0.0
            p.shrink_timer = p.shield_timer = 0.0
            p.h = PADDLE_H
            p.y = clamp(p.y, 0, HEIGHT - p.h)

    def _reset_game(self):
        self.score_p = self.score_a = 0
        self._clear_buffs()
        self.powerups.clear()
        self.popups.clear()
        self.powerup_timer = random.uniform(POWERUP_SPAWN_MIN, POWERUP_SPAWN_MAX)
        self._enter_playing(serve_delay=1.0)

    def _spawn_balls(self, n):
        if not self.balls:
            return
        src = self.balls[0]
        for _ in range(n):
            if len(self.balls) >= BALL_CAP:
                break
            b = Ball()
            b.x, b.y = src.x, src.y
            b.speed = src.speed
            b.accelerated = src.accelerated
            if src.on_fire:
                b.on_fire = True
                b.fire_left = src.fire_left
            ang = random.uniform(-0.65, 0.65)
            direction = random.choice([-1, 1])
            b.vx = b.speed * math.cos(ang) * direction
            b.vy = b.speed * math.sin(ang)
            self.balls.append(b)
        self._sound("power")

    def _paddle_for(self, player):
        return self.left_paddle if self.control["left"] == player else self.right_paddle

    def _opponent_for(self, player):
        return self.right_paddle if self.control["left"] == player else self.left_paddle

    def _side_color(self, side):
        return PLAYER_C if self.control[side] == 1 else AI_C

    def _side_core(self, side):
        return (220, 250, 255) if self.control[side] == 1 else (255, 210, 228)

    def _switch_sides(self):
        # Swap which player controls which side; scores stay with the players.
        self.control["left"], self.control["right"] = self.control["right"], self.control["left"]
        self._sound("power")

    def _deflect(self, ball, paddle):
        # Auto-shield save: knock the ball back toward the opponent, then pop.
        if paddle is self.right_paddle:
            ball.x = self.right_paddle.x - BALL_RADIUS
            ball.vx = -abs(ball.vx)
        else:
            ball.x = self.left_paddle.x + self.left_paddle.w + BALL_RADIUS
            ball.vx = abs(ball.vx)
        paddle.shield_timer = 0.0
        self._sound("shield")
        self._spawn(ball.x, ball.y, (255, 255, 255), 20, 220, 0.5)

    def _score_ball(self, ball, ev):
        if ev == "score_left":       # passed the right edge -> player 1 scores
            scorer, give, side_x, shield_paddle, nxt = "p1", PLAYER_C, WIDTH - 20, self.right_paddle, -1
        else:                        # passed the left edge -> player 2 scores
            scorer, give, side_x, shield_paddle, nxt = "p2", AI_C, 20, self.left_paddle, 1

        if shield_paddle.shield_active:
            self._deflect(ball, shield_paddle)
            return

        self.shake = max(self.shake, 0.45)
        self.flash = 0.35
        self._sound("score")
        pts = 2 if ball.on_fire else 1         # a fire ball scores double
        if scorer == "p1":
            self.score_p += pts
        else:
            self.score_a += pts
        self._spawn(side_x, ball.y, give, 26, 260, 0.5)
        if ball in self.balls:
            self.balls.remove(ball)
        if not self.balls:
            b = Ball()
            b.set_serve(nxt, 0.8)
            self.balls.append(b)
        if self.match_mode == "scratch" and (self.score_p >= WIN_SCORE or self.score_a >= WIN_SCORE):
            self.state = GAME_OVER
            self._sound("win")

    def _collect(self, pu, paddle, opponent):
        self._sound("power")
        self._spawn(pu.rect.centerx, pu.rect.centery, pu.color, 18, 220, 0.5)
        k = pu.kind
        cx, cy = pu.rect.centerx, pu.rect.centery - 22
        if k == "multi":
            self._spawn_balls(2)
            self._popup("+2 BALLS", cx, cy, pu.color)
        elif k == "turbo":
            paddle.boost_timer = POWERUP_TIMER_TURBO
            self._popup("TURBO", cx, cy, pu.color)
        elif k == "grow":
            paddle.grow_timer = POWERUP_TIMER_GROW
            self._popup("GROW", cx, cy, pu.color)
        elif k == "shrink":
            opponent.shrink_timer = POWERUP_TIMER_SHRINK
            self._popup("SHRINK", cx, cy, pu.color)
        elif k == "shield":
            paddle.shield_timer = POWERUP_TIMER_SHIELD
            self._popup("SHIELD", cx, cy, pu.color)
        elif k == "fire":
            for b in self.balls:
                b.apply_fire(POWERUP_TIMER_FIRE)
            self._popup("FIRE BALL", cx, cy, pu.color)
        elif k == "switch":
            self._switch_sides()
            self._popup("SWITCH!", cx, cy, pu.color)

    # -------------------------------------------------------------- events --
    def handle_events(self):
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                self.quit()
                return False
            if e.type == pygame.KEYDOWN:
                if e.key in (pygame.K_ESCAPE, pygame.K_q):
                    self.quit()
                    return False
                if self.state == MENU:
                    if e.key in (pygame.K_UP, pygame.K_DOWN):
                        self.match_mode = "scratch" if self.match_mode == "infinite" else "infinite"
                    elif e.key in (pygame.K_RETURN, pygame.K_SPACE, pygame.K_RIGHT):
                        self.enter_game()
                elif self.state == PLAYING:
                    if e.key in (pygame.K_p, pygame.K_ESCAPE):
                        self.state = PAUSED
                    elif e.key == pygame.K_r:
                        self._reset_game()
                elif self.state == PAUSED:
                    if e.key in (pygame.K_p, pygame.K_ESCAPE, pygame.K_SPACE, pygame.K_RETURN):
                        self.state = PLAYING
                    elif e.key == pygame.K_r:
                        self._reset_game()
                elif self.state == GAME_OVER:
                    if e.key in (pygame.K_RETURN, pygame.K_SPACE):
                        self._reset_game()
                    elif e.key == pygame.K_r:
                        self._reset_game()
        return True

    def enter_game(self):
        self.score_p = self.score_a = 0
        self._clear_buffs()
        self.powerups.clear()
        self.popups.clear()
        self.powerup_timer = random.uniform(POWERUP_SPAWN_MIN, POWERUP_SPAWN_MAX)
        self._enter_playing(serve_delay=1.0)

    def quit(self):
        pygame.quit()
        sys.exit(0)

    # -------------------------------------------------------------- update --
    def update(self, dt):
        if self.state == MENU:
            self._tick_particles(dt)
            return

        if self.state == GAME_OVER:
            self._tick_particles(dt)
            self.shake = max(0.0, self.shake - dt)
            self.flash = max(0.0, self.flash - dt)
            return

        if self.state == PAUSED:
            return

        # PLAYING — local two-player with power-ups.
        keys = pygame.key.get_pressed()
        if self.demo:
            self._track_paddles(dt)
        else:
            p1_dir = 0
            if keys[pygame.K_w]:
                p1_dir -= 1
            if keys[pygame.K_s]:
                p1_dir += 1
            self._paddle_for(1).move(dt, p1_dir)

            p2_dir = 0
            if keys[pygame.K_UP]:
                p2_dir -= 1
            if keys[pygame.K_DOWN]:
                p2_dir += 1
            self._paddle_for(2).move(dt, p2_dir)

        self.left_paddle.tick(dt)
        self.right_paddle.tick(dt)
        self._update_powerups(dt)

        for ball in self.balls[:]:
            ev = ball.update(dt, self.left_paddle, self.right_paddle)
            if ev == "wall":
                self._sound("wall")
                self.shake = max(self.shake, 0.12)
                c = FIRE_C if ball.on_fire else BALL_C
                self._spawn(ball.x, 6 if ball.vy < 0 else HEIGHT - 6, c, 10, 150, 0.4)
            elif ev == "paddle":
                self._sound("paddle")
                self.shake = max(self.shake, 0.18)
                side_x = ball.x + (BALL_RADIUS if ball.vx > 0 else -BALL_RADIUS)
                c = self._side_color("right" if ball.vx > 0 else "left")
                self._spawn(side_x, ball.y, c, 14, 180, 0.45)
            elif ev in ("score_left", "score_right"):
                self._score_ball(ball, ev)

        self._ball_collect_powerups()

        for ball in self.balls:
            if ball.on_fire:
                self._spawn(ball.x, ball.y, FIRE_C, 2, 90, 0.35)

        self._tick_particles(dt)
        self._tick_popups(dt)
        self.shake = max(0.0, self.shake - dt)
        self.flash = max(0.0, self.flash - dt)

    def _track_paddles(self, dt):
        b = self.balls[0] if self.balls else None
        ty = b.y if b else HEIGHT / 2.0
        for paddle in (self.left_paddle, self.right_paddle):
            target = clamp(ty, PADDLE_H / 2.0, HEIGHT - PADDLE_H / 2.0)
            delta = target - paddle.center
            max_step = 300.0 * dt
            if abs(delta) <= max_step:
                paddle.y = target - paddle.h / 2.0
            else:
                paddle.y += math.copysign(max_step, delta)
            paddle.y = clamp(paddle.y, 0, HEIGHT - paddle.h)

    def _update_powerups(self, dt):
        self.powerup_timer -= dt
        if self.powerup_timer <= 0 and len(self.powerups) < 3:
            self.powerups.append(PowerUp(random.choice(POWERUP_TYPES),
                                        random.uniform(60, WIDTH - 60)))
            self.powerup_timer = random.uniform(POWERUP_SPAWN_MIN, POWERUP_SPAWN_MAX)
        for pu in self.powerups[:]:
            pu.update(dt)
            if pu.off_screen():
                self.powerups.remove(pu)

    def _ball_collect_powerups(self):
        # A power-up is collected when the ball hits it. The player who last
        # touched the ball (last_hitter) owns the effect.
        for pu in self.powerups[:]:
            for ball in self.balls:
                if pu.rect.colliderect(ball.rect):
                    if ball.last_hitter == 1:
                        self._collect(pu, self._paddle_for(1), self._opponent_for(1))
                        self.powerups.remove(pu)
                    elif ball.last_hitter == 2:
                        self._collect(pu, self._paddle_for(2), self._opponent_for(2))
                        self.powerups.remove(pu)
                    break

    def _tick_particles(self, dt):
        alive = []
        for p in self.particles:
            p.update(dt)
            if p.life > 0:
                alive.append(p)
        self.particles = alive

    def _tick_popups(self, dt):
        alive = []
        for pop in self.popups:
            pop[3] -= dt
            if pop[3] > 0:
                alive.append(pop)
        self.popups = alive

    # ---------------------------------------------------------------- draw --
    def _draw_round_glow(self, rect, color, core):
        r = rect
        pygame.draw.rect(self.glow, (*color, 40), r.inflate(20, 20), border_radius=10)
        pygame.draw.rect(self.glow, (*color, 80), r.inflate(8, 8), border_radius=8)
        pygame.draw.rect(self.world, color, r, border_radius=6)
        pygame.draw.rect(self.world, core, r.inflate(-6, -6), border_radius=4)

    def _draw_ball_glow(self, b):
        col = FIRE_C if b.on_fire else BALL_C
        for i, (tx, ty) in enumerate(b.trail):
            a = int(140 * (i + 1) / len(b.trail))
            r = max(1, int(BALL_RADIUS * (i + 1) / len(b.trail)))
            pygame.draw.circle(self.glow, (*col, a), (int(tx), int(ty)), r)
        pygame.draw.circle(self.glow, (*col, 34), (int(b.x), int(b.y)), BALL_RADIUS * 3)
        pygame.draw.circle(self.glow, (*col, 70), (int(b.x), int(b.y)), BALL_RADIUS * 2)
        pygame.draw.circle(self.world, col, (int(b.x), int(b.y)), BALL_RADIUS)

    def _draw_paddle_status(self, paddle, color):
        # shield bubble
        if paddle.shield_active:
            r = paddle.rect.inflate(20, 20)
            pygame.draw.rect(self.glow, (*color, 80), r, border_radius=12)
            pygame.draw.rect(self.glow, (*color, 160), r, width=3, border_radius=12)
        # active-buff timer bar (outer wall side)
        frac, buff_color = 0.0, color
        if paddle.boost_timer > 0:
            frac = max(frac, paddle.boost_timer / POWERUP_TIMER_TURBO)
            buff_color = POWERUP_COLORS["turbo"]
        if paddle.grow_timer > 0:
            frac = max(frac, paddle.grow_timer / POWERUP_TIMER_GROW)
            buff_color = POWERUP_COLORS["grow"]
        if paddle.shrink_timer > 0:
            frac = max(frac, paddle.shrink_timer / POWERUP_TIMER_SHRINK)
            buff_color = POWERUP_COLORS["shrink"]
        if paddle.shield_timer > 0:
            frac = max(frac, paddle.shield_timer / POWERUP_TIMER_SHIELD)
            buff_color = POWERUP_COLORS["shield"]
        if frac > 0:
            bar_w = 6
            if paddle is self.left_paddle:
                x = paddle.x - bar_w - 6
            else:
                x = paddle.x + paddle.w + 6
            y = int(paddle.center - 36)
            pygame.draw.rect(self.world, (60, 70, 95), (x, y, bar_w, 72))
            h = int(72 * clamp(frac, 0.0, 1.0))
            if h > 0:
                pygame.draw.rect(self.world, buff_color, (x, y + 72 - h, bar_w, h))

    def _draw_popups(self):
        for text, x, y, life, col in self.popups:
            a = clamp(life, 0.0, 1.0)
            faded = tuple(int(c * a + bgc * (1 - a)) for c, bgc in zip(col, BG))
            self._draw_text(self.world, text, self.font_sm, faded,
                            center=(int(x), int(y - (1.0 - life) * 30)))

    def _draw_text(self, surf, text, font, color, center=None, topleft=None):
        img = font.render(text, True, color)
        rect = img.get_rect()
        if center:
            rect.center = center
        if topleft:
            rect.topleft = topleft
        surf.blit(img, rect)
        return rect

    def _draw_overlay_panel(self, title, lines):
        self.overlay.fill((0, 0, 0, 150))
        self.world.blit(self.overlay, (0, 0))
        panel = pygame.Rect(0, 0, 560, 320)
        panel.center = (WIDTH // 2, HEIGHT // 2)
        pygame.draw.rect(self.world, PANEL, panel, border_radius=16)
        pygame.draw.rect(self.world, (60, 70, 95), panel, width=2, border_radius=16)
        self._draw_text(self.world, title, self.font_med, FG, center=(WIDTH // 2, panel.top + 60))
        y = panel.top + 130
        for line in lines:
            self._draw_text(self.world, line, self.font_sm, MUTED, center=(WIDTH // 2, y))
            y += 34

    def draw(self):
        self.world.blit(self.background, (0, 0))
        self.glow.fill((0, 0, 0, 0))

        # centre dashed line
        for y in range(8, HEIGHT, 26):
            pygame.draw.rect(self.world, GRID_C, (WIDTH // 2 - 2, y, 4, 14))

        self._draw_round_glow(self.left_paddle.rect, self._side_color("left"), self._side_core("left"))
        self._draw_round_glow(self.right_paddle.rect, self._side_color("right"), self._side_core("right"))
        self._draw_paddle_status(self.left_paddle, self._side_color("left"))
        self._draw_paddle_status(self.right_paddle, self._side_color("right"))
        for b in self.balls:
            self._draw_ball_glow(b)
        for pu in self.powerups:
            pu.draw(self.glow, self.world, self.font_power)

        for p in self.particles:
            p.draw(self.glow)

        self.world.blit(self.glow, (0, 0))

        # flash on score (composited over the world, keeping it opaque)
        if self.flash > 0:
            self.flash_surf.fill((255, 255, 255, int(120 * self.flash)))
            self.world.blit(self.flash_surf, (0, 0))

        # score HUD (drawn after the flash so it stays crisp)
        if self.state in (PLAYING, PAUSED, GAME_OVER):
            self._draw_text(self.world, str(self.score_p), self.font_big, PLAYER_C,
                            center=(WIDTH // 2 - 120, 74))
            self._draw_text(self.world, str(self.score_a), self.font_big, AI_C,
                            center=(WIDTH // 2 + 120, 74))
            if self.match_mode == "infinite":
                self._draw_text(self.world, "INFINITE", self.font_tiny, MUTED,
                                center=(WIDTH // 2, 74))

        self._draw_popups()

        if self.state == MENU:
            self._draw_title_screen()
        elif self.state == PAUSED:
            self._draw_overlay_panel("PAUSED", ["Press P/Esc to resume", "Press R to restart the match"])
        elif self.state == GAME_OVER:
            if self.score_p >= WIN_SCORE:
                title, tone = "PLAYER 1 WINS", PLAYER_C
            else:
                title, tone = "PLAYER 2 WINS", AI_C
            self._draw_overlay_panel(title, [f"Final score {self.score_p} - {self.score_a}",
                                             "Press Enter to play again", "Press Esc to quit"])

        # present the fully-composed world to the screen (with screen shake)
        ox = oy = 0
        if self.shake > 0:
            ox = random.uniform(-1, 1) * self.shake * 14
            oy = random.uniform(-1, 1) * self.shake * 14
            self.screen.fill(BG)
            self.screen.blit(self.world, (int(ox), int(oy)))
        else:
            self.screen.blit(self.world, (0, 0))

    def _draw_title_screen(self):
        self._draw_text(self.world, "NEON PONG", self.font_big, FG, center=(WIDTH // 2, 130))
        self._draw_text(self.world, "local 2-player  -  power-ups", self.font_sm, MUTED,
                        center=(WIDTH // 2, 196))

        self._draw_text(self.world, "PLAYER 1", self.font_sm, PLAYER_C, center=(WIDTH // 2 - 180, 292))
        self._draw_text(self.world, "W / S", self.font_med, FG, center=(WIDTH // 2 - 180, 344))
        self._draw_text(self.world, "PLAYER 2", self.font_sm, AI_C, center=(WIDTH // 2 + 180, 292))
        self._draw_text(self.world, "ARROWS", self.font_med, FG, center=(WIDTH // 2 + 180, 344))

        mode_txt = "INFINITE" if self.match_mode == "infinite" else "FIRST TO " + str(WIN_SCORE)
        self._draw_text(self.world, "MODE: " + mode_txt + "   (Up/Down to change)", self.font_sm, MUTED,
                        center=(WIDTH // 2, 420))
        self._draw_text(self.world, "hit the falling drops with the ball!", self.font_tiny, MUTED,
                        center=(WIDTH // 2, 456))
        self._draw_text(self.world, "Enter: start   P: pause   R: restart   Esc: quit", self.font_tiny, MUTED,
                        center=(WIDTH // 2, HEIGHT - 64))

    # ----------------------------------------------------------------- loop --
    def run(self):
        dt = 0.0
        while True:
            dt = self.clock.tick(FPS) / 1000.0
            if not self.handle_events():
                return
            self.update(dt)
            self.draw()
            pygame.display.flip()


def main():
    demo_capture = None
    if "--screenshot" in sys.argv:
        i = sys.argv.index("--screenshot")
        demo_capture = sys.argv[i + 1] if i + 1 < len(sys.argv) else "frame.png"

    game = Game(demo=bool(demo_capture))

    if demo_capture:
        for _ in range(150):
            game.update(1 / 60.0)
        game.draw()
        pygame.image.save(game.screen, demo_capture)
        pygame.quit()
        return

    game.run()


if __name__ == "__main__":
    main()
