// Enhanced Occlusion Layer Module for Foundry VTT

export function registerOcclusionConfig() {
	// Global Hook Registration
	function registerGlobalHooks() {
		const updateTriggers = [
			'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;
}



function debugIntersection(token, tile) {
	const tokenBounds = token.mesh.getBounds();
	const tileBounds = tile.mesh.getBounds();
	
	const intersection = {
		x: Math.max(tokenBounds.x, tileBounds.x),
		y: Math.max(tokenBounds.y, tileBounds.y),
		width: Math.min(tokenBounds.x + tokenBounds.width, tileBounds.x + tileBounds.width) - Math.max(tokenBounds.x, tileBounds.x),
		height: Math.min(tokenBounds.y + tokenBounds.height, tileBounds.y + tileBounds.height) - Math.max(tokenBounds.y, tileBounds.y)
	};
	
	return intersection.width > 0 && intersection.height > 0;
}

// Comprehensive update mechanism for occlusion layer
function updateOcclusionLayer() {
	// Canvas not ready, returning
	if (!canvas.ready) {
		return;
	}

	// Initializing occlusion layer
	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;
	
	// console.log(`Processing ${tokens.length} tokens and ${tiles.length} tiles`);

	tokens.forEach((token, tokenIndex) => {
		// Find intersecting tiles with debugging
		const intersectingTiles = tiles.filter(tile => debugIntersection(token, tile));

		if (intersectingTiles.length > 0) {
			const sprite = createOcclusionSprite(token, intersectingTiles);
			if (sprite) {
				occlusionConfig.tokensLayer.addChild(sprite);
			}
		}
	});
}










// Custom shader for handling both intersection masking and effects
const occlusionVertexShader = `
	attribute vec2 aVertexPosition;
	attribute vec2 aTextureCoord;
	uniform mat3 projectionMatrix;
	varying vec2 vTextureCoord;
	varying vec2 vWorldPos;
	
	void main() {

	}
`;


const occlusionFragmentShader = `
	varying vec2 vTextureCoord;
	varying vec2 vWorldPos;
	
	uniform sampler2D uSampler;           // Token texture
	uniform sampler2D uTileMasks[8];      // Array of tile textures
	uniform vec4 uTileBounds[8];          // Array of tile bounds [x, y, width, height]
	uniform int uTileCount;               // Number of intersecting tiles
	uniform vec4 uColorMatrix;            // Color matrix for greyscale effect
	uniform vec4 uOutlineColor;           // Outline color
	uniform float uOutlineThickness;      // Outline thickness
	uniform float uAlpha;                 // Global alpha value
	
	void main() {
	
	}
`;


// Create the enhanced occlusion filter
class EnhancedOcclusionFilter extends PIXI.Filter {
	constructor() {
		super(occlusionVertexShader, occlusionFragmentShader); //occlusionVertexShader, occlusionFragmentShader
		
		// Initialize uniforms
		this.uniforms.uTileMasks = [];
		this.uniforms.uTileBounds = new Float32Array(32);
		this.uniforms.uTileCount = 0;
		this.uniforms.uColorMatrix = new Float32Array([0.2, 0.2, 0.2, 0.5]);
		this.uniforms.uOutlineColor = new Float32Array([0.0, 1.0, 0.35, 1.0]);
		this.uniforms.uOutlineThickness = 0.001;
		this.uniforms.uAlpha = 1.0;
	}
	
	updateTiles(intersectingTiles) {
		const count = Math.min(intersectingTiles.length, 8);
		this.uniforms.uTileCount = count;
		
		for(let i = 0; i < count; i++) {
			const tile = intersectingTiles[i];
			const bounds = tile.mesh.getBounds();
			
			// Update tile texture
			this.uniforms.uTileMasks[i] = tile.texture;
			
			// Update tile bounds
			const idx = i * 4;
			this.uniforms.uTileBounds[idx] = bounds.x;
			this.uniforms.uTileBounds[idx + 1] = bounds.y;
			this.uniforms.uTileBounds[idx + 2] = bounds.width;
			this.uniforms.uTileBounds[idx + 3] = bounds.height;
		}
	}
}





// Modified createOcclusionSprite function
function createOcclusionSprite(token, intersectingTiles) {
	if (!token.mesh || !token.mesh.texture) return null;

	// Criar sprite com logs
	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);

	// Criar e configurar filtro
	const occlusionFilter = new EnhancedOcclusionFilter();
	
	// Obtenha a matriz de transformação do canvas (worldTransform)
	const worldTransform = canvas.stage.worldTransform;
	  
	// Converta o worldTransform para uma matriz 3x3 para passar para o shader
	const projectionMatrix = new PIXI.Matrix(
			worldTransform.a,
			worldTransform.b, 
			worldTransform.c,
			worldTransform.d, 
			worldTransform.tx,
			worldTransform.ty
	);
	
	// Passe a matriz de projeção para o filtro
	occlusionFilter.uniforms.projectionMatrix = projectionMatrix.toArray(); // Converte a matriz para um array para passar como uniforme

	// Atualiza os tiles intersectados no filtro
	occlusionFilter.updateTiles(intersectingTiles);
	// occlusionFilter.updateTokenTransform(token);
	
	// Aplicar filtro
	sprite.filters = [occlusionFilter, colorMatrix];
	sprite.eventMode = 'passive';
	return sprite;
}






// Create a greyscale/dimming filter
const colorMatrix = new PIXI.ColorMatrixFilter();
colorMatrix.alpha = 1;
colorMatrix.matrix = [
	0.0,  0.0,  0.0,  0.0,  0.0,
	0.0,  0.0,  0.0,  0.0,  0.0,
	1.0,  1.0,  1.0,  0.0,  0.0,
	0.0,  0.0,  0.0,  1.0,  0.0
];