/*
 *  Copyright 2025-2026 R3944Realms
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package top.r3944realms.eroticdungeongame.secret;

import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*;
import net.minecraft.Util;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.renderer.ShaderInstance;
import net.minecraft.network.chat.Component;
import org.jetbrains.annotations.NotNull;
import top.r3944realms.eroticdungeongame.client.shader.EDGShaders;

import java.util.ArrayList;
import java.util.List;

public class SecretScreen extends Screen {

    private final List<String> urls = List.of(
            "https://www.teacon.cn/thank",
            "https://www.teacon.cn/thank",
            "https://www.teacon.cn/thank",
            "https://www.teacon.cn/thank",
            "https://www.teacon.cn/thank",
            "https://www.teacon.cn/thank",
            "https://www.teacon.cn/thank",
            "https://www.teacon.cn/thank",
            "https://www.teacon.cn/thank",
            "https://www.teacon.cn/thank",
            "https://www.bilibili.com/video/BV15irxYzE77",
            "https://www.bilibili.com/video/BV1Sx411N7uH",
            "https://www.bilibili.com/video/BV1jy4y1i75a",
            "https://www.bilibili.com/video/BV1p4r8YwEFq",
            "https://www.bilibili.com/video/BV1XV411b7ZE"
    );

    private final String mayTrue = "https://pic.leisuretimedock.top/images/2026/03/31/pizza_01.png";

    private final List<Collidable> collidables = new ArrayList<>();
    private long startTime;

    private float mouseXCache;
    private float mouseYCache;

    public SecretScreen() {
        super(Component.empty());
    }

    @Override
    protected void init() {
        collidables.clear();
        startTime = System.currentTimeMillis();

        BouncingText text1 = new BouncingText(font, "这是假地址", width * 0.25f, height * 0.2f, 2.5f);
        text1.setVelocity(1,1);
        collidables.add(text1);
        BouncingText text2 = new BouncingText(font, "你必须通过我设计的谜题", width * 0.6f, height * 0.35f, 1.5f);
        text2.setVelocity(1,1);
        collidables.add(text2);
        BouncingText text3 = new BouncingText(font, "才能找到真正的服务器地址", width * 0.2f, height * 0.6f, 1.5f);
        text3.setVelocity(1,1);
        collidables.add(text3);
        BouncingText text4 = new BouncingText(font, "来找到真正的开始按钮吧", width * 0.65f, height * 0.75f, 2.0f);
        text4.setVelocity(1,1);
        collidables.add(text4);

        for (int i = 0; i < 5; i++) {
            createButton(width / 2f, height / 2f);
        }
    }

    private void createButton(float x, float y) {
        BouncingButton btn = new BouncingButton(
                this.font,
                "开始按钮",
                x + random(-100, 100),
                y + random(-60, 60),
                40, 20,
                1f
        );

        btn.setVelocity(randomVel(), randomVel());

        btn.setOnClick(this::handleClick);

        collidables.add(btn);
    }

    private void handleClick(BouncingButton btn) {

        if (Math.random() < 0.85) {
            String url = urls.get((int) (Math.random() * urls.size()));
            Util.getPlatform().openUri(url);
        } else {
            Util.getPlatform().openUri(mayTrue);
            assert minecraft != null;
            minecraft.setScreen(null);
        }

        if (collidables.size() < 120) {
            int count = 2 + (int) (Math.random() * 3);
            for (int i = 0; i < count; i++) {
                createButton(btn.getX(), btn.getY());
            }
        }

        collidables.remove(btn);
    }

    @Override
    public void tick() {
        super.tick();

        for (Collidable c : collidables) {

            if (c instanceof BouncingButton b) {
                applyMouseRepel(b);
            }

            c.tick(width, height);
        }

        // 碰撞
        for (int i = 0; i < collidables.size(); i++) {
            Collidable a = collidables.get(i);
            for (int j = i + 1; j < collidables.size(); j++) {
                Collidable b = collidables.get(j);
                if (a.isColliding(b)) {
                    a.onCollision(b);
                    b.onCollision(a);
                }
            }
        }
    }

    private void applyMouseRepel(BouncingButton btn) {
        float cx = btn.getX() + btn.getWidth() / 2f;
        float cy = btn.getY() + btn.getHeight() / 2f;

        float dx = cx - mouseXCache;
        float dy = cy - mouseYCache;

        float distSq = dx * dx + dy * dy;
        float range = 120f;

        if (distSq < range * range) {
            float dist = (float) Math.sqrt(distSq);
            if (dist < 0.001f) dist = 0.001f;

            float strength = 1f - dist / range;
            strength *= strength;

            float force = 1.2f * strength;

            btn.addVelocity(dx / dist * force, dy / dist * force);
        }
    }

    @Override
    public void render(@NotNull GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
        this.mouseXCache = mouseX;
        this.mouseYCache = mouseY;

        renderBackground(guiGraphics);

        for (Collidable c : collidables) {
            if (c instanceof BouncingText t) t.render(guiGraphics);
            if (c instanceof BouncingButton b) b.render(guiGraphics, mouseX, mouseY);
        }

        super.render(guiGraphics, mouseX, mouseY, partialTick);
    }

    @Override
    public boolean mouseClicked(double mouseX, double mouseY, int button) {
        for (Collidable c : new ArrayList<>(collidables)) {
            if (c instanceof BouncingButton b) {
                b.mouseClicked(mouseX, mouseY, button);
            }
        }
        return super.mouseClicked(mouseX, mouseY, button);
    }

    private float randomVel() {
        return (float) (Math.random() * 2 - 1) * 1.5f;
    }

    private float random(float min, float max) {
        return min + (float) Math.random() * (max - min);
    }

    @Override
    public void renderBackground(@NotNull GuiGraphics guiGraphics) {
        ShaderInstance shader = EDGShaders.getSecretShader();

        if (shader != null) {
            guiGraphics.fill(0, 0, width, height, 0xFF000000);

            RenderSystem.disableDepthTest();
            RenderSystem.setShader(EDGShaders::getSecretShader);

            float time = (System.currentTimeMillis() - startTime) / 1000f;

            shader.safeGetUniform("iTime").set(time);
            shader.safeGetUniform("iResolution").set((float) width, (float) height);

            Tesselator tess = Tesselator.getInstance();
            BufferBuilder buffer = tess.getBuilder();

            buffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION);

            buffer.vertex(width, 0, 0).endVertex();
            buffer.vertex(0, 0, 0).endVertex();
            buffer.vertex(0, height, 0).endVertex();
            buffer.vertex(width, height, 0).endVertex();

            BufferUploader.drawWithShader(buffer.end());

            RenderSystem.enableDepthTest();
        } else {
            super.renderBackground(guiGraphics);
        }
    }
}