package com.mygdx.game;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.Texture;

public class MenuButton {
    private float x, y, width, height;
    private String text;
    private Color normalColor;
    private Color hoverColor;
    private Color textColor;
    private boolean isHovered;
    private Runnable action;
    private String icon;

    public MenuButton(float x, float y, float width, float height, String text,
                      Color normalColor, Color hoverColor, Runnable action) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.text = text;
        this.normalColor = normalColor;
        this.hoverColor = hoverColor;
        this.textColor = Color.WHITE;
        this.isHovered = false;
        this.action = action;
        this.icon = "";
    }

    public MenuButton withIcon(String icon) {
        this.icon = icon;
        return this;
    }
    public String getText() {
        return text;
    }

    public MenuButton withTextColor(Color color) {
        this.textColor = color;
        return this;
    }

    public void update(float mouseX, float mouseY, boolean isClicked) {
        isHovered = mouseX >= x && mouseX <= x + width &&
            mouseY >= y && mouseY <= y + height;

        if (isHovered && isClicked && action != null) {
            action.run();
        }
    }

    public void render(SpriteBatch batch, BitmapFont font, GlyphLayout layout, Texture whitePixel) {
        // Рисуем кнопку
        batch.setColor(isHovered ? hoverColor : normalColor);
        batch.draw(whitePixel, x, y, width, height);

        // Рамка
        batch.setColor(new Color(1, 1, 1, 0.3f));
        batch.draw(whitePixel, x, y, width, 2); // Верх
        batch.draw(whitePixel, x, y + height - 2, width, 2); // Низ
        batch.draw(whitePixel, x, y, 2, height); // Левая
        batch.draw(whitePixel, x + width - 2, y, 2, height); // Правая

        // Текст
        font.setColor(textColor);
        if (!icon.isEmpty()) {
            font.draw(batch, icon + " " + text, x + 20, y + height/2 + 10);
        } else {
            layout.setText(font, text);
            font.draw(batch, text, x + width/2 - layout.width/2, y + height/2 + 10);
        }

        // Эффект при наведении
        if (isHovered) {
            batch.setColor(new Color(1, 1, 1, 0.1f));
            batch.draw(whitePixel, x, y, width, height);
        }
    }

    public boolean contains(float px, float py) {
        return px >= x && px <= x + width && py >= y && py <= y + height;
    }
}
