"""Stellar Fix: explore an alien planet on foot. Collect the eight ship parts,
fight creatures and three bosses, rescue survivors, upgrade at the landing
pad, and fix the ship's four systems to launch.

    python make_art.py     once: draws stand-in art into game-assets/ (sprites are already there)
    python main.py         play it as a desktop window (solo)

In the browser (python build.py, then section 7 of the guide) you can also play
with a friend: Multiplayer > Host a room, and the friend joins with the code.
"""
import asyncio
import json
import traceback

import pygame
from pygame.math import Vector2 as vector

import storage
from characters import Player
from map_gen import SPAWN
from peer import Peer
from settings import *
from sprites import Sprite
from support import import_folder_dict, import_sub_folders
from world import ATTACK_REACH, BOSS_REACH, PAD_REACH, SYSTEM_NAMES, TALK_REACH, World, UPGRADE_COST, \
    UPGRADE_LEVELS, SYSTEM_COST, TRADE_COST, TRADE_SCRAP, RESCUE_COST

CREAM = (232, 238, 246)
GOLD = (255, 204, 64)
RED = (220, 60, 70)
COLOURS = [(255, 204, 64), (120, 230, 255), (255, 120, 190), (150, 255, 140)]
BUTTON_SIZE = (340, 56)
DIGITS = '0123456789'
SAFE_FLASH_MS = 1000
HOST_SILENCE_MS = 5000          # friends: no word from the host for this long means it is gone
HOST_ACTIONS = ('help', 'challenge', 'buy', 'trade')   # what a friend may ask the host to do
JOY_RADIUS = 70                                       # how far a thumb can drag the on-screen stick
ATTACK_BUTTON = (WINDOW_WIDTH - 88, WINDOW_HEIGHT - 150, 50)   # x, y, radius (phones)
TALK_BUTTON = (WINDOW_WIDTH - 192, WINDOW_HEIGHT - 150, 38)
ESC_BUTTON = pygame.Rect(WINDOW_WIDTH - 74, 10, 64, 36)
KEYPAD = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['del', '0', 'join']]


def loading(percent, message=''):
    """Move the page's loading bar (index.html). Does nothing on desktop."""
    if IS_WEB:
        from pyscript import window
        window.loadingStep(percent, message)


def centred(text, font, colour, centre, surface):
    image = font.render(text, True, colour)
    surface.blit(image, image.get_rect(center=centre))


def in_circle(pos, circle):
    x, y, r = circle
    return (pos[0] - x) ** 2 + (pos[1] - y) ** 2 <= r * r


class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
        pygame.display.set_caption('Stellar Fix')
        self.clock = pygame.time.Clock()
        self.font = pygame.font.Font(None, 30)
        self.medium = pygame.font.Font(None, 40)
        self.big = pygame.font.Font(None, 84)
        self.tiles = import_folder_dict('game-assets', 'tiles')
        self.frames = {'player': import_sub_folders('game-assets', 'player'),
                       'creature': import_sub_folders('game-assets', 'creature')}
        self.items = import_folder_dict('game-assets', 'items')       # {'crystal': Surface, 'part': Surface}
        self.boss_image = self.items['boss']
        self.survivor_image = self.items['survivor']
        self.buttons = {}
        for name, y in (('solo', 240), ('multi', 310), ('host', 240), ('join', 310), ('start', 340), ('back', 410)):
            self.buttons[name] = pygame.Rect(0, 0, *BUTTON_SIZE)
            self.buttons[name].center = (WINDOW_WIDTH // 2, y)
        self.scene = 'menu'
        self.note = ''
        self.peer = None
        self.world = None
        self.player = None
        self.me = 0
        self.code = ''
        self.typed = ''
        self.message, self.message_until = '', 0
        self.tap_used = False
        self.pad_open = False
        self.flash_until = 0
        self.swing_until = 0
        self.last_hp = None
        self.send_clock = 0
        self.seen = None                                              # the last counts, for sound effects
        self.save_clock = 0
        self.touch_mode = False                                       # True once a finger has touched the screen
        self.fingers = {}                                             # finger id -> screen position
        self.joy_id, self.joy_origin = None, None                     # the finger on the on-screen stick
        self.name = storage.load('name', '')                          # remembered in the browser
        self.names = {}                                               # slot -> player name, shared by the host
        self.popup = ''                                               # a message box: connection closed, errors
        self.name_typed, self.name_next = '', 'join'
        self.sounds = self.load_sounds()

    def load_sounds(self):
        """Sound effects from game-assets/sounds. If the browser refuses audio, the game is silent, not broken."""
        names = ('crystal_pickup', 'part_collect', 'hurt', 'blaster', 'creature_defeat', 'boss_hit', 'boss_defeat',
                 'door_open', 'purchase', 'system_fixed', 'rescue', 'menu_click', 'win', 'acid_hurt')
        try:
            pygame.mixer.init()
            return {name: pygame.mixer.Sound(f'game-assets/sounds/{name}.wav') for name in names}
        except Exception:
            return {}

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

    # ── rooms ───────────────────────────────────────────────────────
    def hosting(self):
        return self.peer is None or self.peer.host

    def leave(self, note=''):
        if self.peer is not None:
            self.peer.close()
            self.peer = None
        self.world, self.player, self.pad_open = None, None, False
        self.scene, self.note, self.popup = 'menu', '', note
        self.names = {}

    def start_solo(self):
        self.peer = None
        self.begin(0)

    def start_host(self):
        self.peer = Peer(host=True)
        self.names = {0: self.name or 'Player'}
        self.scene, self.note, self.code = 'lobby', 'Making your room...', ''
        asyncio.create_task(self.open_room(self.peer))

    async def open_room(self, peer):
        code = await peer.host_room()
        if self.peer is not peer:
            return
        if code:
            self.code, self.note = code, ''
        else:
            self.leave(peer.error or 'Could not make a room.')

    def start_join(self, code):
        self.peer = Peer(host=False)
        self.scene, self.note = 'waiting', 'Connecting to the room...'
        asyncio.create_task(self.join_room(self.peer, code))

    async def join_room(self, peer, code):
        if await peer.join_room(code):
            if self.peer is peer:
                peer.send({'t': 'hello'})
                peer.send({'t': 'name', 'n': self.name or 'Player'})
                self.note = 'Connected. Waiting for the host to start...'
        elif self.peer is peer:
            self.leave(peer.error or 'Could not join that room.')

    def start_round(self):
        if self.code:
            self.peer.send_all({'t': 'start'})
            self.begin(0)

    def begin(self, me):
        self.me = me
        self.world = World(self.tiles, self.frames, me, self.hosting())
        self.fullscreen()
        if self.peer is None:                        # solo: pick up where you left off
            try:
                self.world.restore(json.loads(storage.load('progress', '{}')))
            except (ValueError, AttributeError, TypeError):
                pass
        self.seen = None                                              # first frame: no sounds yet
        spawn = self.world.centre(SPAWN)
        ship = self.items['ship']
        # Drawn lower than the heroes (z), so a hero standing on the ship is shown on top of it.
        Sprite((spawn[0] - ship.get_width() / 2, spawn[1] - ship.get_height() / 2), ship,
               (self.world.all_sprites,), z=Z_LAYERS['tiles'])
        self.player = Player(spawn, self.frames['player'], (self.world.all_sprites,), self.world.walls,
                             speed=PLAYER_SPEED)
        self.world.report(me, vector(spawn), 'idle_down')
        self.scene, self.note = 'play', ''
        self.pad_open = False
        self.say('Follow the arrows to find the parts and fix the ship. Watch out for creatures and acid!', 5000)
        self.tap_used, self.send_clock, self.save_clock = False, 0, 0
        self.heard_at = pygame.time.get_ticks()

    def say(self, text, ms=2500):
        self.message, self.message_until = text, pygame.time.get_ticks() + ms

    # ── network ─────────────────────────────────────────────────────
    def poll_network(self):
        if self.peer is None:
            return
        for sender, message in self.peer.poll():
            if sender == 0:                                  # 0 is the host: remember when it last spoke
                self.heard_at = pygame.time.get_ticks()
            self.on_message(sender, message)

    def watch_host(self):
        """Friends: the host sends a picture many times a second. Silence for a while means its tab
        was closed or the link died, so the game stops."""
        if self.peer is None or self.hosting() or self.scene != 'play':
            return
        if pygame.time.get_ticks() - self.heard_at > HOST_SILENCE_MS:
            self.leave('The host closed the game or lost the connection.')

    def on_message(self, sender, m):
        kind = m['t']
        if self.peer.host:
            if kind == 'name':
                self.names[sender] = str(m['n'])[:12]
                return
            if kind == 'left':
                self.names.pop(sender, None)
            if kind == 'hello' and self.world is not None:       # a friend arrived after the start
                self.peer.send_to(sender, {'t': 'start'})
            elif self.world is None:
                return
            elif kind == 'in':
                self.world.report(sender, vector(m['p']), m['s'])
            elif kind == 'do' and m['a'] in HOST_ACTIONS:
                getattr(self.world, m['a'])(sender, m.get('i'))
            elif kind == 'atk':
                self.world.attack(sender, pygame.time.get_ticks())
            elif kind == 'left':
                self.world.drop(sender)
        elif kind == 'start' and self.scene == 'waiting':
            self.begin(self.peer.slot)
        elif kind == 'snap' and self.world is not None:
            self.names = {int(k): str(v) for k, v in m.get('n', {}).items()}
            self.world.apply(m['s'])
        elif kind == 'ev' and self.world is not None:
            self.apply_event(m)
        elif kind == 'left':
            self.leave('The host left the room.')

    def process_events(self):
        """Host: the rules that just ran may have moved heroes. Tell each player."""
        for slot, message in self.world.take_events():
            if slot == self.me:
                self.apply_event(message)
            elif self.peer is not None:
                self.peer.send_to(slot, message)

    def apply_event(self, m):
        if m['e'] == 'tp' and self.player is not None:
            self.player.hitbox_rect.center = tuple(m['p'])
            self.player.rect.midbottom = self.player.hitbox_rect.midbottom
        if m['e'] in ('tp', 'hurt'):
            self.flash_until = pygame.time.get_ticks() + SAFE_FLASH_MS

    # ── one frame of play ───────────────────────────────────────────
    def update_play(self, dt):
        world = self.world
        held = pygame.mouse.get_pressed()[0] and not self.tap_used and not self.touch_mode
        self.player.walk_to = vector(pygame.mouse.get_pos()) - world.all_sprites.offset if held else None
        self.player.touch_dir = self.joystick_vector()
        self.player.frozen = self.pad_open
        self.player.update(dt)
        world.report(self.me, vector(self.player.rect.center), self.player.state)
        world.animate(dt)
        if self.hosting():
            world.update(dt)
            self.process_events()

        self.send_clock += dt
        if self.send_clock >= SEND_EVERY:
            self.send_clock = 0
            if self.hosting():
                if self.peer is not None:
                    self.peer.send_all({'t': 'snap', 's': world.snapshot(),
                                        'n': {str(k): v for k, v in self.names.items()}})
            else:
                cx, cy = (round(v) for v in self.player.rect.center)
                self.peer.send({'t': 'in', 'p': [cx, cy], 's': self.player.state})

        hp = world.heroes[self.me].hp if self.me in world.heroes else None
        if hp is not None and self.last_hp is not None and hp < self.last_hp:
            self.flash_until = pygame.time.get_ticks() + SAFE_FLASH_MS
        self.last_hp = hp

        if self.peer is None:
            self.save_clock += dt
            if self.save_clock >= 2:
                self.save_clock = 0
                storage.save('progress', json.dumps(world.progress()))
        self.check_sounds()
        if world.won and self.scene == 'play':
            self.finish()

    def counts(self):
        """The numbers that sound effects react to. Works the same for host and friends."""
        world = self.world
        hero = world.heroes.get(self.me)
        return {'crystals': world.crystal_stock, 'parts': len(world.parts), 'systems': len(world.systems),
                'rescued': len(world.rescued), 'upgrades': world.dmg + world.armour,
                'creatures': sum(c['alive'] for c in world.creatures),
                'bosses': sum(b['alive'] for b in world.bosses), 'boss_hp': sum(b['hp'] for b in world.bosses),
                'doors': sum(wall is None for wall in world.doors.values()),
                'hp': hero.hp if hero else 0, 'home': hero is not None and hero.tile() == SPAWN}

    def check_sounds(self):
        now, before = self.counts(), self.seen
        self.seen = now
        if before is None:
            return
        if now['bosses'] < before['bosses']:
            self.play('boss_defeat')
        elif now['rescued'] > before['rescued']:
            self.play('rescue')
        elif now['parts'] > before['parts']:
            self.play('part_collect')
        elif now['systems'] > before['systems']:
            self.play('system_fixed')
        elif now['upgrades'] > before['upgrades']:
            self.play('purchase')
        elif now['crystals'] > before['crystals']:
            self.play('crystal_pickup')
        elif now['creatures'] < before['creatures']:
            self.play('creature_defeat')
        elif now['boss_hp'] < before['boss_hp']:
            self.play('boss_hit')
        if now['doors'] > before['doors']:
            self.play('door_open')
        if now['hp'] < before['hp']:                 # a pool sends you home, so being home and hurt means acid
            self.play('acid_hurt' if now['home'] else 'hurt')

    def finish(self):
        self.scene = 'won'
        self.play('win')
        if self.peer is None:
            storage.delete('progress')

    def fullscreen(self):
        """Browsers only allow fullscreen after a tap or click, and a game starts from one."""
        if IS_WEB:
            try:
                from pyscript import document
                document.documentElement.requestFullscreen()
            except Exception:
                pass

    # ── actions ─────────────────────────────────────────────────────
    def act(self, name, arg=None):
        """Do a shared action: here if we host, otherwise ask the host."""
        if self.hosting():
            getattr(self.world, name)(self.me, arg)
            self.process_events()
        else:
            self.peer.send({'t': 'do', 'a': name, 'i': arg})

    def swing(self):
        self.swing_until = pygame.time.get_ticks() + 150
        self.play('blaster')
        if self.hosting():
            self.world.attack(self.me, pygame.time.get_ticks())
        else:
            self.peer.send({'t': 'atk'})

    def nearby(self):
        """What E would do right now: ('pad', None), ('boss', i), ('help', i) or None."""
        world = self.world
        here = vector(self.player.rect.center)
        if world.near_pad(self.me):
            return ('pad', None)
        for i, b in enumerate(world.bosses):
            if here.distance_to(world.centre(b['tile'])) < BOSS_REACH:
                return ('boss', i)
        for i, tile in enumerate(world.survivors):
            if i not in world.rescued and here.distance_to(world.centre(tile)) < TALK_REACH:
                return ('help', i)
        return None

    def interact(self):
        target = self.nearby()
        if target is None:
            return
        kind, i = target
        if kind == 'pad':
            self.pad_open = True
        elif kind == 'boss':
            if self.world.bosses[i]['alive']:
                self.say('There is a huge enemy near.', 3000)
                self.act('challenge', i)                 # alive: also step into the arena to fight
            else:
                self.say('The enemy has fallen.', 3000)
        else:
            self.act('help', i)

    # ── input ───────────────────────────────────────────────────────
    def handle_event(self, event):
        if self.popup and event.type in (pygame.KEYDOWN, pygame.MOUSEBUTTONDOWN, pygame.FINGERDOWN):
            self.popup = ''                         # any tap or key closes the message box
            return
        if event.type in (pygame.FINGERDOWN, pygame.FINGERMOTION, pygame.FINGERUP):
            self.touch_mode = True
            self.touch(event)
        elif self.touch_mode and getattr(event, 'touch', False):
            return                                  # the mouse copy of a tap the finger events already handled
        else:
            self.dispatch(event)

    def dispatch(self, event):
        if event.type in (pygame.KEYDOWN, pygame.MOUSEBUTTONDOWN) and self.scene != 'play':
            self.play('menu_click')
        handler = {'menu': self.menu_event, 'multi': self.multi_event, 'join': self.join_event,
                   'lobby': self.lobby_event, 'waiting': self.waiting_event, 'play': self.play_event,
                   'won': self.won_event, 'name': self.name_event}[self.scene]
        handler(event)

    def press(self, key, char=''):
        """Pretend a key was pressed, so touch buttons reuse the keyboard controls."""
        self.dispatch(pygame.event.Event(pygame.KEYDOWN, key=key, unicode=char, mod=0, scancode=0))

    def touch(self, event):
        pos = (round(event.x * WINDOW_WIDTH), round(event.y * WINDOW_HEIGHT))
        if event.type == pygame.FINGERDOWN:
            self.fingers[event.finger_id] = pos
            if (self.scene == 'play' and self.joy_id is None and pos[0] < WINDOW_WIDTH // 2
                    and not self.pad_open):
                self.joy_id, self.joy_origin = event.finger_id, pos      # the left side is the stick
            self.touch_tap(pos)
        elif event.type == pygame.FINGERMOTION:
            if event.finger_id in self.fingers:
                self.fingers[event.finger_id] = pos
        else:
            self.fingers.pop(event.finger_id, None)
            if event.finger_id == self.joy_id:
                self.joy_id, self.joy_origin = None, None

    def touch_tap(self, pos):
        if self.scene == 'play':
            if self.pad_open:
                self.pad_tap(pos)
            elif in_circle(pos, ATTACK_BUTTON):
                self.swing()
            elif in_circle(pos, TALK_BUTTON):
                self.press(pygame.K_e)
            elif ESC_BUTTON.collidepoint(pos):
                self.press(pygame.K_ESCAPE)
            return
        if self.scene != 'menu' and ESC_BUTTON.collidepoint(pos):
            self.press(pygame.K_ESCAPE)
            return
        if self.scene == 'join':
            for rect, key, char in self.keypad_keys():
                if rect.collidepoint(pos):
                    self.press(key, char)
                    return
        self.dispatch(pygame.event.Event(pygame.MOUSEBUTTONDOWN, pos=pos, button=1))

    def pad_tap(self, pos):
        """A tap on the landing pad menu: a line buys it, a tap outside closes the menu."""
        panel = self.pad_panel()
        if not panel.collidepoint(pos):
            self.press(pygame.K_ESCAPE)
            return
        row = (pos[1] - panel.y - 18) // 30
        if 0 <= row <= 6:
            self.press(pygame.K_1 + row)
        elif row == 8:
            self.press(pygame.K_ESCAPE)

    def joystick_vector(self):
        """The on-screen stick as a direction: length 0 (at rest) to 1 (dragged to the edge)."""
        if self.joy_id not in self.fingers:
            return vector()
        drag = vector(self.fingers[self.joy_id]) - self.joy_origin
        if drag.length() < 8:
            return vector()
        if drag.length() > JOY_RADIUS:
            drag.scale_to_length(JOY_RADIUS)
        return drag / JOY_RADIUS

    def menu_choice(self, choice):
        if choice == 'solo':
            self.start_solo()
        elif choice == 'multi':
            self.scene, self.note = 'multi', ''
        elif not IS_WEB:
            self.note = 'Multiplayer works in the browser version of the game.'
        elif choice == 'host':
            self.ask_name('host')
        else:
            self.ask_name('join')

    def menu_event(self, event):
        if event.type == pygame.KEYDOWN:
            choice = {pygame.K_1: 'solo', pygame.K_2: 'multi'}.get(event.key)
            if choice:
                self.menu_choice(choice)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            for name in ('solo', 'multi'):
                if self.buttons[name].collidepoint(event.pos):
                    self.menu_choice(name)

    def multi_event(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                self.scene = 'menu'
            elif event.key == pygame.K_1:
                self.menu_choice('host')
            elif event.key == pygame.K_2:
                self.menu_choice('join')
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if self.buttons['host'].collidepoint(event.pos):
                self.menu_choice('host')
            elif self.buttons['join'].collidepoint(event.pos):
                self.menu_choice('join')
            elif self.buttons['back'].collidepoint(event.pos):
                self.scene = 'menu'

    def join_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:              # a mouse click on the on-screen keypad
            for rect, key, char in self.keypad_keys():
                if rect.collidepoint(event.pos):
                    self.join_event(pygame.event.Event(pygame.KEYDOWN, key=key, unicode=char, mod=0, scancode=0))
            return
        if event.type != pygame.KEYDOWN:
            return
        if event.key == pygame.K_ESCAPE:
            self.leave()
        elif event.key == pygame.K_BACKSPACE:
            self.typed = self.typed[:-1]
        elif event.key in (pygame.K_RETURN, pygame.K_KP_ENTER) and len(self.typed) == 4:
            self.start_join(self.typed)
        elif event.unicode and event.unicode in DIGITS and len(self.typed) < 4:
            self.typed += event.unicode

    def lobby_event(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                self.leave()
            elif event.key in (pygame.K_RETURN, pygame.K_KP_ENTER):
                self.start_round()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if self.buttons['start'].collidepoint(event.pos):
                self.start_round()
            elif self.buttons['back'].collidepoint(event.pos):
                self.leave()

    def waiting_event(self, event):
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            self.leave()

    def play_event(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                if self.pad_open:
                    self.pad_open = False
                else:
                    self.leave()
            elif event.key == pygame.K_SPACE:
                self.swing()
            elif event.key == pygame.K_e:
                if self.pad_open:
                    self.pad_open = False
                else:
                    self.interact()
            elif self.pad_open and event.key in PAD_KEYS:
                self.act('buy', PAD_KEYS[event.key])
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            if self.pad_open:
                self.pad_tap(event.pos)
            else:
                self.tap_used = True
                self.swing()
        elif event.type == pygame.MOUSEBUTTONUP:
            self.tap_used = False

    def won_event(self, event):
        if event.type == pygame.KEYDOWN and event.key in (pygame.K_RETURN, pygame.K_ESCAPE):
            self.leave()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            self.leave()

    # ── drawing ─────────────────────────────────────────────────────
    def draw(self):
        self.screen.fill((14, 22, 40))
        if self.scene == 'play':
            self.draw_play()
        elif self.scene == 'menu':
            self.draw_menu()
        elif self.scene == 'multi':
            self.draw_multi()
        elif self.scene == 'join':
            self.draw_join()
        elif self.scene == 'lobby':
            self.draw_lobby()
        elif self.scene == 'waiting':
            centred(self.note, self.medium, CREAM, (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2), self.screen)
            centred('Esc: leave', self.font, CREAM, (WINDOW_WIDTH // 2, 500), self.screen)
        elif self.scene == 'won':
            self.draw_won()
        elif self.scene == 'name':
            self.draw_name()
        if self.touch_mode and self.scene not in ('play', 'menu'):
            self.draw_esc()
        if self.popup:
            self.draw_popup()

    def ask_name(self, next_step):
        """Multiplayer: type a name first, then go on to host or join."""
        self.name_next, self.name_typed, self.scene, self.note = next_step, self.name, 'name', ''

    def confirm_name(self):
        self.name = self.name_typed.strip()[:12] or 'Player'
        storage.save('name', self.name)
        if self.name_next == 'host':
            self.start_host()
        else:
            self.scene, self.typed, self.note = 'join', '', ''

    def name_keys(self):
        """The name screen's keys: (rectangle, label, key code, character)."""
        rows = [[(c, 0, c) for c in 'ABCDEFGHIJKLM'], [(c, 0, c) for c in 'NOPQRSTUVWXYZ'],
                [(c, 0, c) for c in '0123456789'] + [('Del', pygame.K_BACKSPACE, ''), ('OK', pygame.K_RETURN, '\r')]]
        keys, w, h, gap = [], 52, 40, 6
        for r, row in enumerate(rows):
            x0 = WINDOW_WIDTH // 2 - (len(row) * w + (len(row) - 1) * gap) // 2
            for c, (label, key, char) in enumerate(row):
                keys.append((pygame.Rect(x0 + c * (w + gap), 220 + r * 46, w, h), label, key, char))
        return keys

    def name_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            for rect, label, key, char in self.name_keys():
                if rect.collidepoint(event.pos):
                    self.name_event(pygame.event.Event(pygame.KEYDOWN, key=key, unicode=char, mod=0, scancode=0))
            return
        if event.type != pygame.KEYDOWN:
            return
        if event.key == pygame.K_ESCAPE:
            self.scene = 'multi'
        elif event.key in (pygame.K_RETURN, pygame.K_KP_ENTER):
            self.confirm_name()
        elif event.key == pygame.K_BACKSPACE:
            self.name_typed = self.name_typed[:-1]
        elif event.unicode and event.unicode.isascii() and (event.unicode.isalnum() or event.unicode == ' ') \
                and len(self.name_typed) < 12:
            self.name_typed += event.unicode

    def draw_name(self):
        cx = WINDOW_WIDTH // 2
        centred('Choose your name', self.medium, CREAM, (cx, 110), self.screen)
        box = pygame.Rect(cx - 210, 140, 420, 50)
        pygame.draw.rect(self.screen, (20, 28, 44), box, border_radius=10)
        pygame.draw.rect(self.screen, GOLD, box, 2, border_radius=10)
        cursor = '_' if pygame.time.get_ticks() // 400 % 2 else ' '
        centred(self.name_typed + cursor, self.medium, GOLD, box.center, self.screen)
        for rect, label, key, char in self.name_keys():
            self.frame(rect, rect.collidepoint(pygame.mouse.get_pos()))
            centred(label, self.font, CREAM, rect.center, self.screen)
        centred('Other players see this name. Press ENTER when done.', self.font, CREAM, (cx, 400), self.screen)

    def draw_popup(self):
        cx = WINDOW_WIDTH // 2
        box = pygame.Rect(0, 0, 560, 170)
        box.center = (cx, WINDOW_HEIGHT // 2)
        self.frame(box)
        centred('Connection lost', self.medium, GOLD, (cx, box.y + 40), self.screen)
        centred(self.popup, self.font, 'white', (cx, box.y + 85), self.screen)
        centred('Tap or press a key to continue', self.font, CREAM, (cx, box.y + 130), self.screen)

    def pad_panel(self):
        panel = pygame.Rect(0, 0, 600, 320)
        panel.center = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)
        return panel

    def keypad_keys(self):
        """The join screen's on-screen keys: (rectangle, key code, character) for each one."""
        keys, w, h, gap = [], 96, 44, 10
        x0, y0 = WINDOW_WIDTH // 2 - (3 * w + 2 * gap) // 2, 240
        for r, row in enumerate(KEYPAD):
            for c, label in enumerate(row):
                rect = pygame.Rect(x0 + c * (w + gap), y0 + r * (h + gap), w, h)
                if label == 'del':
                    keys.append((rect, pygame.K_BACKSPACE, ''))
                elif label == 'join':
                    keys.append((rect, pygame.K_RETURN, '\r'))
                else:
                    keys.append((rect, pygame.K_0 + int(label), label))
        return keys

    def draw_touch_controls(self):
        screen = self.screen
        if self.joy_id in self.fingers:                  # the stick: a ring where the thumb landed
            pygame.draw.circle(screen, 'white', self.joy_origin, JOY_RADIUS, 3)
            knob = vector(self.joy_origin) + self.joystick_vector() * JOY_RADIUS
            pygame.draw.circle(screen, GOLD, knob, 22)
        for (x, y, r), label, fill in ((ATTACK_BUTTON, 'HIT', (120, 40, 40)), (TALK_BUTTON, 'E', (40, 60, 96))):
            pygame.draw.circle(screen, fill, (x, y), r)
            pygame.draw.circle(screen, GOLD, (x, y), r, 3)
            centred(label, self.medium, 'white', (x, y), screen)
        self.draw_esc()

    def draw_esc(self):
        self.frame(ESC_BUTTON)
        centred('ESC', self.font, CREAM, ESC_BUTTON.center, self.screen)

    def frame(self, rect, hover=False):
        """A nine-slice button: the corners stay pixel-sharp, the middle stretches to fit."""
        image, b = self.items['button'], 16                     # 48 px image, 16 px corners at 4x
        w, h = image.get_size()
        surf = pygame.Surface(rect.size, pygame.SRCALPHA)
        iw, ih = rect.w - 2 * b, rect.h - 2 * b
        pieces = [((0, 0, b, b), (0, 0, b, b)), ((b, 0, w - 2 * b, b), (b, 0, iw, b)),
                  ((w - b, 0, b, b), (rect.w - b, 0, b, b)),
                  ((0, b, b, h - 2 * b), (0, b, b, ih)), ((b, b, w - 2 * b, h - 2 * b), (b, b, iw, ih)),
                  ((w - b, b, b, h - 2 * b), (rect.w - b, b, b, ih)),
                  ((0, h - b, b, b), (0, rect.h - b, b, b)), ((b, h - b, w - 2 * b, b), (b, rect.h - b, iw, b)),
                  ((w - b, h - b, b, b), (rect.w - b, rect.h - b, b, b))]
        for (sx, sy, sw, sh), (tx, ty, tw, th) in pieces:
            surf.blit(pygame.transform.scale(image.subsurface((sx, sy, sw, sh)), (tw, th)), (tx, ty))
        if hover:
            surf.fill((255, 255, 255, 45), special_flags=pygame.BLEND_RGBA_ADD)
        self.screen.blit(surf, rect.topleft)

    def button(self, name, label):
        rect = self.buttons[name]
        hover = rect.collidepoint(pygame.mouse.get_pos())
        self.frame(rect, hover)
        centred(label, self.medium, 'white' if hover else CREAM, rect.center, self.screen)

    def draw_menu(self):
        cx = WINDOW_WIDTH // 2
        self.screen.blit(self.items['menu_bg'], (0, 0))
        shadow = self.big.render('STELLAR FIX', True, (60, 40, 10))
        self.screen.blit(shadow, shadow.get_rect(center=(cx + 4, 124)))
        centred('STELLAR FIX', self.big, GOLD, (cx, 120), self.screen)
        centred('Repair your ship and escape the alien world.', self.medium, CREAM, (cx, 175), self.screen)
        self.button('solo', 'Play alone  (1)')
        self.button('multi', 'Multiplayer  (2)')
        centred(self.note, self.font, CREAM, (cx, 460), self.screen)
        centred('Arrows or WASD: walk   Space or click: attack   E: talk, read signs, ship   Esc: menu',
                self.font, (150, 165, 190), (cx, WINDOW_HEIGHT - 22), self.screen)

    def draw_multi(self):
        cx = WINDOW_WIDTH // 2
        centred('MULTIPLAYER', self.big, GOLD, (cx, 120), self.screen)
        centred('Host a room, or join a friend with their four-digit code.', self.medium, CREAM, (cx, 175), self.screen)
        self.button('host', 'Host a room  (1)')
        self.button('join', 'Join a friend  (2)')
        self.button('back', 'Back  (Esc)')
        centred(self.note, self.font, CREAM, (cx, 460), self.screen)

    def draw_join(self):
        cx = WINDOW_WIDTH // 2
        centred('Type the four-digit room code', self.medium, CREAM, (cx, 110), self.screen)
        centred(' '.join(self.typed.ljust(4, '_')), self.big, GOLD, (cx, 165), self.screen)
        centred('Use the keys below, or your keyboard. Join or ENTER when done.', self.font, CREAM, (cx, 205),
                self.screen)
        for rect, key, char in self.keypad_keys():
            self.frame(rect, rect.collidepoint(pygame.mouse.get_pos()))
            label = {pygame.K_BACKSPACE: 'Del', pygame.K_RETURN: 'Join'}.get(key, char)
            centred(label, self.medium, CREAM, rect.center, self.screen)
        centred(self.note, self.font, CREAM, (cx, 430), self.screen)

    def draw_lobby(self):
        cx = WINDOW_WIDTH // 2
        centred('Your room code', self.medium, CREAM, (cx, 110), self.screen)
        centred(self.code or '....', self.big, GOLD, (cx, 170), self.screen)
        friends = len(self.peer.friends_here()) if self.peer else 0
        centred(f'Friends here: {friends} of 3', self.medium, CREAM, (cx, 240), self.screen)
        centred('Players: ' + ', '.join(self.names[k] for k in sorted(self.names)), self.font, GOLD,
                (cx, 212), self.screen)
        centred('Friends: choose "Join a friend" and type this code.', self.font, CREAM, (cx, 280), self.screen)
        self.button('start', 'Start  (ENTER)')
        self.button('back', 'Back  (Esc)')
        centred(self.note, self.font, CREAM, (cx, 480), self.screen)

    def draw_won(self):
        cx = WINDOW_WIDTH // 2
        centred('SHIP LAUNCHED!', self.big, GOLD, (cx, 170), self.screen)
        centred('The eight parts are fixed in place. You are going home.', self.medium, CREAM, (cx, 250), self.screen)
        centred(f'Survivors rescued: {len(self.world.rescued)} of {len(self.world.survivors)}', self.font, CREAM, (cx, 300), self.screen)
        centred('Press ENTER for the menu', self.font, CREAM, (cx, 360), self.screen)

    def draw_marks(self, offset):
        """Crystals, parts, the key, the door, the ship, and the survivors."""
        world = self.world
        screen = self.screen
        for index, tile in enumerate(world.crystals):
            if index not in world.crystal_taken:
                x, y = vector(world.centre(tile)) + offset
                screen.blit(self.items['crystal'], self.items['crystal'].get_rect(center=(round(x), round(y))))
        for zone, tile in world.parts_at + [(b['zone'], b['tile']) for b in world.bosses if b['alive']]:
            if zone not in world.parts:
                x, y = vector(world.centre(tile)) + offset
                screen.blit(self.items['part'], self.items['part'].get_rect(center=(round(x), round(y))))
        if not world.has_key:
            x, y = vector(world.centre(world.key)) + offset
            pygame.draw.circle(screen, GOLD, (round(x), round(y)), 10)
            pygame.draw.circle(screen, 'white', (round(x), round(y)), 10, 2)
        for tile, wall in world.doors.items():
            if wall is not None:
                x, y = vector(world.centre(tile)) + offset
                pygame.draw.rect(screen, RED, pygame.Rect(x - 30, y - 32, 60, 64), border_radius=6)
        for b in world.bosses:                                 # a sign beside each boss field
            x, y = vector(world.centre(b['tile'])) + offset
            board = pygame.Rect(0, 0, 52, 30)
            board.center = (round(x - 84), round(y - 10))
            pygame.draw.rect(screen, (110, 80, 50), (board.centerx - 3, board.bottom, 6, 30))
            pygame.draw.rect(screen, (200, 160, 100), board, border_radius=4)
            pygame.draw.rect(screen, (60, 40, 20), board, 2, border_radius=4)
            mark = self.font.render('!' if b['alive'] else 'X', True, RED if b['alive'] else (60, 140, 70))
            screen.blit(mark, mark.get_rect(center=board.center))
        cx, cy = world.centre(SPAWN)
        label_y = cy + offset.y + self.items['ship'].get_height() / 2 + 14
        centred(f'SHIP  {len(world.systems)}/{len(SYSTEM_NAMES)}', self.font, 'white',
                (round(cx + offset.x), round(label_y)), screen)
        for i, tile in enumerate(world.survivors):
            if i not in world.rescued:
                x, y = vector(world.centre(tile)) + offset
                screen.blit(self.survivor_image, self.survivor_image.get_rect(center=(round(x), round(y))))

    def arrow_target(self):
        """Where the arrow points: the nearest ship part (on the ground or held by a boss),
        or the ship once every part is found."""
        world = self.world
        spots = [tile for zone, tile in world.parts_at + [(b['zone'], b['tile']) for b in world.bosses if b['alive']]
                 if zone not in world.parts]
        if not spots:
            return vector(world.centre(SPAWN)) if len(world.parts) == len(world.part_zones) else None
        here = vector(self.player.rect.center)
        return min((vector(world.centre(tile)) for tile in spots), key=here.distance_to)

    def draw_arrow(self, offset):
        here = vector(self.player.rect.center)
        target = self.arrow_target()
        if target is None or here.distance_to(target) < 120:
            return                                             # nothing to point at, or it is right here
        direction = (target - here).normalize()
        tip = here + offset + direction * 80
        base = here + offset + direction * 56
        side = direction.rotate(90) * 14
        pygame.draw.polygon(self.screen, GOLD, [tip, base + side, base - side])
        pygame.draw.polygon(self.screen, 'white', [tip, base + side, base - side], 2)

    def draw_creatures(self, offset):
        now = pygame.time.get_ticks()
        for c in self.world.creatures:
            if c['alive']:
                frames = self.frames['creature'][c['state']]
                image = frames[(now // 250) % len(frames)]
                x, y = c['pos'] + offset
                self.screen.blit(image, image.get_rect(center=(round(x), round(y))))
        for b in self.world.bosses:
            if b['alive']:
                x, y = b['pos'] + offset
                self.screen.blit(self.boss_image, self.boss_image.get_rect(center=(round(x), round(y))))
                bar = pygame.Rect(0, 0, 120, 8)
                bar.center = (round(x), round(y) - 72)
                pygame.draw.rect(self.screen, (60, 20, 20), bar)
                pygame.draw.rect(self.screen, RED, (bar.x, bar.y, 120 * b['hp'] // BOSS_HP_FULL, 8))

    def draw_hearts(self):
        hero = self.world.heroes.get(self.me)
        if hero is None:
            return
        for i in range(self.world.max_hp()):
            colour = RED if i < hero.hp else (50, 40, 50)
            pygame.draw.circle(self.screen, colour, (24 + i * 26, WINDOW_HEIGHT - 26), 10)
            pygame.draw.circle(self.screen, 'white', (24 + i * 26, WINDOW_HEIGHT - 26), 10, 2)

    def next_hint(self):
        world = self.world
        if len(world.parts) < len(world.part_zones):
            return f'Ship parts: {len(world.parts)}/{len(world.part_zones)}. Explore and collect them.'
        return 'All parts found. Go to the ship (E) and fix its systems.'

    def draw_play(self):
        world = self.world
        screen = self.screen
        world.all_sprites.draw(self.player.rect.center)
        offset = world.all_sprites.offset
        self.draw_marks(offset)
        self.draw_creatures(offset)
        self.draw_arrow(offset)
        for slot, ghost in world.ghosts.items():
            name = self.names.get(slot, 'Host' if slot == 0 else f'Friend {slot}')
            tag = self.font.render(name, True, COLOURS[slot % len(COLOURS)])
            screen.blit(tag, tag.get_rect(midbottom=ghost.rect.midtop + offset))
        if pygame.time.get_ticks() < self.flash_until and pygame.time.get_ticks() // 120 % 2:
            flash = pygame.mask.from_surface(self.player.image).to_surface(setcolor='white', unsetcolor=(0, 0, 0, 0))
            screen.blit(flash, self.player.rect.topleft + offset)
        if pygame.time.get_ticks() < self.swing_until:
            pygame.draw.circle(screen, 'white', vector(self.player.rect.center) + offset, ATTACK_REACH, 2)

        screen.blit(self.font.render(
            f'Scrap {world.scrap}     Crystals {world.crystal_stock}     Parts {len(world.parts)}/{len(world.part_zones)}     '
            f'Damage +{world.dmg}   Armour +{world.armour}', True, 'white'), (16, 12))
        screen.blit(self.font.render(self.next_hint(), True, CREAM), (16, 40))
        hint = ('Drag on the left side to walk. HIT attacks, E talks.' if self.touch_mode else
                'Walk: arrows/WASD or mouse.  Space or click: attack.  E: talk / ship.  Esc: menu')
        screen.blit(self.font.render(hint, True, CREAM), (16, 66))
        self.draw_hearts()
        target = self.nearby()
        if target and not self.pad_open:
            text = {'pad': 'E: the landing pad', 'boss': 'E: read the sign', 'help': 'E: help the survivor'}[target[0]]
            centred(text, self.font, GOLD, (WINDOW_WIDTH // 2, 110), screen)
        if pygame.time.get_ticks() < self.message_until:
            box = pygame.Rect(40, WINDOW_HEIGHT - 80, WINDOW_WIDTH - 80, 50)
            pygame.draw.rect(screen, (20, 28, 44), box, border_radius=12)
            pygame.draw.rect(screen, GOLD, box, 3, border_radius=12)
            centred(self.message, self.font, 'white', box.center, screen)
        if self.touch_mode:
            self.draw_touch_controls()
        if self.pad_open:
            self.draw_pad()

    def draw_pad(self):
        world = self.world
        panel = self.pad_panel()
        pygame.draw.rect(self.screen, (20, 28, 44), panel, border_radius=14)
        pygame.draw.rect(self.screen, GOLD, panel, 3, border_radius=14)
        lines = [
            f'1  Blaster upgrade (level {world.dmg}/{UPGRADE_LEVELS})  -  {UPGRADE_COST} scrap',
            f'2  Armour upgrade (level {world.armour}/{UPGRADE_LEVELS})  -  {UPGRADE_COST} scrap',
        ]
        missing = len(world.part_zones) - len(world.parts)
        for k, name in enumerate(SYSTEM_NAMES):
            if k in world.systems:
                state = 'fixed'
            elif missing:
                state = f'locked: {missing} more parts needed'
            elif world.crystal_stock < SYSTEM_COST:
                state = f'{SYSTEM_COST} crystals (you have {world.crystal_stock})'
            else:
                state = f'{SYSTEM_COST} crystals'
            lines.append(f'{3 + k}  Fix {name}  -  {state}')
        lines.append(f'7  Trade {TRADE_COST} crystals for {TRADE_SCRAP} scrap')
        lines.append(f'Ship parts found: {len(world.parts)}/{len(world.part_zones)}')
        lines.append('Esc or E: close')
        for n, text in enumerate(lines):
            self.screen.blit(self.font.render(text, True, CREAM), (panel.x + 24, panel.y + 22 + n * 30))

    # ── main loop ───────────────────────────────────────────────────
    async def run(self):
        loading(100)                                    # lift the loading screen
        while True:
            # In the browser, clock.tick(FPS) would freeze the page: only measure there.
            dt = min(self.clock.tick(0 if IS_WEB else FPS) / 1000, 0.05)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    return
                self.handle_event(event)
            self.poll_network()
            self.watch_host()
            if self.scene == 'play':
                self.update_play(dt)
            self.draw()
            pygame.display.update()
            await asyncio.sleep(1 / FPS if IS_WEB else 0)   # yield to the browser


PAD_KEYS = {pygame.K_1: 1, pygame.K_2: 2, pygame.K_3: 3, pygame.K_4: 4, pygame.K_5: 5,
            pygame.K_6: 6, pygame.K_7: 7}
BOSS_HP_FULL = 12


async def main():
    try:
        loading(92, 'Almost ready...')
        await Game().run()
    except Exception:
        print(traceback.format_exc())           # the details, for you: the browser console (F12)
        if IS_WEB:                              # never leave players staring at a loading bar
            from pyscript import document
            document.getElementById('loading').style.display = 'none'
            box = document.getElementById('error')
            box.textContent = 'Sorry, the game hit a problem. Please reload the page.'
            box.style.display = 'block'
        raise


if __name__ == '__main__':
    try:
        asyncio.get_running_loop()              # PyScript: a loop is already running
        task = asyncio.create_task(main())
    except RuntimeError:
        asyncio.run(main())                     # desktop: python main.py
