#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <dk_buttons_and_leds.h>
#include <openthread/thread.h>
#include <openthread/coap.h>

/* Our new library */
#include "game_logic.h"

LOG_MODULE_REGISTER(weapon_app, LOG_LEVEL_INF);

/* Game context */
static struct game_ctx game;

/* Forward Declarations */
static void on_button_changed(uint32_t button_state, uint32_t has_changed);

/* --- Game Logic Callbacks --- */

static void on_game_state_change(enum game_state new_state)
{
	LOG_INF("APP: Game state changed -> %d", new_state);
	
	switch (new_state) {
	case GAME_STATE_RUNNING:
		dk_set_led_on(DK_LED1); // LED on when game is running
		break;
	case GAME_STATE_FINISHED:
		dk_set_led_off(DK_LED1);
		// Blink or similar
		break;
	default:
		dk_set_led_off(DK_LED1);
		break;
	}
}

static void on_hit_received(uint16_t shooter_id)
{
	LOG_WARN("APP: OUCH! Hit by player %d. Health: %d", shooter_id, game.health);
	
	// Visuelles Feedback: LED 2 blinkt kurz
	dk_set_led_on(DK_LED2);
	k_msleep(200);
	dk_set_led_off(DK_LED2);

	// TODO: Send CoAP message to leader later!
	// send_hit_report_to_leader(...);
}

static void on_shot_fired(void)
{
	LOG_INF("APP: BANG! Shot fired.");
	// TODO: Send IR protocol here (NEC/RC5)
}

/* --- Hardware Callbacks --- */

static void on_button_changed(uint32_t button_state, uint32_t has_changed)
{
	// Button 1: Shoot
	if ((has_changed & DK_BTN1_MSK) && (button_state & DK_BTN1_MSK)) {
		if (game.current_state == GAME_STATE_RUNNING) {
			on_shot_fired();
		} else {
			LOG_INF("Shot blocked - game not running.");
		}
	}

	// Button 2: Simulate hit (Self-Hit Test)
	if ((has_changed & DK_BTN2_MSK) && (button_state & DK_BTN2_MSK)) {
		LOG_INF("Simulating hit by player 99...");
		struct game_hit_packet hit_packet;
		
		// Pretend the IR sensor detected player 99
		if (game_logic_register_hit(99, &hit_packet)) {
			// If hit was valid (game running, we're still alive), we now have a packet
			// that we could send via Thread.
			LOG_INF("Hit registered! Damage: %d", hit_packet.damage);
		}
	}
}

/* --- Main --- */

void main(void)
{
	LOG_INF("Lasertag Weapon Start");

	int err = dk_buttons_init(on_button_changed);
	if (err) {
		LOG_ERR("Buttons could not be initialized (err %d)", err);
	}

	// Game Logic Setup
	game.on_state_change = on_game_state_change;
	game.on_hit_received = on_hit_received;
	
	// Initialize as player with ID from Kconfig (or NVS later)
	game_logic_init(&game, CONFIG_LASERTAG_PLAYER_ID_DEFAULT);

	// For testing, we manually set the status to RUNNING,
	// until we receive the start signal from the leader via Thread.
	struct game_state_packet fake_start = {.state = GAME_STATE_RUNNING};
	game_logic_handle_state_update(&fake_start);

	while (1) {
		k_sleep(K_FOREVER);
	}
}