import 'package:asciineverdie/l10n/app_localizations.dart';
import 'package:asciineverdie/src/core/model/game_state.dart';
import 'package:asciineverdie/src/features/game/game_play_screen.dart';
import 'package:asciineverdie/src/features/game/game_session_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

import '../helpers/mock_factories.dart';
import '../helpers/test_setup.dart';

/// 테스트용 MaterialApp 래퍼 (localization 포함)
/// locale을 영어로 고정하여 테스트 텍스트와 일치시킴
Widget _buildTestApp(Widget child) {
  return MaterialApp(
    localizationsDelegates: L10n.localizationsDelegates,
    supportedLocales: L10n.supportedLocales,
    locale: const Locale('en'), // 영어 locale 고정
    home: child,
  );
}

GameState _createTestState() {
  return GameState.withSeed(
    seed: 42,
    traits: const Traits(
      name: 'TestHero',
      race: 'Elf',
      klass: 'Mage',
      level: 5,
      motto: 'Test Motto',
      guild: '',
    ),
    stats: const Stats(
      str: 10,
      con: 12,
      dex: 14,
      intelligence: 16,
      wis: 11,
      cha: 9,
      hpMax: 50,
      mpMax: 40,
    ),
    progress: const ProgressState(
      task: ProgressBarState(position: 500, max: 1000),
      quest: ProgressBarState(position: 300, max: 600),
      plot: ProgressBarState(position: 1800, max: 3600),
      exp: ProgressBarState(position: 500, max: 1500),
      encumbrance: ProgressBarState(position: 5, max: 20),
      currentTask: TaskInfo(caption: 'Battling a Goblin', type: TaskType.kill),
      plotStageCount: 2,
      questCount: 3,
    ),
  );
}

GameSessionController _createController() {
  return GameSessionController(
    progressService: MockFactories.createProgressService(),
    saveManager: FakeSaveManager(),
    tickInterval: const Duration(seconds: 10), // 느린 틱
    hallOfFameStorage: FakeHallOfFameStorage(),
    statisticsStorage: FakeStatisticsStorage(),
  );
}

/// 데스크톱 레이아웃 테스트를 위한 공통 설정
Future<void> _setupDesktopLayoutTest(WidgetTester tester) async {
  await tester.binding.setSurfaceSize(const Size(1200, 800));
  addTearDown(() => tester.binding.setSurfaceSize(null));
}

/// 프레임 펌프 (localization 로드 대기)
Future<void> _pumpFrames(WidgetTester tester) async {
  await tester.pump();
  await tester.pump(const Duration(milliseconds: 100));
}

void main() {
  // SharedPreferences 모킹
  setUpAll(() {
    TestSetup.mockSharedPreferences();
  });

  // 각 테스트 후 싱글톤 서비스 정리 (타이머 누수 방지)
  tearDown(() {
    TestSetup.resetAllServices();
  });

  testWidgets('GamePlayScreen renders 3-panel layout', (tester) async {
    await _setupDesktopLayoutTest(tester);

    final controller = _createController();
    addTearDown(() async {
      await controller.pause(saveOnStop: false);
      controller.dispose();
    });

    await controller.startNew(_createTestState(), isNewGame: false);

    await tester.pumpWidget(
      _buildTestApp(
        GamePlayScreen(controller: controller, forceDesktopLayout: true),
      ),
    );

    await _pumpFrames(tester);

    // AppBar 타이틀 확인 (L10n 사용) - ASCII NEVER DIE
    expect(find.textContaining('ASCII NEVER DIE'), findsOneWidget);

    // 3패널 헤더 확인 (패널 헤더는 대문자로 표시됨)
    expect(find.text('CHARACTER SHEET'), findsOneWidget);
    expect(find.text('EQUIPMENT'), findsOneWidget);
    expect(find.text('PLOT DEVELOPMENT'), findsOneWidget);
    expect(find.text('QUESTS'), findsOneWidget);

    await controller.pause(saveOnStop: false);
  });

  testWidgets('GamePlayScreen shows character traits', (tester) async {
    await _setupDesktopLayoutTest(tester);

    final controller = _createController();
    addTearDown(() async {
      await controller.pause(saveOnStop: false);
      controller.dispose();
    });

    await controller.startNew(_createTestState(), isNewGame: false);

    await tester.pumpWidget(
      _buildTestApp(
        GamePlayScreen(controller: controller, forceDesktopLayout: true),
      ),
    );

    await _pumpFrames(tester);

    // Traits 섹션 확인 (섹션 헤더는 대문자로 표시됨)
    expect(find.text('TRAITS'), findsOneWidget);
    expect(find.text('TestHero'), findsOneWidget);
    expect(find.text('Elf'), findsOneWidget);
    expect(find.text('Mage'), findsOneWidget);

    await controller.pause(saveOnStop: false);
  });

  testWidgets('GamePlayScreen shows stats', (tester) async {
    await _setupDesktopLayoutTest(tester);

    final controller = _createController();
    addTearDown(() async {
      await controller.pause(saveOnStop: false);
      controller.dispose();
    });

    await controller.startNew(_createTestState(), isNewGame: false);

    await tester.pumpWidget(
      _buildTestApp(
        GamePlayScreen(controller: controller, forceDesktopLayout: true),
      ),
    );

    await _pumpFrames(tester);

    // Stats 섹션 확인 (섹션 헤더는 대문자로 표시됨, 스크롤로 인해 화면 밖에 있을 수 있음)
    expect(find.text('STATS', skipOffstage: false), findsOneWidget);
    expect(find.text('STR', skipOffstage: false), findsOneWidget);
    expect(find.text('CON', skipOffstage: false), findsOneWidget);

    await controller.pause(saveOnStop: false);
  });

  testWidgets('GamePlayScreen shows current task caption', (tester) async {
    await _setupDesktopLayoutTest(tester);

    final controller = _createController();
    addTearDown(() async {
      await controller.pause(saveOnStop: false);
      controller.dispose();
    });

    await controller.startNew(_createTestState(), isNewGame: false);

    await tester.pumpWidget(
      _buildTestApp(
        GamePlayScreen(controller: controller, forceDesktopLayout: true),
      ),
    );

    await _pumpFrames(tester);

    // 현재 태스크 캡션 확인 (퀘스트 목록과 하단 패널에 표시됨)
    expect(find.text('Battling a Goblin'), findsAtLeast(1));

    await controller.pause(saveOnStop: false);
  });

  testWidgets('GamePlayScreen shows progress bars', (tester) async {
    await _setupDesktopLayoutTest(tester);

    final controller = _createController();
    addTearDown(() async {
      await controller.pause(saveOnStop: false);
      controller.dispose();
    });

    await controller.startNew(_createTestState(), isNewGame: false);

    await tester.pumpWidget(
      _buildTestApp(
        GamePlayScreen(controller: controller, forceDesktopLayout: true),
      ),
    );

    await _pumpFrames(tester);

    // 프로그레스 바 관련 섹션 헤더 확인 (커스텀 세그먼트 프로그레스 바 사용)
    expect(find.text('EXPERIENCE', skipOffstage: false), findsOneWidget);
    expect(find.text('ENCUMBRANCE', skipOffstage: false), findsOneWidget);

    await controller.pause(saveOnStop: false);
  });

  testWidgets('Loading state shows CircularProgressIndicator', (tester) async {
    final controller = _createController();
    addTearDown(() {
      controller.dispose();
    });

    // 상태 없이 시작 (startNew 호출 안 함)
    await tester.pumpWidget(
      _buildTestApp(
        GamePlayScreen(controller: controller, forceDesktopLayout: true),
      ),
    );

    // 로딩 인디케이터 확인
    expect(find.byType(CircularProgressIndicator), findsOneWidget);
  });
}
