File size: 29,421 Bytes
7428b13
 
 
a46ce65
7428b13
 
4c208f2
6530b95
a6cc65f
d871370
e8aa797
a46ce65
7428b13
 
 
 
 
c61508c
7428b13
4c208f2
 
 
 
 
 
7428b13
 
 
 
4c208f2
7428b13
 
 
9774b79
 
 
 
 
 
 
0cf8fa8
 
 
 
 
 
4c208f2
7428b13
 
 
81b3c3b
 
 
 
 
e40394b
 
b1c7f35
 
81b3c3b
e8aa797
 
 
 
 
 
 
 
 
a6cc65f
7428b13
4c208f2
6530b95
 
4c208f2
 
6530b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c208f2
 
7428b13
 
9774b79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7428b13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a46ce65
4c208f2
 
7428b13
 
 
4c208f2
 
 
 
 
 
 
 
 
 
74f8c2c
 
 
4c208f2
a46ce65
 
 
8f5f6c9
 
 
4c208f2
8f5f6c9
4c208f2
a46ce65
8f5f6c9
 
 
5d91440
 
 
8f5f6c9
0cf8fa8
4c208f2
0cf8fa8
4c208f2
 
a46ce65
 
4c208f2
 
 
 
0cf8fa8
4c208f2
a46ce65
9774b79
 
0cf8fa8
9774b79
e8aa797
6530b95
 
 
 
 
 
 
0cf8fa8
 
 
 
a46ce65
566cdc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a46ce65
4c208f2
 
 
 
 
 
a46ce65
 
4c208f2
81b3c3b
94e4b64
 
 
81b3c3b
5c9dd93
b1c7f35
94e4b64
b1c7f35
94e4b64
b1c7f35
 
 
 
5c9dd93
81b3c3b
94e4b64
81b3c3b
5529e9d
94e4b64
81b3c3b
5529e9d
81b3c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94e4b64
81b3c3b
 
94e4b64
81b3c3b
 
94e4b64
81b3c3b
 
94e4b64
81b3c3b
 
94e4b64
81b3c3b
 
 
 
 
94e4b64
81b3c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94e4b64
81b3c3b
5529e9d
 
81b3c3b
 
 
 
 
 
e40394b
9774b79
 
81b3c3b
 
 
 
 
e40394b
81b3c3b
 
e40394b
 
 
 
 
 
 
 
 
 
 
81b3c3b
 
 
b1c7f35
 
 
 
 
 
 
 
 
 
81b3c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
566cdc0
 
 
 
 
 
 
 
 
 
5c9dd93
566cdc0
 
5c9dd93
 
 
 
 
566cdc0
 
74f8c2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
566cdc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c9dd93
 
 
 
 
566cdc0
 
 
4c208f2
 
a46ce65
566cdc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c208f2
 
 
 
7428b13
 
 
4c208f2
 
7428b13
6530b95
4c208f2
6530b95
 
 
 
 
 
 
 
9774b79
366ca7a
9774b79
 
 
 
 
 
 
 
366ca7a
6530b95
 
 
 
 
 
 
74f8c2c
 
 
6530b95
 
 
 
366ca7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6530b95
 
 
 
5d91440
 
 
6530b95
0cf8fa8
6530b95
0cf8fa8
6530b95
 
 
4c208f2
6530b95
 
 
4c208f2
0cf8fa8
6530b95
 
9774b79
 
0cf8fa8
9774b79
6530b95
 
 
 
 
 
 
 
0cf8fa8
 
 
 
6530b95
 
 
 
 
 
4c208f2
6530b95
 
 
 
 
7428b13
 
 
 
 
e8aa797
 
 
 
 
 
82b6f62
 
 
 
 
 
 
e8aa797
82b6f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8aa797
82b6f62
e8aa797
 
 
 
 
 
 
 
7428b13
 
90a88fc
7428b13
90a88fc
7428b13
 
 
 
 
 
 
 
4c208f2
 
7428b13
 
 
4c208f2
81b3c3b
 
 
 
e40394b
 
b1c7f35
 
9774b79
 
 
 
 
 
7428b13
 
 
 
 
 
 
 
4c208f2
 
c61508c
4c208f2
566cdc0
7428b13
 
 
 
566cdc0
7428b13
 
e8aa797
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7428b13
 
 
 
90a88fc
 
 
7428b13
 
 
 
 
e95e2d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7428b13
 
 
afa3e65
7428b13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e95e2d9
 
7428b13
e8aa797
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7428b13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
<script lang="ts">
  import { onMount } from 'svelte';
  import { fade } from 'svelte/transition';
  import type { PicletInstance, BattleMove } from '$lib/db/schema';
  import BattleField from '../Battle/BattleField.svelte';
  import BattleControls from '../Battle/BattleControls.svelte';
  import { BattleEngine } from '$lib/battle-engine/BattleEngine';
  import type { BattleState, MoveAction, SwitchAction } from '$lib/battle-engine/types';
  import { picletInstanceToBattleDefinition, battlePicletToInstance, stripBattlePrefix } from '$lib/utils/battleConversion';
  import { calculateBattleXp, processAllLevelUps } from '$lib/services/levelingService';
  import { db } from '$lib/db/index';
  import { getEffectivenessText, getEffectivenessColor } from '$lib/types/picletTypes';
  
  export let playerPiclet: PicletInstance;
  export let enemyPiclet: PicletInstance;
  export let isWildBattle: boolean = true;
  export let onBattleEnd: (result: any) => void = () => {};
  export let rosterPiclets: PicletInstance[] = []; // All roster piclets passed from parent
  
  // Initialize battle engine
  let battleEngine: BattleEngine;
  let battleState: BattleState;
  let currentPlayerPiclet = playerPiclet;
  let currentEnemyPiclet = enemyPiclet;
  
  // Battle state
  let currentMessage = isWildBattle 
    ? `A wild ${enemyPiclet.nickname} appeared!` 
    : `Trainer wants to battle!`;
  let battlePhase: 'intro' | 'main' | 'moveSelect' | 'picletSelect' | 'ended' = 'intro';  
  let processingTurn = false;
  let battleEnded = false;
  
  // Trainer animation states
  let showWhiteFlash = false;
  let playerTrainerVisible = false;
  let enemyTrainerVisible = false;
  let playerTrainerSlideOut = false;
  let enemyTrainerSlideOut = false;
  
  // Message progression system
  let waitingForContinue = false;
  let messageQueue: string[] = [];
  let currentMessageIndex = 0;
  let continueCallback: (() => void) | null = null;
  
  // HP animation states  
  let playerHpPercentage = playerPiclet.currentHp / playerPiclet.maxHp;
  let enemyHpPercentage = enemyPiclet.currentHp / enemyPiclet.maxHp;
  
  // Visual effects state
  let playerEffects: Array<{type: string, emoji: string, duration: number}> = [];
  let enemyEffects: Array<{type: string, emoji: string, duration: number}> = [];
  let playerFlash = false;
  let enemyFlash = false;
  let playerFaint = false;
  let enemyFaint = false;
  let playerLunge = false;
  let enemyLunge = false;
  
  // Battle results state
  let battleResultsVisible = false;
  let battleResults = {
    victory: false,
    xpGained: 0,
    levelUps: [],
    newLevel: 0
  };
  
  
  onMount(() => {
    // Initialize battle engine with converted piclet definitions
    // Convert full roster for switching support
    const playerRosterDefinitions = rosterPiclets.map(p => picletInstanceToBattleDefinition(p));
    const enemyDefinition = picletInstanceToBattleDefinition(enemyPiclet);
    
    // Find the starting player piclet index in the roster
    const startingPlayerIndex = rosterPiclets.findIndex(p => p.id === playerPiclet.id);
    
    // Initialize with full rosters (player roster vs single enemy)
    battleEngine = new BattleEngine(playerRosterDefinitions, enemyDefinition, playerPiclet.level, enemyPiclet.level);
    
    // If starting piclet is not the first in roster, switch to it
    if (startingPlayerIndex > 0) {
      const initialSwitchAction: SwitchAction = {
        type: 'switch',
        piclet: 'player',
        newPicletIndex: startingPlayerIndex
      };
      battleEngine.executeAction(initialSwitchAction, 'player');
    }
    
    battleState = battleEngine.getState();
    
    // Start intro sequence
    setTimeout(() => {
      if (!isWildBattle) {
        // Enemy trainer sends out first
        currentMessage = `Go, ${enemyPiclet.nickname}!`;
        enemyTrainerSlideOut = true;
        setTimeout(() => {
          currentMessage = `Go, ${playerPiclet.nickname}!`;
          playerTrainerSlideOut = true;
          setTimeout(() => {
            currentMessage = `What will ${playerPiclet.nickname} do?`;
            battlePhase = 'main';
          }, 2000); // Wait for trainer slide + flash + monster appear
        }, 2000); // Wait for enemy trainer sequence
      } else {
        // Wild battle - player sends out
        currentMessage = `Go, ${playerPiclet.nickname}!`;
        playerTrainerSlideOut = true;
        setTimeout(() => {
          currentMessage = `What will ${playerPiclet.nickname} do?`;
          battlePhase = 'main';
        }, 2000); // Wait for trainer slide + flash + monster appear
      }
    }, 2000);
  });
  
  function handleAction(action: string) {
    if (processingTurn || battleEnded) return;
    
    switch (action) {
      case 'catch':
        if (isWildBattle) {
          processingTurn = true;
          currentMessage = 'You threw a Piclet Ball!';
          setTimeout(() => {
            currentMessage = 'The wild piclet broke free!';
            processingTurn = false;
          }, 2000);
        }
        break;
      case 'run':
        if (isWildBattle) {
          currentMessage = 'Got away safely!';
          battleEnded = true;
          setTimeout(() => onBattleEnd(false), 1500);
        } else {
          currentMessage = "You can't run from a trainer battle!";
        }
        break;
    }
  }
  
  function handleMoveSelect(move: BattleMove) {
    if (!battleEngine) return;
    
    battlePhase = 'main';
    processingTurn = true;
    
    // Find the corresponding move in the battle engine
    const battleMove = battleState.playerPiclet.moves.find(m => m.move.name === move.name);
    if (!battleMove) return;
    
    const moveAction: MoveAction = {
      type: 'move',
      moveIndex: battleState.playerPiclet.moves.indexOf(battleMove)
    };
    
    try {
      // Select enemy move (wild Piclets always random, trainers could use AI)
      const enemyAction = selectEnemyMove();
      if (!enemyAction) {
        processingTurn = false;
        return;
      }
      
      // Get log entries before action to track new messages
      const logBefore = battleEngine.getLog();
      
      // Execute the turn - battle engine handles priority automatically
      battleEngine.executeActions(moveAction, enemyAction);
      battleState = battleEngine.getState();
      
      // Get only the new log entries from this turn
      const logAfter = battleEngine.getLog();
      const newLogEntries = logAfter.slice(logBefore.length);
      // Filter out faint messages since we handle them manually for proper sequencing
      const filteredLogEntries = newLogEntries.filter(message => !message.includes('fainted'));
      const result = { log: filteredLogEntries };
      
      // Show battle messages with tap-to-continue system
      if (result.log && result.log.length > 0) {
        showMessageSequence(result.log, finalizeTurn);
      } else {
        finalizeTurn();
      }
      
      function finalizeTurn() {
        // Update UI state from battle engine
        updateUIFromBattleState();
        
        // Check for battle end - only show faint message
        if (battleState.winner) {
          battleEnded = true;
          const defeatedPiclet = battleState.winner === 'player' ? currentEnemyPiclet : currentPlayerPiclet;
          
          // Show the faint message and trigger animation
          currentMessage = `${defeatedPiclet.nickname} fainted!`;
          
          // Trigger faint animation for the defeated Piclet
          if (battleState.winner === 'player') {
            enemyFaint = true;
          } else {
            playerFaint = true;
          }
          
          // Wait for faint message, then process battle results
          setTimeout(async () => {
            await handleBattleResults(battleState.winner === 'player');
          }, 2500); // Wait time for faint message and animation
        } else {
          // Check if player Piclet switched due to fainting
          const newPlayerPiclet = battlePicletToInstance(battleState.playerPiclet, currentPlayerPiclet);
          const playerPicletChanged = currentPlayerPiclet.id !== newPlayerPiclet.id;
          
          if (playerPicletChanged) {
            // Player Piclet fainted and auto-switched - show faint message first
            const faintedPiclet = currentPlayerPiclet;
            currentMessage = `${faintedPiclet.nickname} fainted!`;
            playerFaint = true;
            
            // Wait for faint message, then show switch and continue
            setTimeout(() => {
              currentMessage = `Go, ${newPlayerPiclet.nickname}!`;
              // updateUIFromBattleState will handle the white flash transition
              setTimeout(() => {
                currentMessage = `What will ${currentPlayerPiclet.nickname} do?`;
                processingTurn = false;
              }, 1000);
            }, 2500);
          } else {
            // Normal turn end - no faint or switch
            setTimeout(() => {
              currentMessage = `What will ${currentPlayerPiclet.nickname} do?`;
              processingTurn = false;
            }, 1000);
          }
        }
      }
    } catch (error) {
      console.error('Battle engine error:', error);
      currentMessage = 'Something went wrong in battle!';
      processingTurn = false;
    }
  }
  
  
  function triggerVisualEffectsFromMessage(message: string) {
    // Use stripped names since battle messages no longer have prefixes
    const playerName = stripBattlePrefix(battleState?.playerPiclet?.definition?.name || '');
    const enemyName = stripBattlePrefix(battleState?.opponentPiclet?.definition?.name || '');
    
    // Attack lunge effects - trigger immediately when a Piclet uses a move
    if (message.includes(' used ')) {
      if (message.includes(playerName)) {
        triggerLungeAnimation('player');
      } else if (message.includes(enemyName)) {
        triggerLungeAnimation('enemy');
      }
    }
    
    // Damage flash effects - trigger when damage is taken
    if (message.includes('took') && message.includes('damage')) {
      if (message.includes(playerName)) {
        triggerDamageFlash('player');
        updateUIFromBattleState();
      } else if (message.includes(enemyName)) {
        triggerDamageFlash('enemy');
        updateUIFromBattleState();
      }
    }
    
    // Critical hit effects
    if (message.includes('critical hit')) {
      triggerEffect('both', 'critical', 'πŸ’₯', 1000);
    }
    
    // Effectiveness messages
    if (message.includes("It's super effective")) {
      triggerEffect('both', 'superEffective', '⚑', 800);
    } else if (message.includes("not very effective")) {
      triggerEffect('both', 'notVeryEffective', 'πŸ’¨', 800);
    }
    
    // Status effects
    if (message.includes('was burned')) {
      const target = message.includes(playerName) ? 'player' : 'enemy';
      triggerEffect(target, 'burn', 'πŸ”₯', 1200);
    } else if (message.includes('was poisoned')) {
      const target = message.includes(playerName) ? 'player' : 'enemy';
      triggerEffect(target, 'poison', '☠️', 1200);
    } else if (message.includes('was paralyzed')) {
      const target = message.includes(playerName) ? 'player' : 'enemy';
      triggerEffect(target, 'paralyze', '⚑', 1200);
    } else if (message.includes('fell asleep')) {
      const target = message.includes(playerName) ? 'player' : 'enemy';
      triggerEffect(target, 'sleep', '😴', 1200);
    } else if (message.includes('was frozen')) {
      const target = message.includes(playerName) ? 'player' : 'enemy';
      triggerEffect(target, 'freeze', '❄️', 1200);
    }
    
    // Stat changes
    if (message.includes("'s") && (message.includes('rose') || message.includes('fell'))) {
      const target = message.includes(playerName) ? 'player' : 'enemy';
      const isIncrease = message.includes('rose');
      
      if (message.includes('attack')) {
        triggerEffect(target, isIncrease ? 'attackUp' : 'attackDown', isIncrease ? 'βš”οΈ' : 'πŸ”»', 1000);
      } else if (message.includes('defense')) {
        triggerEffect(target, isIncrease ? 'defenseUp' : 'defenseDown', isIncrease ? 'πŸ›‘οΈ' : 'πŸ”»', 1000);
      } else if (message.includes('speed')) {
        triggerEffect(target, isIncrease ? 'speedUp' : 'speedDown', isIncrease ? 'πŸ’¨' : '🐌', 1000);
      } else if (message.includes('accuracy')) {
        triggerEffect(target, isIncrease ? 'accuracyUp' : 'accuracyDown', isIncrease ? '🎯' : 'πŸ‘οΈ', 1000);
      }
    }
    
    // Healing effects
    if (message.includes('recovered') && message.includes('HP')) {
      const target = message.includes(playerName) ? 'player' : 'enemy';
      triggerEffect(target, 'heal', 'πŸ’š', 1000);
      // Update HP bar immediately for healing animation sync
      updateUIFromBattleState();
    }
    
    // Miss effects
    if (message.includes('missed')) {
      triggerEffect('both', 'miss', 'πŸ’«', 800);
    }
    
    // Faint effects - only trigger when we see the faint message from battle log
    // Don't trigger here since we handle it in finalizeTurn for proper sequencing
  }
  
  function triggerDamageFlash(target: 'player' | 'enemy') {
    if (target === 'player') {
      playerFlash = true;
      setTimeout(() => playerFlash = false, 1000); // Match original Snaplings flicker duration
    } else {
      enemyFlash = true;
      setTimeout(() => enemyFlash = false, 1000); // Match original Snaplings flicker duration
    }
  }
  
  function triggerFaintAnimation(target: 'player' | 'enemy') {
    if (target === 'player') {
      playerFaint = true;
      // Don't reset - faint animation should persist until battle ends
    } else {
      enemyFaint = true;
      // Don't reset - faint animation should persist until battle ends
    }
  }
  
  function triggerLungeAnimation(target: 'player' | 'enemy') {
    if (target === 'player') {
      playerLunge = true;
      setTimeout(() => playerLunge = false, 600); // Reset after animation
    } else {
      enemyLunge = true;
      setTimeout(() => enemyLunge = false, 600); // Reset after animation
    }
  }
  
  function triggerEffect(target: 'player' | 'enemy' | 'both', type: string, emoji: string, duration: number) {
    const effect = { type, emoji, duration };
    
    if (target === 'player' || target === 'both') {
      playerEffects = [...playerEffects, effect];
      setTimeout(() => {
        playerEffects = playerEffects.filter(e => e !== effect);
      }, duration);
    }
    
    if (target === 'enemy' || target === 'both') {
      enemyEffects = [...enemyEffects, effect];
      setTimeout(() => {
        enemyEffects = enemyEffects.filter(e => e !== effect);
      }, duration);
    }
  }

  function showMessageSequence(messages: string[], callback: () => void) {
    if (!messages || messages.length === 0) {
      callback();
      return;
    }
    
    messageQueue = messages;
    currentMessageIndex = 0;
    continueCallback = callback;
    
    // Show first message and trigger its effects
    currentMessage = messageQueue[0];
    waitingForContinue = true;
    
    // Trigger visual effects automatically after text appears (with small delay for text animation)
    setTimeout(() => {
      triggerVisualEffectsFromMessage(currentMessage);
    }, 500); // Allow time for typewriter text to complete
  }
  
  function selectEnemyMove(): MoveAction | null {
    const availableEnemyMoves = battleState.opponentPiclet.moves.filter(m => m.currentPP > 0);
    
    if (availableEnemyMoves.length === 0) {
      currentMessage = `${currentEnemyPiclet.nickname} has no moves left!`;
      return null;
    }
    
    if (isWildBattle) {
      // Wild Piclets always use completely random moves (no trainer strategy)
      const randomEnemyMove = availableEnemyMoves[Math.floor(Math.random() * availableEnemyMoves.length)];
      const enemyMoveIndex = battleState.opponentPiclet.moves.indexOf(randomEnemyMove);
      
      return {
        type: 'move', 
        moveIndex: enemyMoveIndex
      };
    } else {
      // Trainer battles - currently also random, but could be enhanced with AI later
      const randomEnemyMove = availableEnemyMoves[Math.floor(Math.random() * availableEnemyMoves.length)];
      const enemyMoveIndex = battleState.opponentPiclet.moves.indexOf(randomEnemyMove);
      
      return {
        type: 'move', 
        moveIndex: enemyMoveIndex
      };
    }
  }

  function handleContinueTap() {
    if (!waitingForContinue || !messageQueue.length) return;
    
    currentMessageIndex++;
    
    if (currentMessageIndex >= messageQueue.length) {
      // Sequence finished
      waitingForContinue = false;
      messageQueue = [];
      currentMessageIndex = 0;
      
      if (continueCallback) {
        continueCallback();
        continueCallback = null;
      }
    } else {
      // Show next message
      currentMessage = messageQueue[currentMessageIndex];
      
      // Trigger visual effects automatically after text appears
      setTimeout(() => {
        triggerVisualEffectsFromMessage(currentMessage);
      }, 500); // Allow time for typewriter text to complete
    }
  }

  function updateUIFromBattleState() {
    if (!battleState) return;
    
    // Check if player Piclet has changed (indicating auto-switch due to fainting)
    const newPlayerPiclet = battlePicletToInstance(battleState.playerPiclet, currentPlayerPiclet);
    const playerPicletChanged = currentPlayerPiclet.id !== newPlayerPiclet.id;
    
    if (playerPicletChanged) {
      // Player Piclet auto-switched due to fainting - show transition
      showWhiteFlash = true;
      setTimeout(() => {
        currentPlayerPiclet = newPlayerPiclet;
        playerHpPercentage = battleState.playerPiclet.currentHp / battleState.playerPiclet.maxHp;
        showWhiteFlash = false;
      }, 300);
    } else {
      // Normal update without switch
      currentPlayerPiclet = newPlayerPiclet;
      playerHpPercentage = battleState.playerPiclet.currentHp / battleState.playerPiclet.maxHp;
    }
    
    // Update enemy piclet state  
    currentEnemyPiclet = battlePicletToInstance(battleState.opponentPiclet, currentEnemyPiclet);
    enemyHpPercentage = battleState.opponentPiclet.currentHp / battleState.opponentPiclet.maxHp;
  }
  
  function handlePicletSelect(piclet: PicletInstance) {
    if (!battleEngine) return;
    
    battlePhase = 'main';
    processingTurn = true;
    
    // Find the index of the selected piclet in the roster
    const picletIndex = rosterPiclets.findIndex(p => p.id === piclet.id);
    if (picletIndex === -1) {
      console.error('Selected piclet not found in roster');
      processingTurn = false;
      return;
    }
    
    // Show the switch message and trigger white flash animation
    currentMessage = `Go, ${piclet.nickname}!`;
    showWhiteFlash = true;
    
    // After flash, update display
    setTimeout(() => {
      currentPlayerPiclet = piclet;
      playerHpPercentage = piclet.currentHp / piclet.maxHp;
      showWhiteFlash = false;
    }, 300);
    
    const switchAction: SwitchAction = {
      type: 'switch',
      piclet: 'player',
      newPicletIndex: picletIndex
    };
    
    try {
      // Select enemy move (wild Piclets always random, trainers could use AI)
      const enemyAction = selectEnemyMove();
      if (!enemyAction) {
        processingTurn = false;
        return;
      }
      
      // Allow time for the visual switch to be seen before processing the turn
      setTimeout(() => {
        // Get log entries before action to track new messages
        const logBefore = battleEngine.getLog();
        
        // Execute the turn - switching vs enemy move
        battleEngine.executeActions(switchAction, enemyAction);
        battleState = battleEngine.getState();
        
        processAfterSwitchTurn(logBefore);
      }, 1000); // 1 second delay to show the switch visually
    } catch (error) {
      console.error('Battle engine error:', error);
      currentMessage = 'Unable to switch Piclets!';
      processingTurn = false;
    }
  }
  
  function processAfterSwitchTurn(logBefore: string[]) {
    try {
      
      // Get only the new log entries from this turn
      const logAfter = battleEngine.getLog();
      const newLogEntries = logAfter.slice(logBefore.length);
      // Filter out faint messages since we handle them manually for proper sequencing
      const filteredLogEntries = newLogEntries.filter(message => !message.includes('fainted'));
      const result = { log: filteredLogEntries };
      
      // Show battle messages with tap-to-continue system
      if (result.log && result.log.length > 0) {
        showMessageSequence(result.log, finalizeSwitchTurn);
      } else {
        finalizeSwitchTurn();
      }
      
      function finalizeSwitchTurn() {
        // Update UI state from battle engine
        updateUIFromBattleState();
        
        // Check for battle end - only show faint message
        if (battleState.winner) {
          battleEnded = true;
          const defeatedPiclet = battleState.winner === 'player' ? currentEnemyPiclet : currentPlayerPiclet;
          
          // Show the faint message and trigger animation
          currentMessage = `${defeatedPiclet.nickname} fainted!`;
          
          // Trigger faint animation for the defeated Piclet
          if (battleState.winner === 'player') {
            enemyFaint = true;
          } else {
            playerFaint = true;
          }
          
          // Wait for faint message, then process battle results
          setTimeout(async () => {
            await handleBattleResults(battleState.winner === 'player');
          }, 2500); // Wait time for faint message and animation
        } else {
          setTimeout(() => {
            currentMessage = `What will ${currentPlayerPiclet.nickname} do?`;
            processingTurn = false;
          }, 1000);
        }
      }
    } catch (error) {
      console.error('Switch error:', error);
      currentMessage = 'Unable to switch Piclets!';
      processingTurn = false;
    }
  }
  
  function handleBack() {
    battlePhase = 'main';
  }
  
  async function handleBattleResults(playerWon: boolean) {
    if (playerWon) {
      // Calculate XP gained from defeating the enemy
      const xpGained = calculateBattleXp(currentEnemyPiclet, 1);
      
      if (xpGained > 0) {
        // Animate XP gain by updating UI first
        const updatedPlayerPiclet = {
          ...currentPlayerPiclet,
          xp: currentPlayerPiclet.xp + xpGained
        };
        currentPlayerPiclet = updatedPlayerPiclet;
        
        // Wait a moment for XP bar animation
        await new Promise(resolve => setTimeout(resolve, 1500));
        
        // Process any level ups
        const { newInstance, levelUpInfo } = processAllLevelUps(updatedPlayerPiclet);
        
        // Save updated Piclet to database
        if (newInstance.id) {
          await db.picletInstances.update(newInstance.id, newInstance);
        }
        
        // Update local state with final leveled instance
        currentPlayerPiclet = newInstance;
        
        // Show level up results if any occurred
        if (levelUpInfo.length > 0) {
          battleResults = {
            victory: true,
            xpGained,
            levelUps: levelUpInfo,
            newLevel: newInstance.level
          };
          
          battleResultsVisible = true;
          
          // Auto-dismiss after showing level up
          setTimeout(() => {
            battleResultsVisible = false;
            onBattleEnd(true);
          }, 4000);
        } else {
          // No level up, just end battle
          onBattleEnd(true);
        }
      } else {
        onBattleEnd(true);
      }
    } else {
      // Player lost - no XP gained
      onBattleEnd(false);
    }
  }
</script>

<div class="battle-page" transition:fade={{ duration: 300 }}>
  <nav class="battle-nav">
    <button class="back-button" on:click={() => onBattleEnd('cancelled')} style="display: none;">
      ← Back
    </button>
    <h1>{isWildBattle ? 'Wild Battle' : 'Battle'}</h1>
    <div class="nav-spacer"></div>
  </nav>
  
  <div class="battle-content">
    <BattleField 
      playerPiclet={currentPlayerPiclet}
      enemyPiclet={currentEnemyPiclet}
      {playerHpPercentage}
      {enemyHpPercentage}
      showIntro={battlePhase === 'intro'}
      {battleState}
      {playerEffects}
      {enemyEffects}
      {playerFlash}
      {enemyFlash}
      {playerFaint}
      {enemyFaint}
      {playerLunge}
      {enemyLunge}
      {isWildBattle}
      {showWhiteFlash}
      {playerTrainerVisible}
      {enemyTrainerVisible}
      {playerTrainerSlideOut}
      {enemyTrainerSlideOut}
    />
    
    <BattleControls
      {currentMessage}
      {battlePhase}
      {processingTurn}
      {battleEnded}
      {isWildBattle}
      playerPiclet={currentPlayerPiclet}
      enemyPiclet={currentEnemyPiclet}
      {rosterPiclets}
      {battleState}
      {waitingForContinue}
      onAction={handleAction}
      onMoveSelect={handleMoveSelect}
      onPicletSelect={handlePicletSelect}
      onBack={handleBack}
      onContinueTap={handleContinueTap}
    />
  </div>
  
  <!-- Battle Results Overlay -->
  {#if battleResultsVisible}
    <div class="battle-results-overlay" transition:fade={{ duration: 300 }}>
      <div class="battle-results-card">
        <h2>{battleResults.victory ? 'Victory!' : 'Defeat!'}</h2>
        
        
        {#if battleResults.levelUps.length > 0}
          {#each battleResults.levelUps as levelUp}
            <div class="level-up" transition:fade={{ duration: 500 }}>
              <h3>πŸŽ‰ Level Up! πŸŽ‰</h3>
              <p><strong>{currentPlayerPiclet.nickname}</strong> grew to level <strong>{levelUp.newLevel}</strong>!</p>
              
              <div class="stat-changes">
                {#if levelUp.statChanges.hp > 0}
                  <div class="stat-change">HP +{levelUp.statChanges.hp}</div>
                {/if}
                {#if levelUp.statChanges.attack > 0}
                  <div class="stat-change">Attack +{levelUp.statChanges.attack}</div>
                {/if}
                {#if levelUp.statChanges.defense > 0}
                  <div class="stat-change">Defense +{levelUp.statChanges.defense}</div>
                {/if}
                {#if levelUp.statChanges.speed > 0}
                  <div class="stat-change">Speed +{levelUp.statChanges.speed}</div>
                {/if}
              </div>
            </div>
          {/each}
        {/if}
      </div>
    </div>
  {/if}
</div>

<style>
  .battle-page {
    position: fixed;
    inset: 0;
    z-index: 1000;
    height: 100vh;
    display: flex;
    flex-direction: column;
    background: #f8f9fa;
    overflow: hidden;
    padding-top: env(safe-area-inset-top);
  }
  
  @media (max-width: 768px) {
    .battle-page {
      background: white;
    }
    
    .battle-page::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: env(safe-area-inset-top);
      background: white;
      z-index: 1;
    }
  }
  
  .battle-nav {
    display: none; /* Hide navigation in battle */
  }
  
  .back-button {
    background: none;
    border: none;
    color: #007bff;
    font-size: 1rem;
    cursor: pointer;
    padding: 0.5rem;
  }
  
  .battle-nav h1 {
    margin: 0;
    font-size: 1.25rem;
    font-weight: 600;
    color: #1a1a1a;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
  }
  
  .nav-spacer {
    width: 60px;
  }
  
  .battle-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    position: relative;
    background: #f8f9fa;
  }
  
  /* Battle Results Overlay */
  .battle-results-overlay {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2000;
  }
  
  .battle-results-card {
    background: white;
    border-radius: 16px;
    padding: 2rem;
    max-width: 400px;
    width: 90%;
    text-align: center;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  }
  
  .battle-results-card h2 {
    margin: 0 0 1rem 0;
    font-size: 1.8rem;
    font-weight: 700;
    color: #1a1a1a;
  }
  
  
  .level-up {
    background: linear-gradient(135deg, #fff3e0 0%, #ffcc02 100%);
    border-radius: 12px;
    padding: 1.5rem;
    margin: 1rem 0;
    border: 3px solid #ff6f00;
    animation: levelUpPulse 0.6s ease-in-out;
  }
  
  .level-up h3 {
    margin: 0 0 0.5rem 0;
    font-size: 1.4rem;
    color: #e65100;
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
  }
  
  .level-up p {
    margin: 0 0 1rem 0;
    font-size: 1.2rem;
    color: #bf360c;
  }
  
  .stat-changes {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    justify-content: center;
  }
  
  .stat-change {
    background: rgba(76, 175, 80, 0.2);
    border: 1px solid #4caf50;
    border-radius: 20px;
    padding: 0.25rem 0.75rem;
    font-size: 0.9rem;
    font-weight: 600;
    color: #2e7d32;
  }
  
  @keyframes levelUpPulse {
    0% {
      transform: scale(0.9);
      opacity: 0;
    }
    50% {
      transform: scale(1.05);
    }
    100% {
      transform: scale(1);
      opacity: 1;
    }
  }
</style>