Anime Card Farm Script (November 2026) – Autoconveyor

PUBLISHEDUPDATED
1 Available ScriptKeyless

Keeping up with the leaderboard in Anime Card Farm is tough when you are tired of clicking nonstop just to earn some cash. Grabbing a solid Anime Card Farm script lets you skip the worst parts of the grind while you focus on collecting the rarest drops.

You spend your time opening card packs, upgrading your favorite anime cards, and hunting for mutated versions with massive stat boosts to make more money. Even when you are offline, packs keep opening and your cash keeps stacking up.

If you want to speed up your production line and get ahead without burning out, you need to check out the working pastebin code below.

Disclaimer: Tora Scripts is an indexing and educational resource. This script was created and maintained by independent third-party developers. We do not host, develop, or claim ownership of this software. All intellectual property belongs to its respective creator. Creators can request removal on our DMCA page.

Anime Card Farm Script – Autoconveyor & More

Autoconveyor & MoreFree
Autoconveyor
--[[
	═══════════════════════════════════════════════════════════════════════════
	 CONVEYOR AUTO  ·  Anime Card Farm            (NextUI edition)
	 Авторолл конвейера + автопокупка паков по белому списку мутаций.
	 Один файл LocalScript. Запуск через исполнитель (Madium / любой с
	 fireclickdetector).

	 ИНТЕРФЕЙС ПЕРЕПИСАН НА NextUI — https://diser.me/nextui/
	   Вся ручная отрисовка (ScreenGui, твины, скроллы, свои дропдауны,
	   тосты, перетаскивание окна) удалена. Теперь окно, вкладки, карточки,
	   переключатели, слайдеры, дропдауны, мультиселекты, кейбинды,
	   уведомления, поиск по элементам, темы и «стекло» — из библиотеки.
	   Логика (конфиг, скан плота, данные паков, remote, движок) не менялась.
	═══════════════════════════════════════════════════════════════════════════

	ЧТО ДЕЛАЕТ
	  • Крутит кнопку "Spawn Pack" на твоём плоте (клик по ClickDetector).
	  • Читает события ConveyorRE: какой пак выпал и с какой мутацией.
	  • Покупает пак только если ОН включён в списке И его мутация отмечена.
	  • Останавливается при "Not enough money" (опция, по умолчанию включена).
	  • Настройки сохраняются в файл и переживают реджойн.

	ЧЕГО НЕ ДЕЛАЕТ
	  • Не продаёт карты, не качает апгрейды, не трогает другие системы.
	  • Не покупает паки, которые не спавнятся кнопкой (Robux-only исключены).

	ВКЛАДКИ
	  Autoroll  — главный переключатель, интервал ролла, джиттер,
	              живой статус, счётчики, «последний увиденный пак».
	  Packs     — выбранный пак + список мутаций для покупки,
	              массовое включение/выключение, применение мутаций ко всем.
	  Settings  — поведение, горячие клавиши, хранилище, обслуживание.

	ГОРЯЧИЕ КЛАВИШИ
	  RightShift или Insert — показать/скрыть окно (меняется в Settings).
	  R                     — старт/стоп авторолла (кнопка клавиши в строке
	                          Autoroll на вкладке Autoroll).
	  Поиск по всем элементам — строка поиска в шапке окна (клавиша «/»).

	КОНСОЛЬ
	  Все сообщения скрипта помечены префиксом [CA].

	СЕКЦИИ
	  CONFIG → STORE → UTIL → SCANNER → DATA → NET → ENGINE → UI → BOOT
═══════════════════════════════════════════════════════════════════════════
]]

--============================================================
-- 0. HEADER — служебные константы и сервисы
--============================================================

local SCRIPT_NAME = "ConveyorAuto"
local VERSION = "2.0.0"
local LOG_PREFIX = "[CA]"
local NEXTUI_URL = "https://diser.me/nextui/source.lua"

if not game:IsLoaded() then
	game.Loaded:Wait()
end

local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local HttpService = game:GetService("HttpService")
local Workspace = game:GetService("Workspace")

local player = Players.LocalPlayer
if not player then
	repeat
		task.wait()
	until Players.LocalPlayer
	player = Players.LocalPlayer
end

--============================================================
-- 1. CONFIG — дефолтные настройки (UI сохраняет значения поверх)
--============================================================

local CONFIG = {
	version = 2,

	-- Интервал между прокрутками в миллисекундах.
	-- Сервер держит CanPress=false ~650 мс, поэтому ниже 700 смысла нет.
	timingMs = 800,
	minTimingMs = 700,
	maxTimingMs = 60000,
	-- Случайная добавка к интервалу (0..jitterMs), чтобы не долбить ровно в такт.
	jitterMs = 60,
	maxJitterMs = 600,

	-- Клавиши. Храним именами KeyCode ("R", "RightShift", ...).
	keybinds = {
		toggleUI = "RightShift",
		toggleRoll = "R",
	},

	options = {
		-- Останавливать авторолл, когда сервер вернул NotEnoughMoney.
		stopOnNoMoney = true,
		-- Запускать авторолл сразу при загрузке скрипта.
		autoStart = false,
		-- Показывать оверлей со списком горячих клавиш NextUI.
		showBindList = false,
	},

	-- Где хранить настройки: "auto" (файл, если доступен, иначе атрибуты),
	-- "file" (только файл), "attributes" (только атрибуты внутри игры).
	storage = "auto",
	storageFolder = "AnimeCardFarm",
	storageFile = "ConveyorAuto.json",

	-- Порядок мутаций в списках: редчайшие сверху.
	-- Первые четыре зафиксированы вручную (у них Weight = 0),
	-- остальные сортируются по Weight по возрастанию автоматически.
	-- Значения — «сырые» имена мутаций из модуля игры.
	mutationOrder = { "Nightmare", "Unknow", "Nullstar", "Admin" },

	--═══ ПОЛНАЯ КАСТОМИЗАЦИЯ ПОКУПОК ═══
	-- Ключ — Id пака из ReplicatedStorage.Modules.ConveyorPacks.
	-- enabled = true  → скрипт вообще рассматривает этот пак.
	-- mutations[имя] = true → покупать только с этой мутацией.
	-- Пустой mutations = пак включён, но не покупается (нет разрешённых мутаций).
	packs = {
		-- Пример (раскомментируй и поправь под себя):
		-- ["Ice Pack"] = {
		-- 	enabled = true,
		-- 	mutations = { Normal = true, Golden = true },
		-- },
	},
	-- Служебный флаг: true, когда паки уже настраивались в UI/сохранены.
	packsConfigured = false,
}

--============================================================
-- 2. STORE — сохранение/загрузка конфига (JSON-файл или атрибуты)
--============================================================

local Store = {}
local state = nil
local storageMode = "attributes"
local dataHolder = nil
local saveSeq = 0

local function deepCopy(value)
	if type(value) ~= "table" then
		return value
	end
	local copy = {}
	for k, v in pairs(value) do
		copy[k] = deepCopy(v)
	end
	return copy
end

-- Аккуратно накладывает загруженные значения на дефолты:
-- типы должны совпадать, неизвестные ключи игнорируются.
local function mergeDefaults(base, incoming)
	if type(incoming) ~= "table" then
		return base
	end
	for k, v in pairs(incoming) do
		local current = base[k]
		if type(current) == "table" and type(v) == "table" then
			mergeDefaults(current, v)
		elseif current ~= nil then
			if type(current) == type(v) then
				base[k] = v
			end
		else
			base[k] = deepCopy(v)
		end
	end
	return base
end

local function clampTiming(value)
	local minValue = CONFIG.minTimingMs
	local maxValue = CONFIG.maxTimingMs
	local n = tonumber(value)
	if not n then
		return CONFIG.timingMs
	end
	n = math.floor(n + 0.5)
	if n < minValue then
		n = minValue
	end
	if n > maxValue then
		n = maxValue
	end
	return n
end

local function clampJitter(value)
	local n = tonumber(value)
	if not n then
		return CONFIG.jitterMs
	end
	n = math.floor(n + 0.5)
	if n < 0 then
		n = 0
	end
	if n > CONFIG.maxJitterMs then
		n = CONFIG.maxJitterMs
	end
	return n
end

-- Кейбинды хранятся строкой ("R"), но старые конфиги с таблицей тоже читаем.
local function normalizeKeyName(raw, fallback)
	if type(raw) == "table" then
		raw = raw.key
	end
	if type(raw) == "string" and raw ~= "" then
		local ok, code = pcall(function()
			return Enum.KeyCode[raw]
		end)
		if ok and code then
			return raw
		end
	end
	return fallback
end

local function normalizeConfig(raw)
	local cfg = deepCopy(CONFIG)
	local savedPacks = nil

	if type(raw) == "table" then
		-- Паки применяем атомарно: если в сохранённом конфиге есть список паков,
		-- он полностью заменяет дефолты из CONFIG (иначе снятые галочки
		-- «возвращались» бы из шапки файла).
		local incoming = deepCopy(raw)
		if type(incoming.packs) == "table" then
			savedPacks = incoming.packs
			incoming.packs = nil
		end
		mergeDefaults(cfg, incoming)
	end

	if savedPacks and cfg.packsConfigured == true then
		cfg.packs = savedPacks
	end

	cfg.timingMs = clampTiming(cfg.timingMs)
	cfg.jitterMs = clampJitter(cfg.jitterMs)
	cfg.keybinds.toggleUI = normalizeKeyName(cfg.keybinds.toggleUI, CONFIG.keybinds.toggleUI)
	cfg.keybinds.toggleRoll = normalizeKeyName(cfg.keybinds.toggleRoll, CONFIG.keybinds.toggleRoll)
	if type(cfg.packs) ~= "table" then
		cfg.packs = {}
	end
	-- Чистим мусорные записи паков, чтобы движок не спотыкался.
	for packId, entry in pairs(cfg.packs) do
		if type(entry) ~= "table" then
			cfg.packs[packId] = nil
		else
			if type(entry.mutations) ~= "table" then
				entry.mutations = {}
			end
			entry.enabled = entry.enabled == true
			for mutName, allowed in pairs(entry.mutations) do
				if allowed ~= true then
					entry.mutations[mutName] = nil
				end
			end
		end
	end
	return cfg
end

local function getHolder()
	local playerGui = player:FindFirstChild("PlayerGui")
	if not playerGui then
		playerGui = player:WaitForChild("PlayerGui", 10)
	end
	if not playerGui then
		return nil
	end
	local holder = playerGui:FindFirstChild("ConveyorAutoData")
	if not holder then
		holder = Instance.new("Folder")
		holder.Name = "ConveyorAutoData"
		holder.Parent = playerGui
	end
	return holder
end

local function hasFileApi()
	return type(writefile) == "function"
		and type(readfile) == "function"
		and type(isfile) == "function"
		and type(makefolder) == "function"
end

local function folderExists(path)
	if type(isfolder) == "function" then
		local ok, value = pcall(isfolder, path)
		return ok and value == true
	end
	return false
end

local function resolveStorage()
	if CONFIG.storage == "file" then
		storageMode = hasFileApi() and "file" or "attributes"
	elseif CONFIG.storage == "attributes" then
		storageMode = "attributes"
	else
		storageMode = hasFileApi() and "file" or "attributes"
	end
end

local function fullPath()
	return CONFIG.storageFolder .. "/" .. CONFIG.storageFile
end

local function readRaw()
	if storageMode == "file" then
		local ok, contents = pcall(readfile, fullPath())
		if ok and type(contents) == "string" and contents ~= "" then
			return contents, "file"
		end
		return nil, "file"
	end
	if dataHolder then
		local ok, value = pcall(function()
			return dataHolder:GetAttribute("Config")
		end)
		if ok and type(value) == "string" and value ~= "" then
			return value, "attributes"
		end
	end
	return nil, "attributes"
end

local function writeRaw(payload)
	if storageMode == "file" then
		if not folderExists(CONFIG.storageFolder) then
			pcall(makefolder, CONFIG.storageFolder)
		end
		local ok, err = pcall(writefile, fullPath(), payload)
		if not ok then
			warn(LOG_PREFIX .. " WARN file save failed: " .. tostring(err))
			return false
		end
		return true
	end
	if dataHolder then
		local ok = pcall(function()
			dataHolder:SetAttribute("Config", payload)
		end)
		return ok
	end
	return false
end

function Store.init()
	resolveStorage()
	dataHolder = getHolder()

	local raw, source = readRaw()
	local loaded = nil
	if raw then
		local ok, decoded = pcall(function()
			return HttpService:JSONDecode(raw)
		end)
		if ok and type(decoded) == "table" then
			loaded = decoded
		else
			warn(LOG_PREFIX .. " WARN config is corrupted, using defaults (" .. source .. ")")
		end
	end

	state = normalizeConfig(loaded)
	Store.save(true)

	if storageMode == "file" then
		print(LOG_PREFIX .. " storage: file → " .. fullPath())
	else
		warn(LOG_PREFIX .. " WARN storage: PlayerGui attributes (settings reset on rejoin)")
	end
	return state
end

function Store.get()
	if not state then
		state = normalizeConfig(nil)
	end
	return state
end

-- Возвращает запись пака, создавая её при необходимости (только для записи).
function Store.packEntry(packId)
	local cfg = Store.get()
	local entry = cfg.packs[packId]
	if type(entry) ~= "table" then
		entry = { enabled = false, mutations = {} }
		cfg.packs[packId] = entry
	end
	if type(entry.mutations) ~= "table" then
		entry.mutations = {}
	end
	cfg.packsConfigured = true
	return entry
end

-- Только чтение: ничего не создаёт (чтобы не засорять конфиг).
function Store.readPack(packId)
	local entry = Store.get().packs[packId]
	if type(entry) ~= "table" then
		return nil
	end
	if type(entry.mutations) ~= "table" then
		entry.mutations = {}
	end
	return entry
end

function Store.isAllowed(packId, mutation)
	local entry = Store.get().packs[packId]
	if type(entry) ~= "table" or entry.enabled ~= true then
		return false
	end
	if type(entry.mutations) ~= "table" then
		return false
	end
	return entry.mutations[mutation] == true
end

function Store.save(immediate)
	if not state then
		return
	end
	saveSeq = saveSeq + 1
	local token = saveSeq

	local function doSave()
		local ok, payload = pcall(function()
			return HttpService:JSONEncode(state)
		end)
		if not ok or type(payload) ~= "string" then
			warn(LOG_PREFIX .. " WARN config encode failed")
			return
		end
		writeRaw(payload)
	end

	if immediate then
		doSave()
	else
		task.delay(0.5, function()
			if token == saveSeq then
				doSave()
			end
		end)
	end
end

function Store.reset()
	state = normalizeConfig(nil)
	Store.save(true)
end

function Store.setTiming(ms)
	local cfg = Store.get()
	cfg.timingMs = clampTiming(ms)
	Store.save()
	return cfg.timingMs
end

function Store.setJitter(ms)
	local cfg = Store.get()
	cfg.jitterMs = clampJitter(ms)
	Store.save()
	return cfg.jitterMs
end

function Store.isFileMode()
	return storageMode == "file"
end

--============================================================
-- 3. UTIL — логи и мелкие помощники
--============================================================

local connections = {}

local function track(connection)
	connections[#connections + 1] = connection
	return connection
end

local function log(...)
	local parts = {}
	for i = 1, select("#", ...) do
		parts[#parts + 1] = tostring(select(i, ...))
	end
	print(LOG_PREFIX .. " " .. table.concat(parts, " "))
end

local function warnLog(...)
	local parts = {}
	for i = 1, select("#", ...) do
		parts[#parts + 1] = tostring(select(i, ...))
	end
	warn(LOG_PREFIX .. " " .. table.concat(parts, " "))
end

local function safeRequire(module)
	if typeof(module) ~= "Instance" or not module:IsA("ModuleScript") then
		return nil
	end
	local ok, result = pcall(require, module)
	if ok then
		return result
	end
	warnLog("WARN require failed: " .. module:GetFullName() .. " → " .. tostring(result))
	return nil
end

local function clamp(value, minValue, maxValue)
	if value < minValue then
		return minValue
	elseif value > maxValue then
		return maxValue
	end
	return value
end

local function round(value)
	return math.floor(value + 0.5)
end

local function formatPrice(value)
	local n = tonumber(value)
	if not n then
		return tostring(value)
	end
	local abs = math.abs(n)
	if abs >= 1e12 then
		return string.format("%.2fT", n / 1e12)
	elseif abs >= 1e9 then
		return string.format("%.2fB", n / 1e9)
	elseif abs >= 1e6 then
		return string.format("%.2fM", n / 1e6)
	elseif abs >= 1e3 then
		return string.format("%.1fK", n / 1e3)
	end
	return tostring(round(n))
end

-- Строка "R" → Enum.KeyCode.R (без падений на кривых конфигах).
local function keyCodeOf(name, fallback)
	local ok, code = pcall(function()
		return Enum.KeyCode[tostring(name)]
	end)
	if ok and typeof(code) == "EnumItem" then
		return code
	end
	return fallback or Enum.KeyCode.R
end

--============================================================
-- 4. SCANNER — поиск плота, кнопки ролла, конвейера и данных
--============================================================

local Scanner = {
	plot = nil,
	plotNumber = nil,
	buttonPart = nil,
	clickDetector = nil,
	localModels = nil,
	packsModule = nil,
	mutationDisplay = nil,
	mutationGradients = nil,
	rarityGradients = nil,
}

local function getPlotNumber()
	local value = player:FindFirstChild("PlotNumber")
	if value and value:IsA("ValueBase") then
		return value.Value, value
	end
	local attr = player:GetAttribute("PlotNumber")
	if attr ~= nil then
		return attr, nil
	end
	return nil, nil
end

local function findPacksModule()
	local modules = ReplicatedStorage:FindFirstChild("Modules")
	if not modules then
		return nil
	end
	return modules:FindFirstChild("ConveyorPacks")
end

function Scanner.refresh()
	local plotNumber, plotValue = getPlotNumber()
	Scanner.plotNumber = plotNumber
	Scanner.plot = nil
	Scanner.buttonPart = nil
	Scanner.clickDetector = nil
	Scanner.localModels = nil

	local map = Workspace:FindFirstChild("MAP")
	local plots = map and map:FindFirstChild("Plots")
	if plots and plotNumber ~= nil then
		local plot = plots:FindFirstChild(tostring(plotNumber))
		if plot then
			local plotN0 = plot:FindFirstChild("Plot_N0")
			Scanner.plot = plotN0 or plot
		end
	end

	if Scanner.plot then
		local button = Scanner.plot:FindFirstChild("ButtonPart")
		if not button then
			-- на всякий случай ищем вглубь, но только кнопку с ClickDetector
			for _, descendant in ipairs(Scanner.plot:GetDescendants()) do
				if descendant.Name == "ButtonPart" and descendant:FindFirstChild("ClickDetector") then
					button = descendant
					break
				end
			end
		end
		if button then
			Scanner.buttonPart = button
			Scanner.clickDetector = button:FindFirstChild("ClickDetector")
				or button:FindFirstChildWhichIsA("ClickDetector", true)
		end
		Scanner.localModels = Scanner.plot:FindFirstChild("LocalConveyorModels")
	end

	local ok = pcall(function()
		Scanner.mutationDisplay = safeRequire(
			ReplicatedStorage:FindFirstChild("Modules")
				and ReplicatedStorage.Modules:FindFirstChild("MutationDisplay")
		)
	end)
	if not ok then
		Scanner.mutationDisplay = nil
	end

	local remotes = ReplicatedStorage:FindFirstChild("Remotes")
	if remotes then
		Scanner.conveyorRE = remotes:FindFirstChild("ConveyorRE")
	end

	local gradients = ReplicatedStorage:FindFirstChild("UiGradient")
	if gradients then
		Scanner.mutationGradients = gradients:FindFirstChild("Mutations")
		Scanner.rarityGradients = gradients:FindFirstChild("Rarity")
	end

	if not Scanner.buttonPart or not Scanner.clickDetector then
		warnLog("WARN spawn button not found (plot " .. tostring(plotNumber) .. ") — rolling disabled")
	end
	return Scanner.buttonPart ~= nil and Scanner.clickDetector ~= nil
end

-- Проверяет, что цель жива; при необходимости пере-сканирует.
function Scanner.ensure()
	local button = Scanner.buttonPart
	local detector = Scanner.clickDetector
	if button and button.Parent and detector and detector.Parent then
		return true
	end
	return Scanner.refresh()
end

function Scanner.getCanPress()
	local button = Scanner.buttonPart
	if not button then
		return nil
	end
	local ok, value = pcall(function()
		return button:GetAttribute("CanPress")
	end)
	if not ok then
		return nil
	end
	return value
end

-- Сэмплирует первый ключевой кадр UIGradient по имени (для цвета чипа).
local function gradientColor(folder, name, fallback)
	if not folder then
		return fallback
	end
	local gradient = folder:FindFirstChild(name)
	if not gradient then
		gradient = folder:FindFirstChild(name .. "1")
	end
	if gradient and gradient:IsA("UIGradient") then
		local ok, sequence = pcall(function()
			return gradient.Color
		end)
		if ok and typeof(sequence) == "ColorSequence" then
			local keypoints = sequence.Keypoints
			if keypoints and #keypoints > 0 then
				return keypoints[1].Value
			end
		end
	end
	return fallback
end

--============================================================
-- 5. DATA — нормализованные паки и мутации из модуля игры
--============================================================

local Data = {
	packs = {},
	packById = {},
	mutations = {},
	mutationByName = {},
	packsModule = nil,
	ready = false,
}

local FALLBACK_MUTATION_COLOR = Color3.fromRGB(180, 190, 210)
local FALLBACK_RARITY_COLOR = Color3.fromRGB(110, 120, 145)

local function displayMutation(name)
	local display = Scanner.mutationDisplay
	if display and type(display.GetDisplayName) == "function" then
		local ok, value = pcall(display.GetDisplayName, name)
		if ok and type(value) == "string" then
			return value
		end
	end
	if name == "Unknow" then
		return "Unknown"
	end
	return name
end

function Data.build()
	Data.packs = {}
	Data.packById = {}
	Data.mutations = {}
	Data.mutationByName = {}
	Data.ready = false

	local moduleInstance = findPacksModule()
	local module = safeRequire(moduleInstance)
	if not module or type(module.List) ~= "table" then
		warnLog("WARN ConveyorPacks module not available — pack list disabled")
		return false
	end

	Data.packsModule = module
	Scanner.packsModule = module

	local rarityRank = type(module.RarityRank) == "table" and module.RarityRank or {}

	--═══ Паки: Robux-only и «мёртвые» (Weight <= 0) полностью исключены ═══
	for _, pack in ipairs(module.List) do
		local skip = pack.RobuxOnly == true
		if not skip and (tonumber(pack.Weight) or 0) <= 0 then
			skip = true
		end
		if not skip then
			local rank = tonumber(rarityRank[pack.Rarity]) or 99
			local entry = {
				id = tostring(pack.Id),
				rarity = tostring(pack.Rarity or "Unknown"),
				rarityRank = rank,
				price = tonumber(pack.Price) or 0,
				weight = tonumber(pack.Weight) or 0,
				openTime = tonumber(pack.OpenTime) or 0,
				color = gradientColor(Scanner.rarityGradients, tostring(pack.Rarity), FALLBACK_RARITY_COLOR),
			}
			Data.packs[#Data.packs + 1] = entry
			Data.packById[entry.id] = entry
		end
	end

	table.sort(Data.packs, function(a, b)
		if a.rarityRank ~= b.rarityRank then
			return a.rarityRank < b.rarityRank
		end
		return a.id < b.id
	end)

	--═══ Мутации: сначала ручной порядок, затем по Weight (редчайшие сверху) ═══
	local orderIndex = {}
	for index, name in ipairs(CONFIG.mutationOrder) do
		orderIndex[name] = index
	end

	for _, mutation in ipairs(module.Mutations or {}) do
		local name = tostring(mutation.Name)
		local entry = {
			name = name,
			display = displayMutation(name),
			weight = tonumber(mutation.Weight) or 0,
			multiplier = tonumber(mutation.PriceMultiplier) or 1,
			eventOnly = mutation.EventOnly == true,
			color = gradientColor(Scanner.mutationGradients, name, FALLBACK_MUTATION_COLOR),
		}
		Data.mutations[#Data.mutations + 1] = entry
		Data.mutationByName[name] = entry
	end

	table.sort(Data.mutations, function(a, b)
		local aIndex = orderIndex[a.name]
		local bIndex = orderIndex[b.name]
		if aIndex and bIndex then
			return aIndex < bIndex
		elseif aIndex then
			return true
		elseif bIndex then
			return false
		end
		if a.weight ~= b.weight then
			return a.weight < b.weight
		end
		return a.name < b.name
	end)

	Data.ready = #Data.packs > 0 and #Data.mutations > 0
	return Data.ready
end

function Data.getPack(packId)
	return Data.packById[packId]
end

function Data.getMutation(name)
	return Data.mutationByName[name]
end

--============================================================
-- 6. NET — клик по кнопке ролла и покупка пака
--============================================================

local Engine
local UI
local destroy

local Net = {
	remote = nil,
	onEvent = nil,
	buySent = {},
	clickMode = "none",
}

local random = Random.new()

local function markBuySent(itemId)
	Net.buySent[itemId] = os.clock()
	-- Чистим старые записи, чтобы таблица не росла бесконечно.
	local now = os.clock()
	for key, at in pairs(Net.buySent) do
		if now - at > 60 then
			Net.buySent[key] = nil
		end
	end
end

-- Клик по кнопке спавна: сначала fireclickdetector, затем мышь.
function Net.click()
	local detector = Scanner.clickDetector
	if not detector then
		return false, "no-detector"
	end

	if type(fireclickdetector) == "function" then
		local ok = pcall(fireclickdetector, detector)
		if ok then
			Net.clickMode = "clickdetector"
			return true
		end
	end

	-- Fallback: наводим мышь на кнопку и кликаем.
	if type(mousemoveabs) == "function" and type(mouse1click) == "function" then
		local part = Scanner.buttonPart
		local camera = Workspace.CurrentCamera
		if part and camera then
			local okPoint, screenPoint = pcall(function()
				return camera:WorldToViewportPoint(part.Position)
			end)
			if okPoint and screenPoint then
				pcall(mousemoveabs, screenPoint.X, screenPoint.Y)
				pcall(mouse1click)
				Net.clickMode = "mouse"
				return true
			end
		end
	end

	Net.clickMode = "none"
	return false, "no-input"
end

-- Покупка пака, который уже доехал до точки B. Один раз на ItemId.
function Net.tryBuy(itemId)
	if itemId == nil or Net.buySent[itemId] then
		return false
	end
	local remote = Net.remote
	if not remote then
		return false
	end
	markBuySent(itemId)
	local ok = pcall(function()
		remote:FireServer("TryBuy", { ItemId = itemId })
	end)
	if not ok then
		warnLog("WARN TryBuy failed for item " .. tostring(itemId))
	end
	return ok
end

function Net.init()
	local remotes = ReplicatedStorage:FindFirstChild("Remotes")
	if not remotes then
		remotes = ReplicatedStorage:WaitForChild("Remotes", 15)
	end
	Net.remote = remotes and remotes:FindFirstChild("ConveyorRE")
	if not Net.remote then
		warnLog("WARN ConveyorRE not found — remote logic disabled")
		return false
	end

	track(Net.remote.OnClientEvent:Connect(function(action, data)
		if Net.onEvent then
			local ok, err = pcall(Net.onEvent, action, data)
			if not ok then
				warnLog("WARN event handler error: " .. tostring(err))
			end
		end
	end))

	log("remote ready: " .. Net.remote:GetFullName())
	return true
end

--============================================================
-- 7. ENGINE — цикл авторолла и автопокупки
--============================================================

Engine = {
	running = false,
	status = "STOPPED",
	readyAt = 0,
	lastClickAt = 0,
	lastItem = nil,
	stats = {
		rolls = 0,
		seen = 0,
		bought = 0,
		skipped = 0,
		failed = 0,
	},
	seq = {
		ack = 0,
		spawn = 0,
		buy = 0,
		resolve = 0,
	},
	pending = {}, -- itemId → { packId, mutation, price, rarity, at }
	flags = {},   -- itemId → { packAtB, buyPending, resolved }
}

local function cleanupMaps()
	local now = os.clock()
	for itemId, info in pairs(Engine.pending) do
		if now - (info.at or now) > 60 then
			Engine.pending[itemId] = nil
			Engine.flags[itemId] = nil
		end
	end
	for itemId, flag in pairs(Engine.flags) do
		if flag.resolved and now - (flag.at or now) > 60 then
			Engine.flags[itemId] = nil
		end
	end
end

local function packLabel(info)
	if not info then
		return "pack", "mutation"
	end
	local pack = Data.getPack(info.packId)
	local mutation = Data.getMutation(info.mutation)
	local packName = pack and pack.id or tostring(info.packId)
	local mutationName = mutation and mutation.display or tostring(info.mutation)
	return packName, mutationName
end

local function resolveItem(itemId, kind, reason)
	local flag = Engine.flags[itemId]
	if not flag or flag.resolved then
		return
	end
	flag.resolved = true
	flag.at = os.clock()
	Engine.seq.resolve = Engine.seq.resolve + 1

	local info = Engine.pending[itemId]
	local packName, mutationName = packLabel(info)

	if kind == "bought" then
		Engine.stats.bought = Engine.stats.bought + 1
		if UI then
			UI.notify("good", "Bought", packName .. " · " .. mutationName)
		end
	elseif kind == "failed" then
		Engine.stats.failed = Engine.stats.failed + 1
		if reason == "NotEnoughMoney" then
			local stopOnNoMoney = Store.get().options.stopOnNoMoney ~= false
			if UI then
				UI.notify("danger", "Not enough money", stopOnNoMoney and "Autoroll stopped" or "Autoroll keeps rolling")
			end
			if stopOnNoMoney then
				warnLog("WARN not enough money — stopping")
				Engine.stop("NO MONEY")
			end
		elseif UI then
			UI.notify("danger", "Buy failed", tostring(reason or "unknown"))
		end
	end

	Engine.pending[itemId] = nil
	if UI then
		UI.updateStats()
	end
end

-- Обработчик всех событий ConveyorRE.
function Engine.handleEvent(action, data)
	if action == "ButtonClicked" then
		Engine.seq.ack = Engine.seq.ack + 1
		if type(data) == "table" and data.PlotNumber ~= nil and Scanner.plotNumber ~= nil then
			if tostring(data.PlotNumber) ~= tostring(Scanner.plotNumber) then
				Engine.seq.ack = Engine.seq.ack - 1
			end
		end
		return
	end

	if action == "PurchaseSound" then
		return
	end

	if type(data) ~= "table" then
		return
	end

	-- События чужого плота игнорируем.
	if data.PlotNumber ~= nil and Scanner.plotNumber ~= nil then
		if tostring(data.PlotNumber) ~= tostring(Scanner.plotNumber) then
			return
		end
	end

	local itemId = data.ItemId
	if itemId == nil then
		return
	end

	if action == "SpawnAndMoveToB" then
		cleanupMaps()
		Engine.pending[itemId] = {
			itemId = itemId,
			packId = tostring(data.PackId or data.PackAssetName or "Unknown"),
			mutation = tostring(data.Mutation or "Normal"),
			price = tonumber(data.Price) or 0,
			rarity = tostring(data.Rarity or ""),
			at = os.clock(),
		}
		Engine.flags[itemId] = { at = os.clock() }
		Engine.lastItem = itemId
		Engine.seq.spawn = Engine.seq.spawn + 1
		Engine.stats.seen = Engine.stats.seen + 1
		if UI then
			UI.updateStats()
		end
	elseif action == "PackAtB" then
		local info = Engine.pending[itemId]
		if not info then
			return
		end
		local flag = Engine.flags[itemId]
		if not flag then
			flag = { at = os.clock() }
			Engine.flags[itemId] = flag
		end
		flag.packAtB = true

		local allowed = Store.isAllowed(info.packId, info.mutation)
		if not allowed then
			if UI then
				UI.updateLastSeen(info)
			end
			return
		end

		flag.buyPending = true
		Engine.seq.buy = Engine.seq.buy + 1
		local delay = 0.06 + random:NextNumber(0, 0.14)
		task.delay(delay, function()
			if not Engine.running then
				if not flag.resolved then
					flag.resolved = true
					Engine.seq.resolve = Engine.seq.resolve + 1
				end
				return
			end
			if not flag.resolved then
				Net.tryBuy(itemId)
			end
		end)
	elseif action == "BoughtAndRemove" then
		resolveItem(itemId, "bought")
	elseif action == "BuyFailed" then
		resolveItem(itemId, "failed", data.Reason)
	elseif action == "MoveToCAndDestroy" then
		local flag = Engine.flags[itemId]
		local info = Engine.pending[itemId]
		if info and (not flag or not flag.resolved) then
			Engine.stats.skipped = Engine.stats.skipped + 1
			if UI then
				UI.updateStats()
			end
		end
		if flag and not flag.resolved then
			flag.resolved = true
			flag.at = os.clock()
			Engine.seq.resolve = Engine.seq.resolve + 1
		end
		Engine.pending[itemId] = nil
	elseif action == "RecoverRollback" or action == "DestroyOrphanedPack" then
		Engine.pending[itemId] = nil
		Engine.flags[itemId] = nil
	end
end

function Engine.setStatus(status)
	Engine.status = status
	if UI then
		UI.setStatus(status)
	end
end

-- Один шаг цикла: клик → ожидание пака → ожидание покупки.
function Engine.step()
	local cfg = Store.get()
	local interval = math.max(CONFIG.minTimingMs, tonumber(cfg.timingMs) or CONFIG.timingMs) / 1000
	local jitter = (tonumber(cfg.jitterMs) or CONFIG.jitterMs) / 1000

	if not Scanner.ensure() then
		if Engine.status ~= "NOT READY" then
			Engine.setStatus("NOT READY")
		end
		task.wait(1)
		return
	end

	if Engine.status == "NOT READY" then
		Engine.setStatus("RUNNING")
	end

	local now = os.clock()
	if now < Engine.readyAt then
		task.wait(math.min(0.05, Engine.readyAt - now))
		return
	end

	local canPress = Scanner.getCanPress()
	if canPress == false then
		task.wait(0.08)
		return
	end

	local spawnBefore = Engine.seq.spawn
	local clickAt = os.clock()
	local clicked, reason = Net.click()
	if not clicked then
		warnLog("WARN roll click failed: " .. tostring(reason))
		Engine.setStatus("NOT READY")
		task.wait(1)
		return
	end

	Engine.stats.rolls = Engine.stats.rolls + 1
	Engine.lastClickAt = clickAt
	Engine.readyAt = clickAt + interval + random:NextNumber(0, jitter)
	if UI then
		UI.updateStats()
	end

	-- Ждём подтверждение спавна от сервера.
	local t0 = os.clock()
	while Engine.running and Engine.seq.spawn == spawnBefore and os.clock() - t0 < 2 do
		task.wait(0.05)
	end
	if Engine.seq.spawn == spawnBefore then
		warnLog("WARN no spawn confirmation within 2s")
		if Engine.running then
			Engine.setStatus("NOT READY")
		end
		task.wait(0.5)
		return
	end

	local itemId = Engine.lastItem
	local flag = itemId and Engine.flags[itemId]
	if flag then
		-- Ждём, пока пак доедет до точки B.
		local t1 = os.clock()
		while Engine.running and not flag.packAtB and not flag.resolved and os.clock() - t1 < 2 do
			task.wait(0.05)
		end
		-- Если покупка запрошена — ждём её результат.
		if flag.buyPending and not flag.resolved then
			local t2 = os.clock()
			while Engine.running and not flag.resolved and os.clock() - t2 < 2 do
				task.wait(0.05)
			end
		end
	end

	if os.clock() > Engine.readyAt then
		Engine.readyAt = os.clock()
	end
end

function Engine.runLoop()
	while Engine.running do
		local ok, err = pcall(Engine.step)
		if not ok then
			warnLog("WARN engine error: " .. tostring(err))
			task.wait(0.5)
		end
	end
end

function Engine.start()
	if Engine.running then
		return
	end
	if not Data.ready then
		warnLog("WARN pack data not ready, autoroll may not buy anything")
	end
	Scanner.refresh()
	Engine.running = true
	Engine.readyAt = os.clock()
	Engine.setStatus("RUNNING")
	task.spawn(Engine.runLoop)
	log("autoroll started")
	if UI then
		UI.onEngineState()
	end
end

function Engine.stop(reason)
	local wasRunning = Engine.running
	Engine.running = false
	Engine.setStatus(reason or "STOPPED")
	if wasRunning then
		log("autoroll stopped" .. (reason and (": " .. reason) or ""))
	end
	if UI then
		UI.onEngineState()
	end
end

function Engine.toggle()
	if Engine.running then
		Engine.stop("STOPPED")
	else
		Engine.start()
	end
end

function Engine.resetStats()
	for key in pairs(Engine.stats) do
		Engine.stats[key] = 0
	end
	if UI then
		UI.updateStats()
	end
end

function Engine.init()
	Engine.running = false
	Engine.setStatus("STOPPED")
	Net.onEvent = Engine.handleEvent

	-- Слежение за сменой плота (респавн / телепорт).
	local plotValue = player:FindFirstChild("PlotNumber")
	if plotValue and plotValue:IsA("ValueBase") then
		track(plotValue.Changed:Connect(function()
			Scanner.refresh()
			if UI then
				UI.refreshAll()
			end
		end))
	end
end

--============================================================
-- 8. UI — интерфейс на NextUI
--============================================================

UI = {
	-- NextUI
	nextui = nil,
	window = nil,
	bindList = nil,

	-- элементы, которые надо обновлять из кода
	autorollToggle = nil,
	intervalSlider = nil,
	jitterSlider = nil,
	stopToggle = nil,
	autoToggle = nil,
	bindListToggle = nil,
	menuKeyBind = nil,
	packDropdown = nil,
	mutSelect = nil,
	bulkSelect = nil,
	statusLabel = nil,
	lastLabel = nil,
	statsLabel = nil,
	storageLabel = nil,
	overviewLabel = nil,

	-- состояние
	open = true,
	status = "STOPPED",
	selectedPack = nil,
	mutLabels = {},   -- display-имена для мультиселекта
	mutToRaw = {},    -- display → raw
	rawToLabel = {},  -- raw → display
	_silent = false,
	_syncing = false,
}

local STATUS_TEXT = {
	STOPPED = "Stopped",
	RUNNING = "Rolling",
	["NOT READY"] = "Waiting for plot / spawn button",
	["NO MONEY"] = "Stopped — not enough money",
}

------------------------------------------------------------------
-- 8.1 Словари мутаций (display ↔ raw)
------------------------------------------------------------------

local function rebuildMutationMaps()
	UI.mutLabels = {}
	UI.mutToRaw = {}
	UI.rawToLabel = {}

	for _, mutation in ipairs(Data.mutations) do
		local label = mutation.display
		if UI.mutToRaw[label] then
			-- редкий случай: одинаковые display-имена — показываем сырое имя
			label = mutation.name
		end
		UI.mutLabels[#UI.mutLabels + 1] = label
		UI.mutToRaw[label] = mutation.name
		UI.rawToLabel[mutation.name] = label
	end
end

local function packNames()
	local names = {}
	for _, pack in ipairs(Data.packs) do
		names[#names + 1] = pack.id
	end
	return names
end

-- NextUI не любит пустые списки значений — подставляем заглушку.
local function safeValues(list, placeholder)
	if type(list) ~= "table" or #list == 0 then
		return { placeholder }
	end
	return list
end

local function allowedLabels(packId)
	local labels = {}
	local entry = Store.readPack(packId)
	if not entry then
		return labels
	end
	for rawName, allowed in pairs(entry.mutations) do
		if allowed == true then
			labels[#labels + 1] = UI.rawToLabel[rawName] or rawName
		end
	end
	table.sort(labels)
	return labels
end

local function writeMutations(packId, labels)
	local entry = Store.packEntry(packId)
	entry.mutations = {}
	for _, label in ipairs(labels or {}) do
		local rawName = UI.mutToRaw[label] or label
		if Data.mutationByName[rawName] then
			entry.mutations[rawName] = true
		end
	end
	Store.save()
end

local function packEntryEnabled(packId)
	local entry = Store.readPack(packId)
	return entry ~= nil and entry.enabled == true
end

local function setPackEnabled(packId, enabled)
	local entry = Store.packEntry(packId)
	entry.enabled = enabled == true
	Store.save()
end

------------------------------------------------------------------
-- 8.2 Тексты для карточек
------------------------------------------------------------------

local function overviewText()
	if not Data.ready then
		return "Pack data is unavailable. The ConveyorPacks module was not found — "
			.. "open the Packs tab again after you joined a plot, or press \"Reload pack data\"."
	end
	local lines = {}
	for _, pack in ipairs(Data.packs) do
		local entry = Store.readPack(pack.id)
		local enabled = entry ~= nil and entry.enabled == true
		local labels = allowedLabels(pack.id)
		local mutationText = "no mutations"
		if #labels > 0 then
			mutationText = table.concat(labels, ", ")
		end
		lines[#lines + 1] = string.format(
			"%s %s — %s",
			enabled and "[ON] " or "[off]",
			pack.id,
			mutationText
		)
	end
	if #lines == 0 then
		lines[1] = "No packs found."
	end
	return table.concat(lines, "\n")
end

local function statsText()
	local s = Engine.stats
	return string.format(
		"Rolls %d   ·   Seen %d   ·   Bought %d\nSkipped %d   ·   Failed %d",
		s.rolls,
		s.seen,
		s.bought,
		s.skipped,
		s.failed
	)
end

local function plotText()
	local parts = {}
	if Scanner.plotNumber ~= nil then
		parts[#parts + 1] = "Plot " .. tostring(Scanner.plotNumber)
	else
		parts[#parts + 1] = "Plot unknown"
	end
	if Scanner.clickDetector then
		parts[#parts + 1] = "spawn button found"
	else
		parts[#parts + 1] = "spawn button missing"
	end
	if Net.clickMode == "clickdetector" then
		parts[#parts + 1] = "click: clickdetector"
	elseif Net.clickMode == "mouse" then
		parts[#parts + 1] = "click: mouse"
	end
	return table.concat(parts, "  ·  ")
end

local function storageText()
	local mode = Store.isFileMode() and ("file: " .. CONFIG.storageFolder .. "/" .. CONFIG.storageFile)
		or "PlayerGui attributes (not saved between rejoins)"
	return string.format(
		"%s\nPacks %d   ·   Mutations %d   ·   Interval %d ms",
		mode,
		#Data.packs,
		#Data.mutations,
		Store.get().timingMs
	)
end

------------------------------------------------------------------
-- 8.3 Публичные методы UI (их зовёт движок)
------------------------------------------------------------------

function UI.notify(kind, title, content)
	local nextui = UI.nextui
	if not nextui then
		log(title .. (content and (" — " .. content) or ""))
		return
	end
	pcall(function()
		if kind == "good" then
			nextui:Success(title, content)
		elseif kind == "danger" then
			nextui:Error(title, content)
		elseif kind == "warn" then
			nextui:Warning(title, content)
		else
			nextui:Info(title, content)
		end
	end)
end

-- Совместимость со старым кодом движка.
function UI.toast(text, kind)
	UI.notify(kind or "info", "Conveyor Auto", text)
end

function UI.updateStats()
	if not UI.statsLabel then
		return
	end
	pcall(function()
		UI.statsLabel:Set("Counters", statsText())
	end)
end

function UI.setStatus(status)
	UI.status = status
	if UI.statusLabel then
		local text = STATUS_TEXT[status] or tostring(status)
		pcall(function()
			UI.statusLabel:Set("State", text .. "\n" .. plotText())
		end)
	end
	if UI.storageLabel then
		pcall(function()
			UI.storageLabel:Set("Storage", storageText())
		end)
	end
end

-- Держит переключатель Autoroll в синхроне с реальным состоянием движка.
function UI.onEngineState()
	if not UI.autorollToggle or UI._syncing then
		return
	end
	local want = Engine.running == true
	local ok, current = pcall(function()
		return UI.autorollToggle:Get()
	end)
	if not ok or current == want then
		return
	end
	UI._syncing = true
	pcall(function()
		UI.autorollToggle:Set(want)
	end)
	UI._syncing = false
end

function UI.updateLastSeen(info)
	if not UI.lastLabel then
		return
	end
	local packName, mutationName = packLabel(info)
	local price = info and info.price or 0
	pcall(function()
		UI.lastLabel:Set("Last seen", string.format("%s  ·  %s  ·  %s", packName, mutationName, formatPrice(price)))
	end)
end

function UI.refreshOverview()
	if not UI.overviewLabel then
		return
	end
	pcall(function()
		UI.overviewLabel:Set("All packs", overviewText())
	end)
end

-- Ставит выбранный пак в дропдаун + его мутации в мультиселект.
function UI.selectPack(packId, skipSync)
	if not Data.packById[packId] then
		for _, pack in ipairs(Data.packs) do
			packId = pack.id
			break
		end
	end
	UI.selectedPack = packId
	if skipSync then
		return
	end
	UI._silent = true
	if UI.packDropdown then
		pcall(function()
			UI.packDropdown:Set(packId)
		end)
	end
	if UI.mutSelect then
		pcall(function()
			UI.mutSelect:Set(allowedLabels(packId))
		end)
	end
	UI._silent = false
end

-- Полное обновление: значения из Store + тексты.
function UI.refreshAll()
	if not UI.window then
		return
	end
	local cfg = Store.get()
	UI._silent = true

	if UI.intervalSlider then
		pcall(function()
			UI.intervalSlider:Set(cfg.timingMs)
		end)
	end
	if UI.jitterSlider then
		pcall(function()
			UI.jitterSlider:Set(cfg.jitterMs)
		end)
	end
	if UI.stopToggle then
		pcall(function()
			UI.stopToggle:Set(cfg.options.stopOnNoMoney == true)
		end)
	end
	if UI.autoToggle then
		pcall(function()
			UI.autoToggle:Set(cfg.options.autoStart == true)
		end)
	end
	if UI.bindListToggle then
		pcall(function()
			UI.bindListToggle:Set(cfg.options.showBindList == true)
		end)
	end
	if UI.menuKeyBind then
		pcall(function()
			UI.menuKeyBind:Set(keyCodeOf(cfg.keybinds.toggleUI, Enum.KeyCode.RightShift))
		end)
	end
	if UI.autorollToggle then
		pcall(function()
			UI.autorollToggle:Set(Engine.running == true)
		end)
	end
	UI._silent = false

	if UI.packDropdown then
		pcall(function()
			UI.packDropdown:Refresh(safeValues(packNames(), "(packs unavailable)"))
		end)
	end
	if UI.bulkSelect then
		pcall(function()
			UI.bulkSelect:Refresh(safeValues(UI.mutLabels, "(no mutations)"))
		end)
	end
	UI.selectPack(UI.selectedPack)
	UI.refreshOverview()
	UI.updateStats()
	UI.updateStatusOnly()
	UI.setStatus(Engine.status)
end

function UI.updateStatusOnly()
	if not UI.statusLabel then
		return
	end
	local text = STATUS_TEXT[UI.status] or tostring(UI.status)
	pcall(function()
		UI.statusLabel:Set("State", text .. "\n" .. plotText())
	end)
end

-- После "Reset defaults" подтягиваем значения заново.
function UI.afterReset()
	UI.refreshAll()
	UI.notify("warn", "Settings reset", "Defaults restored")
end

------------------------------------------------------------------
-- 8.4 Построение окна
------------------------------------------------------------------

function UI.build()
	local compile = loadstring or load
	local loaded, NextUI = pcall(function()
		return compile(game:HttpGet(NEXTUI_URL))()
	end)
	if not loaded or type(NextUI) ~= "table" or type(NextUI.CreateWindow) ~= "function" then
		warnLog("WARN NextUI failed to load — UI disabled (" .. tostring(NextUI) .. ")")
		return false
	end

	UI.nextui = NextUI
	rebuildMutationMaps()

	local cfg = Store.get()

	local okWindow, window = pcall(function()
		return NextUI:CreateWindow({
			Title = "Conveyor Auto",
			SubTitle = "v" .. VERSION .. " · conveyor only",
			Size = Vector2.new(780, 540),
			Theme = "Amethyst",
			Search = true,
			SearchWidth = 180,
			Collapsible = true,
			Stars = true,
			Profile = true,
			MobileButton = "Auto",
			ToggleKeys = { Enum.KeyCode.Insert, Enum.KeyCode.RightShift },
		})
	end)
	if not okWindow or not window then
		warnLog("WARN NextUI CreateWindow failed: " .. tostring(window))
		return false
	end
	UI.window = window

	----------------------------------------------------------------
	-- Вкладка AUTOROLL
	----------------------------------------------------------------
	local FarmTab = window:AddTab({ Title = "Autoroll", Icon = "play" })

	local RollCard = FarmTab:AddSection({
		Title = "Rolling",
		Icon = "timer",
		Side = "Left",
	})

	UI.autorollToggle = RollCard:AddToggle({
		Title = "Autoroll",
		Description = "Spins the spawn button on your plot",
		Style = "Switch",
		Flag = "ca_autoroll",
		Default = false,
		Keybind = keyCodeOf(cfg.keybinds.toggleRoll, Enum.KeyCode.R),
		KeyMode = "Toggle",
		Callback = function(on)
			if UI._silent or UI._syncing then
				return
			end
			if on == (Engine.running == true) then
				return
			end
			if on then
				Engine.start()
			else
				Engine.stop("STOPPED")
			end
		end,
	})

	UI.intervalSlider = RollCard:AddSlider({
		Title = "Roll interval",
		Description = "Server cooldown is about 650 ms",
		Flag = "ca_interval",
		Min = CONFIG.minTimingMs,
		Max = 10000,
		Default = cfg.timingMs,
		Increment = 25,
		Suffix = " ms",
		Callback = function(value)
			if UI._silent then
				return
			end
			Store.setTiming(value)
			UI.setStatus(Engine.status)
		end,
	})

	UI.jitterSlider = RollCard:AddSlider({
		Title = "Random extra delay",
		Description = "Adds 0 to this value so the rhythm is not exact",
		Flag = "ca_jitter",
		Min = 0,
		Max = CONFIG.maxJitterMs,
		Default = cfg.jitterMs,
		Increment = 10,
		Suffix = " ms",
		Callback = function(value)
			if UI._silent then
				return
			end
			Store.setJitter(value)
		end,
	})

	RollCard:AddButton({
		Title = "Stop and reset counters",
		Description = "Stops autoroll and sets all counters back to 0",
		Callback = function()
			Engine.stop("STOPPED")
			Engine.resetStats()
			UI.notify("warn", "Counters reset", "Autoroll stopped")
		end,
	})

	----------------------------------------------------------------
	-- Вкладка AUTOROLL → состояние и статистика
	----------------------------------------------------------------
	local StateCard = FarmTab:AddSection({
		Title = "State",
		Icon = "activity",
		Side = "Right",
	})

	UI.statusLabel = StateCard:AddParagraph({
		Title = "State",
		Content = STATUS_TEXT[Engine.status] or "Stopped",
	})

	UI.lastLabel = StateCard:AddParagraph({
		Title = "Last seen",
		Content = "Nothing yet",
	})

	StateCard:AddButton({
		Title = "Rescan plot",
		Description = "Searches the plot, spawn button and remote again",
		Callback = function()
			Scanner.refresh()
			UI.updateStatusOnly()
			if Scanner.clickDetector then
				UI.notify("good", "Plot scanned", "Spawn button found")
			else
				UI.notify("danger", "Plot scanned", "Spawn button not found")
			end
		end,
	})

	local StatsCard = FarmTab:AddSection({
		Title = "Statistics",
		Icon = "bar-chart",
		Side = "Full",
	})

	UI.statsLabel = StatsCard:AddParagraph({
		Title = "Counters",
		Content = statsText(),
	})

	StatsCard:AddButton({
		Title = "Reset counters",
		Hold = 1.2,
		Callback = function()
			Engine.resetStats()
			UI.notify("info", "Counters reset", "All counters are 0 again")
		end,
	})

	----------------------------------------------------------------
	-- Вкладка PACKS
	----------------------------------------------------------------
	local PacksTab = window:AddTab({ Title = "Packs", Icon = "package" })

	local RuleCard = PacksTab:AddSection({
		Title = "Buy rules",
		Icon = "list",
		Side = "Full",
	})

	UI.packDropdown = RuleCard:AddDropdown({
		Title = "Pack",
		Description = "Pick the pack you want to configure",
		Flag = "ca_pack",
		Values = safeValues(packNames(), "(packs unavailable)"),
		Default = nil,
		Search = true,
		Callback = function(value)
			if UI._silent then
				return
			end
			UI.selectPack(value)
			UI.refreshOverview()
		end,
	})

	UI.mutSelect = RuleCard:AddMultiSelect({
		Title = "Buy only these mutations",
		Description = "Empty list = the pack is enabled but never bought",
		Flag = "ca_pack_mutations",
		Values = safeValues(UI.mutLabels, "(no mutations)"),
		Default = {},
		Placeholder = "Pick mutations",
		Callback = function(list)
			if UI._silent then
				return
			end
			local packId = UI.selectedPack
			if not packId then
				return
			end
			writeMutations(packId, list)
			UI.refreshOverview()
		end,
	})

	RuleCard:AddButton({
		Title = "Enable this pack",
		Callback = function()
			local packId = UI.selectedPack
			if not packId then
				UI.notify("warn", "No pack selected", "Pick a pack first")
				return
			end
			setPackEnabled(packId, true)
			UI.refreshOverview()
			UI.notify("good", "Pack enabled", packId)
		end,
	})

	RuleCard:AddButton({
		Title = "Disable this pack",
		Callback = function()
			local packId = UI.selectedPack
			if not packId then
				UI.notify("warn", "No pack selected", "Pick a pack first")
				return
			end
			setPackEnabled(packId, false)
			UI.refreshOverview()
			UI.notify("info", "Pack disabled", packId)
		end,
	})

	RuleCard:AddButton({
		Title = "Allow all mutations of this pack",
		Callback = function()
			local packId = UI.selectedPack
			if not packId then
				return
			end
			local labels = {}
			for _, label in ipairs(UI.mutLabels) do
				labels[#labels + 1] = label
			end
			writeMutations(packId, labels)
			UI._silent = true
			pcall(function()
				UI.mutSelect:Set(labels)
			end)
			UI._silent = false
			UI.refreshOverview()
		end,
	})

	RuleCard:AddButton({
		Title = "Clear mutations of this pack",
		Callback = function()
			local packId = UI.selectedPack
			if not packId then
				return
			end
			writeMutations(packId, {})
			UI._silent = true
			pcall(function()
				UI.mutSelect:Set({})
			end)
			UI._silent = false
			UI.refreshOverview()
		end,
	})

	local OverviewCard = PacksTab:AddSection({
		Title = "All packs",
		Icon = "table",
		Side = "Left",
		Collapsible = true,
	})

	UI.overviewLabel = OverviewCard:AddParagraph({
		Title = "Current rules",
		Content = overviewText(),
	})

	local BulkCard = PacksTab:AddSection({
		Title = "Bulk",
		Icon = "layers",
		Side = "Right",
	})

	UI.bulkSelect = BulkCard:AddMultiSelect({
		Title = "Mutations for every pack",
		Description = "Does not change which packs are enabled",
		Flag = "ca_bulk_mutations",
		Values = safeValues(UI.mutLabels, "(no mutations)"),
		Default = {},
		Placeholder = "Pick mutations",
	})

	BulkCard:AddButton({
		Title = "Apply to every pack",
		Callback = function()
			local list = {}
			local ok, value = pcall(function()
				return UI.bulkSelect:Get()
			end)
			if ok and type(value) == "table" then
				list = value
			end
			if #list == 0 then
				UI.notify("warn", "Nothing selected", "Pick at least one mutation")
				return
			end
			for _, pack in ipairs(Data.packs) do
				writeMutations(pack.id, list)
			end
			Store.save(true)
			UI.refreshOverview()
			UI.selectPack(UI.selectedPack)
			UI.notify("good", "Mutations applied", string.format("to %d packs", #Data.packs))
		end,
	})

	BulkCard:AddButton({
		Title = "Enable every pack",
		Hold = 1.2,
		Callback = function()
			for _, pack in ipairs(Data.packs) do
				setPackEnabled(pack.id, true)
			end
			Store.save(true)
			UI.refreshOverview()
			UI.notify("warn", "All packs enabled", "Check the mutation lists")
		end,
	})

	BulkCard:AddButton({
		Title = "Disable every pack",
		Callback = function()
			for _, pack in ipairs(Data.packs) do
				setPackEnabled(pack.id, false)
			end
			Store.save(true)
			UI.refreshOverview()
			UI.notify("info", "All packs disabled", nil)
		end,
	})

	----------------------------------------------------------------
	-- Вкладка SETTINGS
	----------------------------------------------------------------
	local SettingsTab = window:AddTab({ Title = "Settings", Icon = "settings" })

	local BehaviourCard = SettingsTab:AddSection({
		Title = "Behaviour",
		Icon = "sliders-horizontal",
		Side = "Left",
	})

	UI.stopToggle = BehaviourCard:AddToggle({
		Title = "Stop when out of money",
		Description = "Pause autoroll when the server rejects a purchase",
		Style = "Switch",
		Flag = "ca_stop_no_money",
		Default = cfg.options.stopOnNoMoney == true,
		Callback = function(state)
			if UI._silent then
				return
			end
			Store.get().options.stopOnNoMoney = state == true
			Store.save()
		end,
	})

	UI.autoToggle = BehaviourCard:AddToggle({
		Title = "Auto-start on load",
		Description = "Begin rolling as soon as the script runs",
		Style = "Switch",
		Flag = "ca_auto_start",
		Default = cfg.options.autoStart == true,
		Callback = function(state)
			if UI._silent then
				return
			end
			Store.get().options.autoStart = state == true
			Store.save()
		end,
	})

	local HotkeyCard = SettingsTab:AddSection({
		Title = "Hotkeys",
		Icon = "keyboard",
		Side = "Right",
	})

	UI.menuKeyBind = HotkeyCard:AddKeybind({
		Title = "Menu key",
		Description = "Shows and hides this window (Insert always works too)",
		Flag = "ca_menu_key",
		Default = keyCodeOf(cfg.keybinds.toggleUI, Enum.KeyCode.RightShift),
		MenuKey = true,
		ChangedCallback = function(key)
			if UI._silent or not key then
				return
			end
			local name = key.Name or tostring(key)
			Store.get().keybinds.toggleUI = name
			Store.save()
		end,
	})

	UI.bindListToggle = HotkeyCard:AddToggle({
		Title = "Keybind list overlay",
		Description = "Small draggable list of every keybind (key K)",
		Style = "Switch",
		Flag = "ca_bind_list",
		Default = cfg.options.showBindList == true,
		Callback = function(state)
			if UI._silent then
				return
			end
			Store.get().options.showBindList = state == true
			Store.save()
			if UI.bindList then
				pcall(function()
					UI.bindList:SetVisible(state == true)
				end)
			end
		end,
	})

	HotkeyCard:AddLabel("The autoroll key sits on the Autoroll switch — click its key cap to rebind.")

	----------------------------------------------------------------
	-- Хранилище и обслуживание
	----------------------------------------------------------------
	local StorageCard = SettingsTab:AddSection({
		Title = "Data & storage",
		Icon = "database",
		Side = "Full",
	})

	UI.storageLabel = StorageCard:AddParagraph({
		Title = "Storage",
		Content = storageText(),
	})

	StorageCard:AddButton({
		Title = "Reload pack data",
		Description = "Re-reads ConveyorPacks and refreshes every list",
		Callback = function()
			local ready = Data.build()
			rebuildMutationMaps()
			if UI.packDropdown then
				pcall(function()
					UI.packDropdown:Refresh(safeValues(packNames(), "(packs unavailable)"))
				end)
			end
			if UI.mutSelect then
				pcall(function()
					UI.mutSelect:Refresh(safeValues(UI.mutLabels, "(no mutations)"))
				end)
			end
			if UI.bulkSelect then
				pcall(function()
					UI.bulkSelect:Refresh(safeValues(UI.mutLabels, "(no mutations)"))
				end)
			end
			UI.selectPack(nil)
			UI.refreshAll()
			if ready then
				UI.notify("good", "Pack data loaded", string.format("%d packs · %d mutations", #Data.packs, #Data.mutations))
			else
				UI.notify("danger", "Pack data unavailable", "ConveyorPacks module not found")
			end
		end,
	})

	StorageCard:AddButton({
		Title = "Save settings now",
		Description = "Writes the config file immediately",
		Callback = function()
			Store.save(true)
			UI.notify("good", "Saved", Store.isFileMode() and "Written to the config file" or "Stored in PlayerGui attributes")
		end,
	})

	local MaintCard = SettingsTab:AddSection({
		Title = "Maintenance",
		Icon = "wrench",
		Side = "Full",
	})

	MaintCard:AddButton({
		Title = "Reset all settings",
		Description = "Hold to wipe packs, keys, interval and options",
		Hold = 1.5,
		Callback = function()
			Store.reset()
			UI.afterReset()
		end,
	})

	MaintCard:AddButton({
		Title = "Unload script",
		Description = "Hold to stop autoroll and remove the interface",
		Hold = 1.5,
		Callback = function()
			if destroy then
				destroy()
			end
		end,
	})

	----------------------------------------------------------------
	-- Оверлей кейбиндов (NextUI)
	----------------------------------------------------------------
	local okList, list = pcall(function()
		return NextUI:CreateKeybindList({
			Key = Enum.KeyCode.K,
			Position = "TopLeft",
			OnlyActive = false,
			Visible = cfg.options.showBindList == true,
		})
	end)
	if okList then
		UI.bindList = list
	end

	----------------------------------------------------------------
	-- Стартовая синхронизация
	----------------------------------------------------------------
	UI.selectPack(nil)
	UI.updateStats()
	UI.lastLabel:Set("Last seen", "Nothing yet")
	UI.setStatus(Engine.status)
	UI.refreshOverview()

	log("ui ready: " .. tostring(#Data.packs) .. " packs, " .. tostring(#Data.mutations) .. " mutations")
	return true
end

--============================================================
-- 9. BOOT — сборка и запуск
--============================================================

function destroy()
	if Engine and Engine.stop then
		Engine.stop("STOPPED")
	end
	for _, connection in ipairs(connections) do
		pcall(function()
			connection:Disconnect()
		end)
	end
	connections = {}
	if UI and UI.nextui then
		pcall(function()
			UI.nextui:Destroy()
		end)
	end
	UI.window = nil
	local env = getgenv and getgenv() or nil
	if env and env.ConveyorAuto and env.ConveyorAuto.version == VERSION then
		env.ConveyorAuto = nil
	end
	log("destroyed")
end

local function boot()
	log("v" .. VERSION .. " starting… (NextUI)")

	-- Корректно снимаем предыдущий запуск, если он был.
	local env = getgenv and getgenv() or nil
	if env and env.ConveyorAuto and type(env.ConveyorAuto.destroy) == "function" then
		pcall(env.ConveyorAuto.destroy)
	end

	Store.init()
	Scanner.refresh()
	Data.build()
	Engine.init()
	local netOk = Net.init()
	local uiOk = UI.build()

	if uiOk then
		UI.refreshAll()
	end

	log(string.format(
		"loaded · packs=%d · mutations=%d · timing=%dms · storage=%s",
		#Data.packs,
		#Data.mutations,
		Store.get().timingMs,
		Store.isFileMode() and "file" or "attributes"
	))

	if not uiOk then
		warnLog("WARN NextUI failed to load — the script keeps running without a window")
	end
	if not netOk then
		warnLog("WARN ConveyorRE unavailable — auto-buy disabled")
	end
	if not Data.ready then
		warnLog("WARN pack data unavailable — pack list disabled")
	end

	if env then
		env.ConveyorAuto = {
			version = VERSION,
			destroy = destroy,
			engine = Engine,
			data = Data,
			store = Store,
			ui = UI,
			net = Net,
			scanner = Scanner,
		}
	end

	if Store.get().options.autoStart then
		task.delay(1, function()
			if not Engine.running then
				Engine.start()
			end
		end)
	end
end

boot()
Executor compatibility changes over time. Check current reports before testing.

Copy the code above into a compatible Roblox script executor if you choose to test it.

Anime Card Farm Script Status

✓AvailabilityFree
$Price$0
◫CompatibilityDesktop & Mobile
★SafetyVerified

Roblox and game updates can affect compatibility, so the script’s status should be treated as temporary rather than guaranteed.

Frequently Asked Questions

What is a Anime Card Farm script?

A Anime Card Farm script is third-party Lua code intended to run alongside the Roblox game through a compatible script executor.

What features does this Anime Card Farm script include?

Different scripts contain different code. This version includes: Autoconveyor.

How do you use the Anime Card Farm script?

Pick a compatible executor such as Hydrogen, MacSploit, AWP.GG, Delta, Fluxus, Codex, launch Roblox and join the game, copy the complete Lua code from the script card above, paste it into the executor’s editor, and click Run or Execute. Compatibility changes over time, so a name here doesn’t guarantee current support.

Can a Anime Card Farm script get your Roblox account banned?

Yes. Third-party scripts can violate Roblox rules and may put an account at risk. Only use code from a source you trust, never enter your Roblox password into a script or executor, and test on an alternate account first.

Does the Anime Card Farm script work on mobile?

Check whether both the executor and the script support your device and the current Roblox version. Mobile executor support does not guarantee that every script will work.

Check out our Roblox Scripts hub and Roblox Games Directory for more.

Leave a Comment