// Enhanced Occlusion Layer Module for Foundry VTT

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

		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 = /*gls l*/`
	
`;

const occlusionFragmentShader = /*gls l*/`
	
`


// Create the enhanced occlusion filter
class EnhancedOcclusionFilter extends PIXI.Filter {
	constructor() {
		super(occlusionVertexShader, occlusionFragmentShader);
		
		// Initialize uniforms
		this.uniforms.uTileMasks = [];
		this.uniforms.uTileBounds = new Float32Array(32);  // Support up to 8 tiles (8 * 4 values)
		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 = 0.8;  // Slightly transparent by default

		// Keep track of current tiles for updates
		this._intersectingTiles = [];
	}
	
	updateTiles(intersectingTiles) {
		const count = Math.min(intersectingTiles.length, 8);
		this.uniforms.uTileCount = count;
		this._intersectingTiles = intersectingTiles.slice(0, 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;
		}
	}

	// Add method to update alpha
	setAlpha(alpha) {
		this.uniforms.uAlpha = Math.max(0, Math.min(1, alpha));
	}
		
	// Add method to update highlight color
	setHighlightColor(r, g, b, a = 1.0) {
		this.uniforms.uColorMatrix = new Float32Array([r, g, b, a]);
	}
}





// 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();

	// Atualiza os tiles intersectados no filtro
	occlusionFilter.updateTiles(intersectingTiles);
	
	// Aplicar filtro
	sprite.filters = [occlusionFilter];
	sprite.eventMode = 'passive';

	return sprite;
}