package com.tiedup.remake.v2.bondage.component;

import com.google.gson.JsonObject;
import com.tiedup.remake.core.SettingsAccessor;
import java.util.List;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.Level;
import org.jetbrains.annotations.Nullable;

/**
 * Component: struggle resistance for data-driven items.
 *
 * <p>Config-driven: {@code "resistance": {"id": "rope"}} delegates to
 * {@link SettingsAccessor#getBindResistance(String)} at runtime.</p>
 *
 * <p>Legacy/override: {@code "resistance": {"base": 150}} uses a hardcoded value.</p>
 */
public class ResistanceComponent implements IItemComponent {

    private final @Nullable String resistanceId;
    private final int fallbackBase;

    private ResistanceComponent(@Nullable String resistanceId, int fallbackBase) {
        this.resistanceId = resistanceId;
        this.fallbackBase = fallbackBase;
    }

    public static IItemComponent fromJson(JsonObject config) {
        String id = null;
        int base = 100;
        if (config != null) {
            if (config.has("id")) {
                id = config.get("id").getAsString();
            }
            if (config.has("base")) {
                base = config.get("base").getAsInt();
            }
        }
        base = Math.max(0, base);
        return new ResistanceComponent(id, base);
    }

    /**
     * Get the base resistance for this item.
     * If a {@code resistanceId} is configured, delegates to server config at runtime.
     * Otherwise returns the hardcoded fallback value.
     */
    public int getBaseResistance() {
        if (resistanceId != null) {
            return SettingsAccessor.getBindResistance(resistanceId);
        }
        return fallbackBase;
    }

    /** The config key used for runtime resistance lookup, or null if hardcoded. */
    public @Nullable String getResistanceId() {
        return resistanceId;
    }

    @Override
    public void appendTooltip(ItemStack stack, @Nullable Level level, List<Component> tooltip, TooltipFlag flag) {
        if (flag.isAdvanced()) {
            tooltip.add(Component.translatable("item.tiedup.tooltip.resistance", getBaseResistance())
                .withStyle(ChatFormatting.DARK_GRAY));
        }
    }
}
