<!DOCTYPE html>
<html lang="fr">
<head>
    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4661631845920943" crossorigin="anonymous"></script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><meta name="description" content="Outil de stratégie interactif pour Brawl Stars. Créez vos tactiques, placez vos brawlers sur les maps officielles et partagez vos animations avec votre équipe.">BrawlStrat v6.5 - Hybrid PC/Mobile</title>
    
    <script src="https://bernardo-castilho.github.io/DragDropTouch/DragDropTouch.js"></script>
    
    <style>
        body {
            font-family: 'Arial', sans-serif; background-color: #121214; color: white;
            margin: 0; padding: 0; height: 100vh; overflow: hidden;
            user-select: none; -webkit-user-select: none;
        }

        /* --- MENU DE SÉLECTION DE MAP & SAUVEGARDES --- */
        #start-menu {
            position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
            background: rgba(18, 18, 20, 0.95); backdrop-filter: blur(10px);
            z-index: 9999; display: flex; flex-direction: column;
            padding: 20px; box-sizing: border-box; overflow-y: auto; align-items: center;
        }
        #start-menu h1 { margin-top: 0; font-size: 32px; color: #f1c40f; text-transform: uppercase; text-shadow: 0 4px 10px rgba(0,0,0,0.5); text-align: center; }
        #start-menu h3 { color: #aaa; margin-bottom: 20px; text-align: center; }
        
        .menu-top-actions { display: flex; gap: 15px; margin-bottom: 20px; flex-wrap: wrap; justify-content: center; width: 100%; max-width: 900px; padding-bottom: 15px; border-bottom: 2px solid #333; }
        
        /* DROPDOWN MENU STYLISÉ */
        .custom-dropdown { position: relative; max-width: 400px; width: 100%; margin-bottom: 30px; user-select: none; }
        .dropdown-selected { background: #222; border: 2px solid #333; padding: 12px 20px; border-radius: 10px; cursor: pointer; display: flex; justify-content: space-between; align-items: center; font-weight: bold; font-size: 16px; color: white; transition: 0.3s; box-shadow: 0 4px 10px rgba(0,0,0,0.3); }
        .dropdown-selected:hover { border-color: #f1c40f; }
        .dropdown-options { position: absolute; top: 100%; left: 0; right: 0; background: #1a1a1e; border: 2px solid #333; border-top: none; border-radius: 0 0 10px 10px; display: none; flex-direction: column; z-index: 100; max-height: 350px; overflow-y: auto; box-shadow: 0 10px 20px rgba(0,0,0,0.7); }
        .dropdown-options.show { display: flex; }
        .dropdown-option { padding: 12px 20px; display: flex; align-items: center; gap: 15px; cursor: pointer; transition: 0.2s; border-bottom: 1px solid #222; font-weight: bold; }
        .dropdown-option:last-child { border-bottom: none; }
        .dropdown-option:hover { background: #f1c40f; color: #111; }

        .mode-btn { padding: 10px 15px; border-radius: 8px; border: 2px solid #333; background: #222; color: white; cursor: pointer; font-weight: bold; transition: 0.2s; text-transform: uppercase; }
        .mode-btn:hover, .mode-btn.active { background: #f1c40f; color: #111; border-color: #f1c40f; }
        .btn-saved-anims { background: #9b59b6; border-color: #9b59b6; color: white; }
        .btn-saved-anims:hover, .btn-saved-anims.active { background: #8e44ad; border-color: #8e44ad; color: white; }

        #map-selection-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 15px; width: 100%; max-width: 1200px; }
        .map-card { background: #222; border-radius: 12px; padding: 10px; cursor: pointer; text-align: center; border: 2px solid #333; transition: transform 0.2s, border-color 0.2s; box-shadow: 0 4px 10px rgba(0,0,0,0.3); }
        .map-card:hover { border-color: #0984e3; }
        .map-card img { width: 100%; border-radius: 8px; pointer-events: none; }
        .map-card span { display: block; margin-top: 10px; font-size: 14px; font-weight: bold; color: #eee; }

        /* --- LISTE DES ANIMATIONS SAUVEGARDÉES --- */
        #saved-animations-list { display: none; flex-direction: column; gap: 12px; width: 100%; max-width: 800px; }
        .saved-anim-card { background: #222; border-radius: 10px; padding: 15px; display: flex; justify-content: space-between; align-items: center; border: 2px solid #333; flex-wrap: wrap; gap: 10px; }
        .saved-anim-info { display: flex; flex-direction: column; gap: 5px; flex-grow: 1; }
        .saved-anim-title { font-size: 18px; color: #f1c40f; font-weight: bold; }
        .saved-anim-meta { font-size: 12px; color: #aaa; }
        .saved-anim-actions { display: flex; gap: 8px; flex-wrap: wrap; }
        .saved-anim-actions button { padding: 8px 12px; border: none; border-radius: 6px; cursor: pointer; font-weight: bold; color: white; transition: 0.2s; font-size: 13px; }
        .btn-play-anim { background: #2ecc71; box-shadow: 0 3px 0 #27ae60; } .btn-play-anim:hover { transform: translateY(2px); box-shadow: 0 1px 0 #27ae60; }
        .btn-rename-anim { background: #0984e3; box-shadow: 0 3px 0 #2980b9; } .btn-rename-anim:hover { transform: translateY(2px); box-shadow: 0 1px 0 #2980b9; }
        .btn-delete-anim { background: #e74c3c; box-shadow: 0 3px 0 #c0392b; } .btn-delete-anim:hover { transform: translateY(2px); box-shadow: 0 1px 0 #c0392b; }

        /* --- LAYOUT GLOBAL (PC) --- */
        #app {
            display: grid;
            grid-template-columns: 320px 1fr 250px;
            grid-template-rows: 1fr minmax(160px, auto);
            height: 100vh;
            width: 100vw;
        }

        .mobile-only { display: none !important; }
        .desktop-only { display: flex; }

        /* --- COLONNE GAUCHE (BRAWLERS & DESSIN PC) --- */
        #left-sidebar { grid-column: 1; grid-row: 1 / 3; background-color: #1a1a1e; border-right: 2px solid #333; padding: 20px; display: flex; flex-direction: column; gap: 15px; z-index: 10; box-shadow: 5px 0 15px rgba(0,0,0,0.5); box-sizing: border-box; }
        .search-bar { padding: 10px; border-radius: 8px; border: 1px solid #444; background-color: #2b2b32; color: white; transition: border-color 0.3s; }
        .search-bar:focus { outline: none; border-color: #0984e3; }
        .team-selector { display: flex; gap: 10px; }
        .team-btn { flex: 1; padding: 10px; border: none; border-radius: 8px; cursor: pointer; font-weight: bold; background-color: #333; color: #aaa; transition: 0.2s; }
        .team-btn.ally.active { background-color: #0984e3; color: white; box-shadow: 0 0 10px rgba(9, 132, 227, 0.5); }
        .team-btn.enemy.active { background-color: #e74c3c; color: white; box-shadow: 0 0 10px rgba(231, 76, 60, 0.5); }
        .brawler-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(50px, 1fr)); gap: 10px; flex-grow: 1; overflow-y: auto; background: #222; padding: 10px; border-radius: 8px; box-shadow: inset 0 4px 10px rgba(0,0,0,0.3); align-content: start; }
        .brawler-token { width: 50px; height: 50px; border-radius: 12px; cursor: grab; border: 2px solid #555; background-size: cover; background-position: center; transition: 0.2s; }
        .brawler-token:hover { transform: scale(1.15) translateY(-2px); border-color: #fff; }
        .mobile-selected { box-shadow: 0 0 15px #2ecc71 !important; border-color: #2ecc71 !important; transform: scale(1.15) !important; filter: brightness(1.2); }

        /* OUTILS DE DESSIN */
        .color-palette { display: flex; gap: 10px; margin-bottom: 5px; flex-wrap: wrap; justify-content: center; }
        .color-btn { width: 25px; height: 25px; border-radius: 50%; border: 2px solid white; cursor: pointer; transition: 0.2s; }
        .color-btn:hover { transform: scale(1.2); }
        .color-btn.eraser { background: repeating-linear-gradient(45deg, #fff, #fff 5px, #ffb8b8 5px, #ffb8b8 10px); border-color: #ff7675; display: flex; align-items: center; justify-content: center; font-size: 14px;}
        
        .shape-tools { display: flex; gap: 8px; margin-bottom: 10px; justify-content: center; width: 100%; }
        .shape-btn { flex: 1; background: #333; border: 2px solid #444; color: white; font-size: 16px; padding: 6px; border-radius: 8px; cursor: pointer; transition: 0.2s; display: flex; align-items: center; justify-content: center; }
        .shape-btn.active { border-color: #f1c40f; background: #222; box-shadow: 0 0 8px rgba(241, 196, 15, 0.4); }

        .action-btn { padding: 12px; background-color: #f1c40f; color: #111; border: none; font-weight: bold; cursor: pointer; border-radius: 8px; transition: 0.1s; box-shadow: 0 4px 0 #c29d0b; text-transform: uppercase; font-size: 12px; width: 100%; box-sizing: border-box; }
        .action-btn:hover { background-color: #f39c12; }
        .action-btn:active { transform: translateY(4px); box-shadow: 0 0 0 #c29d0b; }
        .btn-danger { background-color: #e74c3c; color: white; box-shadow: 0 4px 0 #c0392b; }
        .btn-danger:hover { background-color: #c0392b; }

        /* --- ZONE MAP CENTRALE --- */
        #map-wrapper { grid-column: 2; grid-row: 1; background-color: #111; position: relative; overflow: hidden; display: flex; align-items: center; justify-content: center; }
        #map-container { width: 100%; height: 100%; position: absolute; overflow: hidden; touch-action: none; cursor: default; }
        #strat-board { width: 750px; height: 750px; background-color: #2d3436; background-size: contain; background-position: center; background-repeat: no-repeat; position: absolute; top: 0; left: 0; transform-origin: top left; border: 4px solid #333; box-shadow: 0 10px 40px rgba(0,0,0,0.8); border-radius: 12px; box-sizing: border-box; }
        #draw-layer { position: absolute; top: 0; left: 0; width: 100%; height: 100%; cursor: crosshair; z-index: 2; }

        /* --- NOVEAUX STYLES DE PARTENARIAT ESPORT --- */
        .banniere-partenaire {
            position: absolute;
            top: 15px;
            left: 15px;
            max-height: 40px;
            width: auto;
            opacity: 0.9;
            z-index: 100;
            pointer-events: none;
        }
        .titre-objets {
            display: flex !important;
            align-items: center;
            gap: 10px;
        }
        .logo-partenaire {
            width: 30px;
            height: 30px;
            object-fit: contain;
        }

        /* --- TIMELINE --- */
        #timeline-container { grid-column: 2; grid-row: 2; background-color: #1a1a1e; border-top: 2px solid #333; padding: 15px 20px; display: flex; flex-direction: column; gap: 12px; z-index: 10; box-sizing: border-box; overflow: hidden; }
        .timeline-controls { display: flex; gap: 10px; align-items: center; flex-wrap: nowrap; width: 100%; }
        .timeline-controls .action-btn { width: auto; flex: 1; }
        .timeline-track { display: flex; gap: 8px; background: #222; padding: 12px; border-radius: 6px; overflow-x: auto; min-height: 50px; align-items: center; box-shadow: inset 0 2px 5px rgba(0,0,0,0.4); }
        .kf-badge { background: #0984e3; color: white; padding: 8px 14px; border-radius: 4px; cursor: pointer; font-weight: bold; font-size: 12px; transition: 0.2s; display: flex; align-items: center; gap: 6px; white-space: nowrap; }
        .kf-badge:hover { background: #3498db; }
        .kf-badge.active { background: #2ecc71; box-shadow: 0 0 8px #2ecc71; }
        .delete-kf { background: rgba(0,0,0,0.3); border-radius: 50%; width: 16px; height: 16px; display: inline-flex; align-items: center; justify-content: center; font-size: 9px; cursor: pointer; transition: 0.2s; }
        .delete-kf:hover { background: #e74c3c; transform: scale(1.2); }
        .playing-animation .placed-token { transition: left 1s ease-in-out, top 1s ease-in-out, width 1s ease-in-out, height 1s ease-in-out; }

        /* --- COLONNE DROITE (OBJETS) --- */
        #right-sidebar { grid-column: 3; grid-row: 1 / 3; background-color: #1a1a1e; border-left: 2px solid #333; padding: 20px; display: flex; flex-direction: column; gap: 15px; z-index: 10; overflow-y: auto; box-sizing: border-box; }
        #gadget-panel { background: #222; padding: 15px; border-radius: 8px; flex-grow: 1; text-align: center; color: #aaa; font-size: 14px; }
        .gadget-list { display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; margin-top: 10px; margin-bottom: 20px; }
        .game-ui-btn, .gadget-token { width: 48px; height: 48px; border-radius: 50%; cursor: grab; background-size: cover; background-position: center; box-shadow: 0 4px 8px rgba(0,0,0,0.4); transition: 0.2s; }
        .game-ui-btn:hover, .gadget-token:hover { transform: scale(1.15) translateY(-2px); }
        .gadget-token { border-radius: 12px; border: 2px solid #555; width: 45px; height: 45px; }
        .ball-token { width: 45px; height: 45px; border-radius: 50%; cursor: grab; background-image: url('ball.png'); background-color: #2b2b32; background-size: contain; background-position: center; background-repeat: no-repeat; border: 2px solid #f1c40f; transition: 0.2s; }
        .ball-token:hover { transform: scale(1.15) translateY(-2px); filter: drop-shadow(0 0 8px #fff); }

        /* --- ELEMENTS PLACÉS SUR MAP --- */
        .placed-token { position: absolute; cursor: move; transform-origin: center; background-size: cover; background-position: center; background-repeat: no-repeat; }
        .placed-brawler { width: 35px; height: 35px; border-radius: 50%; z-index: 10; border: 2px solid #555; box-shadow: 0 4px 8px rgba(0,0,0,0.5); touch-action: none; }
        .placed-brawler.selected { box-shadow: 0 0 15px white !important; filter: brightness(1.2); }
        .placed-gadget { width: 25px; height: 25px; border-radius: 50%; background-size: 85%; background-color: #1a1a1e; z-index: 11; border: 2px solid #00a8ff; touch-action: none; }
        .placed-gamebutton { width: 32px; height: 32px; border-radius: 50%; z-index: 9; box-shadow: 0 4px 8px rgba(0,0,0,0.5); touch-action: none; }
        .placed-ball { width: 25px; height: 25px; border-radius: 50%; z-index: 12; filter: drop-shadow(0 4px 6px rgba(0,0,0,0.6)); border: none; touch-action: none; }
        .resizer { width: 12px; height: 12px; background: white; border: 2px solid #111; border-radius: 50%; position: absolute; right: -4px; bottom: -4px; cursor: se-resize; display: none; z-index: 20; touch-action: none; }
        .placed-token:hover .resizer, .placed-token.selected .resizer { display: block; }

        /* --- VERSION MOBILE --- */
        @media (max-width: 850px) {
            body { overflow: hidden; }
            #app { display: flex; flex-direction: column; height: 100vh; width: 100vw; }
            .desktop-only { display: none !important; }
            .mobile-only { display: flex !important; }
            .pane { display: none !important; height: calc(55vh - 55px); overflow-y: auto; width: 100%; padding: 15px; box-sizing: border-box; order: 3; }
            .pane.active-pane { display: flex !important; flex-direction: column; gap: 15px; background: #1a1a1e; }
            #map-wrapper { order: 1; height: 45vh; flex-shrink: 0; width: 100vw; border-bottom: 2px solid #0984e3; }
            #mobile-tabs { order: 2; display: flex; height: 55px; flex-shrink: 0; background: #151518; box-shadow: 0 -2px 10px rgba(0,0,0,0.5); z-index: 20; width: 100%; }
            .mtab { flex: 1; background: none; border: none; color: #666; font-weight: bold; font-size: 11px; border-bottom: 4px solid transparent; transition: 0.2s; display: flex; align-items: center; justify-content: center; text-transform: uppercase; padding: 0 2px; }
            .mtab.active { color: #0984e3; border-bottom-color: #0984e3; background: rgba(9, 132, 227, 0.1); }
            .mtab.menu-tab { color: white; background: #333; border-bottom: none; border-left: 1px solid #111; }
            #left-sidebar, #right-sidebar, #timeline-container { border: none; box-shadow: none; height: calc(55vh - 55px) !important; }
            .timeline-controls { flex-wrap: wrap; justify-content: center; }
            .timeline-controls .action-btn { width: auto; flex-grow: 1; padding: 8px; font-size: 11px; }
            #draw-layer { pointer-events: none; }
        }
        @media (min-width: 851px) {
            .pane { display: flex !important; }
            #mobile-draw-tab { display: none !important; }
        }
    </style>
</head>
<body>

    <div id="start-menu">
        <h1>BrawlStrat v6.5</h1>
        <h3>Sélectionne un mode, une carte officielle, ou charge une animation</h3>
        
        <div class="menu-top-actions">
            <button class="mode-btn btn-saved-anims" id="btn-show-saved" onclick="showSavedAnimations()">📂 Mes Animations</button>
        </div>

        <div class="custom-dropdown" id="mode-dropdown">
            <div class="dropdown-selected" onclick="toggleDropdown()">
                <span id="selected-mode-text">Sélectionner un mode</span>
                <span>▼</span>
            </div>
            <div class="dropdown-options" id="dropdown-options">
                <span style="color:#aaa; padding: 10px;">Chargement des modes...</span>
            </div>
        </div>
        
        <div id="map-selection-grid"></div>
        <div id="saved-animations-list"></div>
    </div>

    <div id="app">
        
        <div id="left-sidebar" class="pane active-pane">
            <button class="action-btn desktop-only" style="background:#333; color:white; box-shadow:0 4px 0 #111; justify-content:center; margin-bottom:5px;" onclick="openMenu()">☰ Menu Principal</button>
            <div class="team-selector">
                <button class="team-btn ally active" id="btnAlly" onclick="setTeam('ally')">Allié</button>
                <button class="team-btn enemy" id="btnEnemy" onclick="setTeam('enemy')">Adversaire</button>
            </div>
            
            <div class="desktop-draw-tools desktop-only" style="flex-direction: column; gap: 8px; margin-top:10px;">
                <div class="shape-tools">
                    <button class="shape-btn active" onclick="setDrawTool('free', this)" title="Crayon">✏️</button>
                    <button class="shape-btn" onclick="setDrawTool('arrow', this)" title="Flèche">↗️</button>
                    <button class="shape-btn" onclick="setDrawTool('circle', this)" title="Cercle Vide">⭕</button>
                    <button class="shape-btn" onclick="setDrawTool('circle-filled', this)" title="Cercle Rempli (Zone)">🔴</button>
                </div>
                <div class="color-palette">
                    <div class="color-btn" style="background: #f1c40f;" onclick="setColor('#f1c40f')"></div>
                    <div class="color-btn" style="background: #0984e3;" onclick="setColor('#0984e3')"></div>
                    <div class="color-btn" style="background: #e74c3c;" onclick="setColor('#e74c3c')"></div>
                    <div class="color-btn" style="background: #2ecc71;" onclick="setColor('#2ecc71')"></div>
                    <div class="color-btn" style="background: #ffffff;" onclick="setColor('#ffffff')"></div>
                    <div class="color-btn eraser" onclick="setEraser()" title="Gomme">🧽</div>
                </div>
                <div style="display: flex; gap: 10px; align-items: center;">
                    <span style="font-size:12px; color:#aaa;">Taille:</span>
                    <input type="range" min="2" max="30" value="4" oninput="updateBrushSize(this.value)" style="flex:1;">
                </div>
                <button class="action-btn" onclick="clearDrawings()">Effacer Dessin</button>
                <button class="action-btn btn-danger" onclick="clearTokens()">Effacer Pions</button>
            </div>
            <hr class="desktop-only" style="border:1px solid #333; width:100%;">
            
            <input type="text" class="search-bar" id="search" placeholder="Chercher un brawler..." oninput="filterBrawlers()">
            <div class="brawler-grid" id="brawlerGrid"></div>
        </div>

        <div id="map-wrapper">
            <!-- 🎯 AJOUT BANNIÈRE ESPORT EN HAUT À GAUCHE -->
            <img src="banniere.jpg" alt="Bannière Esport" class="banniere-partenaire">

            <div id="map-container">
                <div id="strat-board" ondragover="allowDrop(event)" ondrop="drop(event)">
                    <canvas id="draw-layer"></canvas>
                </div>
            </div>
        </div>

        <div id="mobile-tabs" class="mobile-only">
            <button class="mtab active" onclick="switchMobileTab('left-sidebar', this)">Brawlers</button>
            <button class="mtab" onclick="switchMobileTab('right-sidebar', this)">Objets</button>
            <button class="mtab" onclick="switchMobileTab('mobile-draw-tab', this)">Dessin</button>
            <button class="mtab" onclick="switchMobileTab('timeline-container', this)">Anim</button>
            <button class="mtab menu-tab" onclick="openMenu()">☰ Menu</button>
        </div>

        <div id="mobile-draw-tab" class="pane">
            <button id="m-draw-btn" class="action-btn" style="background:#f1c40f; box-shadow:0 4px 0 #c29d0b;" onclick="toggleMobileDrawing()">✋ Mode Déplacement</button>
            
            <div class="shape-tools" style="background: #222; padding: 10px; border-radius: 8px;">
                <button class="shape-btn active" onclick="setDrawTool('free', this)" title="Crayon">✏️</button>
                <button class="shape-btn" onclick="setDrawTool('arrow', this)" title="Flèche">↗️</button>
                <button class="shape-btn" onclick="setDrawTool('circle', this)" title="Cercle Vide">⭕</button>
                <button class="shape-btn" onclick="setDrawTool('circle-filled', this)" title="Cercle Rempli (Zone)">🔴</button>
            </div>

            <div class="color-palette" style="background: #222; padding: 10px; border-radius: 8px;">
                <div class="color-btn" style="background: #f1c40f;" onclick="setColor('#f1c40f')"></div>
                <div class="color-btn" style="background: #0984e3;" onclick="setColor('#0984e3')"></div>
                <div class="color-btn" style="background: #e74c3c;" onclick="setColor('#e74c3c')"></div>
                <div class="color-btn" style="background: #2ecc71;" onclick="setColor('#2ecc71')"></div>
                <div class="color-btn" style="background: #ffffff;" onclick="setColor('#ffffff')"></div>
                <div class="color-btn eraser" onclick="setEraser()" title="Gomme">🧽</div>
            </div>

            <div style="background: #222; padding: 12px; border-radius: 8px; border: 1px solid #333; display: flex; align-items: center; justify-content: space-between;">
                <span style="color:#aaa; font-size:14px; font-weight:bold;">Taille Trait:</span>
                <input type="range" min="2" max="30" value="4" oninput="updateBrushSize(this.value)" style="width: 50%;">
            </div>

            <div style="display: flex; gap:10px; margin-top: auto;">
                <button class="action-btn" onclick="clearDrawings()">🧽 Dessins</button>
                <button class="action-btn btn-danger" onclick="clearTokens()">🗑️ Pions</button>
            </div>
        </div>

        <div id="timeline-container" class="pane">
            <div class="timeline-controls">
                <button class="action-btn" style="background:#2ecc71; color:white; box-shadow:0 4px 0 #27ae60;" onclick="addKeyframe()">+ Point Clé</button>
                <button class="action-btn" id="playBtn" style="background:#0984e3; color:white; box-shadow:0 4px 0 #2980b9;" onclick="playAnimation()">▶ Lire</button>
                <button class="action-btn" id="saveBtn" style="background:#9b59b6; color:white; box-shadow:0 4px 0 #8e44ad;" onclick="saveTimeline()">💾 Enregistrer</button>
                <button class="action-btn btn-danger" onclick="clearTimeline()">Vider Piste</button>
            </div>
            <div class="timeline-track" id="timelineTrack">
                <span style="color:#666; font-size:12px; margin-left:5px;">Aucun point clé ajouté.</span>
            </div>
        </div>

        <div id="right-sidebar" class="pane">
            <!-- 🎯 AJOUT DU LOGO À CÔTÉ DU TITRE -->
            <h3 class="desktop-only titre-objets" style="margin-top:0;">
                <img src="logo.jpg" alt="Logo Esport" class="logo-partenaire">
                Objets & Gadgets
            </h3>
            
            <div id="ball-container" style="display: none; gap: 12px; align-items: center; margin-bottom: 15px; background: #222; padding: 12px; border-radius: 8px; border: 1px solid #333;">
                <span style="font-size: 14px; font-weight: bold; color: #aaa;">Brawl Ball :</span>
                <div class="ball-token" id="ballToken" title="Ballon"></div>
            </div>
            <div id="gadget-panel">Sélectionne un brawler placé sur la map pour voir ses gadgets et pouvoirs !</div>
        </div>

    </div>

    <script>
        window.DragDropTouchCmds = { alwaysCreateImage: false, pressHoldTime: 80 };

        let allBrawlers = [], allMapsData = [], groupedMaps = {};
        let currentColor = '#f1c40f', isErasing = false, currentBrushSize = 4, currentEraserSize = 20, currentTeam = 'ally'; 
        let currentModeName = "";
        let currentMapUrl = ""; 
        
        // DRAWING TOOLS STATE
        let currentDrawTool = 'free'; // 'free', 'arrow', 'circle', 'circle-filled'
        let zoomLevel = 1.0, panX = 0, panY = 0;
        let isPanning = false, panStartX = 0, panStartY = 0;
        let currentDraggedData = null, pendingMobileData = null;  
        let keyframes = [], isPlaying = false, playbackInterval = null, currentPlayIndex = 0;
        let mobileDrawingActive = false, isTouchPanning = false, touchPanStartX = 0, touchPanStartY = 0;

        let initialPinchDist = 0, initialPinchZoom = 1;
        let startTouchCenterX = 0, startTouchCenterY = 0;
        let startPanX = 0, startPanY = 0;

        const UI_ICONS = { attack: 'attack.png', super: 'super.png', hypercharge: 'https://cdn.brawlify.com/icon/Hypercharge.png' };
        
        const targetModes = { 
            "Brawl Ball": "Brawl Ball", 
            "Knockout": "Hors-Jeu", 
            "Hot Zone": "Zone Réservée", 
            "Bounty": "Prime", 
            "Heist": "Braquage",
            "Gem Grab": "Razzia de gemmes"
        };

        const modeIcons = {
            "Brawl Ball": "https://cdn.brawlify.com/gamemode/Brawl-Ball.png",
            "Hors-Jeu": "https://cdn.brawlify.com/gamemode/Knockout.png",
            "Zone Réservée": "https://cdn.brawlify.com/gamemode/Hot-Zone.png",
            "Prime": "https://cdn.brawlify.com/gamemode/Bounty.png",
            "Braquage": "https://cdn.brawlify.com/gamemode/Heist.png",
            "Razzia de gemmes": "https://cdn.brawlify.com/gamemode/Gem-Grab.png"
        };

        // GESTION DU DROPDOWN
        function toggleDropdown() { document.getElementById('dropdown-options').classList.toggle('show'); }
        window.onclick = function(event) {
            if (!event.target.closest('.custom-dropdown')) {
                const dropdowns = document.getElementsByClassName("dropdown-options");
                for (let i = 0; i < dropdowns.length; i++) dropdowns[i].classList.remove('show');
            }
        }

        window.addEventListener('DOMContentLoaded', () => {
            const params = new URLSearchParams(window.location.search);
            const stratData = params.get('strat');
            
            if (stratData) {
                try {
                    const anim = JSON.parse(decodeURIComponent(atob(stratData)));
                    let savedAnims = JSON.parse(localStorage.getItem('brawlstrat_anims') || '[]');
                    anim.id = Date.now(); 
                    anim.name = anim.name + " (Partagée)";
                    savedAnims.push(anim);
                    localStorage.setItem('brawlstrat_anims', JSON.stringify(savedAnims));
                    alert(`L'animation partagée "${anim.name}" a été ajoutée à tes sauvegardes !`);
                    setTimeout(() => playSavedAnimation(anim.id), 1000);
                    window.history.replaceState({}, document.title, window.location.pathname);
                } catch (e) {
                    console.error("Erreur de décodage URL :", e);
                    alert("Le lien partagé semble invalide ou corrompu.");
                }
            }
        });

        function isMobile() { return window.innerWidth <= 850; }

        function switchMobileTab(paneId, btnEl) {
            if (!isMobile()) return;
            document.querySelectorAll('.pane').forEach(el => el.classList.remove('active-pane'));
            document.querySelectorAll('.mtab:not(.menu-tab)').forEach(el => el.classList.remove('active'));
            document.getElementById(paneId).classList.add('active-pane');
            btnEl.classList.add('active');
        }

        async function fetchGameData() {
            try {
                const mapsRes = await fetch('https://api.brawlapi.com/v1/maps');
                const mapsData = await mapsRes.json();
                allMapsData = mapsData.list.filter(map => targetModes[map.gameMode.name] !== undefined && map.disabled === false);
                allMapsData.forEach(map => {
                    const mode = targetModes[map.gameMode.name];
                    if (!groupedMaps[mode]) groupedMaps[mode] = [];
                    groupedMaps[mode].push(map);
                });
                renderModeMenu();

                const brawlersRes = await fetch('https://api.brawlapi.com/v1/brawlers');
                const brawlersData = await brawlersRes.json();
                allBrawlers = brawlersData.list.map(b => ({ id: b.id, name: b.name, img: b.imageUrl, gadgets: b.gadgets || [], hypercharges: b.hypercharges || [] }));
                allBrawlers.sort((a, b) => a.name.localeCompare(b.name));
                initGrid(allBrawlers);
            } catch (error) { console.error("Erreur API :", error); }
        }
        
        function renderModeMenu() {
            const optionsContainer = document.getElementById('dropdown-options');
            optionsContainer.innerHTML = '';
            
            Object.keys(groupedMaps).sort().forEach((mode, index) => {
                const opt = document.createElement('div');
                opt.className = 'dropdown-option';
                opt.dataset.mode = mode;
                
                opt.innerHTML = `<span>${mode}</span>`;
                opt.onclick = () => { 
                    const iconSrc = modeIcons[mode] || "https://cdn.brawlify.com/icon/Info.png";
                    document.getElementById('selected-mode-text').innerHTML = `<div style="display:flex; align-items:center; gap:10px;"><img src="${iconSrc}" style="width:24px;"> ${mode}</div>`;
                    
                    document.getElementById('btn-show-saved').classList.remove('active');
                    document.getElementById('dropdown-options').classList.remove('show');
                    
                    document.querySelectorAll('.dropdown-option').forEach(el => {
                        el.style.display = el.dataset.mode === mode ? 'none' : 'flex';
                    });

                    renderMaps(mode); 
                };
                optionsContainer.appendChild(opt); 
                if(index === 0) opt.click();
            });
        }

        function renderMaps(mode) {
            document.getElementById('saved-animations-list').style.display = 'none';
            document.getElementById('mode-dropdown').style.display = 'block';
            const grid = document.getElementById('map-selection-grid'); 
            grid.style.display = 'grid';
            grid.innerHTML = '';
            groupedMaps[mode].forEach(map => {
                const div = document.createElement('div'); div.className = 'map-card';
                div.innerHTML = `<img src="${map.imageUrl}" alt="${map.name}"><span>${map.name}</span>`;
                div.onclick = () => loadMapIntoBoard(map.imageUrl, mode); grid.appendChild(div);
            });
        }

        function loadMapIntoBoard(url, mode) {
            currentModeName = mode; currentMapUrl = url;
            document.getElementById('strat-board').style.backgroundImage = `url('${url}')`;
            document.getElementById('start-menu').style.display = 'none';
            const ballContainer = document.getElementById('ball-container');
            if(ballContainer) ballContainer.style.display = (mode === "Brawl Ball") ? "flex" : "none";
            clearTokens(); clearDrawings(); clearTimeline(); centerMap();
        }

        function openMenu() { document.getElementById('start-menu').style.display = 'flex'; }
        fetchGameData();

        function saveTimeline() {
            if (keyframes.length === 0) { alert("Crée au moins un point clé avant d'enregistrer !"); return; }
            let name = prompt("Donne un nom à ton animation :", "Ma super strat");
            if (!name || name.trim() === "") return;
            let savedAnims = JSON.parse(localStorage.getItem('brawlstrat_anims') || '[]');
            savedAnims.push({ id: Date.now(), name: name.trim(), mapUrl: currentMapUrl, mode: currentModeName, keyframes: JSON.parse(JSON.stringify(keyframes)) });
            localStorage.setItem('brawlstrat_anims', JSON.stringify(savedAnims));
            alert("Animation sauvegardée avec succès ! Tu la retrouveras dans le Menu.");
        }

        function showSavedAnimations() {
            document.getElementById('mode-dropdown').style.display = 'none';
            document.getElementById('btn-show-saved').classList.add('active');
            document.getElementById('map-selection-grid').style.display = 'none';
            const list = document.getElementById('saved-animations-list');
            list.style.display = 'flex'; list.innerHTML = '';
            
            const btnBack = document.createElement('button');
            btnBack.className = 'action-btn';
            btnBack.style.backgroundColor = '#333';
            btnBack.style.boxShadow = '0 4px 0 #111';
            btnBack.style.color = '#fff';
            btnBack.style.marginBottom = '20px';
            btnBack.innerHTML = '🔙 Retour aux Cartes';
            btnBack.onclick = () => {
                document.getElementById('saved-animations-list').style.display = 'none';
                document.getElementById('mode-dropdown').style.display = 'block';
                document.getElementById('map-selection-grid').style.display = 'grid';
                document.getElementById('btn-show-saved').classList.remove('active');
            };
            list.appendChild(btnBack);

            let savedAnims = JSON.parse(localStorage.getItem('brawlstrat_anims') || '[]');
            
            if (savedAnims.length === 0) {
                const emptyMsg = document.createElement('span');
                emptyMsg.style = "color:#aaa; text-align:center; padding: 20px; font-size: 16px;";
                emptyMsg.innerText = "Aucune animation sauvegardée pour le moment.";
                list.appendChild(emptyMsg);
                return;
            }

            savedAnims.reverse().forEach(anim => {
                const div = document.createElement('div'); div.className = 'saved-anim-card';
                div.innerHTML = `
                    <div class="saved-anim-info">
                        <span class="saved-anim-title">${anim.name}</span>
                        <span class="saved-anim-meta">Mode : ${anim.mode} | Points clés : ${anim.keyframes.length}</span>
                    </div>
                    <div class="saved-anim-actions">
                        <button class="btn-play-anim" onclick="playSavedAnimation(${anim.id})">▶ Jouer</button>
                        <button class="btn-rename-anim" onclick="renameSavedAnimation(${anim.id})">✏️ Renommer</button>
                        <button style="background: #e67e22; box-shadow: 0 3px 0 #d35400; color: white;" onclick="shareAnimation(${anim.id})">🔗 Partager</button>
                        <button class="btn-delete-anim" onclick="deleteSavedAnimation(${anim.id})" title="Supprimer">🗑️</button>
                    </div>
                `;
                list.appendChild(div);
            });
        }

        function shareAnimation(id) {
            let savedAnims = JSON.parse(localStorage.getItem('brawlstrat_anims') || '[]');
            let anim = savedAnims.find(a => a.id === id);
            if (!anim) return;
            const encodedData = btoa(encodeURIComponent(JSON.stringify(anim)));
            const shareUrl = window.location.origin + window.location.pathname + "?strat=" + encodedData;
            navigator.clipboard.writeText(shareUrl).then(() => { alert("🔗 Le lien de la trame a été copié dans ton presse-papier ! Tu peux l'envoyer à tes amis.");
            }).catch(err => { prompt("Copie ce lien manuellement :", shareUrl); });
        }

        function playSavedAnimation(id) {
            let savedAnims = JSON.parse(localStorage.getItem('brawlstrat_anims') || '[]');
            let anim = savedAnims.find(a => a.id === id);
            if (!anim) return;
            loadMapIntoBoard(anim.mapUrl, anim.mode);
            keyframes = JSON.parse(JSON.stringify(anim.keyframes));
            renderTimeline(); loadKeyframe(0, false);
            if (isMobile()) switchMobileTab('timeline-container', document.querySelectorAll('.mtab')[3]);
        }

        function renameSavedAnimation(id) {
            let savedAnims = JSON.parse(localStorage.getItem('brawlstrat_anims') || '[]');
            let anim = savedAnims.find(a => a.id === id); if (!anim) return;
            let newName = prompt("Nouveau nom pour cette animation :", anim.name);
            if (newName && newName.trim() !== "") { anim.name = newName.trim(); localStorage.setItem('brawlstrat_anims', JSON.stringify(savedAnims)); showSavedAnimations(); }
        }

        function deleteSavedAnimation(id) {
            if(!confirm("Es-tu sûr de vouloir supprimer définitivement cette animation ?")) return;
            let savedAnims = JSON.parse(localStorage.getItem('brawlstrat_anims') || '[]');
            savedAnims = savedAnims.filter(a => a.id !== id); localStorage.setItem('brawlstrat_anims', JSON.stringify(savedAnims)); showSavedAnimations(); 
        }

        function centerMap() {
            const mc = document.getElementById('map-container');
            const mcW = mc.clientWidth; const mcH = mc.clientHeight;
            zoomLevel = isMobile() ? (Math.min(mcW, mcH) / 750) * 0.98 : (Math.min(mcW, mcH) / 750) * 0.95;
            panX = (mcW - (750 * zoomLevel)) / 2; panY = (mcH - (750 * zoomLevel)) / 2;
            applyTransform();
        }

        window.addEventListener('resize', () => {
            const isDesktop = !isMobile();
            document.querySelectorAll('.brawler-token, .game-ui-btn, .gadget-token, #ballToken').forEach(el => { el.draggable = isDesktop; });
            if (isDesktop) { pendingMobileData = null; document.querySelectorAll('.mobile-selected').forEach(el => el.classList.remove('mobile-selected')); document.getElementById('draw-layer').style.pointerEvents = "auto"; } 
            else { if(!mobileDrawingActive) document.getElementById('draw-layer').style.pointerEvents = "none"; }
            centerMap();
        });

        function setTeam(team) {
            currentTeam = team; document.getElementById('btnAlly').classList.toggle('active', team === 'ally'); document.getElementById('btnEnemy').classList.toggle('active', team === 'enemy');
        }

        function bindTokenEvents(element, data) {
            element.draggable = !isMobile();
            element.addEventListener('dragstart', (e) => {
                if(isMobile()) return e.preventDefault(); 
                if(data.type === 'brawler') data.team = currentTeam;
                e.dataTransfer.setData('text/plain', data.type); currentDraggedData = data;
            });
            element.addEventListener('click', () => {
                if (isMobile()) {
                    document.querySelectorAll('.mobile-selected').forEach(el => el.classList.remove('mobile-selected')); element.classList.add('mobile-selected');
                    if(data.type === 'brawler') data.team = currentTeam; pendingMobileData = data;
                }
            });
        }

        const grid = document.getElementById('brawlerGrid');
        function initGrid(list) {
            grid.innerHTML = '';
            list.forEach(brawler => {
                const div = document.createElement('div'); div.className = 'brawler-token'; div.style.backgroundImage = `url('${brawler.img}')`;
                bindTokenEvents(div, { type: "brawler", img: brawler.img, brawlerId: brawler.id }); grid.appendChild(div);
            });
        }

        function filterBrawlers() { const query = document.getElementById('search').value.toLowerCase(); initGrid(allBrawlers.filter(b => b.name.toLowerCase().includes(query))); }
        bindTokenEvents(document.getElementById('ballToken'), { type: "ball", img: "ball.png" });

        function toggleMobileDrawing() {
            mobileDrawingActive = !mobileDrawingActive; 
            const btn = document.getElementById('m-draw-btn'); const canvasLayer = document.getElementById('draw-layer');
            if(mobileDrawingActive) { btn.innerText = "✏️ Mode Dessin"; btn.style.background = "#2ecc71"; btn.style.boxShadow = "0 4px 0 #27ae60"; canvasLayer.style.pointerEvents = "auto"; } 
            else { btn.innerText = "✋ Mode Déplacement"; btn.style.background = "#f1c40f"; btn.style.boxShadow = "0 4px 0 #c29d0b"; isDrawing = false; canvasLayer.style.pointerEvents = "none"; }
        }

        function updateBrushSize(val) { currentBrushSize = parseInt(val); currentEraserSize = parseInt(val) * 5; document.querySelectorAll('input[type="range"]').forEach(el => { el.value = val; }); }

        // --- NOUVEAU SYSTÈME DE DESSIN VECTORIEL ---
        const canvas = document.getElementById('draw-layer'); 
        const ctx = canvas.getContext('2d', { willReadFrequently: true });
        canvas.width = 750; canvas.height = 750; 
        
        let isDrawing = false, lastX = 0, lastY = 0;
        let vectorShapes = [];
        let currentShape = null;
        let draggedShape = null;
        let dragAction = null;
        let dragLastX = 0, dragLastY = 0;

        // Calque invisible pour le dessin libre
        const freehandCanvas = document.createElement('canvas');
        freehandCanvas.width = 750; freehandCanvas.height = 750;
        const freehandCtx = freehandCanvas.getContext('2d', { willReadFrequently: true });

        // MODIFICATION: Sélectionner une couleur désélectionne le cercle actuel et prépare le prochain trait
        function setColor(c) { 
            currentColor = c; 
            isErasing = false; 
            vectorShapes.forEach(s => s.selected = false);
            redrawCanvas();
        }
        function setEraser() { isErasing = true; document.querySelectorAll('.shape-btn').forEach(btn => btn.classList.remove('active')); canvas.style.cursor = 'cell'; }

        // MODIFICATION: Sélectionner un outil désélectionne aussi la forme actuelle
        function setDrawTool(tool, element) {
            currentDrawTool = tool; isErasing = false;
            document.querySelectorAll('.shape-btn').forEach(btn => btn.classList.remove('active'));
            if(element) element.classList.add('active'); else document.querySelectorAll('.shape-btn[title="Crayon"]').forEach(b => b.classList.add('active'));
            canvas.style.cursor = 'crosshair';
            vectorShapes.forEach(s => s.selected = false);
            redrawCanvas();
        }

        // Calcule la distance entre un point et un segment (pour hitbox des flèches)
        function distToSegment(px, py, ax, ay, bx, by) {
            const l2 = (bx - ax)**2 + (by - ay)**2;
            if (l2 === 0) return Math.hypot(px - ax, py - ay);
            let t = ((px - ax) * (bx - ax) + (py - ay) * (by - ay)) / l2;
            t = Math.max(0, Math.min(1, t));
            return Math.hypot(px - (ax + t * (bx - ax)), py - (ay + t * (by - ay)));
        }

        // Test de collision pour sélectionner une forme existante
        function hitTest(x, y) {
            // Parcours à l'envers pour attraper l'élément au premier plan
            for (let i = vectorShapes.length - 1; i >= 0; i--) {
                const shape = vectorShapes[i];
                const isSel = shape.selected;
                
                if (shape.type === 'arrow') {
                    if (Math.hypot(x - shape.endX, y - shape.endY) < (isSel ? 15 : 10)) return { shape, part: 'head' };
                    if (Math.hypot(x - shape.startX, y - shape.startY) < (isSel ? 15 : 10)) return { shape, part: 'tail' };
                    if (distToSegment(x, y, shape.startX, shape.startY, shape.endX, shape.endY) < shape.size + 8) return { shape, part: 'body' };
                } 
                else if (shape.type === 'circle' || shape.type === 'circle-filled') {
                    // MODIFICATION: Nouveau calcul pour la hitbox basée sur la bounding box (ellipse)
                    const centerX = (shape.startX + shape.endX) / 2;
                    const centerY = (shape.startY + shape.endY) / 2;
                    const radiusX = Math.abs(shape.endX - shape.startX) / 2;
                    const radiusY = Math.abs(shape.endY - shape.startY) / 2;

                    // Point de redimensionnement (le seul point qui reste, sur le bord endX/endY)
                    if (Math.hypot(x - shape.endX, y - shape.endY) < (isSel ? 15 : 10)) return { shape, part: 'edge' };

                    // Corps de la forme (pour déplacer tout le cercle en cliquant dedans)
                    let inside = false;
                    if (radiusX > 0 && radiusY > 0) {
                        const dx = x - centerX;
                        const dy = y - centerY;
                        inside = (dx*dx)/(radiusX*radiusX) + (dy*dy)/(radiusY*radiusY) <= 1;
                    }
                    if (inside) return { shape, part: 'body' };
                }
            }
            return null;
        }

        function drawArrowVector(context, shape) {
            const angle = Math.atan2(shape.endY - shape.startY, shape.endX - shape.startX);
            const headlen = 15 + shape.size;
            
            context.lineCap = 'round'; context.lineJoin = 'round';
            context.beginPath(); context.moveTo(shape.startX, shape.startY); 
            context.lineTo(shape.endX - headlen * Math.cos(angle) * 0.5, shape.endY - headlen * Math.sin(angle) * 0.5);
            context.strokeStyle = shape.color; context.lineWidth = shape.size; context.stroke();
            
            context.beginPath();
            context.moveTo(shape.endX, shape.endY);
            context.lineTo(shape.endX - headlen * Math.cos(angle - Math.PI / 6), shape.endY - headlen * Math.sin(angle - Math.PI / 6));
            context.lineTo(shape.endX - headlen * Math.cos(angle + Math.PI / 6), shape.endY - headlen * Math.sin(angle + Math.PI / 6));
            context.closePath();
            context.fillStyle = shape.color; context.fill();

            if (shape.selected) {
                context.fillStyle = 'white'; context.strokeStyle = '#333'; context.lineWidth = 2;
                context.beginPath(); context.arc(shape.startX, shape.startY, 6, 0, Math.PI*2); context.fill(); context.stroke();
                context.beginPath(); context.arc(shape.endX, shape.endY, 6, 0, Math.PI*2); context.fill(); context.stroke();
            }
        }
        
        // MODIFICATION: Dessin du cercle avec une logique "Bounding Box" (Top-Left vers Bottom-Right)
        function drawCircleVector(context, shape) {
            const centerX = (shape.startX + shape.endX) / 2;
            const centerY = (shape.startY + shape.endY) / 2;
            const radiusX = Math.abs(shape.endX - shape.startX) / 2;
            const radiusY = Math.abs(shape.endY - shape.startY) / 2;

            context.beginPath();
            // L'ellipse s'adapte parfaitement au glissement de la souris
            context.ellipse(centerX, centerY, radiusX, radiusY, 0, 0, 2 * Math.PI);
            context.strokeStyle = shape.color; context.lineWidth = shape.size;
            
            if (shape.type === 'circle-filled') {
                context.fillStyle = shape.color; context.globalAlpha = 0.4; context.fill();
                context.globalAlpha = 1.0; context.stroke();
            } else { context.stroke(); }

            if (shape.selected) {
                // Point de redimensionnement extérieur toujours visible (le point central a été retiré)
                context.fillStyle = 'white'; context.strokeStyle = '#333'; context.lineWidth = 2;
                context.beginPath(); context.arc(shape.endX, shape.endY, 6, 0, Math.PI*2); context.fill(); context.stroke();
            }
        }

        function redrawCanvas() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(freehandCanvas, 0, 0);
            vectorShapes.forEach(shape => {
                if (shape.type === 'arrow') drawArrowVector(ctx, shape);
                else drawCircleVector(ctx, shape);
            });
        }

        function getCanvasPos(clientX, clientY) {
            const rect = canvas.getBoundingClientRect();
            return { x: (clientX - rect.left) / zoomLevel, y: (clientY - rect.top) / zoomLevel };
        }

        function handleDrawStart(x, y) {
            const hit = hitTest(x, y);
            if (hit && !isErasing) {
                draggedShape = hit.shape; dragAction = hit.part; dragLastX = x; dragLastY = y;
                vectorShapes.forEach(s => s.selected = false);
                draggedShape.selected = true; redrawCanvas(); return;
            }
            
            vectorShapes.forEach(s => s.selected = false); redrawCanvas();

            if (isErasing) {
                if (hit) {
                    vectorShapes = vectorShapes.filter(s => s !== hit.shape); redrawCanvas();
                } else { isDrawing = true; lastX = x; lastY = y; }
            } else if (currentDrawTool !== 'free') {
                isDrawing = true;
                currentShape = { type: currentDrawTool, startX: x, startY: y, endX: x, endY: y, color: currentColor, size: currentBrushSize, selected: true };
                vectorShapes.push(currentShape); redrawCanvas();
            } else { isDrawing = true; lastX = x; lastY = y; }
        }

        function handleDrawMove(x, y) {
            if (!isDrawing && !draggedShape) {
                const hit = hitTest(x, y);
                // Le curseur indique qu'on peut déplacer l'objet entier depuis son "body"
                if (hit) canvas.style.cursor = (hit.part === 'body') ? 'move' : 'pointer';
                else canvas.style.cursor = isErasing ? 'cell' : 'crosshair';
            }

            if (draggedShape) {
                if (dragAction === 'tail') { draggedShape.startX = x; draggedShape.startY = y; } // Pour les flèches
                else if (dragAction === 'head' || dragAction === 'edge') { draggedShape.endX = x; draggedShape.endY = y; }
                else { // Pour déplacer tout le corps (body)
                    const dx = x - dragLastX; const dy = y - dragLastY;
                    draggedShape.startX += dx; draggedShape.startY += dy;
                    draggedShape.endX += dx; draggedShape.endY += dy;
                    dragLastX = x; dragLastY = y;
                }
                redrawCanvas(); return;
            }
            
            if (!isDrawing) return;

            if (isErasing) {
                freehandCtx.globalCompositeOperation = 'destination-out'; freehandCtx.lineWidth = currentEraserSize;
                freehandCtx.lineCap = 'round'; freehandCtx.lineJoin = 'round';
                freehandCtx.beginPath(); freehandCtx.moveTo(lastX, lastY); freehandCtx.lineTo(x, y); freehandCtx.stroke();
                
                const hit = hitTest(x, y);
                if (hit) vectorShapes = vectorShapes.filter(s => s !== hit.shape);
                
                [lastX, lastY] = [x, y]; redrawCanvas();
            } else if (currentDrawTool === 'free') {
                freehandCtx.globalCompositeOperation = 'source-over'; freehandCtx.strokeStyle = currentColor;
                freehandCtx.lineWidth = currentBrushSize; freehandCtx.lineCap = 'round'; freehandCtx.lineJoin = 'round';
                freehandCtx.beginPath(); freehandCtx.moveTo(lastX, lastY); freehandCtx.lineTo(x, y); freehandCtx.stroke();
                [lastX, lastY] = [x, y]; redrawCanvas();
            } else if (currentShape) {
                currentShape.endX = x; currentShape.endY = y; redrawCanvas();
            }
        }

        function handleDrawEnd() {
            if (draggedShape) { draggedShape = null; dragAction = null; }
            if (isDrawing) {
                isDrawing = false;
                if (currentShape) {
                    if (Math.hypot(currentShape.endX - currentShape.startX, currentShape.endY - currentShape.startY) < 5) vectorShapes.pop();
                    currentShape = null; redrawCanvas();
                }
            }
        }

        // EVENT MOUSE DRAWING
        canvas.addEventListener('mousedown', e => { 
            if(e.button === 0 && !isPlaying && (!isMobile() || mobileDrawingActive)) { 
                const pos = getCanvasPos(e.clientX, e.clientY); handleDrawStart(pos.x, pos.y);
            }
        });
        canvas.addEventListener('mousemove', e => {
            if (isPlaying || (isMobile() && !mobileDrawingActive)) return; 
            const pos = getCanvasPos(e.clientX, e.clientY); handleDrawMove(pos.x, pos.y);
        });
        window.addEventListener('mouseup', () => handleDrawEnd());

        // EVENT DOUBLE CLICK TO DELETE SHAPES
        canvas.addEventListener('dblclick', e => {
            const pos = getCanvasPos(e.clientX, e.clientY);
            const hit = hitTest(pos.x, pos.y);
            if (hit) {
                vectorShapes = vectorShapes.filter(s => s !== hit.shape);
                redrawCanvas();
                if (draggedShape === hit.shape) draggedShape = null;
            }
        });

        // EVENT TOUCH DRAWING
        canvas.addEventListener('touchstart', e => {
            if (isMobile() && !mobileDrawingActive) return; 
            if(!isPlaying && e.touches.length === 1) { 
                const pos = getCanvasPos(e.touches[0].clientX, e.touches[0].clientY); handleDrawStart(pos.x, pos.y);
            }
        }, { passive: true });
        canvas.addEventListener('touchmove', e => {
            if ((isMobile() && !mobileDrawingActive) || e.touches.length > 1) return;
            e.preventDefault(); 
            const pos = getCanvasPos(e.touches[0].clientX, e.touches[0].clientY); handleDrawMove(pos.x, pos.y);
        }, { passive: false });
        window.addEventListener('touchend', () => handleDrawEnd());

        function clearDrawings() { 
            freehandCtx.clearRect(0, 0, freehandCanvas.width, freehandCanvas.height); 
            vectorShapes = [];
            redrawCanvas();
        }
        function clearTokens() { document.querySelectorAll('.placed-token').forEach(t => t.remove()); }

        const board = document.getElementById('strat-board'); const mapContainer = document.getElementById('map-container');
        function applyTransform() { board.style.transform = `translate(${panX}px, ${panY}px) scale(${zoomLevel})`; }
        
        mapContainer.addEventListener('wheel', e => { 
            e.preventDefault(); const rect = mapContainer.getBoundingClientRect();
            const mouseX = e.clientX - rect.left; const mouseY = e.clientY - rect.top;
            const oldZoom = zoomLevel; let newZoom = zoomLevel + (e.deltaY < 0 ? 0.1 : -0.1); newZoom = Math.max(0.3, Math.min(3.0, newZoom));
            panX = mouseX - (mouseX - panX) * (newZoom / oldZoom); panY = mouseY - (mouseY - panY) * (newZoom / oldZoom);
            zoomLevel = newZoom; applyTransform(); 
        }, { passive: false });

        mapContainer.addEventListener('contextmenu', e => e.preventDefault());
        mapContainer.addEventListener('mousedown', e => { if(e.button===2 && (!isMobile() || !mobileDrawingActive)) { isPanning = true; panStartX = e.clientX - panX; panStartY = e.clientY - panY; } });
        mapContainer.addEventListener('mousemove', e => { if(isPanning) { panX = e.clientX - panStartX; panY = e.clientY - panStartY; applyTransform(); } });
        window.addEventListener('mouseup', e => { if(e.button===2) isPanning = false; });

        mapContainer.addEventListener('touchstart', e => {
            if (isMobile() && mobileDrawingActive) return; 
            if (e.touches.length === 1) {
                if (e.target.closest('.placed-token')) return;
                isTouchPanning = true; touchPanStartX = e.touches[0].clientX - panX; touchPanStartY = e.touches[0].clientY - panY;
            } else if (e.touches.length === 2) {
                isTouchPanning = false; e.preventDefault(); const rect = mapContainer.getBoundingClientRect();
                initialPinchDist = Math.hypot(e.touches[0].clientX - e.touches[1].clientX, e.touches[0].clientY - e.touches[1].clientY);
                initialPinchZoom = zoomLevel; startTouchCenterX = (e.touches[0].clientX + e.touches[1].clientX) / 2 - rect.left; startTouchCenterY = (e.touches[0].clientY + e.touches[1].clientY) / 2 - rect.top;
                startPanX = panX; startPanY = panY;
            }
        }, { passive: false });

        mapContainer.addEventListener('touchmove', e => {
            if (isMobile() && mobileDrawingActive) return;
            if (e.touches.length === 1 && isTouchPanning) { panX = e.touches[0].clientX - touchPanStartX; panY = e.touches[0].clientY - touchPanStartY; applyTransform(); } 
            else if (e.touches.length === 2) {
                e.preventDefault(); const rect = mapContainer.getBoundingClientRect();
                const dist = Math.hypot(e.touches[0].clientX - e.touches[1].clientX, e.touches[0].clientY - e.touches[1].clientY);
                const newZoom = Math.max(0.3, Math.min(3.0, initialPinchZoom * (dist / initialPinchDist)));
                const currentCenterX = (e.touches[0].clientX + e.touches[1].clientX) / 2 - rect.left; const currentCenterY = (e.touches[0].clientY + e.touches[1].clientY) / 2 - rect.top;
                panX = currentCenterX - ((startTouchCenterX - startPanX) / initialPinchZoom) * newZoom; panY = currentCenterY - ((startTouchCenterY - startPanY) / initialPinchZoom) * newZoom;
                zoomLevel = newZoom; applyTransform();
            }
        }, { passive: false });
        window.addEventListener('touchend', () => { isTouchPanning = false; });

        function getBoardCoords(clientX, clientY) { const rect = board.getBoundingClientRect(); let x = (clientX - rect.left) / zoomLevel; let y = (clientY - rect.top) / zoomLevel; return { x, y }; }

        function placeTokenAt(data, x, y) {
            const token = document.createElement('div'); token.className = 'placed-token'; token.dataset.id = 'tk_' + Date.now() + Math.random().toString(36).substr(2, 5);
            let size = 35;
            if(data.type === 'brawler') { token.classList.add('placed-brawler'); token.dataset.brawlerId = data.brawlerId; token.dataset.team = data.team; token.style.borderColor = data.team === 'ally' ? '#0984e3' : '#e74c3c'; }
            else if(data.type === 'gadget') { token.classList.add('placed-gadget'); size = 25; }
            else if(data.type === 'ball') { token.classList.add('placed-ball'); size = 25; }
            else { token.classList.add('placed-gamebutton'); size = 32; }
            token.style.backgroundImage = `url('${data.img}')`; token.style.width = size+'px'; token.style.height = size+'px'; token.style.left = (x - size/2)+'px'; token.style.top = (y - size/2)+'px';
            const resizer = document.createElement('div'); resizer.className = 'resizer'; token.appendChild(resizer); makeResizable(token, resizer); makeDraggable(token, board);
            token.addEventListener('click', (e) => { e.stopPropagation(); if(data.type === 'brawler') { document.querySelectorAll('.placed-brawler').forEach(el => el.classList.remove('selected')); token.classList.add('selected'); loadOptionsPanel(data.brawlerId); if(isMobile()) switchMobileTab('right-sidebar', document.querySelectorAll('.mtab')[1]); } });
            token.addEventListener('dblclick', () => token.remove()); board.appendChild(token);
        }

        function allowDrop(ev) { ev.preventDefault(); }
        function drop(ev) {
            ev.preventDefault(); if(!currentDraggedData || isPlaying) return; let clientX = ev.clientX, clientY = ev.clientY;
            if(ev.changedTouches && ev.changedTouches.length > 0) { clientX = ev.changedTouches[0].clientX; clientY = ev.changedTouches[0].clientY; }
            const coords = getBoardCoords(clientX, clientY); if(coords.x < 0 || coords.x > 750 || coords.y < 0 || coords.y > 750) return;
            placeTokenAt(currentDraggedData, coords.x, coords.y); currentDraggedData = null;
        }

        let mobileTouchStartX = 0, mobileTouchStartY = 0, mobileTouchStartTime = 0;
        board.addEventListener('touchstart', (e) => {
            if (!isMobile() || isPlaying || !pendingMobileData || mobileDrawingActive) return;
            if (e.touches.length === 1) { mobileTouchStartX = e.touches[0].clientX; mobileTouchStartY = e.touches[0].clientY; mobileTouchStartTime = Date.now(); }
        }, { passive: true });
        board.addEventListener('touchend', (e) => {
            if (!isMobile() || isPlaying || !pendingMobileData || mobileDrawingActive) return; 
            const diffX = Math.abs(e.changedTouches[0].clientX - mobileTouchStartX); const diffY = Math.abs(e.changedTouches[0].clientY - mobileTouchStartY);
            if ((Date.now() - mobileTouchStartTime) < 300 && diffX < 10 && diffY < 10) {
                if (e.target.closest('.placed-token')) return; 
                const coords = getBoardCoords(e.changedTouches[0].clientX, e.changedTouches[0].clientY);
                if(coords.x >= 0 && coords.x <= 750 && coords.y >= 0 && coords.y <= 750) { placeTokenAt(pendingMobileData, coords.x, coords.y); pendingMobileData = null; document.querySelectorAll('.mobile-selected').forEach(el => el.classList.remove('mobile-selected')); }
            }
        });

        function makeResizable(el, res) {
            res.addEventListener('mousedown', e => {
                e.stopPropagation(); let startX = e.clientX; let sW = parseFloat(getComputedStyle(el).width);
                function drag(ev) { let size = Math.max(15, sW + ((ev.clientX - startX) / zoomLevel)); el.style.width = size+'px'; el.style.height = size+'px'; }
                function stop() { document.removeEventListener('mousemove', drag); document.removeEventListener('mouseup', stop); }
                document.addEventListener('mousemove', drag); document.addEventListener('mouseup', stop);
            });
            res.addEventListener('touchstart', e => {
                e.stopPropagation(); e.preventDefault(); let startX = e.touches[0].clientX; let sW = parseFloat(getComputedStyle(el).width);
                function drag(ev) { let size = Math.max(15, sW + ((ev.touches[0].clientX - startX) / zoomLevel)); el.style.width = size+'px'; el.style.height = size+'px'; }
                function stop() { document.removeEventListener('touchmove', drag); document.removeEventListener('touchend', stop); }
                document.addEventListener('touchmove', drag, {passive: false}); document.addEventListener('touchend', stop);
            }, {passive: false});
        }

        function makeDraggable(el, b) {
            el.addEventListener('mousedown', e => {
                if(e.target.classList.contains('resizer') || isPlaying || e.button !== 0 || (isMobile() && mobileDrawingActive)) return; e.stopPropagation();
                let sX = e.clientX, sY = e.clientY, sL = parseFloat(el.style.left)||0, sT = parseFloat(el.style.top)||0;
                function move(ev) { el.style.left = (sL + (ev.clientX - sX)/zoomLevel)+'px'; el.style.top = (sT + (ev.clientY - sY)/zoomLevel)+'px'; }
                function stop(ev) { document.removeEventListener('mousemove', move); document.removeEventListener('mouseup', stop); const r = b.getBoundingClientRect(); if(ev.clientX < r.left || ev.clientX > r.right || ev.clientY < r.top || ev.clientY > r.bottom) el.remove(); }
                document.addEventListener('mousemove', move); document.addEventListener('mouseup', stop);
            });
            el.addEventListener('touchstart', e => {
                if(e.target.classList.contains('resizer') || isPlaying || e.touches.length > 1 || (isMobile() && mobileDrawingActive)) return; e.stopPropagation();
                let t = e.touches[0]; let sX = t.clientX, sY = t.clientY, sL = parseFloat(el.style.left)||0, sT = parseFloat(el.style.top)||0;
                function move(ev) { ev.preventDefault(); let touchMove = ev.touches[0]; el.style.left = (sL + (touchMove.clientX - sX)/zoomLevel)+'px'; el.style.top = (sT + (touchMove.clientY - sY)/zoomLevel)+'px'; }
                function stop(ev) { document.removeEventListener('touchmove', move); document.removeEventListener('touchend', stop); const r = b.getBoundingClientRect(); let touchEnd = ev.changedTouches[0]; if(touchEnd.clientX < r.left || touchEnd.clientX > r.right || touchEnd.clientY < r.top || touchEnd.clientY > r.bottom) el.remove(); }
                document.addEventListener('touchmove', move, {passive: false}); document.addEventListener('touchend', stop);
            }, {passive: false});
        }

        function addKeyframe() {
            const currentTokens = []; document.querySelectorAll('.placed-token').forEach(el => { currentTokens.push({ id: el.dataset.id, className: el.className, brawlerId: el.dataset.brawlerId, team: el.dataset.team, backgroundImage: el.style.backgroundImage, width: el.style.width, height: el.style.height, left: el.style.left, top: el.style.top }); });
            keyframes.push(currentTokens); renderTimeline(); document.querySelectorAll('.placed-gadget, .placed-gamebutton').forEach(el => el.remove());
        }
        function renderTimeline() {
            const track = document.getElementById('timelineTrack'); if(keyframes.length === 0) { track.innerHTML = `<span style="color:#666; font-size:12px; margin-left:5px;">Aucun point clé ajouté.</span>`; return; } track.innerHTML = '';
            keyframes.forEach((kf, index) => { const badge = document.createElement('div'); badge.className = 'kf-badge'; badge.innerHTML = `Point ${index + 1} <span class="delete-kf" onclick="deleteKeyframe(event, ${index})">×</span>`; badge.onclick = (e) => { if (e.target.classList.contains('delete-kf')) return; loadKeyframe(index); }; track.appendChild(badge); });
        }
        function deleteKeyframe(event, index) { event.stopPropagation(); keyframes.splice(index, 1); renderTimeline(); }
        function clearTimeline() { keyframes = []; renderTimeline(); stopAnimation(); }

        function loadKeyframe(index, isAnimating = false) {
            if (index < 0 || index >= keyframes.length) return; const currentKf = keyframes[index]; const currentKfIds = currentKf.map(t => t.id);
            if (!isAnimating) clearTokens(); else { document.querySelectorAll('.placed-token').forEach(el => { if (!currentKfIds.includes(el.dataset.id)) el.remove(); }); }
            currentKf.forEach(t => {
                let token = isAnimating ? document.querySelector(`.placed-token[data-id="${t.id}"]`) : null;
                if (!token) {
                    token = document.createElement('div'); token.className = t.className; token.classList.remove('selected'); token.dataset.id = t.id;
                    if (t.brawlerId) token.dataset.brawlerId = t.brawlerId; 
                    if (t.team) { token.dataset.team = t.team; token.style.borderColor = (t.team === 'ally') ? '#0984e3' : '#e74c3c'; }
                    token.style.backgroundImage = t.backgroundImage; token.style.width = t.width; token.style.height = t.height; token.style.left = t.left; token.style.top = t.top;
                    const resizer = document.createElement('div'); resizer.className = 'resizer'; token.appendChild(resizer); makeResizable(token, resizer); makeDraggable(token, board);
                    token.addEventListener('click', (e) => { e.stopPropagation(); if(token.classList.contains('placed-brawler')) { document.querySelectorAll('.placed-brawler').forEach(el => el.classList.remove('selected')); token.classList.add('selected'); loadOptionsPanel(token.dataset.brawlerId); } });
                    token.addEventListener('dblclick', () => token.remove()); board.appendChild(token);
                } else { token.style.left = t.left; token.style.top = t.top; token.style.width = t.width; token.style.height = t.height; }
            });
            document.querySelectorAll('.kf-badge').forEach((badge, i) => { badge.classList.toggle('active', i === index); });
        }

        function playAnimation(onComplete = null) {
            if (keyframes.length === 0) return; if (isPlaying) { stopAnimation(); return; }
            isPlaying = true; document.getElementById('playBtn').innerText = "⏸ Pause"; currentPlayIndex = 0; board.classList.remove('playing-animation'); loadKeyframe(currentPlayIndex, false);
            playbackInterval = setTimeout(() => { if (!isPlaying) return; board.classList.add('playing-animation'); currentPlayIndex++; nextStep(); }, 2000); 
            function nextStep() { if (!isPlaying) return; if (currentPlayIndex >= keyframes.length) { stopAnimation(); if(typeof onComplete === 'function') onComplete(); return; } loadKeyframe(currentPlayIndex, true); currentPlayIndex++; playbackInterval = setTimeout(nextStep, 3000); }
        }
        function stopAnimation() { isPlaying = false; if (playbackInterval) clearTimeout(playbackInterval); document.getElementById('playBtn').innerText = "▶ Lire"; board.classList.remove('playing-animation'); }

        function loadOptionsPanel(id) {
            const b = allBrawlers.find(x => x.id == id); if(!b) return; const p = document.getElementById('gadget-panel');
            p.innerHTML = `<strong style="color:white; font-size:18px;">${b.name}</strong><br><hr style="border-color:#333"><small>Actions</small><div class="gadget-list" id="act-list"></div>` + (b.gadgets.length > 0 ? `<hr style="border-color:#333"><small>Gadgets</small><div class="gadget-list" id="g-list"></div>` : '') + `<hr style="border-color:#333"><small>Hypercharge</small><div class="gadget-list" id="hc-list"></div>`;
            document.getElementById('act-list').append(createGameUiButton(UI_ICONS.attack, 'attack'), createGameUiButton(UI_ICONS.super, 'super'));
            if(b.gadgets.length > 0) b.gadgets.forEach(g => { if(g.imageUrl) document.getElementById('g-list').appendChild(createGadgetToken(g.imageUrl)); });
            document.getElementById('hc-list').appendChild(createGameUiButton(b.hypercharges.length ? b.hypercharges[0].imageUrl : UI_ICONS.hypercharge, 'hypercharge'));
        }

        function createGameUiButton(url, action) { const d = document.createElement('div'); d.className = 'game-ui-btn'; d.style.backgroundImage = `url('${url}')`; d.style.backgroundColor = action === 'attack' ? '#e74c3c' : (action === 'super' ? '#f1c40f' : '#9b59b6'); bindTokenEvents(d, { type: "game_ui", img: url, action }); return d; }
        function createGadgetToken(url) { const d = document.createElement('div'); d.className = 'gadget-token'; d.style.backgroundImage = `url('${url}')`; bindTokenEvents(d, { type: "gadget", img: url }); return d; }
    </script>
</body>
</html>