package de.winniepat.citrus.gui;

import de.winniepat.citrus.Client;
import de.winniepat.citrus.managers.WallpaperManager;
import de.winniepat.citrus.utils.texture.CdnTextureDrawable;
import de.winniepat.citrus.managers.ConfigManager;
import de.winniepat.citrus.managers.ClientRegistrationManager;
import de.winniepat.citrus.managers.RankManager;
import icyllis.modernui.animation.*;
import icyllis.modernui.core.Context;
import icyllis.modernui.fragment.Fragment;
import icyllis.modernui.graphics.drawable.*;
import icyllis.modernui.markflow.Markflow;
import icyllis.modernui.mc.*;
import icyllis.modernui.text.TextPaint;
import icyllis.modernui.util.DataSet;
import icyllis.modernui.view.*;
import icyllis.modernui.widget.*;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.multiplayer.MultiplayerScreen;
import net.minecraft.client.gui.screen.option.OptionsScreen;
import net.minecraft.client.gui.screen.world.SelectWorldScreen;
import net.minecraft.util.Util;
import org.jetbrains.annotations.*;

import com.google.gson.*;
import java.net.URI;
import java.net.http.*;
import java.util.*;
import java.util.concurrent.CompletableFuture;

public class MainMenuScreen extends Fragment implements ScreenCallback {

    private FrameLayout mBackgroundView;
    private View mBackgroundView1;
    private View mBackgroundView2;
    private CdnTextureDrawable mBackground1Drawable;
    private CdnTextureDrawable mBackground2Drawable;
    private boolean mIsUsingView1 = true;
    private TextView mOnlineCountTv;
    private View mRankIconView;
    private LinearLayout mNewsContainer;
    private LinearLayout mWpOptionsContainer;
    private TextView mCurrentWpTv;
    private final List<View> mStaggeredViews = new ArrayList<>();
    private final String[] mSplashes = {
            "100% freshly squeezed!",
            "Optimized to the core.",
            "Latency? Never heard of it.",
            "Taste the difference!",
            "Still fresh.",
            "Fresh since 1.0!",
            "Powered by WinniePat."
    };

    private float getGuiScale() {
        return (float) MinecraftClient.getInstance().getWindow().getScaleFactor();
    }

    private void setFixedTextSize(TextView tv, float px) {
        float scale = getGuiScale();
        tv.setTextSize(px / scale);
    }

    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable DataSet savedInstanceState) {
        Context context = requireContext();

        FrameLayout root = new FrameLayout(context);
        root.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        ));

        mBackgroundView = new FrameLayout(context);
        mBackgroundView.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        ));
        mBackgroundView.setScaleX(1.1f);
        mBackgroundView.setScaleY(1.1f);

        mBackgroundView1 = new View(context);
        mBackgroundView1.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        ));
        mBackgroundView.addView(mBackgroundView1);

        mBackgroundView2 = new View(context);
        mBackgroundView2.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        ));
        mBackgroundView2.setAlpha(0f);
        mBackgroundView.addView(mBackgroundView2);

        root.addView(mBackgroundView);

        WallpaperManager.init();

        mBackground1Drawable = new CdnTextureDrawable();
        mBackground2Drawable = new CdnTextureDrawable();
        mBackgroundView1.setBackground(mBackground1Drawable);
        mBackgroundView2.setBackground(mBackground2Drawable);

        String currentWallpaper = ConfigManager.config.mainmenuWallpaper;
        if (currentWallpaper == null || currentWallpaper.isEmpty()) {
            currentWallpaper = "default.png";
            ConfigManager.config.mainmenuWallpaper = currentWallpaper;
        }

        loadInitialWallpaper(currentWallpaper);

        ObjectAnimator bgPulseX = ObjectAnimator.ofFloat(mBackgroundView, View.SCALE_X, 1.1f, 1.15f);
        ObjectAnimator bgPulseY = ObjectAnimator.ofFloat(mBackgroundView, View.SCALE_Y, 1.1f, 1.15f);
        bgPulseX.setDuration(15000);
        bgPulseY.setDuration(15000);
        bgPulseX.setRepeatCount(ValueAnimator.INFINITE);
        bgPulseY.setRepeatCount(ValueAnimator.INFINITE);
        bgPulseX.setRepeatMode(ValueAnimator.REVERSE);
        bgPulseY.setRepeatMode(ValueAnimator.REVERSE);
        bgPulseX.start();
        bgPulseY.start();

        startParallaxLoop();

        FrameLayout contentWrapper = new FrameLayout(context);
        contentWrapper.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        ));
        root.addView(contentWrapper);

        View logoView = new View(context);
        FrameLayout.LayoutParams logoLp = new FrameLayout.LayoutParams(150, 150);
        logoLp.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
        logoLp.setMargins(0, dp(30), 0, 0);
        logoView.setLayoutParams(logoLp);
        ImageDrawable logoDrawable = new ImageDrawable("citrus", "startscreen/logo.png");
        logoDrawable.setGravity(Gravity.FILL);
        logoView.setBackground(logoDrawable);
        contentWrapper.addView(logoView);
        mStaggeredViews.add(logoView);

        LinearLayout titleLayout = new LinearLayout(context);
        titleLayout.setOrientation(LinearLayout.VERTICAL);
        FrameLayout.LayoutParams titleLp = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        titleLp.setMargins(60,50, 0, 0);
        titleLayout.setLayoutParams(titleLp);

        TextView title = new TextView(context);
        title.setText("CITRUS");
        setFixedTextSize(title,186);
        title.getPaint().setTextStyle(TextPaint.BOLD);
        title.setTextColor(0xFFFFFFFF);
        titleLayout.addView(title);

        TextView subtitle = new TextView(context);
        subtitle.setText("made by WinniePatGG, FullRiskk and AAirCrafter");
        setFixedTextSize(subtitle,36);
        subtitle.setTextColor(0xCCFFFFFF);
        titleLayout.addView(subtitle);

        TextView splash = new TextView(context);
        splash.setText(mSplashes[(int) (Math.random() * mSplashes.length)]);
        setFixedTextSize(splash,30);
        splash.setTextColor(0xFFFFFF00);
        splash.getPaint().setTextStyle(TextPaint.ITALIC);
        titleLayout.addView(splash);

        contentWrapper.addView(titleLayout);
        mStaggeredViews.add(titleLayout);

        LinearLayout navLayout = new LinearLayout(context);
        navLayout.setOrientation(LinearLayout.VERTICAL);
        FrameLayout.LayoutParams navLp = new FrameLayout.LayoutParams(
                280,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        navLp.gravity = Gravity.CENTER_VERTICAL;
        navLp.setMargins(60, 0, 0, 0);
        navLayout.setLayoutParams(navLp);

        addNavButton(navLayout, "Singleplayer", "singleplayer_icon", v -> {
            MinecraftClient.getInstance().execute(() -> {
                MinecraftClient.getInstance().setScreen(new SelectWorldScreen(MinecraftClient.getInstance().currentScreen));
            });
        });
        addNavButton(navLayout, "Multiplayer", "multiplayer_icon", v -> {
            MinecraftClient.getInstance().execute(() -> {
                MinecraftClient.getInstance().setScreen(new MultiplayerScreen(MinecraftClient.getInstance().currentScreen));
            });
        });
        addNavButton(navLayout, "Friends", "multiplayer_icon", v -> {
            MinecraftClient.getInstance().execute(() -> {
                MinecraftClient.getInstance().setScreen(MuiModApi.get().createScreen(new FriendsFragment(), null, MinecraftClient.getInstance().currentScreen));
            });
        });
        addNavButton(navLayout, "Profiles", "multiplayer_icon", v -> {
            MinecraftClient.getInstance().execute(() -> {
                MinecraftClient.getInstance().setScreen(MuiModApi.get().createScreen(new ProfileScreen(), null, MinecraftClient.getInstance().currentScreen));
            });
        });
        addNavButton(navLayout, "Settings", "settings_icon", v -> {
            MinecraftClient.getInstance().execute(() -> {
                MinecraftClient.getInstance().setScreen(new OptionsScreen(MinecraftClient.getInstance().currentScreen, MinecraftClient.getInstance().options));
            });
        });
        addNavButton(navLayout, "test", "settings_icon", v -> {
            MinecraftClient.getInstance().execute(() -> {
                MinecraftClient.getInstance().setScreen(MuiModApi.get().createScreen(new TestScreen(), null, MinecraftClient.getInstance().currentScreen));
            });
        });
        addNavButton(navLayout, "Discord", "discord_icon", v -> {
            Util.getOperatingSystem().open("https://dc.citrus-client.de");
        });
        addNavButton(navLayout, "Quit", "door_icon", v -> {
            MinecraftClient.getInstance().scheduleStop();
        });

        contentWrapper.addView(navLayout);

        mNewsContainer = new LinearLayout(context);
        mNewsContainer.setOrientation(LinearLayout.VERTICAL);
        mNewsContainer.setPadding(20, 20, 20, 20);

        LinearLayout newsSection = new LinearLayout(context);
        newsSection.setOrientation(LinearLayout.VERTICAL);
        FrameLayout.LayoutParams newsSectionLp = new FrameLayout.LayoutParams(
                360,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        newsSectionLp.gravity = Gravity.CENTER_VERTICAL | Gravity.RIGHT;
        newsSectionLp.setMargins(0, 0, 50, 0);
        newsSection.setLayoutParams(newsSectionLp);

        TextView newsLabel = new TextView(context);
        newsLabel.setText("NEWS");
        newsLabel.setTextSize(36);
        setFixedTextSize(newsLabel,72);
        newsLabel.getPaint().setTextStyle(TextPaint.BOLD);
        newsLabel.setTextColor(0xFFFFFFFF);
        newsLabel.setGravity(Gravity.CENTER);
        LinearLayout.LayoutParams newsLabelLp = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        newsLabelLp.setMargins(0, 0, 0, 12);
        newsLabel.setLayoutParams(newsLabelLp);
        newsSection.addView(newsLabel);

        ScrollView newsScroll = new ScrollView(context);
        LinearLayout.LayoutParams newsScrollLp = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                400
        );
        newsScroll.setScrollBarSize(10);
        newsScroll.setLayoutParams(newsScrollLp);

        ShapeDrawable newsBg = new ShapeDrawable();
        newsBg.setShape(ShapeDrawable.RECTANGLE);
        newsBg.setColor(0x33000000);
        newsBg.setCornerRadius(16);
        newsScroll.setBackground(newsBg);

        newsScroll.addView(mNewsContainer);
        newsSection.addView(newsScroll);

        contentWrapper.addView(newsSection);
        mStaggeredViews.add(newsSection);

        mOnlineCountTv = new TextView(context);
        mOnlineCountTv.setText("Online Users: -");
        setFixedTextSize(mOnlineCountTv,30);
        mOnlineCountTv.setTextColor(0x88FFFFFF);
        FrameLayout.LayoutParams onlineLp = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        onlineLp.gravity = Gravity.BOTTOM | Gravity.RIGHT;
        onlineLp.setMargins(0, 0, 60, 20);
        mOnlineCountTv.setLayoutParams(onlineLp);
        contentWrapper.addView(mOnlineCountTv);
        mStaggeredViews.add(mOnlineCountTv);

        LinearLayout profileLayout = new LinearLayout(context);
        profileLayout.setOrientation(LinearLayout.HORIZONTAL);
        profileLayout.setGravity(Gravity.CENTER_VERTICAL);
        FrameLayout.LayoutParams profileLp = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        profileLp.gravity = Gravity.TOP | Gravity.RIGHT;
        profileLp.setMargins(0, 40, 60, 0);
        profileLayout.setLayoutParams(profileLp);
        
        mRankIconView = new View(context);
        LinearLayout.LayoutParams rankIconLp = new LinearLayout.LayoutParams(20, 20);
        rankIconLp.setMargins(0, 0, 4, 0);
        mRankIconView.setLayoutParams(rankIconLp);
        UUID currentUuid = MinecraftClient.getInstance().getSession().getUuidOrNull();
        if (currentUuid != null) {
            String rank = RankManager.getRank(currentUuid);
            if (rank.equals("none") || rank.equals("loading")) {
                mRankIconView.setVisibility(View.GONE);
            } else {
                mRankIconView.setVisibility(View.VISIBLE);
                ImageDrawable rankIcon = new ImageDrawable("citrus", "ranks/" + rank + ".png");
                rankIcon.setGravity(Gravity.FILL);
                mRankIconView.setBackground(rankIcon);
            }
        }
        profileLayout.addView(mRankIconView);

        TextView playerName = new TextView(context);
        playerName.setText(MinecraftClient.getInstance().getSession().getUsername());
        playerName.setTextSize(16);
        setFixedTextSize(playerName,42);
        playerName.setTextColor(0xFFFFFFFF);
        playerName.setPadding(0, 0, 12, 0);
        profileLayout.addView(playerName);

        contentWrapper.addView(profileLayout);
        mStaggeredViews.add(profileLayout);

        LinearLayout wallpaperLayout = new LinearLayout(context);
        wallpaperLayout.setOrientation(LinearLayout.VERTICAL);
        FrameLayout.LayoutParams wallpaperLp = new FrameLayout.LayoutParams(
                160,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        wallpaperLp.gravity = Gravity.BOTTOM | Gravity.LEFT;
        wallpaperLp.setMargins(60, 0, 0, 40);
        wallpaperLayout.setLayoutParams(wallpaperLp);

        TextView wallpaperLabel = new TextView(context);
        wallpaperLabel.setText("Select Wallpaper");
        setFixedTextSize(wallpaperLabel,28);
        wallpaperLabel.setTextColor(0x88FFFFFF);
        wallpaperLabel.setPadding(0, 0, 0, 4);
        wallpaperLayout.addView(wallpaperLabel);

        mCurrentWpTv = new TextView(context);
        String displayWallpaper = ConfigManager.config.mainmenuWallpaper;
        if (displayWallpaper == null || displayWallpaper.isEmpty()) {
            displayWallpaper = "default.png";
        }
        mCurrentWpTv.setText(displayWallpaper);
        setFixedTextSize(mCurrentWpTv,36);
        mCurrentWpTv.setTextColor(0xFFFFFFFF);
        mCurrentWpTv.setPadding(12, 8, 12, 9);

        ShapeDrawable wpBg = new ShapeDrawable();
        wpBg.setShape(ShapeDrawable.RECTANGLE);
        wpBg.setColor(0x26FFFFFF);
        wpBg.setCornerRadius(dp(8));
        mCurrentWpTv.setBackground(wpBg);
        mCurrentWpTv.setClickable(true);

        wallpaperLayout.addView(mCurrentWpTv);

        ScrollView wpScroll = new ScrollView(context);
        LinearLayout.LayoutParams wpScrollLp = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                120
        );
        wpScrollLp.setMargins(0, 4, 0, 0);
        wpScroll.setLayoutParams(wpScrollLp);
        wpScroll.setVisibility(View.GONE);

        mWpOptionsContainer = new LinearLayout(context);
        mWpOptionsContainer.setOrientation(LinearLayout.VERTICAL);
        mWpOptionsContainer.setPadding(4, 4, 4, 4);
        ShapeDrawable optionsBg = new ShapeDrawable();
        optionsBg.setShape(ShapeDrawable.RECTANGLE);
        optionsBg.setColor(0xCC000000);
        optionsBg.setCornerRadius(8);
        mWpOptionsContainer.setBackground(optionsBg);

        mCurrentWpTv.setOnClickListener(v -> {
            wpScroll.setVisibility(wpScroll.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
        });

        populateWallpaperOptions(wpScroll);

        wpScroll.addView(mWpOptionsContainer);
        wallpaperLayout.addView(wpScroll);
        contentWrapper.addView(wallpaperLayout);
        mStaggeredViews.add(wallpaperLayout);

        animateEntrance();

        fetchNews();
        updatePlayerInfo();

        return root;
    }

    private void updatePlayerInfo() {
        CompletableFuture.runAsync(() -> {
            try {
                int count = ClientRegistrationManager.getOnlineCitrusUsers().size();
                MuiModApi.postToUiThread(() -> {
                    if (mOnlineCountTv != null) {
                        mOnlineCountTv.setText("Online Users: " + count);
                    }
                });
            } catch (Exception ignored) {}
        });

        UUID uuid = MinecraftClient.getInstance().getSession().getUuidOrNull();
        if (uuid != null) {
            CompletableFuture.runAsync(() -> {
                String rank = RankManager.getRank(uuid);
                int attempts = 0;
                while (rank.equals("loading") && attempts < 10) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        break;
                    }
                    rank = RankManager.getRank(uuid);
                    attempts++;
                }
                
                String finalRank = rank;
                MuiModApi.postToUiThread(() -> {
                    if (mRankIconView != null) {
                        if (finalRank.equals("none") || finalRank.equals("loading")) {
                            mRankIconView.setVisibility(View.GONE);
                        } else {
                            mRankIconView.setVisibility(View.VISIBLE);
                            ImageDrawable rankIcon = new ImageDrawable("citrus", "ranks/" + finalRank + ".png");
                            rankIcon.setGravity(Gravity.FILL);
                            mRankIconView.setBackground(rankIcon);
                        }
                    }
                });
            });
        }
    }

    private void addNavButton(LinearLayout parent, String text, String iconPath, View.OnClickListener listener) {
        Context context = requireContext();
        
        FrameLayout btnWrapper = new FrameLayout(context);
        LinearLayout.LayoutParams wrapperLp = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                50
        );
        wrapperLp.setMargins(0, 6, 0, 6);
        btnWrapper.setLayoutParams(wrapperLp);

        ShapeDrawable btnBg = new ShapeDrawable();
        btnBg.setShape(ShapeDrawable.RECTANGLE);
        btnBg.setColor(0x1AFFFFFF);
        btnBg.setCornerRadius(10);
        btnWrapper.setBackground(btnBg);

        LinearLayout content = new LinearLayout(context);
        content.setOrientation(LinearLayout.HORIZONTAL);
        content.setGravity(Gravity.CENTER_VERTICAL);
        content.setPadding(20, 0, 20, 0);
        
        ImageDrawable icon = new ImageDrawable("citrus", "startscreen/" + iconPath + ".png");
        icon.setBounds(0, 0, 24, 24);
        
        TextView tv = new TextView(context);
        tv.setText(text);
        setFixedTextSize(tv,36);
        tv.setTextColor(0xFFFFFFFF);
        tv.setCompoundDrawables(icon, null, null, null);
        tv.setCompoundDrawablePadding(16);
        
        content.addView(tv);
        btnWrapper.addView(content);
        
        btnWrapper.setClickable(true);
        btnWrapper.setFocusable(true);
        btnWrapper.setOnClickListener(listener);

        btnWrapper.setOnHoverListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_HOVER_ENTER) {
                ObjectAnimator animator = ObjectAnimator.ofFloat(v, View.TRANSLATION_X, 0f, (float) dp(15));
                animator.setDuration(250);
                animator.setInterpolator(MotionEasingUtils.LINEAR_OUT_SLOW_IN);
                animator.start();
                btnBg.setColor(0x33FFFFFF);
                return true;
            } else if (event.getAction() == MotionEvent.ACTION_HOVER_EXIT) {
                ObjectAnimator animator = ObjectAnimator.ofFloat(v, View.TRANSLATION_X, (float) dp(15), 0f);
                animator.setDuration(250);
                animator.setInterpolator(MotionEasingUtils.LINEAR_OUT_SLOW_IN);
                animator.start();
                btnBg.setColor(0x1AFFFFFF);
                return true;
            }
            return false;
        });

        parent.addView(btnWrapper);
        mStaggeredViews.add(btnWrapper);
    }

    private void animateEntrance() {
        long delay = 200;
        for (View v : mStaggeredViews) {
            v.setAlpha(0);
            float startX = -dp(40);
            
            ViewGroup.LayoutParams lp = v.getLayoutParams();
            if (lp instanceof FrameLayout.LayoutParams flp) {
                if ((flp.gravity & Gravity.RIGHT) == Gravity.RIGHT) {
                    startX = dp(40);
                }
            }

            v.setTranslationX(startX);

            ObjectAnimator alpha = ObjectAnimator.ofFloat(v, View.ALPHA, 0f, 1f);
            ObjectAnimator trans = ObjectAnimator.ofFloat(v, View.TRANSLATION_X, startX, 0f);
            
            AnimatorSet set = new AnimatorSet();
            set.playTogether(alpha, trans);
            set.setDuration(1000);
            set.setStartDelay(delay);
            set.setInterpolator(MotionEasingUtils.MOTION_EASING_EMPHASIZED_DECELERATE);
            set.start();
            
            delay += 80;
        }
    }

    private void fetchNews() {
        CompletableFuture.runAsync(() -> {
            try {
                HttpClient client = HttpClient.newHttpClient();
                HttpRequest request = HttpRequest.newBuilder()
                        .uri(URI.create(Client.API_URL + "/news"))
                        .build();

                var response = client.send(request, HttpResponse.BodyHandlers.ofString());
                JsonObject json = new Gson().fromJson(response.body(), JsonObject.class);

                if (json.get("success").getAsBoolean()) {
                    JsonArray array = json.getAsJsonArray("news");

                    MuiModApi.postToUiThread(() -> {
                        if (mNewsContainer == null) return;
                        mNewsContainer.removeAllViews();
                        for (var element : array) {
                            JsonObject obj = element.getAsJsonObject();
                            mNewsContainer.addView(createNewsCard(
                                    obj.get("title").getAsString(),
                                    obj.get("content").getAsString(),
                                    obj.get("date").getAsString()
                            ));
                        }
                    });
                }
            } catch (Exception e) {
                Client.logger.error("Error while fetching news", e);
            }
        });
    }

    private View createNewsCard(String title, String content, String date) {
        LinearLayout card = new LinearLayout(requireContext());
        card.setOrientation(LinearLayout.VERTICAL);
        card.setPadding(12, 12, 12, 12);
        
        LinearLayout.LayoutParams cardLp = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        cardLp.setMargins(0, 0, 0, 15);
        card.setLayoutParams(cardLp);
        
        ShapeDrawable cardBg = new ShapeDrawable();
        cardBg.setShape(ShapeDrawable.RECTANGLE);
        cardBg.setColor(0x26FFFFFF);
        cardBg.setCornerRadius(8);
        card.setBackground(cardBg);

        TextView titleTv = new TextView(requireContext());
        titleTv.setText(title);
        setFixedTextSize(titleTv,33);
        titleTv.setTextColor(0xFFFFFFFF);
        titleTv.getPaint().setTextStyle(TextPaint.BOLD);
        card.addView(titleTv);

        TextView dateTv = new TextView(requireContext());
        dateTv.setText(date);
        setFixedTextSize(dateTv,22);
        dateTv.setTextColor(0x88FFFFFF);
        dateTv.setPadding(0, 2, 0, 6);
        card.addView(dateTv);

        TextView contentTv = new TextView(requireContext());
        Markflow.create(requireContext()).setMarkdown(contentTv, content);
        setFixedTextSize(contentTv,30);
        contentTv.setTextColor(0xCCFFFFFF);
        card.addView(contentTv);

        return card;
    }

    private int dp(int value) {
        return (int) (value * requireContext().getResources().getDisplayMetrics().density);
    }

    @Override
    public boolean isPauseScreen() {
        return false;
    }

    @Override
    public boolean shouldBlurBackground() {
        return false;
    }

    @Override
    public boolean hasDefaultBackground() {
        return false;
    }

    private void startParallaxLoop() {
        if (mBackgroundView == null) return;
        mBackgroundView.postOnAnimation(new Runnable() {
            @Override
            public void run() {
                if (mBackgroundView != null && mBackgroundView.isAttachedToWindow() && isAdded()) {
                    MinecraftClient mc = MinecraftClient.getInstance();
                    double mouseX = mc.mouse.getX();
                    double mouseY = mc.mouse.getY();
                    int width = mc.getWindow().getWidth();
                    int height = mc.getWindow().getHeight();

                    if (width > 0 && height > 0) {
                        float maxMove = dp(20);
                        float moveX = (float) ((mouseX - width / 2.0) / (width / 2.0) * maxMove);
                        float moveY = (float) ((mouseY - height / 2.0) / (height / 2.0) * maxMove);

                        mBackgroundView.setTranslationX(-moveX);
                        mBackgroundView.setTranslationY(-moveY);
                    }
                    mBackgroundView.postOnAnimation(this);
                }
            }
        });
    }

    private void loadInitialWallpaper(String wallpaper) {
        WallpaperManager.loadWallpaperWithData(wallpaper, imageData -> {
            if (imageData != null) {
                MuiModApi.postToUiThread(() -> {
                    mBackground1Drawable.setImageData(imageData);
                    mBackgroundView1.invalidate();
                });
            }
        });
    }

    private void populateWallpaperOptions(ScrollView wpScroll) {
        Context context = requireContext();

        if (WallpaperManager.isWallpapersListLoaded()) {
            addWallpaperOptionsToContainer(context, wpScroll);
        } else {
            TextView loadingTv = new TextView(context);
            loadingTv.setText("Loading wallpapers...");
            setFixedTextSize(loadingTv, 24);
            loadingTv.setTextColor(0x88FFFFFF);
            loadingTv.setPadding(dp(10), dp(6), dp(10), dp(6));
            mWpOptionsContainer.addView(loadingTv);

            WallpaperManager.onWallpapersLoaded(() -> {
                MuiModApi.postToUiThread(() -> {
                    mWpOptionsContainer.removeAllViews();
                    addWallpaperOptionsToContainer(context, wpScroll);
                });
            });
        }
    }

    private void addWallpaperOptionsToContainer(Context context, ScrollView wpScroll) {
        List<String> wallpapers = WallpaperManager.getAvailableWallpapers();

        for (String wp : wallpapers) {
            TextView option = new TextView(context);
            option.setText(wp);
            setFixedTextSize(option, 24);
            option.setTextColor(0xFFFFFFFF);
            option.setPadding(dp(10), dp(6), dp(10), dp(6));
            option.setClickable(true);
            option.setOnClickListener(v_opt -> {
                ConfigManager.config.mainmenuWallpaper = wp;
                ConfigManager.save();
                mCurrentWpTv.setText(wp);
                updateBackground(wp);
                wpScroll.setVisibility(View.GONE);
            });
            option.setOnHoverListener((v_opt, event) -> {
                if (event.getAction() == MotionEvent.ACTION_HOVER_ENTER) {
                    option.setBackground(new ColorDrawable(0x33FFFFFF));
                } else if (event.getAction() == MotionEvent.ACTION_HOVER_EXIT) {
                    option.setBackground(null);
                }
                return false;
            });
            mWpOptionsContainer.addView(option);
        }
    }

    private void updateBackground(String wallpaper) {
        View activeView = mIsUsingView1 ? mBackgroundView1 : mBackgroundView2;
        View nextView = mIsUsingView1 ? mBackgroundView2 : mBackgroundView1;
        CdnTextureDrawable nextDrawable = mIsUsingView1 ? mBackground2Drawable : mBackground1Drawable;

        WallpaperManager.loadWallpaperWithData(wallpaper, imageData -> {
            MuiModApi.postToUiThread(() -> {
                if (imageData != null) {
                    nextDrawable.setImageData(imageData);
                    nextView.invalidate();
                }

                ObjectAnimator fadeIn = ObjectAnimator.ofFloat(nextView, View.ALPHA, 0f, 1f);
                ObjectAnimator fadeOut = ObjectAnimator.ofFloat(activeView, View.ALPHA, 1f, 0f);
                fadeIn.setDuration(800);
                fadeOut.setDuration(800);
                fadeIn.start();
                fadeOut.start();

                mIsUsingView1 = !mIsUsingView1;
            });
        });
    }

    private void toggleWallpaperDropdown(ScrollView wpScroll, boolean show) {
        if (show) {
            wpScroll.setVisibility(View.VISIBLE);
            wpScroll.setAlpha(0f);
            wpScroll.setTranslationY(-dp(10));
            ObjectAnimator.ofFloat(wpScroll, View.ALPHA, 0f, 1f).setDuration(250).start();
            ObjectAnimator.ofFloat(wpScroll, View.TRANSLATION_Y, -dp(10), 0f).setDuration(250).start();
        } else {
            ObjectAnimator.ofFloat(wpScroll, View.ALPHA, 1f, 0f).setDuration(250).start();
            ObjectAnimator.ofFloat(wpScroll, View.TRANSLATION_Y, 0f, -dp(10)).setDuration(250).start();
            CompletableFuture.delayedExecutor(250, java.util.concurrent.TimeUnit.MILLISECONDS).execute(() -> {
                MuiModApi.postToUiThread(() -> wpScroll.setVisibility(View.GONE));
            });
        }
    }

}
