package com.mygdx.game;


import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import java.util.ArrayList;
import java.util.List;

public class MenuRenderer {
    private final SpriteBatch batch;
    private BitmapFont titleFont;
    private BitmapFont font;
    private GlyphLayout layout;
    private Texture whitePixel;
    private int width, height;

    private List<MenuButton> mainMenuButtons;
    private List<MenuButton> planetSelectButtons;
    private List<MenuButton> helpButtons;
    private List<MenuButton> achievementsButtons;

    private float titlePulse = 0;
    private float starTimer = 0;

    public MenuRenderer(SpriteBatch batch, BitmapFont font, GlyphLayout layout,
                        Texture whitePixel, int width, int height) {
        this.batch = batch;
        this.font = font;
        this.layout = layout;
        this.whitePixel = whitePixel;
        this.width = width;
        this.height = height;

        // Создаем увеличенный шрифт для заголовка
        this.titleFont = new BitmapFont();
        this.titleFont.getData().setScale(2.5f);

        createMainMenuButtons();
        createPlanetSelectButtons();
        createHelpButtons();
        createAchievementsButtons();
    }

    private void createMainMenuButtons() {
        mainMenuButtons = new ArrayList<>();
        float buttonWidth = 400;
        float buttonHeight = 70;
        float startY = height/2 + 30;
        float spacing = 75;

        // Кнопка "Продолжить" (если есть сохранение)
        mainMenuButtons.add(new MenuButton(
            width/2 - buttonWidth/2, startY, buttonWidth, buttonHeight,
            Localization.continueGame(),
            GameConfig.BUTTON_HELP,
            GameConfig.BUTTON_HELP_HOVER,
            () -> {}
        ).withTextColor(Color.WHITE));

        // Кнопка "Новая игра"
        mainMenuButtons.add(new MenuButton(
            width/2 - buttonWidth/2, startY - spacing, buttonWidth, buttonHeight,
            Localization.newGame(),
            GameConfig.BUTTON_NEW_GAME,
            GameConfig.BUTTON_NEW_GAME_HOVER,
            () -> {}
        ).withTextColor(Color.YELLOW));

        // Кнопка "Выбор планеты"
        mainMenuButtons.add(new MenuButton(
            width/2 - buttonWidth/2, startY - spacing * 2, buttonWidth, buttonHeight,
            Localization.selectPlanet(),
            GameConfig.BUTTON_PLANET,
            GameConfig.BUTTON_PLANET_HOVER,
            () -> {}
        ));

        // Кнопка "Достижения"
        mainMenuButtons.add(new MenuButton(
            width/2 - buttonWidth/2, startY - spacing * 3, buttonWidth, buttonHeight,
            Localization.achievements(),
            new Color(0.9f, 0.7f, 0.2f, 0.9f),
            new Color(1.0f, 0.8f, 0.3f, 1f),
            () -> {}
        ));

        // Кнопка "Помощь"
        mainMenuButtons.add(new MenuButton(
            width/2 - buttonWidth/2, startY - spacing * 4, buttonWidth, buttonHeight,
            Localization.help(),
            GameConfig.BUTTON_HELP,
            GameConfig.BUTTON_HELP_HOVER,
            () -> {}
        ));

        // Кнопка "Выход"
        mainMenuButtons.add(new MenuButton(
            width/2 - buttonWidth/2, startY - spacing * 5, buttonWidth, buttonHeight,
            Localization.exit(),
            GameConfig.BUTTON_EXIT,
            GameConfig.BUTTON_EXIT_HOVER,
            () -> System.exit(0)
        ));
    }

    /**
     * Обновить тексты кнопок меню (при смене языка).
     */
    public void refreshMenuTexts() {
        createMainMenuButtons();
        createPlanetSelectButtons();
        createHelpButtons();
        createAchievementsButtons();
    }

    private void createPlanetSelectButtons() {
        planetSelectButtons = new ArrayList<>();
        float buttonWidth = 350;
        float buttonHeight = 100;
        float startY = height/2 + 50;
        float spacing = 120;

        // Земля
        planetSelectButtons.add(new MenuButton(
            width/2 - buttonWidth - 20, startY, buttonWidth, buttonHeight,
            Localization.earth(),
            GameConfig.BUTTON_EARTH,
            GameConfig.BUTTON_EARTH_HOVER,
            () -> {}
        ).withTextColor(Color.WHITE));

        // Марс
        planetSelectButtons.add(new MenuButton(
            width/2 + 20, startY, buttonWidth, buttonHeight,
            Localization.mars(),
            GameConfig.BUTTON_MARS,
            GameConfig.BUTTON_MARS_HOVER,
            () -> {}
        ));

        // Венера
        planetSelectButtons.add(new MenuButton(
            width/2 - buttonWidth/2, startY - spacing, buttonWidth, buttonHeight,
            Localization.venus(),
            GameConfig.BUTTON_VENUS,
            GameConfig.BUTTON_VENUS_HOVER,
            () -> {}
        ));

        // Кнопка "Назад"
        planetSelectButtons.add(new MenuButton(
            50, 50, 200, 60,
            Localization.back(),
            GameConfig.BUTTON_BACK,
            GameConfig.BUTTON_BACK_HOVER,
            () -> {}
        ));
    }

    private void createHelpButtons() {
        helpButtons = new ArrayList<>();

        // Кнопка "Назад"
        helpButtons.add(new MenuButton(
            50, 50, 200, 60,
            Localization.back(),
            GameConfig.BUTTON_BACK,
            GameConfig.BUTTON_BACK_HOVER,
            () -> {}
        ));
    }

    private void createAchievementsButtons() {
        achievementsButtons = new ArrayList<>();

        // Кнопка "Назад"
        achievementsButtons.add(new MenuButton(
            50, 50, 200, 60,
            Localization.back(),
            GameConfig.BUTTON_BACK,
            GameConfig.BUTTON_BACK_HOVER,
            () -> {}
        ));
    }

    public void update(float deltaTime) {
        titlePulse += deltaTime * 2;
        starTimer += deltaTime;
    }

    public void renderMainMenu(float mouseX, float mouseY) {
        batch.begin();

        // Космический фон
        renderSpaceBackground();

        // Заголовок
        renderTitle();

        // Подзаголовок
        font.setColor(new Color(0.8f, 0.9f, 1.0f, 0.8f));
        font.getData().setScale(1.2f);
        String subtitle = Localization.gameSubtitle();
        layout.setText(font, subtitle);
        font.draw(batch, subtitle, width/2 - layout.width/2, height - 150);
        font.getData().setScale(1.0f);

        // Кнопки
        boolean hasSave = GameSave.hasSave();
        for (int i = 0; i < mainMenuButtons.size(); i++) {
            MenuButton button = mainMenuButtons.get(i);
            // Скрываем кнопку "Продолжить" если нет сохранения
            if (i == 0 && !hasSave) {
                continue;
            }
            button.render(batch, font, layout, whitePixel);
        }

        // Переключатель языка
        renderLanguageSwitch(mouseX, mouseY);

        // Статистика
        renderStats();

        // Автор
        font.setColor(new Color(1, 1, 1, 0.5f));
        font.getData().setScale(0.8f);
        font.draw(batch, "© 2024 Absurd City Builder", width - 250, 30);
        font.getData().setScale(1.0f);

        batch.end();
    }

    private void renderLanguageSwitch(float mouseX, float mouseY) {
        float langX = width - 80;
        float langY = height - 50;
        float langW = 60;
        float langH = 35;

        // Фон кнопки
        boolean hovered = mouseX >= langX && mouseX <= langX + langW && 
                         mouseY >= langY && mouseY <= langY + langH;
        batch.setColor(hovered ? new Color(0.4f, 0.5f, 0.6f, 0.9f) : new Color(0.3f, 0.4f, 0.5f, 0.8f));
        batch.draw(whitePixel, langX, langY, langW, langH);

        // Рамка
        batch.setColor(Color.WHITE);
        batch.draw(whitePixel, langX, langY, langW, 2);
        batch.draw(whitePixel, langX, langY + langH - 2, langW, 2);
        batch.draw(whitePixel, langX, langY, 2, langH);
        batch.draw(whitePixel, langX + langW - 2, langY, 2, langH);

        // Текст языка
        font.setColor(Color.WHITE);
        font.getData().setScale(1.0f);
        String langText = Localization.getLanguageLabel();
        layout.setText(font, langText);
        font.draw(batch, langText, langX + langW/2 - layout.width/2, langY + langH/2 + layout.height/2);
    }

    private void renderStats() {
        font.setColor(new Color(0.7f, 0.8f, 0.9f, 0.7f));
        font.getData().setScale(0.8f);
        
        int total = GameSave.getTotalBuildings();
        int achievements = Achievements.getUnlockedCount();
        int totalAch = Achievements.getTotalCount();
        
        String stats = Localization.isRu() 
            ? "Построено зданий: " + total + " | Достижения: " + achievements + "/" + totalAch
            : "Buildings: " + total + " | Achievements: " + achievements + "/" + totalAch;
        
        layout.setText(font, stats);
        font.draw(batch, stats, width/2 - layout.width/2, 60);
        font.getData().setScale(1.0f);
    }

    /**
     * Проверить клик на переключатель языка.
     */
    public boolean checkLanguageClick(float mouseX, float mouseY) {
        float langX = width - 80;
        float langY = height - 50;
        float langW = 60;
        float langH = 35;
        
        return mouseX >= langX && mouseX <= langX + langW && 
               mouseY >= langY && mouseY <= langY + langH;
    }

    public void renderPlanetSelect(float mouseX, float mouseY) {
        batch.begin();

        // Космический фон
        renderSpaceBackground();

        // Заголовок
        titleFont.setColor(new Color(1, 1, 1, 0.9f));
        String title = Localization.selectPlanet();
        layout.setText(titleFont, title);
        titleFont.draw(batch, title, width/2 - layout.width/2, height - 100);

        // Описание
        font.setColor(new Color(0.8f, 0.9f, 1.0f, 0.8f));
        font.getData().setScale(1.1f);
        String desc = Localization.isRu() ? "Выберите планету для строительства:" : "Select a planet for building:";
        layout.setText(font, desc);
        font.draw(batch, desc, width/2 - layout.width/2, height - 170);
        font.getData().setScale(1.0f);

        // Описания планет
        font.setColor(Color.LIGHT_GRAY);
        font.getData().setScale(0.9f);

        // Земля
        String earthText = Localization.isRu() 
            ? "Мультяшные здания\nЯркие цвета\nМилые жители"
            : "Cartoon buildings\nBright colors\nCute residents";
        font.draw(batch, earthText, width/2 - 380, height/2 - 50);

        // Марс
        String marsText = Localization.isRu()
            ? "Технологичные постройки\nКрасный пейзаж\nМарсианские роботы"
            : "Tech buildings\nRed landscape\nMartian robots";
        font.draw(batch, marsText, width/2 + 30, height/2 - 50);

        // Венера
        String venusText = Localization.isRu()
            ? "Вулканические здания\nРаскаленная атмосфера\nКристаллические формы"
            : "Volcanic buildings\nHot atmosphere\nCrystal forms";
        font.draw(batch, venusText, width/2 - 175, height/2 - 200);
        font.getData().setScale(1.0f);

        // Кнопки
        for (MenuButton button : planetSelectButtons) {
            button.render(batch, font, layout, whitePixel);
        }

        batch.end();
    }

    public void renderHelp(float mouseX, float mouseY) {
        batch.begin();

        // Фон
        batch.setColor(GameConfig.MENU_SPACE_BG);
        batch.draw(whitePixel, 0, 0, width, height);
        batch.setColor(Color.WHITE);

        // Заголовок
        titleFont.setColor(Color.YELLOW);
        String title = Localization.isRu() ? "❓ ПОМОЩЬ И УПРАВЛЕНИЕ" : "❓ HELP & CONTROLS";
        layout.setText(titleFont, title);
        titleFont.draw(batch, title, width/2 - layout.width/2, height - 100);

        // Инструкции
        font.setColor(Color.WHITE);
        font.getData().setScale(1.1f);

        float textY = height - 200;
        float lineHeight = 35;

        String[] instructions = Localization.isRu() ? new String[] {
            "🎮 ОСНОВНОЕ УПРАВЛЕНИЕ:",
            "• ЛКМ - кликнуть на поле для строительства",
            "• ←/→ - выбрать тип здания",
            "• Enter - отправить ответ на задачу",
            "• Backspace - удалить блок/символ",
            "• Delete/Ctrl+Z - удалить здание",
            "• ESC - отмена ввода / меню",
            "",
            "🪐 УПРАВЛЕНИЕ ПЛАНЕТАМИ:",
            "• ↑/↓ - переключить планету",
            "• 1 - Земля, 2 - Марс, 3 - Венера",
            "",
            "🎯 КАК ИГРАТЬ:",
            "1. Выберите тип здания",
            "2. Кликните на игровом поле",
            "3. Решите математическую задачу",
            "4. Постройте 3 блока для завершения"
        } : new String[] {
            "🎮 BASIC CONTROLS:",
            "• LMB - click on the field to build",
            "• ←/→ - select building type",
            "• Enter - submit answer",
            "• Backspace - delete block/character",
            "• Delete/Ctrl+Z - delete building",
            "• ESC - cancel input / menu",
            "",
            "🪐 PLANET CONTROLS:",
            "• ↑/↓ - switch planet",
            "• 1 - Earth, 2 - Mars, 3 - Venus",
            "",
            "🎯 HOW TO PLAY:",
            "1. Select building type",
            "2. Click on the game field",
            "3. Solve the math problem",
            "4. Build 3 blocks to complete"
        };

        for (String line : instructions) {
            if (line.startsWith("🎮") || line.startsWith("🪐") || line.startsWith("🎯")) {
                font.setColor(Color.CYAN);
            } else if (line.startsWith("•")) {
                font.setColor(Color.LIGHT_GRAY);
            } else {
                font.setColor(Color.WHITE);
            }
            font.draw(batch, line, 100, textY);
            textY -= lineHeight;
        }

        font.getData().setScale(1.0f);

        // Кнопки
        for (MenuButton button : helpButtons) {
            button.render(batch, font, layout, whitePixel);
        }

        batch.end();
    }

    public void renderAchievements(float mouseX, float mouseY) {
        batch.begin();

        // Фон
        batch.setColor(new Color(0.08f, 0.05f, 0.12f, 1));
        batch.draw(whitePixel, 0, 0, width, height);
        batch.setColor(Color.WHITE);

        // Заголовок
        titleFont.setColor(new Color(1f, 0.85f, 0.3f, 1));
        String title = Localization.achievements();
        layout.setText(titleFont, title);
        titleFont.draw(batch, title, width/2 - layout.width/2, height - 80);

        // Прогресс
        font.setColor(new Color(0.8f, 0.8f, 0.8f, 1));
        font.getData().setScale(1.0f);
        String progress = Achievements.getUnlockedCount() + " / " + Achievements.getTotalCount();
        layout.setText(font, progress);
        font.draw(batch, progress, width/2 - layout.width/2, height - 120);

        // Список достижений
        float startY = height - 180;
        float itemHeight = 70;
        float itemWidth = 600;
        float itemX = width/2 - itemWidth/2;

        Achievement[] all = Achievements.getAll();
        for (int i = 0; i < all.length; i++) {
            Achievement a = all[i];
            boolean unlocked = Achievements.isUnlocked(a);
            float y = startY - i * itemHeight;

            // Фон элемента
            if (unlocked) {
                batch.setColor(new Color(0.2f, 0.3f, 0.2f, 0.8f));
            } else {
                batch.setColor(new Color(0.15f, 0.15f, 0.2f, 0.6f));
            }
            batch.draw(whitePixel, itemX, y, itemWidth, itemHeight - 5);

            // Рамка
            batch.setColor(unlocked ? new Color(0.5f, 0.8f, 0.5f, 0.5f) : new Color(0.3f, 0.3f, 0.4f, 0.3f));
            batch.draw(whitePixel, itemX, y, itemWidth, 2);
            batch.draw(whitePixel, itemX, y + itemHeight - 7, itemWidth, 2);

            // Иконка
            font.getData().setScale(1.3f);
            font.setColor(unlocked ? new Color(0.3f, 0.9f, 0.3f, 1) : new Color(0.4f, 0.4f, 0.5f, 1));
            font.draw(batch, unlocked ? "✓" : "○", itemX + 15, y + itemHeight - 25);

            // Название
            font.getData().setScale(1.1f);
            font.setColor(unlocked ? Color.WHITE : new Color(0.6f, 0.6f, 0.6f, 1));
            font.draw(batch, a.getTitle(), itemX + 55, y + itemHeight - 20);

            // Описание
            font.getData().setScale(0.85f);
            font.setColor(unlocked ? new Color(0.8f, 0.8f, 0.8f, 1) : new Color(0.5f, 0.5f, 0.5f, 1));
            font.draw(batch, a.getDescription(), itemX + 55, y + itemHeight - 45);
        }

        font.getData().setScale(1.0f);

        // Кнопка назад
        for (MenuButton button : achievementsButtons) {
            button.render(batch, font, layout, whitePixel);
        }

        batch.end();
    }

    public void renderAbout(float mouseX, float mouseY) {
        batch.begin();

        // Галактический фон
        batch.setColor(GameConfig.MENU_SPACE_BG);
        batch.draw(whitePixel, 0, 0, width, height);

        // Звезды
        batch.setColor(Color.WHITE);
        for (int i = 0; i < 50; i++) {
            float starX = (float)Math.sin(starTimer + i) * width + width/2;
            float starY = (float)Math.cos(starTimer * 0.5f + i) * height/2 + height/2;
            float size = 1 + (float)Math.sin(starTimer * 2 + i) * 2;
            batch.draw(whitePixel, starX, starY, size, size);
        }

        batch.setColor(Color.WHITE);

        // Заголовок
        titleFont.setColor(new Color(0.8f, 0.4f, 1.0f, 1));
        String title = Localization.about();
        layout.setText(titleFont, title);
        titleFont.draw(batch, title, width/2 - layout.width/2, height - 100);

        // Описание игры
        font.setColor(new Color(0.9f, 0.9f, 1.0f, 0.9f));
        font.getData().setScale(1.2f);

        String[] aboutText = Localization.isRu() ? new String[] {
            "Absurd City Builder - это уникальная игра,",
            "где вы строите безумные города на разных планетах!",
            "",
            "Особенности игры:",
            "• 3 уникальные планеты с разными зданиями",
            "• Забавные математические задачи",
            "• Мультяшная графика и анимации",
            "• Система достижений",
            "• Поддержка русского и английского языков",
            "",
            "Разработано с ❤️ для любителей абсурда и математики.",
            "",
            "Версия 1.1"
        } : new String[] {
            "Absurd City Builder is a unique game",
            "where you build crazy cities on different planets!",
            "",
            "Features:",
            "• 3 unique planets with different buildings",
            "• Fun math puzzles",
            "• Cartoon graphics and animations",
            "• Achievement system",
            "• Russian and English support",
            "",
            "Made with ❤️ for absurdity and math lovers.",
            "",
            "Version 1.1"
        };

        float textY = height - 200;
        for (String line : aboutText) {
            layout.setText(font, line);
            font.draw(batch, line, width/2 - layout.width/2, textY);
            textY -= 40;
        }

        font.getData().setScale(1.0f);

        // Кнопка "Назад"
        MenuButton backButton = new MenuButton(
            50, 50, 200, 60,
            Localization.back(),
            GameConfig.BUTTON_BACK,
            GameConfig.BUTTON_BACK_HOVER,
            () -> {}
        );
        backButton.render(batch, font, layout, whitePixel);

        batch.end();
    }

    private void renderSpaceBackground() {
        // Темный космический фон
        batch.setColor(GameConfig.MENU_SPACE_BG);
        batch.draw(whitePixel, 0, 0, width, height);

        // Звезды
        batch.setColor(Color.WHITE);
        for (int i = 0; i < 100; i++) {
            float starX = (i * 37.3f) % width;
            float starY = (i * 23.7f) % height;
            float twinkle = 0.5f + 0.5f * (float)Math.sin(starTimer * 3 + i);
            batch.setColor(new Color(1, 1, 1, twinkle));
            float size = 1 + (i % 3);
            batch.draw(whitePixel, starX, starY, size, size);
        }
        batch.setColor(Color.WHITE);

        // Планеты на заднем фоне
        batch.setColor(new Color(0.3f, 0.6f, 0.9f, 0.3f));
        batch.draw(whitePixel, width - 200, 100, 150, 150);

        batch.setColor(new Color(0.8f, 0.3f, 0.2f, 0.3f));
        batch.draw(whitePixel, 100, height - 200, 120, 120);

        batch.setColor(new Color(1.0f, 0.7f, 0.2f, 0.3f));
        batch.draw(whitePixel, width - 150, height - 150, 100, 100);
    }

    private void renderTitle() {
        // Пульсирующий заголовок
        float pulse = 0.8f + 0.2f * (float)Math.sin(titlePulse);
        titleFont.setColor(new Color(1, pulse, 0.5f, 1));

        String title = Localization.gameTitle();
        layout.setText(titleFont, title);
        titleFont.draw(batch, title, width/2 - layout.width/2, height - 100);

        // Блестки вокруг заголовка
        batch.setColor(new Color(1, 1, 0.5f, 0.3f));
        for (int i = 0; i < 8; i++) {
            float angle = titlePulse + i * 0.785f;
            float sparkleX = width/2 + (float)Math.cos(angle) * 200;
            float sparkleY = height - 100 + (float)Math.sin(angle) * 50;
            float size = 5 + (float)Math.sin(titlePulse * 2 + i) * 3;
            batch.draw(whitePixel, sparkleX, sparkleY, size, size);
        }
    }

    public MenuButton getMainMenuButtonAt(float x, float y) {
        boolean hasSave = GameSave.hasSave();
        for (int i = 0; i < mainMenuButtons.size(); i++) {
            // Пропускаем кнопку "Продолжить" если нет сохранения
            if (i == 0 && !hasSave) {
                continue;
            }
            MenuButton button = mainMenuButtons.get(i);
            if (button.contains(x, y)) {
                return button;
            }
        }
        return null;
    }

    public MenuButton getPlanetSelectButtonAt(float x, float y) {
        for (MenuButton button : planetSelectButtons) {
            if (button.contains(x, y)) {
                return button;
            }
        }
        return null;
    }

    public MenuButton getHelpButtonAt(float x, float y) {
        for (MenuButton button : helpButtons) {
            if (button.contains(x, y)) {
                return button;
            }
        }
        return null;
    }

    public MenuButton getAchievementsButtonAt(float x, float y) {
        for (MenuButton button : achievementsButtons) {
            if (button.contains(x, y)) {
                return button;
            }
        }
        return null;
    }

    public void dispose() {
        titleFont.dispose();
    }
}
