import 'package:flame/components.dart';
import 'package:shitman/game/components/base.dart';
import 'package:shitman/game/components/neighborhood.dart';

class TargetHouse extends ShitComponent {
  House? currentTarget;
  bool missionActive = false;

  @override
  Future<void> onLoad() async {
    await super.onLoad();
    selectNewTarget();
  }

  void selectNewTarget() {
    // Find the neighborhood component
    final neighborhood = parent?.children.whereType<Neighborhood>().firstOrNull;
    if (neighborhood == null) return;

    // Clear previous target
    if (currentTarget != null) {
      currentTarget!.isTarget = false;
    }

    // Select random house as new target
    currentTarget = neighborhood.getRandomHouse();
    if (currentTarget != null) {
      currentTarget!.isTarget = true;
      missionActive = true;
      appLog.finest('New target selected at ${currentTarget!.position}');
    }
  }

  void completeMission() {
    if (currentTarget != null) {
      currentTarget!.isTarget = false;
      currentTarget = null;
    }
    missionActive = false;
  }

  bool isPlayerNearTarget(Vector2 playerPosition, {double threshold = 50.0}) {
    if (currentTarget?.doorPosition == null) return false;

    final distance = (playerPosition - currentTarget!.doorPosition!).length;
    return distance < threshold;
  }

  Vector2? getTargetPosition() {
    return currentTarget?.doorPosition;
  }

  @override
  Future<void> reset() async {
    // Reset target house state
    currentTarget?.isTarget = false;
    currentTarget = null;
    missionActive = false;
    appLog.finest('Target house reset');
  }
}
