/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   menu.c                                             :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: qmennen <qmennen@student.codam.nl>         +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2025/05/27 14:31:53 by qmennen           #+#    #+#             */
/*   Updated: 2025/06/11 15:02:35 by qmennen          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "game_menu.h"

t_menu	*menu_create(t_game_manager *manager, char *b_path,
					const t_menu_item *options[])
{
	t_menu	*menu;
	int		i;

	menu = malloc(sizeof(t_menu));
	if (!menu)
		return (NULL);
	ft_memset(menu, 0, sizeof(t_menu));
	menu_set_background(menu, manager->game->screen->mlx, b_path);
	menu->hidden = 1;
	i = -1;
	while (options[++i])
		menu->items[i] = (t_menu_item *)options[i];
	menu->selector = mlx_put_string(manager->game->screen->mlx, ">", 0, 0);
	menu->selector->instances[0].enabled = false;
	menu->num_options = i;
	return (menu);
}

void	menu_display(t_menu *menu, t_screen *screen)
{
	int	i;
	int	half_h;

	half_h = screen->height / 2;
	if (menu->hidden)
		menu_toggle(menu);
	menu->selector->instances[0].x = 150;
	menu->selector->instances[0].y = half_h + menu->selected_option * 50;
	i = 0;
	while (i < menu->num_options)
	{
		menu->items[i]->image->instances[0].x = 200;
		menu->items[i]->image->instances[0].y = half_h + i * 50;
		i++;
	}
}

void	menu_toggle(t_menu *menu)
{
	int	i;

	if (!menu)
		return ;
	menu->hidden = !menu->hidden;
	if (menu->selector)
		menu->selector->instances[0].enabled = !menu->hidden;
	if (menu->background)
		menu->background->instances[0].enabled = !menu->hidden;
	i = -1;
	while (++i < menu->num_options)
	{
		menu->items[i]->image->instances[0].enabled = !menu->hidden;
		mlx_set_instance_depth(menu->items[i]->image->instances, 7);
	}
}

void	menu_free(t_menu *menu, t_screen *screen)
{
	int	i;

	(void)screen;
	i = 0;
	if (!menu)
		return ;
	while (i < menu->num_options)
	{
		free(menu->items[i]);
		i++;
	}
	free(menu);
}
