quests = {
    {title = "Introduction", text = "Welcome, player. This is the Quest Book, " .. 
                                        "here you can check out what tasks you have to do and the materials you will need for each quest. " .. 
                                        "You can also just ignore the Quest Book if you are an experienced player. " .. 
                                        "Now, to get started look down at the core. Punching it will give you your first resources. " .. 
                                        "These Quests are in no particular order, but you might need items from one Quest for another. " ..
                                        "\nTIP: If you lose your Quest Book, you can use /qb to get it back."},

    {title = "A bigger platform", text = "Isn't this one node a little too crammed? " .. 
                                            "Let's do something about that. " .. 
                                            "Punch the Core a little more. With nine 'Matter Dust', you can craft yourself a 'Matter Blob'. " .. 
                                            "Check the Quest Book again when you've done that."},


    {title = "Antimatter", text = "Unfortunately, you dont seem to be strong enough to destroy that node once you place it. " .. 
                                    "That kind of sucks, so let's craft something that can. " .. 
                                    "Craft some 'Antimatter Dust', we'll need it for later. " .. 
                                    "It's made by mixing 'Matter Dust' and 'Core Dust'. Let's see you figure this out, smart one."},

    {title = "Annihilator", text = "Does it feel weird to be holding antimatter? " .. 
                                    "Now, to craft a 'Matter Annihilator' you'll need a couple things: " .. 
                                    "One 'Antimatter Dust', one 'Charged Particle' and three 'Matter Blob'. " .. 
                                    "Make sure the 'Charged Particle' is properly enclosed in matter, or it'll escape."},

    {title = "Charged Field", text = "Now, then. We have one more thing to do before we can start automating. Can you guess what it is? " .. 
                                    "That's right! We need power generation. " .. 
                                    "Using nine 'Charged Particle', you can craft yourself a 'Simple Charged Field' " .. 
                                    "But listen up! Charged Fields decay over time. Since you are using a 'Simple Charged Field', it should last you a couple of minutes of power generation. " .. 
                                    "Yeah, it uses energy even when there's nothing connected to it. Since resources are infinite here, time is your resource. " .. 
                                    "Anyways, I talked a lot, didn't I? Maybe too much. Let's get automating."},

    {title = "Automation", text = "Finally! Automation! Let's get on that, shall we? " .. 
                                    "Here's what you'll need for a 'Simple Matter Extractor'. " .. 
                                    "One 'Matter Annihilator', four 'Matter Blob' and four 'Core Dust' " .. 
                                    "\nTIP: Machines without power occasionally emit red particles."},

    {title = "Advanced Extractors", text = "That's a shiny new machine you've got there! " .. 
                                                "Do you also want to increase production? Sure you do. " .. 
                                                "For Advanced Extractors you'll obviously need a Simple Matter Extractor, " .. 
                                                "then four 'Matter Annihilator' and four 'Matter Blob'. That's a lot of resouces, " .. 
                                                "but this Extractor will also occasionally generate 'Core Dust'!"},

    {title = "Circuitry", text = "Circuits are important crafting components for future recipes. " .. 
                                    "You'll need them for lots of recipes, and many of them too. " .. 
                                    "Green Circuits are the most simple to craft, but there are diffrent circuit types which are used in diffrent recipes. " .. 
                                    "All diffrent Circuit types use Green Circuits as their base. " .. 
                                    "To craft a Simple Circuit, you'll need one 'Core Dust' and one 'Matter Blob'. " .. 
                                    "You'll get two Simple Circuits from that craft."},

    {title = "Generators", text = "Right now, you're probably using 'Simple Charged Field' nodes to generate your Global Power, " .. 
                                    "but since they decay, they dont last forever, which is not convenient. " .. 
                                    "They also leave behind indestructible residue which can be very annoying. " .. 
                                    "To solve that, you can use a generator, it consumes 'Core Dust' as fuel over time " .. 
                                    "and provides you with more power than 'Simple Charged Field' nodes do. " .. 
                                    "However, Generators are very expensive. Here is the list of materials required: " .. 
                                    "Four 'Simple Charged Field', one 'Antimatter Dust', three 'Matter Blob' and one 'Matter Annihilator'."},

    {title = "Matter Plates", text = "Matter Plates are often used for machinery. They are simple to craft, yet important." .. 
                                    "You can get four 'Matter Plate' by placing one 'Matter Blob' into the crafting grid."},

    {title = "Retaining Circuits", text = "Retaining Circuits are a type of Circuit often used in nodes which Store items, either permanently or temporarily. " .. 
                                    "Circuits depend on other circuits which is why you will need a Simple Circuit to craft this Circuit. " .. 
                                    "The list of materials is as follows: one 'Simple Circuit', one 'Charged Particle' and one 'Antimatter Dust'. " .. 
                                    "Unlike Simple Circuits, this will only craft one Retaining Circuit."},

    {title = "Storinators", text = "Storinators are the solution to clogged up inventories. " .. 
                                    "They have 30 Slots of Inventory, and function like a chest. " .. 
                                    "The more red/green dots the front of a storinator displays, the more full/empty it is. " .. 
                                    "You will need one 'Simple Charged Field', one 'Simple Circuit', four 'Matter Plate' and three 'Retaining Circuit' " .. 
                                    "to craft one Storinator."},

    {title = "Emitter Immitators", text = "Emitter Immitators are decorational nodes providing light. " .. 
                                    "You can get one, by surrounding a 'Matter Blob' with 'Antimatter Dust'. It doesn't glow as much as The Core though. " .. 
                                    "\nTIP: Emitter Immitators spawn a lot of particles when punched, try it!"},

    {title = "Global Power", text = "Global Power is the power system in this game. Power can be produced anywhere and is available anywhere, globally. " .. 
                                    "If global power goes into the negatives, it means you are producing less than you are consuming and " .. 
                                    "if global power is exactly zero, you are producing the exact same as you are consuming. " .. 
                                    "Should your global power go below zero, all machines will stop working because your power grid can't handle the draw. " .. 
                                    "Be careful though, everything that generates power will keep running, and you will loose the power. " .. 
                                    "Get at least one global power to complete this Quest."},

    {title = "Pretty Pebbles", text = "We're making the jump from generic matter to stone now! Here is where building a space station gets fun! " .. 
                                    "First, before we can make Stone nodes we will need Pebbles. They are quite difficult to make, requiring three " .. 
                                    "'Matter Blob' in a shapeless craft. Pebbles will unlock a lot of decorational nodes to spice up your island, " .. 
                                    "and if you want you can even start building your own planet. It's all up to your imagination!"},

    {title = "Concrete Plan", text = "Just regular old boring stone, nothing really to add here. Like, it's literally just stone. You know, the kind that would make even a rock collector yawn and say, I've seen gravel with more personality. It sits around all day, doing nothing—no metamorphosis, no glittering crystals—just living its best sedentary life. " .. 
                                    "That said, it's made using 9 pebbles. "},
}

function unlock_achievement(player_name, achievement_id)
    local player = minetest.get_player_by_name(player_name)
    if not player then
        return
    end
    
    local meta = player:get_meta()
    if not is_achievement_unlocked(player_name, achievement_id) then
        meta:set_string(achievement_id, "true")
        minetest.chat_send_player(player_name, "Quest Completed: " .. achievement_id .. "!")

        local pos = player:get_pos()
        minetest.add_particlespawner({
            amount = 50,
            time = 1,
            minpos = {x = pos.x - 0.5, y = pos.y - 0.5, z = pos.z - 0.5},
            maxpos = {x = pos.x + 0.5, y = pos.y + 0.5, z = pos.z + 0.5},
            minvel = {x = -5, y = -5, z = -5},
            maxvel = {x = 5, y = 5, z = 5},
            minacc = {x = 0, y = 0, z = 0},
            maxacc = {x = 0, y = 0, z = 0},
            minexptime = 15,
            maxexptime = 25,
            minsize = 0.5,
            maxsize = 1.0,
            collisiondetection = false,
            vertical = false,
            texture = "organic_particle.png",
            glow = 10
        })
    end
end

function revoke_achievement(player_name, achievement_id)
    local player = minetest.get_player_by_name(player_name)
    if not player then
        return
    end
    
    local meta = player:get_meta()
    if is_achievement_unlocked(player_name, achievement_id) then
        meta:set_string(achievement_id, "")
        minetest.chat_send_player(player_name, "Quest revoked: " .. achievement_id)
    end
end

function is_achievement_unlocked(player_name, achievement_id)
    local player = minetest.get_player_by_name(player_name)
    if not player then
        return false
    end

    local meta = player:get_meta()
    if meta then
        return meta:get_string(achievement_id) == "true"
    else
        return false
    end
end


-- Function to create the formspec
local function get_questbook_formspec(selected_quest_index, player_name)
    local selected_quest = quests[selected_quest_index]
    local quest_list = ""

    for i, quest in ipairs(quests) do
        if is_achievement_unlocked(player_name, quest.title) then
            quest_list = quest_list .. "✔️" .. quest.title .. ","
        else
            quest_list = quest_list .. quest.title .. ","
        end
    end
    quest_list = quest_list:sub(1, -2)

    local formspec = "formspec_version[7]" ..
                     "size[12,8]" ..
                     "label[0,0.2;Quest List]" ..
                     "textlist[0,0.7;5.8,7;quest_list;" .. quest_list .. ";" .. selected_quest_index .. "]" ..
                     "label[6,0.2;Quest Details]" ..
                     "label[6,0.7;Title: " .. minetest.formspec_escape(selected_quest.title) .. "]" ..
                     "textarea[6,1.2;5.8,5;;;" .. minetest.formspec_escape(selected_quest.text) .. "]" ..
                     "label[6,7.2;" .. (is_achievement_unlocked(player_name, selected_quest.title) and "✔️ You have completed this Quest." or "You have not completed this Quest.") .. "]"


    -- play page sound lol

    minetest.sound_play("questbook", {
        to_player = player_name,
        gain = 1.0,
    })

    return formspec
end

-- Handle form submissions
minetest.register_on_player_receive_fields(function(player, formname, fields)
    if formname == "questbook:main" then
        if fields.quest_list then
            local event = minetest.explode_textlist_event(fields.quest_list)
            if event.type == "CHG" then
                local selected_quest_index = event.index
                local name = player:get_player_name()

                -- set selected quest index
                local meta = player:get_meta()
                if meta then
                    meta:set_int("selected_quest_index", selected_quest_index)
                end

                minetest.show_formspec(name, "questbook:main", get_questbook_formspec(selected_quest_index, player:get_player_name()))
            end
        end
    end
end)


minetest.register_craftitem("sbz_progression:questbook", {
    description = "Quest Book",
    inventory_image = "questbook.png",
    stack_max = 1,
    on_use = function(itemstack, player, pointed_thing)

        local selected_quest_index = 1
        local meta = player:get_meta()
        if meta then
            selected_quest_index = meta:get_int("selected_quest_index")
        end
        if selected_quest_index == 0 then selected_quest_index = 1 end

        minetest.show_formspec(player:get_player_name(), "questbook:main", get_questbook_formspec(selected_quest_index, player:get_player_name()))
    end
})