import { world, system } from "@minecraft/server";
import { ModalFormData } from "@minecraft/server-ui";
import { fo } from './utilities/fo_constants.js';

export function initSetUpAltar() {

    
    const

        MESSAGE_KEYS = [
            "fo.SetupMessage01",
            "fo.SetupMessage02",
            "fo.SetupMessage03",
            "fo.SetupMessage04",
            "fo.SetupMessage05",
            "fo.SetupMessage06",
            "fo.SetupMessage07",
            "fo.SetupMessage08",
            "fo.SetupMessage09",
        ],

        MENU_KEYS = [
            "fo.Menu01",
            "fo.Menu02",
            "fo.Menu03",
            "fo.Menu04",
            "fo.Menu05",
            "fo.Menu06",
            "fo.Menu07",
            "fo.Menu08",
            "fo.Menu09",
            "fo.Menu10"
        ],

        TOOLTIPS_KEYS = [
            "fo.Tooltip02",
            "fo.Tooltip03",
            "fo.Tooltip04",
            "fo.Tooltip05",
            "fo.Tooltip06",
            "fo.Tooltip07",
            "fo.Tooltip08",
            "fo.Tooltip09",
            "fo.Tooltip10"
        ],

        CHAPTER_KEYS = [
            "fo.Chapter00",
            "fo.Chapter01",
            "fo.Chapter02",
            "fo.Chapter03",
            "fo.Chapter04",
            "fo.Chapter05",
            "fo.Chapter06"
        ],

        PERFORMANCE_KEYS = [
            "fo.PerformanceMode00",
            "fo.PerformanceMode01",
            "fo.PerformanceMode02",
            "fo.PerformanceMode03",
        ];


    const overworld = fo.overworld;

    
    const chapters = [
        { name: { translate: CHAPTER_KEYS[0] }, number: 0, foreboding: null }, 
        { name: { translate: CHAPTER_KEYS[1] }, number: 1, foreboding: 0 },
        { name: { translate: CHAPTER_KEYS[2] }, number: 2, foreboding: 1 },
        { name: { translate: CHAPTER_KEYS[3] }, number: 3, foreboding: fo.scoreChapter3 },
        { name: { translate: CHAPTER_KEYS[4] }, number: 4, foreboding: fo.scoreChapter4 },
        { name: { translate: CHAPTER_KEYS[5] }, number: 5, foreboding: fo.scoreChapter5 },
        { name: { translate: CHAPTER_KEYS[6] }, number: 6, foreboding: -1 },
    ];

    
    const noneChapterName = chapters[0].name;

    
    const eventMod = [
        { name: "x0.5", value: 0.5 },
        { name: "x1", value: 1 },
        { name: "x1.5", value: 1.5 },
        { name: "x2", value: 2 },
        { name: "x2.5", value: 2.5 },
        { name: "x3", value: 3 },
    ];

    
    function getProbabilityModifierIndex(currentValue) {
        return eventMod.findIndex(mod => mod.value === currentValue);
    }

    
    const performanceModes = [
        { name: { translate: PERFORMANCE_KEYS[0] }, modifier: 1 },
        { name: { translate: PERFORMANCE_KEYS[1] }, modifier: 1.5 },
        { name: { translate: PERFORMANCE_KEYS[2] }, modifier: 2.5 },
        { name: { translate: PERFORMANCE_KEYS[3] }, modifier: 4 },
    ];

    function getPerformanceModifierIndex(currentValue) {
        return performanceModes.findIndex(p => p.modifier === currentValue);
    }

    
    function isCorrectStructureBelowMycelium(block) {
        const myceliumPosition = block.location;
        const mossyCobbleId = "minecraft:mossy_cobblestone";
        const goldBlockId = "minecraft:gold_block";
        const redstoneTorchId = "minecraft:redstone_torch";

        
        const mossyCobblePosition = {
            x: myceliumPosition.x,
            y: myceliumPosition.y - 1,
            z: myceliumPosition.z
        };
        const mossyCobbleBlock = overworld.getBlock(mossyCobblePosition);
        if (!mossyCobbleBlock || mossyCobbleBlock.typeId !== mossyCobbleId) {
            return false;
        }

        
        const offsets = [
            { x: -1, z: -1 }, { x: 0, z: -1 }, { x: 1, z: -1 },
            { x: -1, z: 0 }, { x: 1, z: 0 },
            { x: -1, z: 1 }, { x: 0, z: 1 }, { x: 1, z: 1 }
        ];

        for (const offset of offsets) {
            const goldBlockPosition = {
                x: myceliumPosition.x + offset.x,
                y: myceliumPosition.y - 1,
                z: myceliumPosition.z + offset.z
            };
            const goldBlock = overworld.getBlock(goldBlockPosition);
            if (!goldBlock || goldBlock.typeId !== goldBlockId) {
                return false;
            }
        }

        
        const cardinalOffsets = [
            { x: 0, z: -1 }, 
            { x: 0, z: 1 },  
            { x: -1, z: 0 }, 
            { x: 1, z: 0 }   
        ];

        for (const offset of cardinalOffsets) {
            const torchPosition = {
                x: myceliumPosition.x + offset.x,
                y: myceliumPosition.y,
                z: myceliumPosition.z + offset.z
            };
            const torchBlock = overworld.getBlock(torchPosition);
            if (!torchBlock || torchBlock.typeId !== redstoneTorchId) {
                return false;
            }
        }

        return true;
    };

    
    function isBlockUnderground(blockAffected) {
        const blockStart = blockAffected.location;
        const maxHeight = Math.min((319 - blockStart.y), 120); 
        const airBlock = "minecraft:air";

        
        for (let y = blockStart.y + 2; y <= maxHeight; y++) {
            const blockLocation = { x: blockStart.x, y, z: blockStart.z };
            const block = overworld.getBlock(blockLocation);

            
            if (block.typeId !== airBlock) {
                return true;
            }
        }

        
        return false;
    };


    
    function createRandomExplosion(blockLocation) {
        
        const offsetX = (Math.random() * 2 - 1); 
        const offsetZ = (Math.random() * 2 - 1); 

        const ExplosionOptions = {
            allowUnderwater: true,
            breaksBlocks: false,
            causesFire: true,
        };
        const explosionRadius = 1; 

        
        const explosionLocation = {
            x: blockLocation.x + offsetX,
            y: blockLocation.y + 3,
            z: blockLocation.z + offsetZ,
        };

        
        overworld.createExplosion(explosionLocation, explosionRadius, ExplosionOptions);
        
    }

    
    function altar(player, blockAffected) {

        
        if (isBlockUnderground(blockAffected)) {
            
            const totalExplosions = 3;
            const delayBetweenExplosions = 3; 

            
            for (let i = 0; i < totalExplosions; i++) {
                system.runTimeout(() => {
                    createRandomExplosion(blockAffected.location);
                }, i * delayBetweenExplosions);
            }
        } else {
            
            overworld.spawnEntity("lightning_bolt", blockAffected.location)
        };


        
        if (player.location.y > 30) {
            player.runCommand(`fog @s push foreboding:fog08 FogR`);
        } else player.runCommand(`fog @s push foreboding:fog08u FogR`);

        system.runTimeout(() => {
            const MusicOptions = {
                fade: 10,
                loop: true,
                volume: 1,
            };
            player.playMusic("fo_whispers", MusicOptions);
            
        }, 1)

        
        overworld.spawnParticle("fo_setup", player.location);
    };

    
    world.afterEvents.itemStartUseOn.subscribe((event) => {
        const player = event.source;
        const item = event.itemStack;
        const blockAffected = event.block;
        const face = event.blockFace;

        if (player.playerPermissionLevel < 2) return;
        
        const objective = fo.forebodingObjective;


        
        

        if (player.dimension === overworld) { 

            
            if (item && item.typeId === "minecraft:flint_and_steel" && face === "Up") {
                const blockPosition = {
                    x: Math.floor(blockAffected.location.x),
                    y: Math.floor(blockAffected.location.y),
                    z: Math.floor(blockAffected.location.z)
                };

                
                const block = overworld.getBlock(blockPosition);

                
                if (block && block.typeId === "minecraft:mycelium") {
                    
                    
                    if (isCorrectStructureBelowMycelium(block)) {
                        
                        system.runTimeout(() => {
                            altar(player, blockAffected)
                        }, 10);

                        
                        const currentTotalDuration = world.getDynamicProperty("totalDuration");
                        const currentProbabilityModifier = world.getDynamicProperty("probabilityModifier");
                        const currentEndlessMode = world.getDynamicProperty("endlessMode");
                        const currentCreditsToggle = world.getDynamicProperty("creditsToggle");
                        const currentMaintainChapter = world.getDynamicProperty("maintainChapter");
                        const currentRandomTick = world.getDynamicProperty("randomTick");
                        const currentStructuresToggle = world.getDynamicProperty("minorStructures");
                        const currentPerformanceMode = world.getDynamicProperty("performanceMode");


                        
                        const probabilityModifierIndex = getProbabilityModifierIndex(currentProbabilityModifier);
                        const currentPerformanceModeIndex = getPerformanceModifierIndex(currentPerformanceMode);

                        
                        let form = new ModalFormData();
                        let eventModifier = eventMod.map(mod => mod.name); 
                        let shortCut = chapters.map(chapter => chapter.name); 
                        let performanceModifiers = performanceModes.map(p => p.name); 
                        form.title({ translate: MENU_KEYS[0] });
                        form.slider({ translate: MENU_KEYS[1] }, 10, 30, { valueStep: 5, defaultValue: currentTotalDuration, tooltip: { translate: TOOLTIPS_KEYS[0] } });
                        form.dropdown({ translate: MENU_KEYS[2] }, eventModifier, { defaultValueIndex: probabilityModifierIndex, tooltip: { translate: TOOLTIPS_KEYS[1] } });
                        form.toggle({ translate: MENU_KEYS[3] }, { defaultValue: currentEndlessMode, tooltip: { translate: TOOLTIPS_KEYS[2] } });
                        form.toggle({ translate: MENU_KEYS[5] }, { defaultValue: currentCreditsToggle, tooltip: { translate: TOOLTIPS_KEYS[4] } });
                        form.toggle({ translate: MENU_KEYS[6] }, { defaultValue: currentMaintainChapter, tooltip: { translate: TOOLTIPS_KEYS[5] } });
                        form.toggle({ translate: MENU_KEYS[7] }, { defaultValue: currentRandomTick, tooltip: { translate: TOOLTIPS_KEYS[6] } });
                        form.toggle({ translate: MENU_KEYS[8] }, { defaultValue: currentStructuresToggle, tooltip: { translate: TOOLTIPS_KEYS[7] } });
                        form.dropdown({ translate: MENU_KEYS[4] }, shortCut, { tooltip: { translate: TOOLTIPS_KEYS[3] } });
                        form.dropdown({ translate: MENU_KEYS[9] }, performanceModifiers, { defaultValueIndex: currentPerformanceModeIndex, tooltip: { translate: TOOLTIPS_KEYS[8] } });

                        system.runTimeout(() => {
                            
                            form.show(event.source).then(response => {
                                
                                if (response.canceled) {
                                    
                                    system.runTimeout(() => {
                                        player.runCommand(`fog @s remove FogR`);
                                        objective.setScore(player, 0);
                                        player.stopMusic();

                                        system.runTimeout(() => {
                                            const forebodingScore = fo.forebodingScore;
                                            if (forebodingScore > fo.scoreChapter3) player.playMusic("forefeelM", { volume: 0.01, loop: true });
                                            if (forebodingScore < fo.scoreChapter7s) player.playMusic("phurpa", { fade: 10, loop: true, volume: 0.01, });
                                        }, 9)
                                    }, 1);
                                    return;
                                };

                                
                                const [totalDuration, probabilityModifierIndex, endlessMode, creditsToggle, maintainChapter, randomTick, minorStructures, chapterSelectionIndex, performanceModifierIndex] = response.formValues;

                                const selectedModifier = eventMod[probabilityModifierIndex];
                                const selectedChapter = chapters[chapterSelectionIndex];
                                const selectedPerformanceModifier = performanceModes[performanceModifierIndex]

                                
                                

                                
                                if (currentRandomTick && !randomTick) {
                                    system.runTimeout(() => { 
                                        world.gameRules.randomTickSpeed = true;
                                    }, 20)
                                }


                                
                                if (selectedChapter.name !== noneChapterName) {
                                    if (objective) {
                                        
                                        overworld.runCommand(`function Fo/FoL5`) 
                                        objective.setScore("Counter ", selectedChapter.foreboding);

                                    } else {
                                        
                                    }
                                }

                                
                                world.setDynamicProperty("totalDuration", totalDuration);
                                world.setDynamicProperty("probabilityModifier", selectedModifier.value);
                                world.setDynamicProperty("endlessMode", endlessMode);
                                world.setDynamicProperty("creditsToggle", creditsToggle);
                                world.setDynamicProperty("maintainChapter", maintainChapter);
                                world.setDynamicProperty("randomTick", randomTick);
                                world.setDynamicProperty("minorStructures", minorStructures);
                                world.setDynamicProperty("performanceMode", selectedPerformanceModifier.modifier);


                                
                                

                                
                                system.runTimeout(() => {
                                    player.runCommand(`fog @s remove FogR`);
                                    player.runCommand(`fog @s remove FogF`);
                                    objective.setScore(player, 0)
                                    player.stopMusic();

                                    const forebodingScore = fo.forebodingScore;
                                    if (forebodingScore > fo.scoreChapter3) player.playMusic("forefeelM", { volume: 0.01, loop: true });
                                    if (forebodingScore < fo.scoreChapter7s) player.playMusic("phurpa", { volume: 0.01, loop: true });
                                }, 1)
                            }).catch(error => {
                                console.error("Error showing form:", error, error.stack);
                            });
                        }, 60)

                    }
                }
            }
        }
    })



}