package com.tiedup.remake.client.gui.screens;

import com.tiedup.remake.client.gui.util.GuiStatsRenderer;
import com.tiedup.remake.client.gui.util.GuiTextureHelper;
import com.tiedup.remake.network.ModNetwork;
import com.tiedup.remake.network.cell.PacketRequestCellList;
import com.tiedup.remake.network.personality.PacketDisciplineAction;
import com.tiedup.remake.network.personality.PacketNpcCommand;
import com.tiedup.remake.network.personality.PacketRequestNpcInventory;
import com.tiedup.remake.personality.DisciplineType;
import com.tiedup.remake.personality.NpcCommand;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.Tooltip;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

@OnlyIn(Dist.CLIENT)
public class CommandWandScreen extends Screen {

    private enum Tab {
        STATUS,
        COMMAND,
        JOBS,
    }

    private Tab currentTab = Tab.STATUS;

    // NPC data from packet
    private final java.util.UUID entityUUID;
    private final String npcName;
    private final String personalityName;
    private final String activeCommand;
    private final float hunger;
    private final float rest;
    private final float mood;
    private final String followDistanceMode;
    private final String homeType;
    private final boolean autoRestEnabled;
    private final String cellName;
    private final String cellQualityName;
    private final String activeJobLevelName;
    private final int activeJobXp;
    private final int activeJobXpMax;

    // Layout constants
    private static final int PANEL_WIDTH = 260;
    private static final int PANEL_HEIGHT = 330;
    private static final int MARGIN = 8;
    private static final int LINE_HEIGHT = 10;
    private static final int BUTTON_HEIGHT = 15;
    private static final int BTN_SPACING = 1;
    private static final int TAB_HEIGHT = 20;

    // Color constants
    private static final int COLOR_WHITE = 0xFFFFFF;
    private static final int COLOR_GRAY = 0xAAAAAA;
    private static final int COLOR_ORANGE = 0xFF9800;

    // Calculated positions
    private int leftPos;
    private int topPos;

    public CommandWandScreen(
        java.util.UUID entityUUID,
        String npcName,
        String personalityName,
        String activeCommand,
        float hunger,
        float rest,
        float mood,
        String followDistanceMode,
        String homeType,
        boolean autoRestEnabled
    ) {
        this(
            entityUUID,
            npcName,
            personalityName,
            activeCommand,
            hunger,
            rest,
            mood,
            followDistanceMode,
            homeType,
            autoRestEnabled,
            "",
            "",
            "",
            0,
            0
        );
    }

    public CommandWandScreen(
        java.util.UUID entityUUID,
        String npcName,
        String personalityName,
        String activeCommand,
        float hunger,
        float rest,
        float mood,
        String followDistanceMode,
        String homeType,
        boolean autoRestEnabled,
        String cellName,
        String cellQualityName
    ) {
        this(
            entityUUID,
            npcName,
            personalityName,
            activeCommand,
            hunger,
            rest,
            mood,
            followDistanceMode,
            homeType,
            autoRestEnabled,
            cellName,
            cellQualityName,
            "",
            0,
            0
        );
    }

    public CommandWandScreen(
        java.util.UUID entityUUID,
        String npcName,
        String personalityName,
        String activeCommand,
        float hunger,
        float rest,
        float mood,
        String followDistanceMode,
        String homeType,
        boolean autoRestEnabled,
        String cellName,
        String cellQualityName,
        String activeJobLevelName,
        int activeJobXp,
        int activeJobXpMax
    ) {
        super(Component.translatable("gui.tiedup.command_wand"));
        this.entityUUID = entityUUID;
        this.npcName = npcName;
        this.personalityName = personalityName;
        this.activeCommand = activeCommand;
        this.hunger = hunger;
        this.rest = rest;
        this.mood = mood;
        this.followDistanceMode = followDistanceMode;
        this.homeType = homeType;
        this.autoRestEnabled = autoRestEnabled;
        this.cellName = cellName;
        this.cellQualityName = cellQualityName;
        this.activeJobLevelName = activeJobLevelName;
        this.activeJobXp = activeJobXp;
        this.activeJobXpMax = activeJobXpMax;
    }

    @Override
    protected void init() {
        super.init();
        this.leftPos = (this.width - PANEL_WIDTH) / 2;
        this.topPos = (this.height - PANEL_HEIGHT) / 2;
        rebuildButtons();
    }

    private void rebuildButtons() {
        this.clearWidgets();

        int contentX = leftPos + MARGIN;
        int contentWidth = PANEL_WIDTH - MARGIN * 2;

        // Tab buttons
        int tabWidth = contentWidth / 3;
        int tabY = topPos + 30;

        Button statusTab = Button.builder(
            Component.translatable("gui.tiedup.command_wand.tab.status"),
            b -> {
                currentTab = Tab.STATUS;
                rebuildButtons();
            }
        )
            .bounds(contentX, tabY, tabWidth, TAB_HEIGHT)
            .build();
        statusTab.active = currentTab != Tab.STATUS;

        Button commandTab = Button.builder(
            Component.translatable("gui.tiedup.command_wand.tab.command"),
            b -> {
                currentTab = Tab.COMMAND;
                rebuildButtons();
            }
        )
            .bounds(contentX + tabWidth, tabY, tabWidth, TAB_HEIGHT)
            .build();
        commandTab.active = currentTab != Tab.COMMAND;

        Button jobsTab = Button.builder(
            Component.translatable("gui.tiedup.command_wand.tab.jobs"),
            b -> {
                currentTab = Tab.JOBS;
                rebuildButtons();
            }
        )
            .bounds(
                contentX + tabWidth * 2,
                tabY,
                contentWidth - tabWidth * 2,
                TAB_HEIGHT
            )
            .build();
        jobsTab.active = currentTab != Tab.JOBS;

        this.addRenderableWidget(statusTab);
        this.addRenderableWidget(commandTab);
        this.addRenderableWidget(jobsTab);

        int contentY = tabY + TAB_HEIGHT + 4;

        switch (currentTab) {
            case STATUS -> buildStatusTab(contentX, contentWidth, contentY);
            case COMMAND -> buildCommandTab(contentX, contentWidth, contentY);
            case JOBS -> buildJobsTab(contentX, contentWidth, contentY);
        }

        addBottomButtons();
    }

    // Status Tab

    /** Calculate Y position after all rendered status content (needs, mood, cell, home) */
    private int getStatusButtonsY(int startY) {
        int y = startY;
        y += 14; // needs section header
        y += 8 + 6; // need bar height + padding
        y += LINE_HEIGHT + 2; // mood line
        y += LINE_HEIGHT + 2; // cell line
        y += LINE_HEIGHT + 4; // home line + padding
        return y;
    }

    private void buildStatusTab(int contentX, int contentWidth, int y) {
        int halfWidth = (contentWidth - BTN_SPACING) / 2;

        // Calculate where rendered content ends
        y = getStatusButtonsY(y);

        // Auto-Rest + Follow Distance side by side
        addAutoRestButton(contentX, y, halfWidth);
        addFollowDistanceButton(
            contentX + halfWidth + BTN_SPACING,
            y,
            halfWidth
        );
        y += BUTTON_HEIGHT + 4;

        // Current Activity section header + content
        y += 14; // section header
        y += LINE_HEIGHT; // command name line

        // If active job, skip space for XP bar
        NpcCommand cmd = NpcCommand.fromString(activeCommand);
        if (cmd.isActiveJob() && !activeJobLevelName.isEmpty()) {
            y += LINE_HEIGHT; // tier text
            y += 6; // xp bar
        }

        y += 8;

        // Discipline section
        int thirdWidth = (contentWidth - BTN_SPACING * 2) / 3;

        Button praiseBtn = Button.builder(
            Component.translatable("gui.tiedup.dialogue.praise"),
            b -> sendDiscipline(DisciplineType.PRAISE)
        )
            .bounds(contentX, y, thirdWidth, BUTTON_HEIGHT)
            .tooltip(
                Tooltip.create(
                    Component.translatable("gui.tiedup.dialogue.praise.tooltip")
                )
            )
            .build();
        this.addRenderableWidget(praiseBtn);

        Button scoldBtn = Button.builder(
            Component.translatable("gui.tiedup.dialogue.scold"),
            b -> sendDiscipline(DisciplineType.SCOLD)
        )
            .bounds(
                contentX + thirdWidth + BTN_SPACING,
                y,
                thirdWidth,
                BUTTON_HEIGHT
            )
            .tooltip(
                Tooltip.create(
                    Component.translatable("gui.tiedup.dialogue.scold.tooltip")
                )
            )
            .build();
        this.addRenderableWidget(scoldBtn);

        Button threatenBtn = Button.builder(
            Component.translatable("gui.tiedup.dialogue.threaten"),
            b -> sendDiscipline(DisciplineType.THREATEN)
        )
            .bounds(
                contentX + (thirdWidth + BTN_SPACING) * 2,
                y,
                thirdWidth,
                BUTTON_HEIGHT
            )
            .tooltip(
                Tooltip.create(
                    Component.translatable(
                        "gui.tiedup.dialogue.threaten.tooltip"
                    )
                )
            )
            .build();
        this.addRenderableWidget(threatenBtn);
    }

    // Commands Tab

    private static final int SECTION_HEADER_H = 16; // header line + text + padding

    private void buildCommandTab(int contentX, int contentWidth, int y) {
        // -- Movement section --
        y += SECTION_HEADER_H; // space for rendered section header

        int followW = 50;
        int distW = 18;
        int comeW = 50;
        int goHomeW = contentWidth - followW - distW - comeW - 6;

        int x = contentX;
        addCommandButton(x, y, NpcCommand.FOLLOW, followW);
        x += followW + 2;
        addFollowDistanceCycleButton(x, y, distW);
        x += distW + 2;
        addCommandButton(x, y, NpcCommand.COME, comeW);
        x += comeW + 2;
        addCommandButton(x, y, NpcCommand.GO_HOME, goHomeW);
        y += BUTTON_HEIGHT + 4;

        // -- Position section --
        y += SECTION_HEADER_H; // space for rendered section header

        int quarterWidth = (contentWidth - BTN_SPACING * 3) / 4;
        addCommandButton(contentX, y, NpcCommand.STAY, quarterWidth);
        addCommandButton(
            contentX + (quarterWidth + BTN_SPACING),
            y,
            NpcCommand.SIT,
            quarterWidth
        );
        addCommandButton(
            contentX + (quarterWidth + BTN_SPACING) * 2,
            y,
            NpcCommand.KNEEL,
            quarterWidth
        );
        addCommandButton(
            contentX + (quarterWidth + BTN_SPACING) * 3,
            y,
            NpcCommand.IDLE,
            quarterWidth
        );
    }

    // Jobs Tab

    private void buildJobsTab(int contentX, int contentWidth, int y) {
        int thirdWidth = (contentWidth - BTN_SPACING * 2) / 3;
        int halfWidth = (contentWidth - BTN_SPACING) / 2;

        // -- Resource section -- (Farm, Mine, Fish)
        y += SECTION_HEADER_H;
        addWorkCommandButton(contentX, y, NpcCommand.FARM, thirdWidth);
        addWorkCommandButton(
            contentX + thirdWidth + BTN_SPACING,
            y,
            NpcCommand.MINE,
            thirdWidth
        );
        addWorkCommandButton(
            contentX + (thirdWidth + BTN_SPACING) * 2,
            y,
            NpcCommand.FISH,
            thirdWidth
        );
        y += BUTTON_HEIGHT + 4;

        // -- Animal section -- (Breed, Shear)
        y += SECTION_HEADER_H;
        addWorkCommandButton(contentX, y, NpcCommand.BREED, halfWidth);
        addWorkCommandButton(
            contentX + halfWidth + BTN_SPACING,
            y,
            NpcCommand.SHEAR,
            halfWidth
        );
        y += BUTTON_HEIGHT + 4;

        // -- Logistics section -- (Cook, Transfer, Sort)
        y += SECTION_HEADER_H;
        addWorkCommandButton(contentX, y, NpcCommand.COOK, thirdWidth);
        addWorkCommandButton(
            contentX + thirdWidth + BTN_SPACING,
            y,
            NpcCommand.TRANSFER,
            thirdWidth
        );
        addWorkCommandButton(
            contentX + (thirdWidth + BTN_SPACING) * 2,
            y,
            NpcCommand.SORT,
            thirdWidth
        );
        y += BUTTON_HEIGHT + 4;

        // -- Security section -- (Patrol, Guard, Collect)
        y += SECTION_HEADER_H;
        addWorkCommandButton(contentX, y, NpcCommand.PATROL, thirdWidth);
        addWorkCommandButton(
            contentX + thirdWidth + BTN_SPACING,
            y,
            NpcCommand.GUARD,
            thirdWidth
        );
        addWorkCommandButton(
            contentX + (thirdWidth + BTN_SPACING) * 2,
            y,
            NpcCommand.COLLECT,
            thirdWidth
        );
        y += BUTTON_HEIGHT + 4;

        // -- Utility section -- (Assign Cell, Fetch)
        y += SECTION_HEADER_H;
        addAssignCellButton(contentX, y, halfWidth);
        addCommandButton(
            contentX + halfWidth + BTN_SPACING,
            y,
            NpcCommand.FETCH,
            halfWidth
        );
    }

    // Bottom Buttons (all tabs)

    private void addBottomButtons() {
        int bottomBtnWidth = 90;
        int bottomBtnSpacing = 4;
        int totalBottomWidth = bottomBtnWidth * 2 + bottomBtnSpacing;
        int bottomBtnX = leftPos + (PANEL_WIDTH - totalBottomWidth) / 2;

        int closeY = topPos + PANEL_HEIGHT - MARGIN - BUTTON_HEIGHT;
        Button closeBtn = Button.builder(
            Component.translatable("gui.tiedup.close"),
            b -> onClose()
        )
            .bounds(bottomBtnX, closeY, totalBottomWidth, BUTTON_HEIGHT)
            .build();
        this.addRenderableWidget(closeBtn);

        int actionY = closeY - BUTTON_HEIGHT - 3;
        Button inventoryBtn = Button.builder(
            Component.translatable("gui.tiedup.command_wand.inventory"),
            b -> openInventory()
        )
            .bounds(bottomBtnX, actionY, bottomBtnWidth, BUTTON_HEIGHT)
            .build();
        this.addRenderableWidget(inventoryBtn);

        Button stopBtn = Button.builder(
            Component.translatable("gui.tiedup.command_wand.stop_action"),
            b -> cancelCommand()
        )
            .bounds(
                bottomBtnX + bottomBtnWidth + bottomBtnSpacing,
                actionY,
                bottomBtnWidth,
                BUTTON_HEIGHT
            )
            .build();
        stopBtn.active = !activeCommand.equals("NONE");
        this.addRenderableWidget(stopBtn);
    }

    // Button helpers

    private void addCommandButton(int x, int y, NpcCommand command, int width) {
        boolean isActive = activeCommand.equals(command.name());
        Component label = Component.translatable(
            "tiedup.command." + command.name().toLowerCase()
        );
        Button btn = Button.builder(label, b -> sendCommand(command))
            .bounds(x, y, width, BUTTON_HEIGHT)
            .tooltip(
                Tooltip.create(
                    Component.translatable(
                        "tiedup.command." +
                            command.name().toLowerCase() +
                            ".tooltip"
                    )
                )
            )
            .build();
        btn.active = !isActive;
        this.addRenderableWidget(btn);
    }

    private void addWorkCommandButton(
        int x,
        int y,
        NpcCommand command,
        int width
    ) {
        boolean isActive = activeCommand.equals(command.name());
        Component label = Component.translatable(
            "tiedup.command." + command.name().toLowerCase()
        );
        Button btn = Button.builder(label, b -> selectWorkCommand(command))
            .bounds(x, y, width, BUTTON_HEIGHT)
            .tooltip(
                Tooltip.create(
                    Component.translatable(
                        "tiedup.command." +
                            command.name().toLowerCase() +
                            ".tooltip"
                    )
                )
            )
            .build();
        btn.active = !isActive;
        this.addRenderableWidget(btn);
    }

    private void addFollowDistanceCycleButton(int x, int y, int width) {
        Component modeLabel = Component.translatable(
            "gui.tiedup.command_wand.follow_distance.abbrev." + followDistanceMode.toLowerCase()
        );

        Component tooltip = Component.translatable(
            "gui.tiedup.command_wand.follow_distance.tooltip"
        )
            .append("\n")
            .append(
                Component.translatable(
                    "gui.tiedup.command_wand.follow_distance.current"
                )
            )
            .append(": ")
            .append(
                Component.translatable(
                    "tiedup.follow_distance." + followDistanceMode.toLowerCase()
                )
            );

        Button btn = Button.builder(modeLabel, b ->
            cycleFollowDistance()
        )
            .bounds(x, y, width, BUTTON_HEIGHT)
            .tooltip(Tooltip.create(tooltip))
            .build();
        this.addRenderableWidget(btn);
    }

    private void addFollowDistanceButton(int contentX, int y, int width) {
        String modeText = switch (followDistanceMode) {
            case "HEEL" -> "H";
            case "CLOSE" -> "C";
            case "FAR" -> "F";
            default -> "?";
        };

        Component label = Component.translatable(
            "gui.tiedup.command_wand.follow_distance"
        ).append(": " + modeText);

        Component tooltip = Component.translatable(
            "gui.tiedup.command_wand.follow_distance.tooltip"
        )
            .append("\n")
            .append(
                Component.translatable(
                    "gui.tiedup.command_wand.follow_distance.current"
                )
            )
            .append(": ")
            .append(
                Component.translatable(
                    "tiedup.follow_distance." + followDistanceMode.toLowerCase()
                )
            );

        Button btn = Button.builder(label, b -> cycleFollowDistance())
            .bounds(contentX, y, width, BUTTON_HEIGHT)
            .tooltip(Tooltip.create(tooltip))
            .build();
        this.addRenderableWidget(btn);
    }

    private void addAutoRestButton(int x, int y, int width) {
        String stateText = autoRestEnabled ? "ON" : "OFF";
        Component label = Component.translatable(
            "gui.tiedup.command_wand.auto_rest"
        ).append(": " + stateText);

        Button btn = Button.builder(label, b -> toggleAutoRest())
            .bounds(x, y, width, BUTTON_HEIGHT)
            .tooltip(
                Tooltip.create(
                    Component.translatable(
                        "gui.tiedup.command_wand.auto_rest.tooltip"
                    )
                )
            )
            .build();
        btn.active = !cellName.isEmpty();
        this.addRenderableWidget(btn);
    }

    private void addAssignCellButton(int x, int y, int width) {
        Component label = cellName.isEmpty()
            ? Component.translatable("gui.tiedup.command_wand.assign_cell")
            : Component.translatable(
                  "gui.tiedup.command_wand.assign_cell"
              ).append(" \u2713");

        Component tooltip = cellName.isEmpty()
            ? Component.translatable(
                  "gui.tiedup.command_wand.assign_cell.tooltip"
              )
            : Component.translatable(
                  "gui.tiedup.command_wand.assign_cell.tooltip.assigned"
              ).append(": " + cellName);

        Button btn = Button.builder(label, b -> openCellSelector())
            .bounds(x, y, width, BUTTON_HEIGHT)
            .tooltip(Tooltip.create(tooltip))
            .build();
        this.addRenderableWidget(btn);
    }

    // Network actions

    private void sendCommand(NpcCommand command) {
        ModNetwork.sendToServer(
            PacketNpcCommand.giveCommand(entityUUID, command, null)
        );
        onClose();
    }

    private void selectWorkCommand(NpcCommand command) {
        ModNetwork.sendToServer(
            PacketNpcCommand.selectJob(entityUUID, command)
        );
        onClose();
    }

    private void cycleFollowDistance() {
        ModNetwork.sendToServer(
            PacketNpcCommand.cycleFollowDistance(entityUUID, true)
        );
    }

    private void toggleAutoRest() {
        ModNetwork.sendToServer(
            PacketNpcCommand.toggleAutoRest(entityUUID, true)
        );
    }

    private void openInventory() {
        ModNetwork.sendToServer(new PacketRequestNpcInventory(entityUUID));
    }

    private void openCellSelector() {
        ModNetwork.sendToServer(new PacketRequestCellList(entityUUID));
    }

    private void cancelCommand() {
        ModNetwork.sendToServer(PacketNpcCommand.cancelCommand(entityUUID));
        onClose();
    }

    private void sendDiscipline(DisciplineType type) {
        int entityId = getEntityIdFromUUID(entityUUID);
        if (entityId != -1) {
            ModNetwork.sendToServer(new PacketDisciplineAction(entityId, type));
            onClose();
        }
    }

    private int getEntityIdFromUUID(java.util.UUID uuid) {
        Minecraft mc = Minecraft.getInstance();
        if (mc.level != null) {
            for (net.minecraft.world.entity.Entity entity : mc.level.entitiesForRendering()) {
                if (entity.getUUID().equals(uuid)) {
                    return entity.getId();
                }
            }
        }
        return -1;
    }

    // Render

    @Override
    public void render(
        GuiGraphics graphics,
        int mouseX,
        int mouseY,
        float partialTick
    ) {
        this.renderBackground(graphics);

        GuiTextureHelper.renderBeveledPanel(
            graphics,
            leftPos,
            topPos,
            PANEL_WIDTH,
            PANEL_HEIGHT
        );

        int contentX = leftPos + MARGIN;
        int contentWidth = PANEL_WIDTH - MARGIN * 2;
        int y = topPos + MARGIN;

        // --- Header: NPC name ---
        graphics.drawCenteredString(
            this.font,
            npcName,
            leftPos + PANEL_WIDTH / 2,
            y,
            COLOR_WHITE
        );
        y += LINE_HEIGHT;

        // --- Header: Personality + mood color dot ---
        int moodDotColor =
            mood >= 70 ? 0xFF4CAF50 : mood >= 40 ? 0xFFFF9800 : 0xFFF44336;
        String personalityText = personalityName;
        int personalityWidth = this.font.width(personalityText);
        int headerCenterX = leftPos + PANEL_WIDTH / 2;
        int textStartX = headerCenterX - (personalityWidth + 8) / 2;
        graphics.drawString(
            this.font,
            personalityText,
            textStartX + 8,
            y,
            COLOR_GRAY,
            false
        );
        graphics.fill(textStartX, y + 2, textStartX + 5, y + 7, moodDotColor);
        y += LINE_HEIGHT + 3;

        // Tab content area starts after tabs
        y = topPos + 30 + TAB_HEIGHT + 4;

        switch (currentTab) {
            case STATUS -> renderStatusContent(
                graphics,
                contentX,
                contentWidth,
                y,
                mouseX,
                mouseY
            );
            case COMMAND -> renderCommandContent(
                graphics,
                contentX,
                contentWidth,
                y
            );
            case JOBS -> renderJobsContent(graphics, contentX, contentWidth, y);
        }

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

    // Render: Status Tab

    private void renderStatusContent(
        GuiGraphics graphics,
        int contentX,
        int contentWidth,
        int y,
        int mouseX,
        int mouseY
    ) {
        // -- Needs section --
        renderSectionHeader(
            graphics,
            contentX,
            contentWidth,
            y,
            "gui.tiedup.command_wand.needs"
        );
        y += 14;

        // Hunger bar
        int barW = 80;
        int barH = 8;
        int hungerLabelW =
            this.font.width(
                Component.translatable("tiedup.need.hunger").getString()
            ) +
            4;
        graphics.drawString(
            this.font,
            Component.translatable("tiedup.need.hunger"),
            contentX,
            y,
            COLOR_GRAY,
            false
        );
        renderNeedBar(graphics, contentX + hungerLabelW, y, barW, barH, hunger);

        // Rest bar
        int restX = contentX + contentWidth / 2 + 4;
        int restLabelW =
            this.font.width(
                Component.translatable("tiedup.need.rest").getString()
            ) +
            4;
        graphics.drawString(
            this.font,
            Component.translatable("tiedup.need.rest"),
            restX,
            y,
            COLOR_GRAY,
            false
        );
        renderNeedBar(graphics, restX + restLabelW, y, barW, barH, rest);

        // Hunger bar tooltip
        if (
            mouseX >= contentX + hungerLabelW &&
            mouseX <= contentX + hungerLabelW + barW &&
            mouseY >= y &&
            mouseY <= y + barH
        ) {
            graphics.renderTooltip(
                this.font,
                Component.translatable("gui.tiedup.command_wand.percent", (int) hunger),
                mouseX,
                mouseY
            );
        }
        // Rest bar tooltip
        if (
            mouseX >= restX + restLabelW &&
            mouseX <= restX + restLabelW + barW &&
            mouseY >= y &&
            mouseY <= y + barH
        ) {
            graphics.renderTooltip(
                this.font,
                Component.translatable("gui.tiedup.command_wand.percent", (int) rest),
                mouseX,
                mouseY
            );
        }

        y += barH + 6;

        // -- Mood --
        int moodColor = GuiStatsRenderer.getValueColor(mood);
        String moodWord = mood >= 70 ? "Happy" : mood >= 40 ? "Neutral" : "Sad";
        Component moodKey = Component.translatable(
            "gui.tiedup.command_wand.mood." + moodWord.toLowerCase()
        );
        graphics.drawString(
            this.font,
            Component.translatable("gui.tiedup.command_wand.mood")
                .append(": " + (int) mood + "% (")
                .append(moodKey)
                .append(")"),
            contentX,
            y,
            moodColor,
            false
        );
        y += LINE_HEIGHT + 2;

        // -- Cell info --
        String cellDisplay = cellName.isEmpty() ? "-" : cellName;
        if (!cellQualityName.isEmpty()) cellDisplay +=
            " (" + cellQualityName + ")";
        graphics.drawString(
            this.font,
            Component.translatable("gui.tiedup.command_wand.cell").append(
                ": " + cellDisplay
            ),
            contentX,
            y,
            COLOR_GRAY,
            false
        );
        y += LINE_HEIGHT + 2;

        // -- Home type --
        graphics.drawString(
            this.font,
            Component.translatable("gui.tiedup.command_wand.home_type")
                .append(": ")
                .append(
                    Component.translatable(
                        "gui.tiedup.command_wand.home_type." +
                            homeType.toLowerCase()
                    )
                ),
            contentX,
            y,
            COLOR_GRAY,
            false
        );
        y += LINE_HEIGHT + 4;

        // Auto-Rest and Follow Distance buttons are placed by buildStatusTab at this Y
        y += BUTTON_HEIGHT + 4;

        // -- Current Activity section --
        renderSectionHeader(
            graphics,
            contentX,
            contentWidth,
            y,
            "gui.tiedup.command_wand.section.activity"
        );
        y += 14;

        NpcCommand cmd = NpcCommand.fromString(activeCommand);
        if (!activeCommand.equals("NONE")) {
            graphics.drawString(
                this.font,
                Component.translatable(
                    "tiedup.command." + activeCommand.toLowerCase()
                ),
                contentX,
                y,
                COLOR_ORANGE,
                false
            );
        } else {
            graphics.drawString(
                this.font,
                Component.translatable("tiedup.command.none"),
                contentX,
                y,
                0x666666,
                false
            );
        }
        y += LINE_HEIGHT;

        // Job XP bar (only if active command is a job)
        if (cmd.isActiveJob() && !activeJobLevelName.isEmpty()) {
            graphics.drawString(
                this.font,
                activeJobLevelName +
                    " (" +
                    activeJobXp +
                    "/" +
                    activeJobXpMax +
                    ")",
                contentX,
                y,
                COLOR_GRAY,
                false
            );
            y += LINE_HEIGHT;
            int xpBarW = contentWidth;
            float xpProgress =
                activeJobXpMax > 0 ? (float) activeJobXp / activeJobXpMax : 0f;
            GuiTextureHelper.renderXpBar(
                graphics,
                contentX,
                y,
                xpBarW,
                xpProgress
            );
        }
    }

    private void renderNeedBar(
        GuiGraphics graphics,
        int x,
        int y,
        int w,
        int h,
        float value
    ) {
        graphics.fill(x, y, x + w, y + h, 0xFF000000);
        int fillW = (int) (w * (value / 100f));
        int barColor =
            value >= 70 ? 0xFF4CAF50 : value >= 40 ? 0xFFFF9800 : 0xFFF44336;
        if (fillW > 0) {
            graphics.fill(x, y, x + fillW, y + h, barColor);
        }
    }

    // Render: Commands Tab

    private void renderCommandContent(
        GuiGraphics graphics,
        int contentX,
        int contentWidth,
        int y
    ) {
        // Movement section header
        renderSectionHeader(
            graphics,
            contentX,
            contentWidth,
            y,
            "gui.tiedup.command_wand.section.movement"
        );
        y += SECTION_HEADER_H + BUTTON_HEIGHT + 4;

        // Position section header
        renderSectionHeader(
            graphics,
            contentX,
            contentWidth,
            y,
            "gui.tiedup.command_wand.section.position"
        );
    }

    // Render: Jobs Tab

    private void renderJobsContent(
        GuiGraphics graphics,
        int contentX,
        int contentWidth,
        int y
    ) {
        // Resource section (1 row of 3)
        renderSectionHeader(
            graphics,
            contentX,
            contentWidth,
            y,
            "gui.tiedup.command_wand.section.resource"
        );
        y += SECTION_HEADER_H + BUTTON_HEIGHT + 4;

        // Animal section (1 row of 2)
        renderSectionHeader(
            graphics,
            contentX,
            contentWidth,
            y,
            "gui.tiedup.command_wand.section.animal"
        );
        y += SECTION_HEADER_H + BUTTON_HEIGHT + 4;

        // Logistics section (1 row of 3)
        renderSectionHeader(
            graphics,
            contentX,
            contentWidth,
            y,
            "gui.tiedup.command_wand.section.logistics"
        );
        y += SECTION_HEADER_H + BUTTON_HEIGHT + 4;

        // Security section (1 row of 3)
        renderSectionHeader(
            graphics,
            contentX,
            contentWidth,
            y,
            "gui.tiedup.command_wand.section.security"
        );
        y += SECTION_HEADER_H + BUTTON_HEIGHT + 4;

        // Utility section (1 row of 2)
        renderSectionHeader(
            graphics,
            contentX,
            contentWidth,
            y,
            "gui.tiedup.command_wand.section.utility"
        );
    }

    // Render helpers

    private void renderSectionHeader(
        GuiGraphics graphics,
        int x,
        int contentWidth,
        int y,
        String translationKey
    ) {
        graphics.fill(x, y, x + contentWidth, y + 1, 0xFF373737);
        graphics.drawString(
            this.font,
            Component.translatable(translationKey),
            x,
            y + 4,
            COLOR_WHITE,
            false
        );
    }

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