-- =============================================================================
-- Dialogue: EventHandler Component Integration
-- =============================================================================
-- This example demonstrates how to use the EventHandlerComponent to trigger
-- dialogue automatically when an event is received.
--
-- The EventHandlerComponent links an event name to a GoapAction. When the
-- event fires, the action's behavior tree is executed. This allows you to
-- wire up dialogue triggers declaratively without writing Lua code.
--
-- Combined with the EventBus, you can create complex event-driven dialogue
-- sequences where one event triggers dialogue, and the player's choice
-- triggers another event.
--
-- Note: DialogueSystem is a singleton. No ECS DialogueComponent is needed.
--       Dialogue is shown via ecs.dialogue.show() or ecs.send_event().
-- =============================================================================

-- ---------------------------------------------------------------------------
-- 1. Create an NPC with EventHandler for dialogue triggers
-- ---------------------------------------------------------------------------

local npc = ecs.create_entity()
ecs.set_entity_name(npc, "QuestGiver")

ecs.set_component(npc, "Transform", {
    position = { 5, 0, 5 },
    rotation = { 1, 0, 0, 0 },
    scale = { 1, 1, 1 }
})

ecs.set_component(npc, "Renderable", {
    meshName = "character.mesh",
    visible = true
})

-- Add an EventHandler that triggers dialogue when the player approaches
ecs.set_component(npc, "EventHandler", {
    eventName = "player_approached",
    actionName = "npc_greeting",
    enabled = true
})

print("Created NPC with EventHandler for player_approached event")

-- ---------------------------------------------------------------------------
-- 2. Create an EventHandler that triggers on quest completion
-- ---------------------------------------------------------------------------

local quest_npc = ecs.create_entity()
ecs.set_entity_name(quest_npc, "QuestRewarder")

ecs.set_component(quest_npc, "EventHandler", {
    eventName = "quest_completed",
    actionName = "quest_reward_dialogue",
    enabled = true
})

print("Created NPC with EventHandler for quest_completed event")

-- ---------------------------------------------------------------------------
-- 3. Trigger dialogue via events from other game systems
-- ---------------------------------------------------------------------------

-- Simulate a proximity trigger: when the player gets close to an NPC,
-- send an event that triggers the dialogue.

function on_player_near_npc(npc_name, distance)
    print("Player is " .. distance .. "m from " .. npc_name)

    if distance < 5.0 then
        -- Send the event that the EventHandler is listening for
        ecs.send_event("player_approached", {
            npc_name = npc_name,
            location = "town_square",
            distance = distance
        })

        -- Also show dialogue directly via singleton API
        ecs.dialogue.show(
            "Hello there! I have a quest for a brave adventurer.",
            { "I'll help!", "What's the reward?", "Not interested" },
            npc_name
        )
    end
end

-- Simulate the player approaching
on_player_near_npc("QuestGiver", 3.0)

-- ---------------------------------------------------------------------------
-- 4. Chain events: choice -> event -> next dialogue
-- ---------------------------------------------------------------------------
-- When the player makes a choice, we can send a new event that triggers
-- another EventHandler, creating a chain reaction.

-- Since choice selection happens via C++ callback, in a real game you'd
-- wire the callback to send events. From Lua, we can demonstrate by
-- sending follow-up events manually.

function on_dialogue_choice_made(choice_text)
    print("Player chose: " .. choice_text)

    if choice_text == "I'll help!" then
        -- Player accepted the quest - trigger quest acceptance event
        ecs.send_event("quest_accepted", {
            quest_name = "The Lost Artifact",
            giver = "QuestGiver",
            reward_gold = 100,
            reward_xp = 500
        })

        -- Show follow-up dialogue
        ecs.dialogue.show(
            "Excellent! The ancient artifact was stolen from the temple.\nBring it back and you'll be richly rewarded!",
            { "Where is the temple?", "I'm on it!", "Tell me more" },
            "QuestGiver"
        )

    elseif choice_text == "What's the reward?" then
        ecs.dialogue.show(
            "100 gold pieces and a magical amulet! What do you say?",
            { "I'll help!", "Sounds good", "Maybe later" },
            "QuestGiver"
        )

    elseif choice_text == "Not interested" then
        ecs.dialogue.show(
            "Very well. The offer stands if you change your mind.",
            {},
            "QuestGiver"
        )
    end
end

-- Simulate choices
on_dialogue_choice_made("I'll help!")
on_dialogue_choice_made("What's the reward?")

-- ---------------------------------------------------------------------------
-- 5. Subscribe to custom events for game logic
-- ---------------------------------------------------------------------------

-- Listen for quest acceptance
local quest_sub = ecs.subscribe_event("quest_accepted", function(event, params)
    local quest_name = params.quest_name or "unknown"
    local reward = params.reward_gold or 0
    local xp = params.reward_xp or 0

    print("Quest accepted: " .. quest_name)
    print("  Reward: " .. reward .. " gold, " .. xp .. " XP")

    -- This could trigger other EventHandlers on other entities
    ecs.send_event("quest_log_updated", {
        quest_name = quest_name,
        active_quests = 1
    })
end)

print("Subscribed to quest_accepted events")

-- ---------------------------------------------------------------------------
-- 6. Practical: Zone entry dialogue
-- ---------------------------------------------------------------------------
-- When the player enters a new area, show contextual dialogue.

function on_zone_entered(zone_name)
    local zone_dialogues = {
        forest = {
            text = "You enter the Dark Forest. The trees loom overhead,\nblocking out the sunlight.",
            speaker = "Narrator"
        },
        village = {
            text = "Welcome to Greenhaven Village. Smoke rises from\nchimneys and children play in the streets.",
            speaker = "Narrator"
        },
        dungeon = {
            text = "The air grows cold and damp as you descend into\nthe ancient dungeon. Somewhere, water drips.",
            speaker = "Narrator"
        },
        beach = {
            text = "The sea stretches to the horizon. Waves crash\nagainst the shore. A ship is docked nearby.",
            speaker = "Narrator"
        }
    }

    local dialogue = zone_dialogues[zone_name]
    if dialogue then
        ecs.dialogue.show(dialogue.text, {}, dialogue.speaker)

        -- Also send a zone-specific event for other systems
        ecs.send_event("zone_entered", {
            zone = zone_name
        })
    end
end

-- Simulate zone transitions
on_zone_entered("forest")
on_zone_entered("village")
on_zone_entered("dungeon")

-- ---------------------------------------------------------------------------
-- 7. Practical: Item pickup dialogue
-- ---------------------------------------------------------------------------

function on_item_picked_up(item_name, item_count)
    local pickup_messages = {
        health_potion = "You pick up a Health Potion. It glows with a warm light.",
        ancient_key = "An ancient key, covered in rust. It must open something important.",
        gold_coins = "You find " .. item_count .. " gold coins. They clink satisfyingly.",
        mysterious_map = "A faded map with markings you can't decipher. Someone might know what it means.",
        sword = "A fine steel sword. It feels balanced in your hand."
    }

    local message = pickup_messages[item_name]
    if message then
        ecs.dialogue.show(message, {}, "Narrator")
    end
end

-- Simulate item pickups
on_item_picked_up("health_potion", 1)
on_item_picked_up("ancient_key", 1)
on_item_picked_up("gold_coins", 50)

-- =============================================================================
-- Summary
-- =============================================================================
-- EventHandler + Dialogue integration patterns:
--
-- 1. Proximity triggers:
--    Player near NPC -> send event -> EventHandler triggers action -> dialogue
--
-- 2. Choice chaining:
--    Player picks choice -> send event -> EventHandler triggers -> next dialogue
--
-- 3. Zone entry:
--    Player enters area -> send event -> dialogue shows description
--
-- 4. Item pickup:
--    Player picks up item -> send event -> contextual dialogue
--
-- 5. Quest flow:
--    Accept quest -> event -> update quest log -> next dialogue
--    Complete quest -> event -> reward dialogue -> next dialogue
--
-- No ECS DialogueComponent needed — use ecs.dialogue.show() or
-- ecs.send_event("dialogue_show", { ... }) to display dialogue.
-- =============================================================================

print("Dialogue EventHandler integration examples completed!")
