#!/usr/bin/env python3
"""
╔══════════════════════╗
║      WET  FEET       ║
║  Autor: Max Hauliš   ║
╚══════════════════════╝
Pohyb: WASD / šipky
Interakce: E nebo klik na zvýrazněný objekt
"""
import pygame, sys, math, random, colorsys, os
from pygame.locals import *

pygame.init()
pygame.display.set_caption("WET FEET")
W, H = 1280, 720
screen = pygame.display.set_mode((W, H))
clock  = pygame.time.Clock()
FPS    = 60

# ─── Fonty ────────────────────────────────────────────────────────────────
def mkfont(size, bold=False):
    for nm in ("Arial","Helvetica Neue","DejaVu Sans","FreeSans",None):
        try:
            return pygame.font.SysFont(nm, size, bold=bold)
        except Exception:
            pass
    return pygame.font.Font(None, size)

FH = mkfont(86, True)
FB = mkfont(54, True)
FM = mkfont(32)
FS = mkfont(22)
FC = mkfont(28, True)

# ─── Barvy ────────────────────────────────────────────────────────────────
BK=(0,0,0);   WT=(255,255,255); RD=(190,20,20); BLD=(110,0,0)
VDG=(26,28,32); DG=(46,50,56); MG=(85,90,96); LG=(150,155,160)
TILE1=(80,84,90); TILE2=(70,74,80); CEIL=(50,54,60)
LOCK=(48,52,58); LKHI=(72,78,88); FLUO=(210,220,200)
BENCH=(108,96,78); PIPE=(115,128,140); SKIN=(200,160,130)
BLOOD=(160,10,10); LEECH=(18,18,20); ELEC=(220,230,255)
GORE_TINT=(60,0,0)

# ─── Stav hry ─────────────────────────────────────────────────────────────
room         = 0        # 0-5
completed    = set()    # dokončené metody
TOTAL        = 10
state        = "playing"  # playing | transition | ending
trans_phase  = 0          # 0=fade_in 1=hold 2=fade_out
trans_alpha  = 0.0
trans_name   = ""
trans_count  = 0
trans_timer  = 0.0
ending_t     = 0.0
interact_id  = -1         # která metoda běží (-1 = žádná)
interact_t   = 0.0        # čas v interakci (sec)
interact_dur = 0.0        # délka interakce
shake_t      = 0.0
shake_i      = 0.0
cam_bob      = 0.0        # kývání kamery při chůzi
move_t       = 0.0        # pro plynulý pohyb
walk_anim    = 0.0        # animace chůze
gore_flash   = 0.0        # červený záblesk

# Navigace: pro každou místnost seznam sousedů (forward, back, left, right)
# None = zeď
NAV = {
  0: {"w":2, "s":None, "a":None, "d":1},   # hlavní chodba
  1: {"w":0, "s":None, "a":None, "d":None}, # koupelna
  2: {"w":4, "s":0,    "a":3,    "d":None}, # hluboká chodba
  3: {"w":None,"s":None,"a":None,"d":2},    # výklenek (vysoušeč)
  4: {"w":5, "s":2,    "a":None, "d":None}, # sprchy
  5: {"w":None,"s":4,  "a":None, "d":None}, # místnost personálu
}

ROOM_NAMES = [
    "Šatna - hlavní chodba",
    "Koupelna",
    "Šatna - hluboká chodba",
    "Výklenek",
    "Sprchy",
    "Místnost pro personál",
]

# Metody: (id, room, name_cz, prompt, gore)
METHODS = [
  (0, 0, "fén kámo",                  "fénem si usušit nohy",       False),
  (1, 0, "kapesník",                  "vzít kapesník",              False),
  (2, 1, "toaleťák",                  "vzít ruličku",               False),
  (3, 1, "radiátor",                  "přiložit chodidla",          False),
  (4, 2, "jakobych necítil bolest",   "dát nohy do skříňky",        True),
  (5, 2, "výměna kůže",               "zvednout střep",             True),
  (6, 3, "vysoušeč rukou (vylepšený)","strčit nohy do vysoušeče",   True),
  (7, 4, "pijavice",                  "stoupnout na pijavice",      True),
  (8, 5, "mikrovlnka (cože?)",        "strčit nohy do mikrovlnky",  True),
  (9, 5, "krvavý odpařovák",          "uchopit kabel",              True),
]

# Interaktivní objekty v místnostech: (method_id, rect, label)
# Rect je přibližná plocha na obrazovce pro zvýraznění
OBJ_RECTS = {
  0: [(0, pygame.Rect(200,230,160,220), "[E] fén"),
      (1, pygame.Rect(780,380,200, 80), "[E] kapesník")],
  1: [(2, pygame.Rect(580,330,120,200), "[E] toaleťák"),
      (3, pygame.Rect(200,440,200,100), "[E] radiátor")],
  2: [(4, pygame.Rect(650,280,170,260), "[E] skříňka"),
      (5, pygame.Rect(480,500,130, 80), "[E] střep")],
  3: [(6, pygame.Rect(490,250,300,260), "[E] vysoušeč")],
  4: [(7, pygame.Rect(400,480,480,140), "[E] pijavice")],
  5: [(8, pygame.Rect(330,300,250,220), "[E] mikrovlnka"),
      (9, pygame.Rect(700,520,200, 80), "[E] kabel")],
}

particles = []

# ─── Pomocné funkce ───────────────────────────────────────────────────────
def lerp(a, b, t):
    return a + (b - a) * t

def clamp(v, lo, hi):
    return max(lo, min(hi, v))

def draw_text_centered(surf, text, font, color, cx, cy, shadow=True):
    if shadow:
        sh = font.render(text, True, (0,0,0))
        surf.blit(sh, sh.get_rect(center=(cx+2, cy+2)))
    tx = font.render(text, True, color)
    surf.blit(tx, tx.get_rect(center=(cx, cy)))

def draw_text(surf, text, font, color, x, y):
    surf.blit(font.render(text, True, color), (x, y))

def spawn_particles(x, y, color, n=24, spd=4, life=50, sz=(3,8)):
    for _ in range(n):
        a = random.uniform(0, 2*math.pi)
        s = random.uniform(0.4, spd)
        particles.append({
            'x':x,'y':y,
            'vx':math.cos(a)*s,'vy':math.sin(a)*s,
            'life':random.randint(life//2,life),'ml':life,
            'color':color,'size':random.randint(*sz)
        })

def update_draw_particles(surf):
    global particles
    alive = []
    for p in particles:
        p['x'] += p['vx']; p['y'] += p['vy']; p['vy'] += 0.12
        p['life'] -= 1
        if p['life'] > 0:
            a = p['life'] / p['ml']
            c = tuple(int(ch*a) for ch in p['color'])
            r = max(1, int(p['size']*a))
            pygame.draw.circle(surf, c, (int(p['x']),int(p['y'])), r)
            alive.append(p)
    particles = alive

# ─── Rendering místností ──────────────────────────────────────────────────
VPX, VPY = W//2, int(H*0.38)

def draw_perspective_room(surf, room_id, bob=0.0, flicker=1.0):
    """Základní vykreslení první osoby pro danou místnost."""
    bvp = (VPX, VPY + int(bob * 8))

    # --- STROP ---
    pygame.draw.rect(surf, CEIL, (0, 0, W, bvp[1]))
    # Zářivky
    for lx in [W//4, W//2, 3*W//4]:
        lw = 180; lh = 14
        lcolor = tuple(int(c*flicker) for c in FLUO)
        pygame.draw.rect(surf, lcolor, (lx - lw//2, 8, lw, lh))
        # záře
        glow = pygame.Surface((lw+60, 50), pygame.SRCALPHA)
        glow_a = int(40 * flicker)
        pygame.draw.ellipse(glow, (*FLUO, glow_a), (0,0,lw+60,50))
        surf.blit(glow, (lx - lw//2 - 30, 0))

    # --- PODLAHA (perspektivní dlaždice) ---
    floor_top = bvp[1]
    n_rows = 12; n_cols = 10
    for r in range(n_rows):
        t1 = r / n_rows; t2 = (r+1) / n_rows
        y1 = int(lerp(floor_top, H, t1))
        y2 = int(lerp(floor_top, H, t2))
        # width expands as we go down
        spread1 = lerp(0, W, t1)
        spread2 = lerp(0, W, t2)
        xl1 = int(W//2 - spread1/2); xr1 = int(W//2 + spread1/2)
        xl2 = int(W//2 - spread2/2); xr2 = int(W//2 + spread2/2)
        for c in range(n_cols):
            tc1 = c/n_cols; tc2 = (c+1)/n_cols
            x0 = int(lerp(xl1, xr1, tc1)); x1b = int(lerp(xl1, xr1, tc2))
            x2b = int(lerp(xl2, xr2, tc2)); x3 = int(lerp(xl2, xr2, tc1))
            base_col = TILE1 if (r+c)%2==0 else TILE2
            # Lehký mokrý odlesk
            if r == n_rows-1:
                wet_factor = 0.85
                base_col = tuple(int(v*wet_factor + 30*(1-wet_factor)) for v in base_col)
            pygame.draw.polygon(surf, base_col, [(x0,y1),(x1b,y1),(x2b,y2),(x3,y2)])
        pygame.draw.line(surf, DG, (0, y1), (W, y1), 1)

    # --- BOČNÍ STĚNY s skříňkami ---
    _draw_lockers(surf, bvp, room_id, flicker)

    # --- Specifické objekty místnosti ---
    _draw_room_objects(surf, room_id, bvp)

def _draw_lockers(surf, bvp, room_id, flicker):
    """Vykreslí skříňkové stěny v perspektivě."""
    vpy = bvp[1]
    n = 7  # počet skříněk na stranu

    for side in ('L', 'R'):
        for i in range(n):
            t1 = i / n; t2 = (i+1) / n
            # Přední (blízký) okraj skříňky
            if side == 'L':
                near_x = 0; far_x = bvp[0]
            else:
                near_x = W; far_x = bvp[0]

            x1 = int(lerp(near_x, far_x, t1))
            x2 = int(lerp(near_x, far_x, t2))
            y_top1 = int(lerp(0, vpy, t1 * 0.5))
            y_top2 = int(lerp(0, vpy, t2 * 0.5))
            y_bot1 = int(lerp(H, vpy + (H-vpy)*0.15, t1))
            y_bot2 = int(lerp(H, vpy + (H-vpy)*0.15, t2))

            shade = 1.0 - t1 * 0.4
            c = tuple(int(v * shade) for v in LOCK)
            pts = [(x1,y_top1),(x2,y_top2),(x2,y_bot2),(x1,y_bot1)]
            pygame.draw.polygon(surf, c, pts)
            pygame.draw.polygon(surf, DG, pts, 1)

            # Klika/logo skříňky
            if t1 > 0.05:
                hx = int(lerp(x1,x2,0.5))
                hy = int(lerp(y_top1+20, y_bot1-20, 0.6))
                hs = max(2, int((1-t1)*10))
                handle_c = tuple(int(v*(shade*0.8)) for v in FMET if isinstance(v,int)) if False else MG
                pygame.draw.circle(surf, MG, (hx,hy), hs)

            # Otevřená skříňka v místnosti 2 (gore metoda 4)
            if room_id == 2 and side == 'R' and i == 2 and 4 not in completed:
                _draw_open_locker(surf, x1, x2, y_top1, y_top2, y_bot1, y_bot2)

def _draw_open_locker(surf, x1, x2, yt1, yt2, yb1, yb2):
    """Otevřená skříňka — tmavý interiér."""
    # Interiér (tmavá díra)
    inner = [(x1+4,yt1+4),(x2-4,yt2+4),(x2-4,yb2-4),(x1+4,yb1-4)]
    pygame.draw.polygon(surf, VDG, inner)
    # Dveře (nakloněné)
    door_pts = [(x1,yt1),(x1-40,yt1+10),(x1-40,yb1-10),(x1,yb1)]
    pygame.draw.polygon(surf, LOCK, door_pts)
    pygame.draw.polygon(surf, MG, door_pts, 2)

def _draw_room_objects(surf, room_id, bvp):
    """Vykreslí specifické objekty pro každou místnost."""
    vpy = bvp[1]

    if room_id == 0:
        # Fén na zdi (vlevo, střed hloubky)
        if 0 not in completed:
            _draw_hairdryer(surf, 195, 295)
        # Lavička s krabičkou kapesníků
        _draw_bench(surf, 680, vpy + int((H - vpy)*0.55))
        if 1 not in completed:
            _draw_tissuebox(surf, 820, vpy + int((H-vpy)*0.35))
        # Jmenovka místnosti
        _draw_room_sign(surf, "ŠATNA  A")

    elif room_id == 1:
        # Toaletní papír v záchodovém boxu
        _draw_wc_stall(surf, bvp)
        if 2 not in completed:
            _draw_toiletpaper(surf, 622, 450)
        # Radiátor pod lavičkou
        _draw_bench(surf, 150, vpy + int((H-vpy)*0.55))
        if 3 not in completed:
            _draw_radiator(surf, 170, vpy + int((H-vpy)*0.62))
        _draw_room_sign(surf, "KOUPELNA")

    elif room_id == 2:
        # Skleněný střep na podlaze
        if 5 not in completed:
            _draw_shard(surf, 530, 540)
        # Lavičky
        _draw_bench(surf, 600, vpy + int((H-vpy)*0.58))
        _draw_room_sign(surf, "ŠATNA  B")

    elif room_id == 3:
        # Vysoušeč rukou na stěně (velký, v centru)
        if 6 not in completed:
            _draw_hand_dryer(surf, W//2 - 150, 220)
        _draw_room_sign(surf, "VÝKLENEK")

    elif room_id == 4:
        # Sprchové kouty v pozadí
        _draw_shower_stalls(surf, bvp)
        # Pijavice na podlaze
        if 7 not in completed:
            _draw_leeches(surf, W//2, H - 80)
        _draw_room_sign(surf, "SPRCHY")

    elif room_id == 5:
        # Pult s mikrovlnkou
        _draw_counter(surf, bvp)
        if 8 not in completed:
            _draw_microwave(surf, 390, 310)
        # Kabel na podlaze
        if 9 not in completed:
            _draw_cable(surf, 740, 540)
        _draw_room_sign(surf, "PERSONÁL")

# ─── Objekty ─────────────────────────────────────────────────────────────
def _draw_hairdryer(surf, x, y):
    # Tělo fénu
    pygame.draw.rect(surf, DG,  (x,    y,     80, 120), border_radius=8)
    pygame.draw.rect(surf, MG,  (x,    y,     80, 120), 2, border_radius=8)
    # Tryska
    pygame.draw.rect(surf, DG,  (x+80, y+40,  40,  40))
    pygame.draw.rect(surf, MG,  (x+80, y+40,  40,  40), 2)
    # LED kontrolka
    pygame.draw.circle(surf, (80,220,80), (x+20, y+20), 6)
    # Mřížka
    for i in range(3):
        pygame.draw.line(surf, MG, (x+10, y+60+i*15), (x+70, y+60+i*15), 1)

def _draw_tissuebox(surf, x, y):
    w, h = 130, 60
    pygame.draw.rect(surf, (210,210,200), (x, y, w, h), border_radius=5)
    pygame.draw.rect(surf, LG, (x, y, w, h), 2, border_radius=5)
    # Logo
    pygame.draw.ellipse(surf, WT, (x+45, y+8, 40, 20))
    # Kapesník trčí ven
    pygame.draw.rect(surf, WT, (x+55, y-10, 20, 20))

def _draw_bench(surf, x, y):
    bw = 300; bh = 30
    pygame.draw.rect(surf, BENCH, (x, y, bw, bh), border_radius=3)
    pygame.draw.rect(surf, (80,70,55), (x, y, bw, bh), 2, border_radius=3)
    # Nohy
    for lx in [x+20, x+bw-30]:
        pygame.draw.rect(surf, (75,65,50), (lx, y+bh, 20, 50))

def _draw_toiletpaper(surf, x, y):
    pygame.draw.circle(surf, WT, (x, y), 35)
    pygame.draw.circle(surf, LG, (x, y), 35, 2)
    pygame.draw.circle(surf, CEIL, (x, y), 12)
    # Přeložení papíru
    pygame.draw.arc(surf, LG, (x-35,y-35,70,70), 0.3, 1.2, 3)

def _draw_radiator(surf, x, y):
    rw, rh = 200, 80
    pygame.draw.rect(surf, (140,150,160), (x, y, rw, rh), border_radius=4)
    pygame.draw.rect(surf, PIPE, (x, y, rw, rh), 2, border_radius=4)
    for i in range(8):
        lx = x + 15 + i * 22
        pygame.draw.line(surf, PIPE, (lx, y+8), (lx, y+rh-8), 6)

def _draw_wc_stall(surf, bvp):
    # Záchodová kabinka v pozadí
    vpy = bvp[1]
    door_x = 560; door_y = int(vpy + (H-vpy)*0.05)
    door_h = int((H - door_y) * 0.85)
    door_w = 130
    pygame.draw.rect(surf, DG, (door_x, door_y, door_w, door_h))
    pygame.draw.rect(surf, MG, (door_x, door_y, door_w, door_h), 3)
    # Klika
    pygame.draw.circle(surf, LG, (door_x + door_w - 15, door_y + door_h//2), 7)

def _draw_shard(surf, x, y):
    # Ostrý střep skla
    pts = [(x, y-25),(x+18, y-5),(x+10, y+8),(x-8, y+10),(x-20, y-8)]
    pygame.draw.polygon(surf, (180,210,230), pts)
    pygame.draw.polygon(surf, WT, pts, 2)
    # Odlesk
    pygame.draw.line(surf, WT, (x-5, y-18), (x+8, y-2), 3)

def _draw_hand_dryer(surf, x, y):
    # Velký průmyslový vysoušeč rukou
    w, h = 300, 240
    pygame.draw.rect(surf, DG,  (x, y,     w, h), border_radius=14)
    pygame.draw.rect(surf, MG,  (x, y,     w, h), 3, border_radius=14)
    # Logo / displej
    pygame.draw.rect(surf, VDG, (x+30, y+30, w-60, 60), border_radius=5)
    # Sensor LED
    pygame.draw.circle(surf, RD, (x+w//2, y+110), 10)
    # Výfuk dole
    pygame.draw.rect(surf, VDG, (x+80, y+h-40, w-160, 30), border_radius=3)
    # Nápis
    lbl = FS.render("DYSON AIR", True, LG)
    surf.blit(lbl, (x + w//2 - lbl.get_width()//2, y + 50))

def _draw_shower_stalls(surf, bvp):
    vpy = bvp[1]
    for i, sx in enumerate([200, 550, 860]):
        # Sprchový kout
        sy = int(vpy + (H-vpy)*0.05)
        sw = 180; sh = int((H - sy)*0.85)
        shade = 0.7 - i*0.08
        c = tuple(int(v*shade) for v in DG)
        pygame.draw.rect(surf, c, (sx, sy, sw, sh))
        pygame.draw.rect(surf, MG, (sx, sy, sw, sh), 2)
        # Sprchová hlavice
        pygame.draw.circle(surf, MG, (sx+sw//2, sy+30), 20)
        pygame.draw.circle(surf, PIPE, (sx+sw//2, sy+30), 16)

def _draw_leeches(surf, cx, cy):
    # Hromada pijavic
    random.seed(42)
    for _ in range(60):
        lx = cx + random.randint(-200, 200)
        ly = cy + random.randint(-40, 40)
        lw = random.randint(20, 50)
        lh = random.randint(8, 16)
        angle = random.uniform(-0.5, 0.5)
        lsurf = pygame.Surface((lw, lh), pygame.SRCALPHA)
        pygame.draw.ellipse(lsurf, LEECH, (0,0,lw,lh))
        # Wiggle (jemný, klidný)
        rot = pygame.transform.rotate(lsurf, math.degrees(angle))
        surf.blit(rot, (lx - rot.get_width()//2, ly - rot.get_height()//2))
    random.seed()

def _draw_counter(surf, bvp):
    vpy = bvp[1]
    y = int(vpy + (H-vpy)*0.5)
    pygame.draw.rect(surf, (60,62,68), (100, y, W-200, 30))
    pygame.draw.rect(surf, MG, (100, y, W-200, 30), 2)
    # Přední panel pultu
    pygame.draw.rect(surf, DG, (100, y+30, W-200, 100))
    pygame.draw.rect(surf, MG, (100, y+30, W-200, 100), 2)

def _draw_microwave(surf, x, y):
    w, h = 250, 190
    pygame.draw.rect(surf, DG,  (x, y,     w, h), border_radius=8)
    pygame.draw.rect(surf, MG,  (x, y,     w, h), 3, border_radius=8)
    # Okénko
    pygame.draw.rect(surf, VDG, (x+15, y+20, w-90, h-50), border_radius=5)
    pygame.draw.rect(surf, MG,  (x+15, y+20, w-90, h-50), 2, border_radius=5)
    # Ovládací panel
    pygame.draw.rect(surf, (30,32,38), (x+w-65, y+15, 55, h-30), border_radius=5)
    # Displej
    pygame.draw.rect(surf, (0,60,0), (x+w-60, y+20, 46, 22))
    disp = FS.render("00:00", True, (0,200,0))
    surf.blit(disp, (x+w-58, y+22))
    # Tlačítka
    for bi in range(3):
        for bj in range(3):
            pygame.draw.rect(surf, MG, (x+w-58+bj*16, y+50+bi*14, 12, 10), border_radius=2)

def _draw_cable(surf, x, y):
    # Elektrický kabel na podlaze — kroutí se
    pts = []
    for i in range(20):
        t = i / 19.0
        cx2 = x + int((t-0.5)*220) + int(math.sin(t*math.pi*4)*20)
        cy2 = y + int(t*30)
        pts.append((cx2, cy2))
    if len(pts) > 1:
        pygame.draw.lines(surf, (30,30,35), False, pts, 8)
        pygame.draw.lines(surf, (50,50,60), False, pts, 4)
    # Konektor (oranžový = pod proudem)
    pygame.draw.circle(surf, (220,120,20), pts[-1], 10)
    pygame.draw.circle(surf, (255,180,50), pts[-1], 6)

def _draw_room_sign(surf, name):
    lbl = FS.render(name, True, (80,85,90))
    surf.blit(lbl, (W - lbl.get_width() - 20, 20))

# ─── Navigační šipky ─────────────────────────────────────────────────────
NAV_ARROWS = {
    "w": pygame.Rect(W//2-40, H-130, 80, 60),
    "s": pygame.Rect(W//2-40, H-60,  80, 60),
    "a": pygame.Rect(W//2-130,H-95,  80, 60),
    "d": pygame.Rect(W//2+50, H-95,  80, 60),
}
ARROW_LABELS = {"w":"↑","s":"↓","a":"←","d":"→"}

def draw_nav_arrows(surf, room_id):
    nav = NAV[room_id]
    for key, rect in NAV_ARROWS.items():
        if nav.get(key) is not None:
            c = (70,75,82)
            pygame.draw.rect(surf, c, rect, border_radius=6)
            pygame.draw.rect(surf, MG, rect, 2, border_radius=6)
            lbl = FM.render(ARROW_LABELS[key], True, LG)
            surf.blit(lbl, lbl.get_rect(center=rect.center))

# ─── Interakce (animace) ──────────────────────────────────────────────────
def draw_interaction(surf, mid, t):
    """Vykreslí close-up scénu interakce pro metodu mid, t = čas v sec."""
    surf.fill(VDG)

    if mid == 0:   _interact_hairdryer(surf, t)
    elif mid == 1: _interact_tissue(surf, t)
    elif mid == 2: _interact_toiletpaper(surf, t)
    elif mid == 3: _interact_radiator(surf, t)
    elif mid == 4: _interact_locker(surf, t)
    elif mid == 5: _interact_shard(surf, t)
    elif mid == 6: _interact_handdryer(surf, t)
    elif mid == 7: _interact_leeches(surf, t)
    elif mid == 8: _interact_microwave(surf, t)
    elif mid == 9: _interact_cable(surf, t)

    # Progress indikátor
    _draw_progress_bar(surf, t, interact_dur)

def _draw_feet(surf, x, y, dry=False, gore=0):
    """Vykreslí chodidla z první osoby (pohled dolu)."""
    fc = SKIN if not dry else (180, 140, 100)
    if gore == 1:   fc = (160, 60, 60)
    elif gore == 2: fc = (100, 80, 70)
    elif gore == 3: fc = (40, 30, 25)

    for side, ox in [("L",-130), ("R", 60)]:
        bx = x + ox
        # Chodidlo
        pts = [(bx, y),(bx+80, y-20),(bx+90, y+40),(bx, y+60),(bx-10, y+30)]
        pygame.draw.polygon(surf, fc, pts)
        pygame.draw.polygon(surf, tuple(max(0,c-30) for c in fc), pts, 2)
        # Prsty
        for i in range(5):
            tx = bx + i*16; ty = y - 15 - max(0,(2-abs(i-2))*8)
            r = 8 - abs(i-2)
            pygame.draw.circle(surf, fc, (tx, ty), r)

    # Mokrá aura
    if not dry and gore == 0:
        for ox in [-130, 60]:
            bx = x + ox + 40
            pygame.draw.ellipse(surf, (80,100,160,80),
                                pygame.Rect(bx-50, y+50, 100, 20))

def _draw_progress_bar(surf, t, dur):
    if dur <= 0: return
    prog = clamp(t / dur, 0, 1)
    bx, by, bw, bh = 40, H-35, W-80, 12
    pygame.draw.rect(surf, DG, (bx,by,bw,bh), border_radius=6)
    pygame.draw.rect(surf, LG, (bx,by,int(bw*prog),bh), border_radius=6)

# — Konkrétní interakce —

def _interact_hairdryer(surf, t):
    # Zoom na fén
    scale = clamp(1.0 + t*0.3, 1.0, 1.6)
    # Fén close-up
    cx, cy = W//2 - 60, H//2 - 60
    pygame.draw.rect(surf, DG,  (cx,cy,120,180), border_radius=10)
    pygame.draw.rect(surf, MG,  (cx,cy,120,180), 3, border_radius=10)
    pygame.draw.rect(surf, DG,  (cx+120,cy+60,60,60))
    pygame.draw.rect(surf, MG,  (cx+120,cy+60,60,60), 2)
    # Teplý vzduch (vlny)
    if t > 0.5:
        for i in range(5):
            ax = cx + 185 + int(t*20 + i*15)
            ay = cy + 80 + i*8
            wave_a = max(0, 200 - int((t*20 + i*15)*8))
            pygame.draw.arc(surf, (220,160,80,wave_a),
                            pygame.Rect(ax,ay,40,30), 0, math.pi, 3)
    # Chodidla dole
    _draw_feet(surf, W//2, H-180, dry=t>3.0)
    # Popisek
    if t < 1.0:
        lbl = FM.render("ZAPÍNÁM FÉN...", True, LG)
        surf.blit(lbl, lbl.get_rect(center=(W//2, 60)))

def _interact_tissue(surf, t):
    # Krabička kapesníků
    kx, ky = W//2 - 80, H//2 - 100
    pygame.draw.rect(surf, (210,210,200), (kx,ky,160,80), border_radius=6)
    pygame.draw.rect(surf, LG, (kx,ky,160,80), 2, border_radius=6)
    pygame.draw.rect(surf, WT, (kx+60,ky-20,40,30))
    if t > 0.8:
        # Kapesník v ruce
        hx, hy = W//2 - 30, H//2
        pygame.draw.rect(surf, WT, (hx, hy, 60, 80), border_radius=5)
        pygame.draw.rect(surf, LG, (hx, hy, 60, 80), 1, border_radius=5)
    _draw_feet(surf, W//2, H-160, dry=t>3.5)
    if t < 1.0:
        lbl = FM.render("BERU KAPESNÍK...", True, LG)
        surf.blit(lbl, lbl.get_rect(center=(W//2, 60)))

def _interact_toiletpaper(surf, t):
    # Omotávání nohama
    cx, cy = W//2, H//2 - 40
    # Rulička
    pygame.draw.circle(surf, WT, (cx, cy), 50)
    pygame.draw.circle(surf, LG, (cx, cy), 50, 2)
    pygame.draw.circle(surf, CEIL, (cx, cy), 18)
    # Papír se odvíjí
    paper_len = clamp(int(t * 80), 0, 300)
    if paper_len > 0:
        pygame.draw.rect(surf, WT, (cx+50, cy-10, paper_len, 20))
    # Chodidla s papírovým obalem
    wrap = clamp(t / 2.0, 0, 1)
    _draw_feet(surf, W//2, H-160, dry=wrap > 0.7)
    if t < 1.0:
        lbl = FM.render("OMOTÁVÁM NOHY...", True, LG)
        surf.blit(lbl, lbl.get_rect(center=(W//2, 60)))

def _interact_radiator(surf, t):
    # Radiátor close-up + pára
    rx, ry = W//2 - 150, H//2 - 30
    pygame.draw.rect(surf, (140,150,160), (rx,ry,300,100), border_radius=5)
    pygame.draw.rect(surf, PIPE, (rx,ry,300,100), 3, border_radius=5)
    for i in range(10):
        lx = rx + 20 + i*26
        pygame.draw.line(surf, PIPE, (lx,ry+10),(lx,ry+90), 8)
    # Pára při kontaktu
    if t > 0.5:
        for i in range(4):
            sx = rx + 40 + i*60
            sy = ry - int(t*15) - 30
            pulse = 0.5 + 0.5*math.sin(t*3 + i)
            steam_a = int(80*pulse)
            for s in range(3):
                steam_y = sy - s*20
                pygame.draw.circle(surf, tuple(min(255,v) for v in (180,190,200)),
                                   (sx + int(math.sin(t+i+s)*8), steam_y), 10-s*2)
    _draw_feet(surf, W//2, H-140, dry=t>4.0)
    if t < 1.0:
        lbl = FM.render("PŘIKLÁDÁM CHODIDLA...", True, LG)
        surf.blit(lbl, lbl.get_rect(center=(W//2, 60)))

def _interact_locker(surf, t):
    # GORE: skříňka + mlácení
    global gore_flash
    # Skříňka
    lx, ly = W//2 - 100, 100
    lw, lh = 200, 400
    pygame.draw.rect(surf, LOCK, (lx,ly,lw,lh), border_radius=5)
    pygame.draw.rect(surf, MG,   (lx,ly,lw,lh), 3, border_radius=5)
    # Dveře bouchají
    slam_phase = t % 0.8
    door_angle = 0
    if slam_phase < 0.3 and t > 0.5:
        door_angle = slam_phase / 0.3 * 40
    door_pts = [
        (lx, ly),
        (lx - int(40 * math.cos(math.radians(door_angle))), ly + int(40*math.sin(math.radians(door_angle)))),
        (lx - int(40 * math.cos(math.radians(door_angle))), ly + lh + int(40*math.sin(math.radians(door_angle)))),
        (lx, ly + lh)
    ]
    pygame.draw.polygon(surf, LKHI, door_pts)
    pygame.draw.polygon(surf, MG, door_pts, 2)

    # Krev se šíří
    blood_amount = clamp(int((t-1.0) * 60), 0, 200)
    for i in range(blood_amount):
        random.seed(i*7+13)
        bx2 = lx + random.randint(-50, lw+50)
        by2 = ly + lh - random.randint(0, 150)
        pygame.draw.circle(surf, BLOOD, (bx2, by2), random.randint(2,8))
    random.seed()

    # Gore záblesky
    if t > 1.0 and int(t*4) % 2 == 0:
        gore_flash = 0.5

    # Nohy (po 3s odpadnou)
    if t < 3.5:
        _draw_feet(surf, W//2+80, H-140, gore=1)
    else:
        # Odříznuté nohy na zemi
        _draw_feet(surf, W//2, H-100, gore=2)
        lbl = FM.render("...UTÍRÁM SI JE O VLASY...", True, RD)
        surf.blit(lbl, lbl.get_rect(center=(W//2, 80)))

    spawn_particles(lx, ly+lh, BLOOD, n=3, spd=3, life=25)
    update_draw_particles(surf)

def _interact_shard(surf, t):
    # GORE: střep + řezání
    # Střep v ruce close-up
    sx, sy = W//2 - 20, H//2 - 100
    pts = [(sx,sy-60),(sx+40,sy-15),(sx+25,sy+20),(sx-20,sy+25),(sx-45,sy-20)]
    pygame.draw.polygon(surf, (180,215,235), pts)
    pygame.draw.polygon(surf, WT, pts, 2)
    pygame.draw.line(surf, WT, (sx-10,sy-45),(sx+15,sy-5), 3)

    # Řez probíhá pomalu
    cut_prog = clamp((t-0.5)/5.0, 0, 1)
    if cut_prog > 0:
        # Krvavá linie na chodidle
        for i in range(int(cut_prog*10)):
            cx2 = W//2 - 130 + i * 22
            pygame.draw.circle(surf, BLOOD, (cx2, H-165), 5)

    gore_level = 1 if t < 3.0 else 2
    _draw_feet(surf, W//2, H-140, gore=gore_level)

    # Krvavé kapky
    if t > 1.0:
        spawn_particles(W//2-60, H-170, BLOOD, n=2, spd=2, life=30)
    update_draw_particles(surf)

    if t < 1.0:
        lbl = FM.render("BERU STŘEP...", True, LG)
        surf.blit(lbl, lbl.get_rect(center=(W//2, 60)))
    elif t > 3.0:
        lbl = FM.render("POD KŮŽÍ JE TO... SUCHÉ.", True, RD)
        surf.blit(lbl, lbl.get_rect(center=(W//2, 60)))

def _interact_handdryer(surf, t):
    # GORE: lis drtí nohy
    dx, dy = W//2 - 150, 80
    dw, dh = 300, 240

    # Vysoušeč se mění na lis
    if t < 2.0:
        pygame.draw.rect(surf, DG, (dx,dy,dw,dh), border_radius=14)
        pygame.draw.rect(surf, MG, (dx,dy,dw,dh), 3, border_radius=14)
        lbl = FM.render("NORMÁLNÍ VYSOUŠEČ...", True, LG)
        surf.blit(lbl, lbl.get_rect(center=(W//2, 50)))
    else:
        # LIS se spouští
        press_down = clamp((t-2.0)/2.0, 0, 1)
        press_y = int(dy + dh + press_down * 200)
        pygame.draw.rect(surf, (100,30,30), (dx, press_y-20, dw, 40))
        pygame.draw.rect(surf, RD, (dx, press_y-20, dw, 40), 3)
        lbl = FM.render("— LIS —", True, RD)
        surf.blit(lbl, lbl.get_rect(center=(W//2, 50)))

        if press_down > 0.5:
            spawn_particles(W//2, press_y, BLOOD, n=4, spd=5, life=40)

    gore_lv = 0 if t < 2 else (1 if t < 3 else 3)
    _draw_feet(surf, W//2, H-140, gore=gore_lv)
    update_draw_particles(surf)

def _interact_leeches(surf, t):
    # Pijavice sají
    # Podlaha sprchy
    pygame.draw.rect(surf, (65,68,74), (0, H//2, W, H//2))
    pygame.draw.rect(surf, (55,58,64), (0, H//2, W, 5))

    # Animované pijavice
    n_leeches = 80
    for i in range(n_leeches):
        random.seed(i*11+7)
        lx2 = W//2 + random.randint(-280, 280)
        ly2 = H-100 + random.randint(-30, 30)
        wiggle = math.sin(t*4 + i*0.5) * 5
        lw2 = random.randint(25, 55)
        lsurf = pygame.Surface((lw2, 14), pygame.SRCALPHA)
        pygame.draw.ellipse(lsurf, LEECH, (0,0,lw2,14))
        # Pijavice se plní krví (červená)
        fill = clamp(t/5.0, 0, 1)
        fill_c = tuple(int(lerp(20,120,fill)) for _ in range(3))
        fill_c = (int(lerp(20,120,fill)), 0, 0)
        pygame.draw.ellipse(lsurf, fill_c, (2,2,lw2-4,10))
        surf.blit(lsurf, (int(lx2 + wiggle), int(ly2)))
    random.seed()

    gore_lv = 0 if t < 1 else (1 if t < 4 else 2)
    _draw_feet(surf, W//2, H-100, gore=gore_lv)

    if t > 4.0:
        lbl = FM.render("ZBYLY JEN ŠLACHY...", True, RD)
        surf.blit(lbl, lbl.get_rect(center=(W//2, 60)))

def _interact_microwave(surf, t):
    # Mikrovlnka close-up
    mx, my = W//2 - 160, 100
    mw, mh = 320, 240

    pygame.draw.rect(surf, DG, (mx,my,mw,mh), border_radius=8)
    pygame.draw.rect(surf, MG, (mx,my,mw,mh), 3, border_radius=8)
    # Okénko
    pygame.draw.rect(surf, VDG, (mx+15,my+20,mw-90,mh-50), border_radius=5)

    # Vnitřní záře s praskáním
    if t > 1.5:
        glow_i = 0.5 + 0.5*math.sin(t*15)
        glow_c = (int(220*glow_i), int(100*glow_i), 0)
        pygame.draw.rect(surf, glow_c, (mx+20,my+25,mw-100,mh-60))
        # Jiskry
        if int(t*10)%3==0:
            for _ in range(3):
                sx2 = mx + 20 + random.randint(0, mw-100)
                sy2 = my + 25 + random.randint(0, mh-60)
                pygame.draw.circle(surf, WT, (sx2,sy2), random.randint(2,5))

    # Dveře se otevřou na konci
    if t > 5.5:
        pygame.draw.rect(surf, LOCK, (mx-60, my, 55, mh))
        pygame.draw.rect(surf, MG, (mx-60, my, 55, mh), 2)

    gore_lv = 0 if t < 1.5 else (1 if t < 3 else 3)
    _draw_feet(surf, W//2, H-140, gore=gore_lv)
    update_draw_particles(surf)

    if t > 3.0:
        spawn_particles(W//2, H-160, (150,80,30), n=2, spd=1, life=60, sz=(4,12))
    if t < 1.5:
        lbl = FM.render("PLNÝ VÝKON...", True, LG)
        surf.blit(lbl, lbl.get_rect(center=(W//2, 50)))
    elif t > 4.5:
        lbl = FM.render("KŘUPAVĚ SUCHÉ.", True, RD)
        surf.blit(lbl, lbl.get_rect(center=(W//2, 50)))

def _interact_cable(surf, t):
    # Elektrický kabel + výboj
    # Kabel
    pts2 = []
    for i in range(20):
        ti = i/19.0
        cx2 = W//2 + int((ti-0.5)*250) + int(math.sin(ti*math.pi*3 + t*2)*15)
        cy2 = H//2 + int(ti*80)
        pts2.append((cx2,cy2))
    if len(pts2) > 1:
        pygame.draw.lines(surf, (30,30,38), False, pts2, 10)
        pygame.draw.lines(surf, (60,60,70), False, pts2, 5)
    pygame.draw.circle(surf, (220,120,20), pts2[-1], 14)

    if t > 1.5:
        # VÝBOJ
        zap_t = (t - 1.5)
        if zap_t < 0.5:
            # Bílý záblesk + elektrický oblouk
            flash_a = int(255 * (1 - zap_t/0.5))
            flash_surf = pygame.Surface((W,H))
            flash_surf.fill(ELEC)
            flash_surf.set_alpha(flash_a)
            surf.blit(flash_surf, (0,0))
            # Blesk
            for _ in range(8):
                ax = W//2 + random.randint(-150,150)
                ay = H//2 + random.randint(-100,100)
                pygame.draw.line(surf, ELEC, (W//2, H//2), (ax,ay),
                                 random.randint(1,4))
        elif zap_t < 2.5:
            # Krvavý kouř
            spawn_particles(W//2, H-150, BLOOD, n=3, spd=2, life=80, sz=(6,18))
            spawn_particles(W//2, H-150, (40,30,25), n=2, spd=1, life=100, sz=(8,20))

    update_draw_particles(surf)

    gore_lv = 0 if t < 1.5 else 3
    _draw_feet(surf, W//2, H-140, gore=gore_lv)

    if t < 1.0:
        lbl = FM.render("PŘIKLÁDÁM KABEL K NOHÁM...", True, LG)
        surf.blit(lbl, lbl.get_rect(center=(W//2, 60)))
    elif t > 2.5:
        lbl = FM.render("VODA SE V MŽIKU VYPAŘÍ.", True, ELEC)
        surf.blit(lbl, lbl.get_rect(center=(W//2, 60)))

# Délky interakcí
INTERACT_DURATIONS = [4.5, 4.0, 5.0, 5.0, 6.0, 6.0, 6.0, 7.0, 7.0, 5.5]

# ─── Overlay: přechod (černá obrazovka) ───────────────────────────────────
def draw_transition_overlay(surf, alpha, count, name):
    overlay = pygame.Surface((W, H))
    overlay.fill(BK)
    overlay.set_alpha(int(clamp(alpha, 0, 255)))
    surf.blit(overlay, (0,0))

    if alpha > 200:
        counter_txt = FC.render(f"{count}/{TOTAL}   -{name}-", True, WT)
        surf.blit(counter_txt, counter_txt.get_rect(center=(W//2, H//2)))

# ─── Ending: rainbow disco ─────────────────────────────────────────────────
def draw_ending(surf, t):
    # Blikající duhová barva pozadí
    hue = (t * 0.15) % 1.0
    r,g,b = colorsys.hsv_to_rgb(hue, 0.95, 1.0)
    bg_color = (int(r*255), int(g*255), int(b*255))
    surf.fill(bg_color)

    # Blikající bloky
    for i in range(0, W, 80):
        for j in range(0, H, 80):
            bh2 = (i/W + j/H + t*0.3) % 1.0
            br,bg2,bb = colorsys.hsv_to_rgb(bh2, 1.0, 1.0)
            bc = (int(br*255), int(bg2*255), int(bb*255))
            if int((i//80 + j//80 + int(t*8))) % 2 == 0:
                pygame.draw.rect(surf, bc, (i,j,80,80))

    # Hlavní text
    th2 = (t * 0.4 + 0.3) % 1.0
    tr,tg,tb = colorsys.hsv_to_rgb(th2, 1.0, 1.0)
    tc = (int(tr*255), int(tg*255), int(tb*255))
    scale = 1.0 + math.sin(t*6)*0.08
    win_surf = FH.render("JÓOO VYHRÁL JSI!!!", True, tc)
    # Stín
    sh_surf = FH.render("JÓOO VYHRÁL JSI!!!", True, BK)
    surf.blit(sh_surf, sh_surf.get_rect(center=(W//2+4, H//2-80+4)))
    surf.blit(win_surf, win_surf.get_rect(center=(W//2, H//2-80)))

    # 10/10
    score_h = (t*0.5+0.6)%1.0
    sr,sg2,sb = colorsys.hsv_to_rgb(score_h,1.0,1.0)
    score_c = (int(sr*255),int(sg2*255),int(sb*255))
    score_surf = FB.render("10 / 10", True, score_c)
    surf.blit(score_surf, score_surf.get_rect(center=(W//2, H//2+20)))

    # Autor
    auth_surf = FM.render("tuto hru vymyslel Max Hauliš", True, WT)
    surf.blit(auth_surf, auth_surf.get_rect(center=(W//2, H//2+100)))

    # ESC
    esc_surf = FS.render("[ESC] Ukončit", True, (200,200,200))
    surf.blit(esc_surf, (W-180, H-30))

# ─── HUD ──────────────────────────────────────────────────────────────────
def draw_hud(surf, room_id):
    # Counter vlevo nahoře
    count_txt = FC.render(f"{len(completed)}/{TOTAL}", True, LG)
    surf.blit(count_txt, (18, 18))

    # Hover objekt
    mx, my = pygame.mouse.get_pos()
    hovered = None
    for (mid, rect, label) in OBJ_RECTS.get(room_id, []):
        if mid not in completed and rect.collidepoint(mx, my):
            hovered = (mid, rect, label)

    if hovered:
        mid, rect, label = hovered
        # Zvýraznění objektu
        highlight = pygame.Surface((rect.w, rect.h), pygame.SRCALPHA)
        highlight.fill((255,255,200,30))
        surf.blit(highlight, rect.topleft)
        pygame.draw.rect(surf, (220,220,150), rect, 2, border_radius=4)
        # Prompt
        prompt_txt = FM.render(f"[E]  {label}", True, WT)
        surf.blit(prompt_txt, prompt_txt.get_rect(center=(W//2, H-170)))

    # Název místnosti dole
    room_lbl = FS.render(ROOM_NAMES[room_id], True, (70,74,80))
    surf.blit(room_lbl, (18, H-30))

# ─── Hlavní smyčka ────────────────────────────────────────────────────────
def start_interaction(mid):
    global state, interact_id, interact_t, interact_dur
    state = "interacting"
    interact_id = mid
    interact_t = 0.0
    interact_dur = INTERACT_DURATIONS[mid]

def finish_interaction():
    global state, completed, trans_phase, trans_alpha, trans_name, trans_count
    global trans_timer
    completed.add(interact_id)
    trans_count = len(completed)
    trans_name  = METHODS[interact_id][2]
    trans_phase = 0
    trans_alpha = 0.0
    trans_timer = 0.0
    state = "transition"

def get_hovered_method():
    mx, my = pygame.mouse.get_pos()
    for (mid, rect, label) in OBJ_RECTS.get(room, []):
        if mid not in completed and rect.collidepoint(mx, my):
            return mid
    return None

def main():
    global state, room, trans_phase, trans_alpha, trans_timer, trans_count, trans_name
    global interact_t, interact_id, interact_dur, ending_t, cam_bob, walk_anim
    global gore_flash

    flicker_timer = 0.0
    flicker_val   = 1.0

    running = True
    while running:
        dt = clock.tick(FPS) / 1000.0
        dt = min(dt, 0.05)  # cap

        # ── Eventy ──
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False

            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    running = False

                if state == "playing":
                    # Navigace
                    key_map = {K_w:"w", K_UP:"w", K_s:"s", K_DOWN:"s",
                               K_a:"a", K_LEFT:"a", K_d:"d", K_RIGHT:"d"}
                    if event.key in key_map:
                        direction = key_map[event.key]
                        next_room = NAV[room].get(direction)
                        if next_room is not None:
                            room = next_room
                            walk_anim = 0.3

                    # Interakce klávesou E
                    if event.key == K_e:
                        hov = get_hovered_method()
                        if hov is not None:
                            start_interaction(hov)

            if event.type == MOUSEBUTTONDOWN and event.button == 1:
                if state == "playing":
                    hov = get_hovered_method()
                    if hov is not None:
                        start_interaction(hov)
                    # Navigační šipky
                    for key, rect in NAV_ARROWS.items():
                        if rect.collidepoint(event.pos):
                            next_room = NAV[room].get(key)
                            if next_room is not None:
                                room = next_room
                                walk_anim = 0.3

        # ── Update ──
        if state == "playing":
            walk_anim = max(0, walk_anim - dt*2)
            cam_bob = math.sin(walk_anim * math.pi * 6) * walk_anim

            flicker_timer -= dt
            if flicker_timer <= 0:
                flicker_timer = random.uniform(0.1, 3.0)
                if random.random() < 0.15:
                    flicker_val = random.uniform(0.3, 0.8)
                else:
                    flicker_val = 1.0

            gore_flash = max(0, gore_flash - dt * 3)

        elif state == "interacting":
            interact_t += dt
            gore_flash = max(0, gore_flash - dt * 2)
            if interact_t >= interact_dur:
                finish_interaction()

        elif state == "transition":
            trans_timer += dt
            FADE_DUR  = 0.7
            HOLD_DUR  = 2.5
            FADE_OUT  = 0.7

            if trans_phase == 0:   # fade to black
                trans_alpha = clamp(trans_timer / FADE_DUR * 255, 0, 255)
                if trans_timer >= FADE_DUR:
                    trans_phase = 1; trans_timer = 0.0

            elif trans_phase == 1:  # hold
                trans_alpha = 255
                if trans_timer >= HOLD_DUR:
                    trans_phase = 2; trans_timer = 0.0
                    # Check if it was the last method
                    if trans_count >= TOTAL:
                        state = "ending"; ending_t = 0.0; continue

            elif trans_phase == 2:  # fade back
                trans_alpha = clamp((1 - trans_timer / FADE_OUT) * 255, 0, 255)
                if trans_timer >= FADE_OUT:
                    trans_alpha = 0; state = "playing"

        elif state == "ending":
            ending_t += dt

        # ── Draw ──
        screen.fill(VDG)

        if state in ("playing", "transition"):
            flicker = lerp(flicker_val, 1.0, 0.9)
            draw_perspective_room(screen, room, cam_bob, flicker)
            draw_nav_arrows(screen, room)
            draw_hud(screen, room)

            # Gore červený tint
            if gore_flash > 0:
                tint = pygame.Surface((W,H))
                tint.fill(GORE_TINT)
                tint.set_alpha(int(gore_flash * 120))
                screen.blit(tint, (0,0))

        elif state == "interacting":
            draw_interaction(screen, interact_id, interact_t)

        elif state == "ending":
            draw_ending(screen, ending_t)

        if state == "transition":
            draw_transition_overlay(screen, trans_alpha, trans_count, trans_name)

        # Title na začátku
        if state == "playing" and len(completed) == 0:
            hint = FS.render("Najdi způsob, jak si usušit nohy. WASD pro pohyb, E / klik pro interakci.", True, (80,85,92))
            screen.blit(hint, hint.get_rect(center=(W//2, H-12)))

        pygame.display.flip()

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()
