import { world, system } from "@minecraft/server";
import { Vector } from "../util/vector";
import { settingEnabled } from "../settings"; // Assuming this function is available

// Constants
const lensFlareDelayTicks = 2;

// Function to calculate the angle of the sun based on the absolute time
function getSunAngle(absoluteTime) {
    const timeOfDay = absoluteTime % 24000;
    const sunPosition = ((timeOfDay + 6000) % 24000) - 12000;
    return (sunPosition / 12000) * Math.PI;
}

// Function to calculate the dot product between two vectors
function dotProduct(vec1, vec2) {
    return vec1.x * vec2.x + vec1.y * vec2.y + vec1.z * vec2.z;
}

// Function to calculate the magnitude of a vector
function magnitude(vec) {
    return Math.sqrt(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z);
}

// Function to calculate the angle between two vectors
function angleBetweenVectors(vec1, vec2) {
    const dot = dotProduct(vec1, vec2);
    const mag1 = magnitude(vec1);
    const mag2 = magnitude(vec2);
    return Math.acos(dot / (mag1 * mag2));
}

// Normalize a vector
function normalizeVector(vec) {
    const mag = magnitude(vec);
    return { x: vec.x / mag, y: vec.y / mag, z: vec.z / mag };
}

// Main loop to check all players at regular intervals
system.runInterval(() => {
    const overworld = world.getDimension("overworld");
    const absoluteTime = world.getAbsoluteTime();
    const timeOfDay = absoluteTime % 24000;
    const isDayTime = (timeOfDay >= 23200 && timeOfDay <= 24000) || (timeOfDay >= 0 && timeOfDay <= 12800);

    // Check if the lens flare setting is enabled
    const lensFlareEnabled = settingEnabled("lens_flare");

    // If not enabled, return
    if (!lensFlareEnabled) return;

    overworld.getPlayers().forEach(player => {
        if (!player.isValid()) return;

        if (isDayTime) {
            const sunAngle = getSunAngle(absoluteTime);

            const sunDistance = 55;
            const offset = {
                x: -Math.sin(sunAngle) * sunDistance,
                y: Math.cos(sunAngle) * sunDistance + 14, // Adjusted y offset to align with the sun
                z: 0,
            };

            // Normalize the sun direction vector
            const sunDirection = normalizeVector(offset);

            // Remove any existing lens flare entities
            overworld.getEntities({ type: "squaredreams_realism:lens_flare" }).forEach(sunEntity => {
                if (sunEntity.isValid()) {
                    sunEntity.remove();
                }
            });

            const playerEyePosition = {
                x: player.location.x,
                y: player.location.y + 1.8,
                z: player.location.z,
            };

            const playerViewDirection = normalizeVector(player.getViewDirection());

            // Calculate the angle between the player's view direction and the sun direction
            const angle = angleBetweenVectors(playerViewDirection, sunDirection);
            const maxAngle = Math.PI;
            if (angle < maxAngle) {
                // Cast a ray to check if the sun is visible
                const ray = overworld.getBlockFromRay(playerEyePosition, offset, {
                    includeLiquidBlocks: true,
                    includePassableBlocks: false,
                    maxDistance: 100,
                });

                const isBlocked = ray && ray.block && ray.block.isValid() && !ray.block.isAir;

                if (!isBlocked) {
                    try {
                        const sunPosition = Vector.add(playerEyePosition, offset);
                        const sunEntity = overworld.spawnEntity("squaredreams_realism:lens_flare", sunPosition);
                        if (sunEntity && sunEntity.isValid()) {
                            const velocity = player.getVelocity();
                            sunEntity.applyImpulse(velocity);
                        }
                    } catch (err) {}
                }
            }
        }
    });
}, lensFlareDelayTicks);