export function registerOcclusionConfig() {
	// Global Hook Registration
	function registerGlobalHooks() {
		const updateTriggers = [ // Update triggers for occlusion layer
			'canvasReady', 
			'canvasPan',
			'canvasTokensRefresh', 
			'updateToken', 
			'controlToken', 
			'refreshToken',
			'preUpdateScene',
			'updateScene'
		];

		updateTriggers.forEach(hookName => {
			Hooks.on(hookName, () => {
				updateOcclusionLayer();
			});
		});
	}

	// Initial layer setup
	Hooks.once('ready', () => {
		if (canvas.ready)
			initializeOcclusionLayer();
	});

	// Initialize on canvas setup
	Hooks.on('canvasInit', () => {
		initializeOcclusionLayer();
	});

	// Reset on scene change
	Hooks.on('changeScene', () => {
		if (occlusionConfig.container) {
			canvas.stage.removeChild(occlusionConfig.container);
			occlusionConfig.container.destroy({ children: true });
			occlusionConfig.container = null;
			occlusionConfig.tokensLayer = null;
			occlusionConfig.initialized = false;
		}
	});

	// Start the module
	registerGlobalHooks();
}


// Persistent occlusion layer configuration
const occlusionConfig = {
	container: null,
	tokensLayer: null,
	initialized: false
};

// Initialize or reset the occlusion layer
function initializeOcclusionLayer() {
	// Remove existing container if it exists
	if (occlusionConfig.container) {
		canvas.stage.removeChild(occlusionConfig.container);
		occlusionConfig.container.destroy({ children: true });
	}

	// Create the main occlusion container
	occlusionConfig.container = new PIXI.Container();
	occlusionConfig.container.name = "OcclusionContainer";
	occlusionConfig.container.eventMode = 'passive';

	// Create a layer for occlusion tokens
	occlusionConfig.tokensLayer = new PIXI.Container();
	occlusionConfig.tokensLayer.name = "OcclusionTokens";
	occlusionConfig.tokensLayer.sortableChildren = true;

	// Add the layer to the container
	occlusionConfig.container.addChild(occlusionConfig.tokensLayer);

	// Add to canvas stage
	canvas.stage.addChild(occlusionConfig.container);
	canvas.stage.sortChildren();

	occlusionConfig.initialized = true;
}



// Comprehensive update mechanism for occlusion layer
function updateOcclusionLayer() {
	// Ensure canvas is ready and layer is initialized
	if (!canvas.ready) return;

	// Reinitialize if not yet set up
	if (!occlusionConfig.initialized) {
		initializeOcclusionLayer();
	}

	// Clear existing occlusion tokens
	occlusionConfig.tokensLayer.removeChildren();

	// Get all tokens and tiles
	const tokens = canvas.tokens.placeables;
	const tiles = canvas.tiles.placeables;

	tokens.forEach(token => {
		// Find tiles that intersect with this token
		const intersectingTiles = tiles.filter(tile => 
			checkTokenTileIntersection(token, tile)
		);

		// If there are intersecting tiles, create an occlusion sprite
		if (intersectingTiles.length > 0) {
			const occlusionSprite = createOcclusionSprite(token, intersectingTiles);
			if (occlusionSprite) {
				occlusionConfig.tokensLayer.addChild(occlusionSprite);
			}
		}
	});
}

// Token-Tile Intersection Check
function checkTokenTileIntersection(token, tile) {
	// Basic intersection check using bounding boxes
	const tokenBounds = token.mesh.getBounds();
	const tileBounds = tile.mesh.getBounds();

	return (
		tokenBounds.x < tileBounds.x + tileBounds.width &&
		tokenBounds.x + tokenBounds.width > tileBounds.x &&
		tokenBounds.y < tileBounds.y + tileBounds.height &&
		tokenBounds.y + tokenBounds.height > tileBounds.y
	);
}







// Create Occlusion Sprite with Advanced Masking
function createOcclusionSprite(token, intersectingTiles) {
	if (!token.mesh || !token.mesh.texture) return null;

	// Create a sprite from the token's texture
	const sprite = new PIXI.Sprite(token.mesh.texture);
	sprite.position.set(token.mesh.position.x, token.mesh.position.y);
	sprite.anchor.set(token.mesh.anchor.x, token.mesh.anchor.y);
	sprite.angle = token.mesh.angle;
	sprite.scale.set(token.mesh.scale.x, token.mesh.scale.y);

	// Create a mask for the occlusion
	const mask = createOcclusionMask(token, intersectingTiles);
	
	if (mask) {
		sprite.mask = mask;
	}

	// sprite.filters = [colorMatrix, outlineFilter, alphaFilter];
	sprite.filters = [colorMatrix, outlineFilter]; //criados no fim do arquivo

	//sprite.alpha = 0.75;
	sprite.eventMode = 'passive';

	return sprite;
}














// Advanced Occlusion Mask Creation
const alphaFragmentShader = `
varying vec2 vTextureCoord;
uniform sampler2D uSampler;       // Textura do token (não usada aqui)
uniform sampler2D uTileMask;      // Textura do tile
uniform vec4 dimensions;          // [x, y, width, height] da interseção
uniform vec4 tileDimensions;      // [x, y, width, height] do tile

void main(void) {
		// Posição local do fragmento na interseção
		vec2 localPos = gl_FragCoord.xy - dimensions.xy;
    
		// Coordenadas UV normalizadas para a textura do tile
		vec2 tileCoord = vec2(
				(localPos.x / dimensions.z) * (tileDimensions.z / dimensions.z),
				(localPos.y / dimensions.w) * (tileDimensions.w / dimensions.w)
		);

		// Ajuste para considerar a posição do tile no canvas
		tileCoord.x += (dimensions.x - tileDimensions.x) / tileDimensions.z;
		tileCoord.y += (dimensions.y - tileDimensions.y) / tileDimensions.w;

		// Amostra a textura do tile
		vec4 tileColor = texture2D(uTileMask, tileCoord);

		// Amostra a textura do token
		vec4 tokenColor = texture2D(uSampler, vTextureCoord);

		// Se o pixel do tile for opaco, cria uma máscara branca opaca
		if (tileColor.a > 0.1) {
				gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0); // Branco opaco
		} else {
				gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0); // Transparente
		}
}
`;

function createOcclusionMask(token, intersectingTiles) {
		const maskGraphics = new PIXI.Graphics();
		maskGraphics.beginFill(0xffffff);

		intersectingTiles.forEach(tile => {
			const tokenBounds = token.mesh.getBounds();
			const tileBounds = tile.mesh.getBounds();
	
			// Calculate intersection area
			const x = Math.max(tokenBounds.x, tileBounds.x);
			const y = Math.max(tokenBounds.y, tileBounds.y);
			const width = Math.min(tokenBounds.x + tokenBounds.width, tileBounds.x + tileBounds.width) - x;
			const height = Math.min(tokenBounds.y + tokenBounds.height, tileBounds.y + tileBounds.height) - y;

			if (width <= 0 || height <= 0) return;

			// Draw intersection area
			maskGraphics.drawRect(x, y, width, height);

			// Create and apply alpha filter
			const alphaFilter = new PIXI.Filter(undefined, alphaFragmentShader, {
				uTileMask: tile.texture,
				dimensions: new Float32Array([x, y, width, height]),
				tileDimensions: new Float32Array([
					tileBounds.x, tileBounds.y, tileBounds.width, tileBounds.height
				])
			});

			// Aplica o filtro ao gráfico
			maskGraphics.filters = [...(maskGraphics.filters || []), alphaFilter];
		});

		maskGraphics.endFill();
		return maskGraphics;
}