const PLUGIN_NAME = 'ShoppingMall';
const PLUGIN_VERSION = [3, 6, 6];
const PLUGIN_DESCRIPTION = 'SM';

ll.registerPlugin(PLUGIN_NAME, PLUGIN_DESCRIPTION, PLUGIN_VERSION, {});

const path = '.\\plugins\\ShoppingMall\\';
const configPath = path + 'config.json';
const shopsDataPath = path + 'ShoppingMall.json';
const officialShopDataPath = path + 'OfficialShop.json';
const forbiddenItemsPath = path + 'forbiddenItems.json';
const uiIconsPath = path + 'ui_icons.json';
const rankingDataPath = path + 'rankingData.json';
const purchaseLogsPath = path + "purchaseLogs.json";
const chatMessagesPath = path + 'chatMessages.json'; 
const mentionDataPath = path + 'mentionData.json';
const purchaseRequestsPath = path + 'purchaseRequests.json';
const itemsDataPath = path + 'Items.json';
const priceHistoryPath = path + 'priceHistory.json';
const taxRecordsPath = path + 'taxRecords.json';
const dynamicRecyclePath = path + 'dynamicRecycle.json';
const recycleLimitsPath = path + 'recycleLimits.json';
const warehousePath = path + 'warehouse.json';
const playerRecordsPath = path + 'playerRecords.json';
const giftRecordsPath = path + 'giftRecords.json';
const dbMigrationFlagPath = path + 'db_migrated.flag';
const dbPath = path + 'database';

let smDB = null;
try {
  smDB = new KVDatabase(dbPath);
  if (smDB) {
    log('§a数据库连接成功');
  }
} catch (e) {
  log(`§c数据库创建失败: ${e.message}`);
  smDB = null;
}

const useDatabase = smDB !== null;

const DB_KEYS = {
  SHOPS: 'shops_data',
  OFFICIAL_SHOP: 'official_shop',
  WAREHOUSE: 'warehouse',
  PLAYER_RECORDS: 'player_records',
  GIFT_RECORDS: 'gift_records',
  PURCHASE_LOGS: 'purchase_logs',
  CHAT_MESSAGES: 'chat_messages',
  MENTION_DATA: 'mention_data',
  PURCHASE_REQUESTS: 'purchase_requests',
  PRICE_HISTORY: 'price_history',
  TAX_RECORDS: 'tax_records',
  DYNAMIC_RECYCLE: 'dynamic_recycle',
  RECYCLE_LIMITS: 'recycle_limits',
  RANKING: 'ranking_data',
  FORBIDDEN_ITEMS: 'forbidden_items',
  ITEMS_DATA: 'items_data'
};

const JSON_FALLBACK_PATHS = {
  [DB_KEYS.SHOPS]: shopsDataPath,
  [DB_KEYS.OFFICIAL_SHOP]: officialShopDataPath,
  [DB_KEYS.WAREHOUSE]: warehousePath,
  [DB_KEYS.PLAYER_RECORDS]: playerRecordsPath,
  [DB_KEYS.GIFT_RECORDS]: giftRecordsPath,
  [DB_KEYS.PURCHASE_LOGS]: purchaseLogsPath,
  [DB_KEYS.CHAT_MESSAGES]: chatMessagesPath,
  [DB_KEYS.MENTION_DATA]: mentionDataPath,
  [DB_KEYS.PURCHASE_REQUESTS]: purchaseRequestsPath,
  [DB_KEYS.PRICE_HISTORY]: priceHistoryPath,
  [DB_KEYS.TAX_RECORDS]: taxRecordsPath,
  [DB_KEYS.DYNAMIC_RECYCLE]: dynamicRecyclePath,
  [DB_KEYS.RECYCLE_LIMITS]: recycleLimitsPath,
  [DB_KEYS.RANKING]: rankingDataPath,
  [DB_KEYS.FORBIDDEN_ITEMS]: forbiddenItemsPath,
  [DB_KEYS.ITEMS_DATA]: itemsDataPath
};

function dbGet(key, defaultValue = null) {
  if (smDB) {
    try {
      const data = smDB.get(key);
      if (data !== null) return data;
    } catch (e) {
      log(`数据库读取失败 [${key}]: ${e.message}`);
    }
  }
  
  const jsonPath = JSON_FALLBACK_PATHS[key];
  if (jsonPath && File.exists(jsonPath)) {
    try {
      const raw = File.readFrom(jsonPath);
      if (raw && raw.trim()) {
        return JSON.parse(raw);
      }
    } catch (e) {
      log(`JSON回退读取失败 [${key}]: ${e.message}`);
    }
  }
  return defaultValue;
}

function dbSet(key, value) {
  if (smDB) {
    try {
      if (smDB.set(key, value)) {
        return true;
      }
    } catch (e) {
      log(`数据库写入失败 [${key}]: ${e.message}`);
    }
  }
  
  const jsonPath = JSON_FALLBACK_PATHS[key];
  if (jsonPath) {
    try {
      File.writeTo(jsonPath, JSON.stringify(value, null, 2));
      return true;
    } catch (e) {
      log(`JSON回退写入失败 [${key}]: ${e.message}`);
    }
  }
  return false;
}

function migrateJsonToDatabase() {
  if (!useDatabase) {
    log('§c数据库不可用，跳过迁移');
    return;
  }
  
  if (File.exists(dbMigrationFlagPath)) {
    log('§a数据库迁移已完成，跳过迁移');
    return;
  }
  
  log('§e开始数据库迁移...');
  let migrationSuccess = true;
  let migratedCount = 0;
  
  const migrations = [
    { path: shopsDataPath, key: DB_KEYS.SHOPS, default: {} },
    { path: officialShopDataPath, key: DB_KEYS.OFFICIAL_SHOP, default: { purchaseItems: {}, recycleItems: {} } },
    { path: warehousePath, key: DB_KEYS.WAREHOUSE, default: {} },
    { path: playerRecordsPath, key: DB_KEYS.PLAYER_RECORDS, default: {} },
    { path: giftRecordsPath, key: DB_KEYS.GIFT_RECORDS, default: {} },
    { path: purchaseLogsPath, key: DB_KEYS.PURCHASE_LOGS, default: { global: [], players: {} } },
    { path: chatMessagesPath, key: DB_KEYS.CHAT_MESSAGES, default: [] },
    { path: mentionDataPath, key: DB_KEYS.MENTION_DATA, default: {} },
    { path: purchaseRequestsPath, key: DB_KEYS.PURCHASE_REQUESTS, default: { requests: [], history: [] } },
    { path: priceHistoryPath, key: DB_KEYS.PRICE_HISTORY, default: {} },
    { path: taxRecordsPath, key: DB_KEYS.TAX_RECORDS, default: { totalCollected: 0, playerRecords: {}, dailyRecords: {} } },
    { path: dynamicRecyclePath, key: DB_KEYS.DYNAMIC_RECYCLE, default: { itemPrices: {}, recycleHistory: {}, lastUpdate: {} } },
    { path: recycleLimitsPath, key: DB_KEYS.RECYCLE_LIMITS, default: { globalLimits: {}, playerLimits: {}, globalUsage: {}, playerUsage: {}, lastReset: Date.now() } },
    { path: rankingDataPath, key: DB_KEYS.RANKING, default: {} },
    { path: forbiddenItemsPath, key: DB_KEYS.FORBIDDEN_ITEMS, default: [] },
    { path: itemsDataPath, key: DB_KEYS.ITEMS_DATA, default: { items: [] } }
  ];
  
  for (const m of migrations) {
    try {
      let jsonData = m.default;
      if (File.exists(m.path)) {
        const rawContent = File.readFrom(m.path);
        if (rawContent && rawContent.trim()) {
          try {
            jsonData = JSON.parse(rawContent);
          } catch (parseErr) {
            log(`§c警告: ${m.path} JSON解析失败，使用默认值: ${parseErr.message}`);
            jsonData = m.default;
          }
        }
      }
      
      if (dbSet(m.key, jsonData)) {
        log(`§a迁移成功: ${m.key}`);
        migratedCount++;
      } else {
        log(`§c迁移失败: ${m.key}`);
        migrationSuccess = false;
      }
    } catch (e) {
      log(`§c迁移错误 [${m.key}]: ${e.message}`);
      migrationSuccess = false;
    }
  }
  
  if (migrationSuccess) {
    File.writeTo(dbMigrationFlagPath, `migrated_at: ${new Date().toISOString()}\ncount: ${migratedCount}`);
    log(`§a§l数据库迁移完成！共迁移 ${migratedCount} 项数据`);
  } else {
    log('§c§l部分数据迁移失败，请检查日志');
  }
}

if (useDatabase) {
  migrateJsonToDatabase();
}

const defaultConfig = {
  cmd: 'sm',
  cmdDescription: "打开商店菜单",
  economySystem: 'llmoney',
  scoreboardObjective: 'money',
  shopCreationCost: 1000,
  shopNameChangeCost: 500,
  shopNameChangeCooldown: 168,
  enableShopRanking: true,
  showOfficialPurchase: true,
  enableChatLobby: true,
  notifyDiscountToAll: true,
  notifyItemListingToAll: true,
  chatHistoryLimit: 30,
  enablePurchaseRequests: true,
  purchaseRequestFee: 0,
  purchaseRequestExpiry: 72,
  notifyPurchaseRequestToAll: true,
  enableShopLevelSystem: false,
  shopDefaultItemTypes: 15,        
  shopDefaultTotalItems: 960,      
  shopUpgradeBasePrice: 1000,      
  shopUpgradePriceIncrement: 150,  
  shopUpgradeItemTypeIncrement: 1, 
  shopUpgradeTotalIncrement: 64,   
  enableBatchShopUpgrade: true,
  advertSlotsSetting: {
    "1":  { price: 1000, duration: 24 },
    "2":  { price: 1000, duration: 24 },
    "3":  { price: 1000, duration: 24 },
    "4":  { price: 1000, duration: 24 },
    "5":  { price: 1000, duration: 24 },
    "6":  { price: 1000, duration: 24 },
    "7":  { price: 1000, duration: 24 },
    "8":  { price: 1000, duration: 24 },
    "9":  { price: 1000, duration: 24 },
    "10": { price: 1000, duration: 24 }
  },
  allowedDomain: "",
  enableLocalIcon: true,
  localIconChangeCost: 200,
  localIconChangeCooldown: 72,
  enableCustomPathIcon: true,
  customPathIconChangeCost: 200,
  customPathIconChangeCooldown: 72,
  pageSizeLimit: 30,
  shopSortMode: "随机",
  officialShopSortMode: "随机",
  enableItemCategories: true,
  itemCategories: ["全部", "武器", "工具", "装备", "方块", "食物", "药水", "附魔书", "材料", "装饰", "其他"],
  enableBatchOperations: true,
  enableTaxSystem: true,
  taxRate: 0.05,
  taxOnlyOfficialShop: true,
  enablePriceHistory: true,
  priceHistoryDays: 30,
  priceHistoryMaxRecords: 1000,
  showMainMenuStatistics: true,
  mainMenuButtons: {
    chatLobby: { enabled: true, order: 1 },
    globalSearch: { enabled: true, order: 2 },
    shoppingCenter: { enabled: true, order: 3 },
    myShop: { enabled: true, order: 4 },
    officialShop: { enabled: true, order: 5 },
    purchaseRequests: { enabled: true, order: 6 },
    warehouse: { enabled: true, order: 7 },
    shopRanking: { enabled: true, order: 8 },
    tradeLogs: { enabled: true, order: 9 }
  },
  enableRecycleLimits: false,
  recycleLimitGlobal: {},
  recycleLimitPlayer: {},
  recycleLimitResetHours: 24,
  enableGiftSystem: true,
  maxWarehouseSlots: 50,
  enableWarehousePurchase: 1,
  warehouseMode: 0,
  warehouseBuyoutPrice: 10000,
  warehouseRentalPrice: 1,
  warehouseRentalMinutes: 1440,
  warehouseMinRentalTime: 60,
  allowSelfPurchase: false
};

const config = data.openConfig(configPath, 'json', JSON.stringify(defaultConfig, null, 4));

function updateConfigWithMissingEntries() {
  let configUpdated = false;
  
  if (config.get('notifyDiscountToAll') === undefined) {
    config.set('notifyDiscountToAll', true);
    configUpdated = true;
  }
  
  if (config.get('enableChatLobby') === undefined) {
    config.set('enableChatLobby', true);
    configUpdated = true;
  }
  
  if (config.get('notifyItemListingToAll') === undefined) {
    config.set('notifyItemListingToAll', true);
    configUpdated = true;
  }
  
  if (config.get('chatHistoryLimit') === undefined) {
    config.set('chatHistoryLimit', 30);
    configUpdated = true;
  }
  
  if (config.get('enablePurchaseRequests') === undefined) {
    config.set('enablePurchaseRequests', true);
    configUpdated = true;
  }
  
  if (config.get('purchaseRequestFee') === undefined) {
    config.set('purchaseRequestFee', 0);
    configUpdated = true;
  }
  
  if (config.get('purchaseRequestExpiry') === undefined) {
    config.set('purchaseRequestExpiry', 72);
    configUpdated = true;
  }
  
  if (config.get('notifyPurchaseRequestToAll') === undefined) {
    config.set('notifyPurchaseRequestToAll', true);
    configUpdated = true;
  }
  
  if (config.get('enableShopLevelSystem') === undefined) {
    config.set('enableShopLevelSystem', false);
    configUpdated = true;
  }
  
  if (config.get('shopDefaultItemTypes') === undefined) {
    config.set('shopDefaultItemTypes', 15);
    configUpdated = true;
  }
  
  if (config.get('shopDefaultTotalItems') === undefined) {
    config.set('shopDefaultTotalItems', 960);
    configUpdated = true;
  }
  
  if (config.get('shopUpgradeBasePrice') === undefined) {
    config.set('shopUpgradeBasePrice', 1000);
    configUpdated = true;
  }
  
  if (config.get('shopUpgradePriceIncrement') === undefined) {
    config.set('shopUpgradePriceIncrement', 500);
    configUpdated = true;
  }
  
  if (config.get('shopUpgradeItemTypeIncrement') === undefined) {
    config.set('shopUpgradeItemTypeIncrement', 5);
    configUpdated = true;
  }
  
  if (config.get('shopUpgradeTotalIncrement') === undefined) {
    config.set('shopUpgradeTotalIncrement', 64);
    configUpdated = true;
  }
  
  if (config.get('enableBatchShopUpgrade') === undefined) {
    config.set('enableBatchShopUpgrade', true);
    configUpdated = true;
  }
  
  if (config.get('enableItemCategories') === undefined) {
    config.set('enableItemCategories', true);
    configUpdated = true;
  }
  
  if (config.get('itemCategories') === undefined) {
    config.set('itemCategories', ["全部", "武器", "工具", "装备", "方块", "食物", "药水", "附魔书", "材料", "装饰", "其他"]);
    configUpdated = true;
  }
  
  if (config.get('enableBatchOperations') === undefined) {
    config.set('enableBatchOperations', true);
    configUpdated = true;
  }
  
  if (config.get('enableTaxSystem') === undefined) {
    config.set('enableTaxSystem', true);
    configUpdated = true;
  }
  
  if (config.get('taxRate') === undefined) {
    config.set('taxRate', 0.05);
    configUpdated = true;
  }
  
  if (config.get('taxOnlyOfficialShop') === undefined) {
    config.set('taxOnlyOfficialShop', true);
    configUpdated = true;
  }
  
  if (config.get('enablePriceHistory') === undefined) {
    config.set('enablePriceHistory', true);
    configUpdated = true;
  }
  
  if (config.get('priceHistoryDays') === undefined) {
    config.set('priceHistoryDays', 30);
    configUpdated = true;
  }
  
  if (config.get('priceHistoryMaxRecords') === undefined) {
    config.set('priceHistoryMaxRecords', 1000);
    configUpdated = true;
  }
  
  if (config.get('showMainMenuStatistics') === undefined) {
    config.set('showMainMenuStatistics', true);
    configUpdated = true;
  }
  
  if (config.get('mainMenuButtons') === undefined) {
    config.set('mainMenuButtons', {
      chatLobby: { enabled: true, order: 1 },
      globalSearch: { enabled: true, order: 2 },
      shoppingCenter: { enabled: true, order: 3 },
      myShop: { enabled: true, order: 4 },
      officialShop: { enabled: true, order: 5 },
      purchaseRequests: { enabled: true, order: 6 },
      warehouse: { enabled: true, order: 7 },
      shopRanking: { enabled: true, order: 8 },
      tradeLogs: { enabled: true, order: 9 }
    });
    configUpdated = true;
  }
  
  if (config.get('dynamicRecycle') === undefined) {
    config.set('dynamicRecycle', {
      enabled: false,
      priceDecayRate: 5,
      maxPriceDecrease: 50,
      maxPriceIncrease: 20,
      recoveryRate: 2,
      timeWindow: 60,
      recycleThreshold: 5,
      recoveryTime: 120,
      checkInterval: 30
    });
    configUpdated = true;
  }
  
  if (config.get('enableRecycleLimits') === undefined) {
    config.set('enableRecycleLimits', false);
    configUpdated = true;
  }
  
  if (config.get('recycleLimitGlobal') === undefined) {
    config.set('recycleLimitGlobal', {});
    configUpdated = true;
  }
  
  if (config.get('recycleLimitPlayer') === undefined) {
    config.set('recycleLimitPlayer', {});
    configUpdated = true;
  }
  
  if (config.get('recycleLimitResetHours') === undefined) {
    config.set('recycleLimitResetHours', 24);
    configUpdated = true;
  }
  
  if (config.get('enableGiftSystem') === undefined) {
    config.set('enableGiftSystem', true);
    configUpdated = true;
  }
  
  if (config.get('maxWarehouseSlots') === undefined) {
    config.set('maxWarehouseSlots', 50);
    configUpdated = true;
  }
  
  if (config.get('enableWarehousePurchase') === undefined) {
    config.set('enableWarehousePurchase', 1);
    configUpdated = true;
  }
  
  if (config.get('warehouseMode') === undefined) {
    config.set('warehouseMode', 0);
    configUpdated = true;
  }
  
  if (config.get('warehouseBuyoutPrice') === undefined) {
    config.set('warehouseBuyoutPrice', 10000);
    configUpdated = true;
  }
  
  if (config.get('warehouseRentalPrice') === undefined) {
    config.set('warehouseRentalPrice', 1);
    configUpdated = true;
  }
  
  if (config.get('warehouseRentalMinutes') === undefined) {
    config.set('warehouseRentalMinutes', 1440);
    configUpdated = true;
  }
  
  if (config.get('warehouseMinRentalTime') === undefined) {
    config.set('warehouseMinRentalTime', 60);
    configUpdated = true;
  }
  
  if (config.get('allowSelfPurchase') === undefined) {
    config.set('allowSelfPurchase', false);
    configUpdated = true;
  }
  
  const existingMainMenuButtons = config.get('mainMenuButtons');
  if (existingMainMenuButtons && !existingMainMenuButtons.warehouse) {
    existingMainMenuButtons.warehouse = { enabled: true, order: 7 };
    if (existingMainMenuButtons.shopRanking && existingMainMenuButtons.shopRanking.order === 7) {
      existingMainMenuButtons.shopRanking.order = 8;
    }
    if (existingMainMenuButtons.tradeLogs && existingMainMenuButtons.tradeLogs.order === 8) {
      existingMainMenuButtons.tradeLogs.order = 9;
    }
    config.set('mainMenuButtons', existingMainMenuButtons);
    configUpdated = true;
  }
  
  if (configUpdated) {
  }
}

updateConfigWithMissingEntries();

let warehouseData = dbGet(DB_KEYS.WAREHOUSE, {});

let playerRecords = dbGet(DB_KEYS.PLAYER_RECORDS, {});
let restockCooldowns = {};

for (const xuid in playerRecords) {
  const record = playerRecords[xuid];
  if (!record || typeof record !== 'object') {
    delete playerRecords[xuid];
    continue;
  }
  if (!record.nameHistory || !Array.isArray(record.nameHistory)) {
    record.nameHistory = record.name ? [record.name] : [];
  }
  if (!record.name && record.nameHistory.length > 0) {
    record.name = record.nameHistory[record.nameHistory.length - 1];
  }
  if (!record.firstSeen) {
    record.firstSeen = record.lastSeen || Date.now();
  }
  if (!record.lastSeen) {
    record.lastSeen = Date.now();
  }
}
dbSet(DB_KEYS.PLAYER_RECORDS, playerRecords);

let giftRecords = dbGet(DB_KEYS.GIFT_RECORDS, {});

function saveGiftRecords() {
  dbSet(DB_KEYS.GIFT_RECORDS, giftRecords);
}

function showGiftRecords(player) {
  const form = mc.newSimpleForm();
  form.setTitle('§d§l礼物记录');
  form.setContent('§e请选择要查看的记录类型：');
  
  form.addButton('§a收到的礼物', 'textures/ui/icon_import');
  form.addButton('§b送出的礼物', 'textures/ui/icon_steve');
  form.addButton('§c返回仓库', 'textures/ui/arrow_dark_left_stretch');
  
  player.sendForm(form, (pl, id) => {
    if (id === null || id === 2) {
      showPlayerWarehouse(pl);
      return;
    }
    
    if (id === 0) {
      showReceivedGifts(pl);
    } else if (id === 1) {
      showSentGifts(pl);
    }
  });
}

function showReceivedGifts(player) {
  const playerGifts = giftRecords[player.xuid];
  const receivedGifts = playerGifts ? playerGifts.received : [];
  
  if (receivedGifts.length === 0) {
    const form = mc.newSimpleForm();
    form.setTitle('§a§l收到的礼物');
    form.setContent('§e您还没有收到过任何礼物！\n\n§f当其他玩家给您送礼时，记录会显示在这里。');
    form.addButton('§c返回', 'textures/ui/arrow_dark_left_stretch');
    
    player.sendForm(form, (pl, id) => {
      showGiftRecords(pl);
    });
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle('§a§l收到的礼物');
  form.setContent(`§e您总共收到了 §a${receivedGifts.length}§e 个礼物记录：\n§f点击查看详细信息`);
  
  receivedGifts.reverse().forEach((record) => {
    const timeStr = new Date(record.timestamp).toLocaleString();
    const offlineText = record.isOffline ? ' §3(离线收取)' : '';
    form.addButton(`§b${record.itemName} §fx${record.quantity}\n§3来自：§f${record.senderName}${offlineText}\n§3${timeStr}`, 'textures/ui/icon_setting');
  });
  
  form.addButton('§c返回', 'textures/ui/arrow_dark_left_stretch');
  
  player.sendForm(form, (pl, id) => {
    if (id === null || id === receivedGifts.length) {
      showGiftRecords(pl);
      return;
    }
    
    showGiftRecordDetails(pl, receivedGifts[id], true);
  });
}

function showSentGifts(player) {
  const playerGifts = giftRecords[player.xuid];
  const sentGifts = playerGifts ? playerGifts.sent : [];
  
  if (sentGifts.length === 0) {
    const form = mc.newSimpleForm();
    form.setTitle('§b§l送出的礼物');
    form.setContent('§e您还没有送出过任何礼物！\n\n§f当您给其他玩家送礼时，记录会显示在这里。');
    form.addButton('§c返回', 'textures/ui/arrow_dark_left_stretch');
    
    player.sendForm(form, (pl, id) => {
      showGiftRecords(pl);
    });
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle('§b§l送出的礼物');
  form.setContent(`§e您总共送出了 §a${sentGifts.length}§e 个礼物记录：\n§f点击查看详细信息`);
  
  sentGifts.reverse().forEach((record) => {
    const timeStr = new Date(record.timestamp).toLocaleString();
    const offlineText = record.isOffline ? ' §3(离线送达)' : '';
    form.addButton(`§b${record.itemName} §fx${record.quantity}\n§3送给：§f${record.recipientName}${offlineText}\n§3${timeStr}`, 'textures/ui/icon_setting');
  });
  
  form.addButton('§c返回', 'textures/ui/arrow_dark_left_stretch');
  
  player.sendForm(form, (pl, id) => {
    if (id === null || id === sentGifts.length) {
      showGiftRecords(pl);
      return;
    }
    
    showGiftRecordDetails(pl, sentGifts[id], false);
  });
}

function showGiftRecordDetails(player, record, isReceived) {
  const form = mc.newSimpleForm();
  form.setTitle('§3§l礼物详情');
  
  const timeStr = new Date(record.timestamp).toLocaleString();
  const typeText = isReceived ? '收到' : '送出';
  const partnerText = isReceived ? `发送者：§f${record.senderName}` : `接收者：§f${record.recipientName}`;
  const offlineText = record.isOffline ? '\n§3状态：离线处理' : '\n§a状态：在线处理';
  
  let content = `§e礼物类型：§a${typeText}\n`;
  content += `§e${partnerText}\n`;
  content += `§e物品名称：§b${record.itemName}\n`;
  content += `§e物品数量：§f${record.quantity}\n`;
  content += `§e礼物价值：§3${record.price} 金币\n`;
  content += `§e交易时间：§f${timeStr}`;
  content += offlineText;
  
  if (isReceived) {
    content += `\n\n§f这是一份来自 §a${record.senderName}§f 的礼物！`;
  } else {
    content += `\n\n§f您向 §a${record.recipientName}§f 送出了这份礼物！`;
  }
  
  form.setContent(content);
  form.addButton('§c返回列表', 'textures/ui/arrow_dark_left_stretch');
  
  player.sendForm(form, (pl, id) => {
    if (isReceived) {
      showReceivedGifts(pl);
    } else {
      showSentGifts(pl);
    }
  });
}

function addGiftRecord(senderXuid, senderName, recipientXuid, recipientName, itemName, quantity, price, isOffline = false) {
  const timestamp = Date.now();
  const record = {
    senderXuid,
    senderName,
    recipientXuid,
    recipientName,
    itemName,
    quantity,
    price,
    timestamp,
    isOffline
  };
  
  if (!giftRecords[senderXuid]) {
    giftRecords[senderXuid] = { sent: [], received: [] };
  }
  if (!giftRecords[recipientXuid]) {
    giftRecords[recipientXuid] = { sent: [], received: [] };
  }
  
  giftRecords[senderXuid].sent.push(record);
  if (giftRecords[senderXuid].sent.length > 30) {
    giftRecords[senderXuid].sent.shift();
  }
  
  giftRecords[recipientXuid].received.push(record);
  if (giftRecords[recipientXuid].received.length > 30) {
    giftRecords[recipientXuid].received.shift();
  }
  
  saveGiftRecords();
}

function savePlayerRecords() {
  dbSet(DB_KEYS.PLAYER_RECORDS, playerRecords);
}

function recordPlayerData(player) {
  if (!player || !player.xuid || !player.realName) {
    return;
  }
  
  const xuid = player.xuid;
  const name = player.realName;
  const now = Date.now();
  
  if (!playerRecords[xuid]) {
    playerRecords[xuid] = {
      name: name,
      firstSeen: now,
      lastSeen: now,
      nameHistory: [name]
    };
  } else {
    const record = playerRecords[xuid];
    
    if (!record.nameHistory || !Array.isArray(record.nameHistory)) {
      record.nameHistory = [record.name || name];
    }
    
    record.lastSeen = now;
    
    if (!record.firstSeen) {
      record.firstSeen = now;
    }
    
    if (record.name !== name) {
      if (!record.nameHistory.includes(name)) {
        record.nameHistory.push(name);
      }
      record.name = name;
    }
  }
  savePlayerRecords();
}

function searchPlayersByName(keyword) {
  const results = [];
  const lowerKeyword = keyword.toLowerCase();
  
  for (const xuid in playerRecords) {
    const record = playerRecords[xuid];
    
    if (!record || !record.name) {
      continue;
    }
    
    const currentName = record.name.toLowerCase();
    
    if (currentName.includes(lowerKeyword)) {
      results.push({
        xuid: xuid,
        name: record.name,
        lastSeen: record.lastSeen || Date.now(),
        isCurrentName: true
      });
      continue;
    }
    
    if (record.nameHistory && Array.isArray(record.nameHistory)) {
      for (const historyName of record.nameHistory) {
        if (historyName && historyName.toLowerCase().includes(lowerKeyword)) {
          results.push({
            xuid: xuid,
            name: record.name,
            historyName: historyName,
            lastSeen: record.lastSeen || Date.now(),
            isCurrentName: false
          });
          break;
        }
      }
    }
  }
  
  results.sort((a, b) => {
    if (a.isCurrentName && !b.isCurrentName) return -1;
    if (!a.isCurrentName && b.isCurrentName) return 1;
    return b.lastSeen - a.lastSeen;
  });
  
  return results.slice(0, 20);
}

function migrateWarehouseData() {
  try {
    for (const xuid in warehouseData) {
      const playerData = warehouseData[xuid];
      if (!playerData) continue;

      if (playerData.purchased === undefined) {
        playerData.purchased = !config.get('enableWarehousePurchase');
      }

      if (Array.isArray(playerData.items)) {
        const cleaned = [];
        for (const item of playerData.items) {
          if (!item) continue;

          if (item.nbt && typeof item.nbt === 'object' && !item.itemData) {
            continue;
          }
          if (!item.itemData && typeof item.nbt === 'string') {
            item.itemData = item.nbt;
            delete item.nbt;
          }

          if (item.itemData && typeof item.itemData === 'string' && item.itemData.trim().startsWith('{')) {
            cleaned.push(item);
          }
        }
        playerData.items = cleaned;
      }
    }
    saveWarehouseData();
  } catch (e) {
    log(`仓库数据迁移失败: ${e.message}`);
  }
}

migrateWarehouseData();

let purchaseLogs = dbGet(DB_KEYS.PURCHASE_LOGS, { global: [], players: {} });
let chatMessages = dbGet(DB_KEYS.CHAT_MESSAGES, []);
let mentionData = dbGet(DB_KEYS.MENTION_DATA, {});
let purchaseRequests = dbGet(DB_KEYS.PURCHASE_REQUESTS, { requests: [], history: [] });
let itemsData = dbGet(DB_KEYS.ITEMS_DATA, { items: [] });
let priceHistory = dbGet(DB_KEYS.PRICE_HISTORY, {});
let taxRecords = dbGet(DB_KEYS.TAX_RECORDS, { totalCollected: 0, playerRecords: {}, dailyRecords: {} });
let dynamicRecycleData = dbGet(DB_KEYS.DYNAMIC_RECYCLE, { itemPrices: {}, recycleHistory: {}, lastUpdate: {} });
let recycleLimitsData = dbGet(DB_KEYS.RECYCLE_LIMITS, { globalLimits: {}, playerLimits: {}, globalUsage: {}, playerUsage: {}, lastReset: Date.now() });

let dynamicPriceRecoveryTimer = null;

function stopDynamicPriceRecoveryTimer() {
  if (dynamicPriceRecoveryTimer) {
    clearInterval(dynamicPriceRecoveryTimer);
    dynamicPriceRecoveryTimer = null;
  }
}

function startDynamicPriceRecoveryTimer() {
  const dynamicConfig = config.get('dynamicRecycle') || {};
  
  if (dynamicPriceRecoveryTimer) {
    clearInterval(dynamicPriceRecoveryTimer);
    dynamicPriceRecoveryTimer = null;
  }
  
  if (dynamicConfig.enabled) {
    const checkInterval = (dynamicConfig.checkInterval || 30) * 60 * 1000;
    
    dynamicPriceRecoveryTimer = setInterval(() => {
      scheduleDynamicPriceRecovery();
    }, checkInterval);
  }
}

function scheduleDynamicPriceRecovery() {
  const dynamicConfig = config.get('dynamicRecycle') || {};
  
  if (!dynamicConfig.enabled) {
    return;
  }
  
  const now = Date.now();
  const recoveryTime = dynamicConfig.recoveryTime * 60 * 1000;
  
  for (const itemKey in dynamicRecycleData.itemPrices) {
    const priceData = dynamicRecycleData.itemPrices[itemKey];
    const recycleHistory = dynamicRecycleData.recycleHistory[itemKey] || [];
    
    if (recycleHistory.length === 0) continue;
    
    const lastRecycleTime = Math.max(...recycleHistory);
    
    if (now - lastRecycleTime >= recoveryTime && 
        priceData.currentPrice < priceData.originalPrice) {
      
      const recoveryRate = dynamicConfig.recoveryRate / 100;
      const maxIncrease = dynamicConfig.maxPriceIncrease / 100;
      const maxPrice = Math.ceil(priceData.originalPrice * (1 + maxIncrease));
      
      const hoursSinceLastRecycle = (now - lastRecycleTime) / (1000 * 60 * 60);
      const recoveryAmount = Math.floor(hoursSinceLastRecycle * recoveryRate * priceData.originalPrice / 100);
      const newPrice = Math.min(maxPrice, priceData.currentPrice + recoveryAmount);
      
      if (newPrice > priceData.currentPrice) {
        priceData.currentPrice = newPrice;
        dynamicRecycleData.lastUpdate[itemKey] = now;
      }
    }
  }
  
  saveDynamicRecycleData();
}

function savePurchaseRequests() {
  dbSet(DB_KEYS.PURCHASE_REQUESTS, purchaseRequests);
}

function saveChatData() {
  const limit = config.get('chatHistoryLimit') || 30;
  chatMessages = chatMessages.slice(-limit);
  dbSet(DB_KEYS.CHAT_MESSAGES, chatMessages);
}

function saveMentionData() {
  dbSet(DB_KEYS.MENTION_DATA, mentionData);
}

function savePriceHistory() {
  dbSet(DB_KEYS.PRICE_HISTORY, priceHistory);
}

function saveTaxRecords() {
  dbSet(DB_KEYS.TAX_RECORDS, taxRecords);
}

function saveDynamicRecycleData() {
  dbSet(DB_KEYS.DYNAMIC_RECYCLE, dynamicRecycleData);
}

function saveRecycleLimitsData() {
  dbSet(DB_KEYS.RECYCLE_LIMITS, recycleLimitsData);
}

function saveWarehouseData() {
  dbSet(DB_KEYS.WAREHOUSE, warehouseData);
}

function isItemAlreadyInOfficialPurchase(itemNbt) {
  return officialShopData.purchaseItems.hasOwnProperty(itemNbt);
}

function isItemAlreadyInOfficialRecycle(itemNbt) {
  return officialShopData.recycleItems.hasOwnProperty(itemNbt);
}

function hasWarehouseAccess(playerXuid) {
  const mode = config.get('warehouseMode') || 0;
  
  if (mode === 0) {
    return true;
  }
  
  if (mode === 1) {
    if (!warehouseData[playerXuid] || !warehouseData[playerXuid].purchased) {
      return false;
    }
    return true;
  }
  
  if (mode === 2) {
    if (!warehouseData[playerXuid] || !warehouseData[playerXuid].expireTime) {
      return false;
    }
    return Date.now() < warehouseData[playerXuid].expireTime;
  }
  
  return false;
}

function getRemainingTime(playerXuid) {
  const mode = config.get('warehouseMode') || 0;
  
  if (mode !== 2 || !warehouseData[playerXuid] || !warehouseData[playerXuid].expireTime) {
    return null;
  }
  
  const remaining = warehouseData[playerXuid].expireTime - Date.now();
  return remaining > 0 ? remaining : 0;
}

function formatTime(milliseconds) {
  const minutes = Math.floor(milliseconds / 60000);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  
  if (days > 0) {
    return `${days}天${hours % 24}小时${minutes % 60}分钟`;
  } else if (hours > 0) {
    return `${hours}小时${minutes % 60}分钟`;
  } else {
    return `${minutes}分钟`;
  }
}

function showWarehousePurchaseMenu(player) {
  const mode = config.get('warehouseMode') || 0;
  const form = mc.newSimpleForm();
  
  if (mode === 1) {
    const buyoutPrice = config.get('warehouseBuyoutPrice') || 10000;
    form.setTitle('§3§l购买仓库');
    form.setContent(`§e仓库一次性购买价格：§a${buyoutPrice} ${getEconomyInterface().name}\n\n§a购买后可永久使用仓库功能！`);
    
    form.addButton('§a立即购买', 'textures/ui/MCoin');
    form.addButton('§c返回', 'textures/ui/cancel');
    
    player.sendForm(form, (pl, id) => {
      if (id === null || id === 1) {
        showMainMenu(pl);
        return;
      }
      
      if (id === 0) {
        confirmWarehousePurchase(pl);
      }
    });
  } else if (mode === 2) {
    const rentalPrice = config.get('warehouseRentalPrice') || 1;
    const rentalMinutes = config.get('warehouseRentalMinutes') || 1440;
    const minRental = config.get('warehouseMinRentalTime') || 60;
    
    form.setTitle('§3§l租用仓库');
    form.setContent(`§e仓库租赁价格：§a${rentalPrice} ${getEconomyInterface().name}/分钟\n§e每${rentalMinutes}分钟为一个计费周期\n§e最低租用时间：§a${minRental}分钟\n\n§f输入要租用的时间（分钟）：`);
    
    const customForm = mc.newCustomForm();
    customForm.setTitle('§3§l租用仓库');
    customForm.addLabel(`§e仓库租赁价格：§a${rentalPrice} ${getEconomyInterface().name}/分钟\n§e最低租用时间：§a${minRental}分钟`);
    customForm.addInput('§e租用时间（分钟）：', `最少${minRental}分钟`, minRental.toString());
    
    player.sendForm(customForm, (pl, data) => {
      if (!data) {
        showMainMenu(pl);
        return;
      }
      
      const minutes = parseInt(data[1]);
      if (isNaN(minutes) || minutes < minRental) {
        pl.tell(`§c租用时间不能少于${minRental}分钟！`);
        showWarehousePurchaseMenu(pl);
        return;
      }
      
      confirmWarehouseRental(pl, minutes);
    });
  }
}

function confirmWarehousePurchase(player) {
  const buyoutPrice = config.get('warehouseBuyoutPrice') || 10000;
  const playerMoney = getEconomyInterface().getMoney(player);
  
  if (playerMoney < buyoutPrice) {
    player.tell(`§c您的${getEconomyInterface().name}不足！需要：${buyoutPrice}，当前：${playerMoney}`);
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle('§a§l确认购买');
  form.setContent(`§e确认花费 §c${buyoutPrice} ${getEconomyInterface().name} §e购买仓库？\n\n§a购买后可永久使用仓库功能！`);
  
  form.addButton('§a确认购买', 'textures/ui/check');
  form.addButton('§c取消', 'textures/ui/cancel');
  
  player.sendForm(form, (pl, id) => {
    if (id === null || id === 1) {
      showWarehousePurchaseMenu(pl);
      return;
    }
    
    if (id === 0) {
      const currentMoney = getEconomyInterface().getMoney(pl);
      if (currentMoney < buyoutPrice) {
        pl.tell(`§c您的${getEconomyInterface().name}不足！`);
        return;
      }
      
      getEconomyInterface().reduceMoney(pl, buyoutPrice);
      
      if (!warehouseData[pl.xuid]) {
        warehouseData[pl.xuid] = {
          playerName: pl.realName,
          items: []
        };
      }
      
      warehouseData[pl.xuid].purchased = true;
      warehouseData[pl.xuid].purchaseTime = Date.now();
      saveWarehouseData();
      
      pl.tell(`§a成功购买仓库！花费：${buyoutPrice} ${getEconomyInterface().name}`);
      pl.sendToast('§a仓库购买成功', '已永久开通仓库功能');
      showPlayerWarehouse(pl);
    }
  });
}

function confirmWarehouseRental(player, minutes) {
  const rentalPrice = config.get('warehouseRentalPrice') || 1;
  const totalCost = minutes * rentalPrice;
  const playerMoney = getEconomyInterface().getMoney(player);
  
  if (playerMoney < totalCost) {
    player.tell(`§c您的${getEconomyInterface().name}不足！需要：${totalCost}，当前：${playerMoney}`);
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle('§a§l确认租用');
  form.setContent(`§e确认花费 §c${totalCost} ${getEconomyInterface().name} §e租用仓库？\n\n§e租用时间：§a${minutes}分钟\n§e到期时间：§a${new Date(Date.now() + minutes * 60000).toLocaleString()}`);
  
  form.addButton('§a确认租用', 'textures/ui/check');
  form.addButton('§c取消', 'textures/ui/cancel');
  
  player.sendForm(form, (pl, id) => {
    if (id === null || id === 1) {
      showWarehousePurchaseMenu(pl);
      return;
    }
    
    if (id === 0) {
      const currentMoney = getEconomyInterface().getMoney(pl);
      if (currentMoney < totalCost) {
        pl.tell(`§c您的${getEconomyInterface().name}不足！`);
        return;
      }
      
      getEconomyInterface().reduceMoney(pl, totalCost);
      
      if (!warehouseData[pl.xuid]) {
        warehouseData[pl.xuid] = {
          playerName: pl.realName,
          items: []
        };
      }
      
      const currentTime = Date.now();
      const existingTime = warehouseData[pl.xuid].expireTime || currentTime;
      const newExpireTime = Math.max(existingTime, currentTime) + (minutes * 60000);
      
      warehouseData[pl.xuid].expireTime = newExpireTime;
      warehouseData[pl.xuid].lastRentalTime = currentTime;
      saveWarehouseData();
      
      pl.tell(`§a成功租用仓库！花费：${totalCost} ${getEconomyInterface().name}`);
      pl.tell(`§e到期时间：${new Date(newExpireTime).toLocaleString()}`);
      pl.sendToast('§a仓库租用成功', `使用时长：${minutes}分钟`);
      showPlayerWarehouse(pl);
    }
  });
}

function getLatestChatMessage() {
  if (chatMessages.length === 0) {
    return "暂无消息";
  }
  const latestMsg = chatMessages[chatMessages.length - 1];
  let content = latestMsg.content;
  
  content = content.replace(/§[0-9a-fk-or]/g, '');
  content = content.replace(/[\n\r]/g, ' ');
  if (content.length > 25) {
    content = content.substring(0, 22) + "...";
  }
  
  return content || "暂无消息";
}

function recordPriceHistory(itemKey, shopXuid, price, isOfficial = false) {
  if (!config.get('enablePriceHistory')) return;
  
  const now = Date.now();
  const historyKey = isOfficial ? `official_${itemKey}` : `${shopXuid}_${itemKey}`;
  
  if (!priceHistory[historyKey]) {
    priceHistory[historyKey] = {
      records: [],
      currentPrice: price,
      minPrice: price,
      maxPrice: price,
      avgPrice: price
    };
  }
  
  priceHistory[historyKey].records.push({
    price: price,
    timestamp: now
  });
  
  priceHistory[historyKey].currentPrice = price;
  
  const maxRecords = config.get('priceHistoryMaxRecords') || 1000;
  if (priceHistory[historyKey].records.length > maxRecords) {
    priceHistory[historyKey].records.shift();
  }
  
  const cutoffTime = now - (config.get('priceHistoryDays') * 24 * 60 * 60 * 1000);
  priceHistory[historyKey].records = priceHistory[historyKey].records.filter(r => r.timestamp > cutoffTime);
  
  const prices = priceHistory[historyKey].records.map(r => r.price);
  priceHistory[historyKey].minPrice = Math.min(...prices);
  priceHistory[historyKey].maxPrice = Math.max(...prices);
  priceHistory[historyKey].avgPrice = Math.round(prices.reduce((a, b) => a + b, 0) / prices.length);
  
  savePriceHistory();
}

function recordTaxCollection(buyerXuid, amount, itemName) {
  if (!config.get('enableTaxSystem')) return;
  
  const date = new Date().toLocaleDateString();
  
  taxRecords.totalCollected += amount;
  
  if (!taxRecords.playerRecords[buyerXuid]) {
    taxRecords.playerRecords[buyerXuid] = {
      totalPaid: 0,
      transactions: []
    };
  }
  
  taxRecords.playerRecords[buyerXuid].totalPaid += amount;
  taxRecords.playerRecords[buyerXuid].transactions.push({
    amount: amount,
    itemName: itemName,
    timestamp: Date.now()
  });
  
  if (!taxRecords.dailyRecords[date]) {
    taxRecords.dailyRecords[date] = {
      total: 0,
      count: 0
    };
  }
  
  taxRecords.dailyRecords[date].total += amount;
  taxRecords.dailyRecords[date].count++;
  
  saveTaxRecords();
}


/**
 * 根据指定mode，对给定的店铺数组进行排序。
 * @param {Array} shopList - 店铺列表
 * @param {String} mode - 排序模式
 * @param {Object} ranking 用于拿销量
 * @return {Array} 排好序的新数组
 */
function sortShopsByMode(shopList, mode, ranking) {
  let arr = [...shopList];

  if (mode === "随机") {
    for (let i = arr.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
  }

  arr.sort((a, b) => {
    let axuid = a.ownerXuid, bxuid = b.ownerXuid;
    let aSales = (ranking[axuid]?.salesCount) || 0;
    let bSales = (ranking[bxuid]?.salesCount) || 0;
    let aQty = Object.keys(a.items||{}).length; 
    let bQty = Object.keys(b.items||{}).length;

    if (mode === "销量") {
      return bSales - aSales;
    } else if (mode === "在售") {
      return bQty - aQty;
    } else if (mode === "销量+在售") {
      let aSum = aSales + aQty;
      let bSum = bSales + bQty;
      return bSum - aSum;
    }
    return 0;
  });
  return arr;
}

function savePurchaseLogs() {
  dbSet(DB_KEYS.PURCHASE_LOGS, purchaseLogs);
}

let shopsData = dbGet(DB_KEYS.SHOPS, {});
let officialShopData = dbGet(DB_KEYS.OFFICIAL_SHOP, { purchaseItems: {}, recycleItems: {} });

function getItemFriendlyName(itemName, itemType) {
  if (itemName && typeof itemName === 'string' && itemName.trim() !== '') {
    return itemName;
  }
  
  if (itemsData && itemsData.items) {
    const normalizedType = itemType.includes(':') ? itemType : 'minecraft:' + itemType;
    const foundItem = itemsData.items.find(i => 
      i.typeName === normalizedType || 
      i.typeName === itemType
    );
    
    if (foundItem && foundItem.name) {
      return foundItem.name;
    }
  }
  
  const typeParts = itemType.split(':');
  let baseName = typeParts.length > 1 ? typeParts[1] : itemType;
  
  baseName = baseName.split('_')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
    .join(' ');
  
  return baseName;
}

function createSNBTString(itemType, aux, displayName) {
  let minecraftNamespace = '';
  
  if (itemType.includes(':')) {
    minecraftNamespace = itemType;
  } else {
    minecraftNamespace = 'minecraft:' + itemType;
  }
  
  let nbtString = '';
  if (displayName && displayName !== getItemFriendlyName(null, itemType)) {
    nbtString = `{Count:1b,Name:"${minecraftNamespace}",Damage:${aux}s,WasPickedUp:0b,tag:{display:{Name:"${displayName}"}}}`;
  } else {
    nbtString = `{Count:1b,Name:"${minecraftNamespace}",Damage:${aux}s,WasPickedUp:0b}`;
  }
  
  return nbtString;
}
function migrateShopDataFormat() {
  const shopDataPath = path + 'shopdata.json';
  if (File.exists(shopDataPath)) {
    try {
      const shopData = JSON.parse(File.readFrom(shopDataPath));
      
      let importedPurchaseCount = 0;
      let importedRecycleCount = 0;
      
      if (shopData.Buy && Array.isArray(shopData.Buy)) {
        importedPurchaseCount = processItems(shopData.Buy, false);
      }
      
      if (shopData.Sell && Array.isArray(shopData.Sell)) {
        importedRecycleCount = processItems(shopData.Sell, true);
      }
      
      saveOfficialShopData();
      
      if (importedPurchaseCount > 0 || importedRecycleCount > 0) {
        File.delete(shopDataPath);
      } else {
      }
    } catch (e) {
    }
  }
  
  function processItems(items, isRecycle) {
    let count = 0;
    
    for (const item of items) {
      if (item.type === 'group' && Array.isArray(item.data)) {
        count += processItems(item.data, isRecycle);
      } else if (item.type === 'exam' && item.data) {
        try {
          const itemData = item.data;
          const itemType = itemData.type;
          const itemAux = itemData.aux || 0;
          const money = itemData.money || 0;
          
          if (!itemType) {
            continue;
          }
          
          const displayName = getItemFriendlyName(item.name, itemType);
          
          const nbtString = createSNBTString(itemType, itemAux, displayName);
          
          if (isRecycle) {
            officialShopData.recycleItems[nbtString] = {
              itemData: nbtString,
              name: displayName,
              displayName: displayName,
              price: money,
              remark: itemData.remark !== '<Null>' ? itemData.remark : ''
            };
            count++;
          } else {
            officialShopData.purchaseItems[nbtString] = {
              itemData: nbtString,
              name: displayName,
              displayName: displayName,
              price: money,
              quantity: -1,
              remark: itemData.remark !== '<Null>' ? itemData.remark : '',
              category: "全部"
            };
            count++;
          }
        } catch (processErr) {
        }
      }
    }
    
    return count;
  }
  
  function getItemFriendlyName(itemName, itemType) {
    if (itemName && typeof itemName === 'string' && itemName.trim() !== '') {
      return itemName;
    }
    
    if (itemsData && itemsData.items) {
      const normalizedType = itemType.includes(':') ? itemType : 'minecraft:' + itemType;
      const foundItem = itemsData.items.find(i => 
        i.typeName === normalizedType || 
        i.typeName === itemType
      );
      
      if (foundItem && foundItem.name) {
        return foundItem.name;
      }
    }
    
    const typeParts = itemType.split(':');
    let baseName = typeParts.length > 1 ? typeParts[1] : itemType;
    
    baseName = baseName.split('_')
      .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
      .join(' ');
    
    return baseName;
  }
  
  function createSNBTString(itemType, aux, displayName) {
    let minecraftNamespace = '';
    
    if (itemType.includes(':')) {
      minecraftNamespace = itemType;
    } else {
      minecraftNamespace = 'minecraft:' + itemType;
    }
    
    let nbtString = '';
    if (displayName && displayName !== getItemFriendlyName(null, itemType)) {
      nbtString = `{Count:1b,Name:"${minecraftNamespace}",Damage:${aux}s,WasPickedUp:0b,tag:{display:{Name:"${displayName}"}}}`;
    } else {
      nbtString = `{Count:1b,Name:"${minecraftNamespace}",Damage:${aux}s,WasPickedUp:0b}`;
    }
    
    return nbtString;
  }
}

migrateShopDataFormat();

let forbiddenItems = dbGet(DB_KEYS.FORBIDDEN_ITEMS, []);
let rankingData = dbGet(DB_KEYS.RANKING, {});
let officialPurchaseAllKeys = [];

function saveShopsData() {
  dbSet(DB_KEYS.SHOPS, shopsData);
}
function saveOfficialShopData() {
  dbSet(DB_KEYS.OFFICIAL_SHOP, officialShopData);
}
function saveForbiddenItems() {
  dbSet(DB_KEYS.FORBIDDEN_ITEMS, forbiddenItems);
}
function saveRankingData() {
  dbSet(DB_KEYS.RANKING, rankingData);
}

function getItemNameFromType(item) {
  try {
    if (!item || (item.isNull && item.isNull())) {
      return '空物品';
    }
    
    if (typeof item.name === 'string' && item.name.trim() !== '') {
      return item.name;
    }
    
    if (typeof item.displayName === 'string' && item.displayName.trim() !== '') {
      return item.displayName;
    }
    
    if (typeof item.type === 'string' && item.type.trim() !== '') {
      const typeName = item.type.replace('minecraft:', '').replace(/_/g, ' ');
      return typeName === 'air' ? '空物品' : typeName;
    }
    
    return '未知物品';
  } catch (e) {
    return '未知物品';
  }
}

function safeCreateItem(nbtData) {
  try {
    if (!nbtData) {
      return null;
    }
    
    let nbt;
    
    if (typeof nbtData === 'string') {
      if (nbtData.startsWith('{')) {
        nbt = NBT.parseSNBT(nbtData);
      } else {
        return null;
      }
    } else if (typeof nbtData === 'object') {
      try {
        const snbtString = convertJsonToSNBT(nbtData);
        nbt = NBT.parseSNBT(snbtString);
      } catch (e) {
        return null;
      }
    } else {
      nbt = nbtData;
    }
    
    if (!nbt) {
      return null;
    }
    
    const item = mc.newItem(nbt);
    if (!item || (item.isNull && item.isNull())) {
      return null;
    }
    
    return item;
  } catch (error) {
    return null;
  }
}

function safeNewItem(typeOrNbt, count) {
  try {
    if (typeof typeOrNbt === 'string' && count !== undefined) {
      return mc.newItem(typeOrNbt, count);
    } else if (typeOrNbt) {
      let nbt = typeOrNbt;
      if (typeof typeOrNbt === 'string') {
        try {
          nbt = NBT.parseSNBT(typeOrNbt);
        } catch (e) {
          return null;
        }
      }
      if (!nbt) {
        return null;
      }
      const item = mc.newItem(nbt);
      if (!item || (item.isNull && item.isNull())) {
        return null;
      }
      return item;
    }
    return null;
  } catch (error) {
    return null;
  }
}

function safeParseAndCreateItem(itemDataString) {
  try {
    if (!itemDataString || typeof itemDataString !== 'string') {
      return null;
    }
    const nbt = NBT.parseSNBT(itemDataString);
    if (!nbt) {
      return null;
    }
    const item = mc.newItem(nbt);
    if (!item || (item.isNull && item.isNull())) {
      return null;
    }
    return item;
  } catch (error) {
    return null;
  }
}

function convertJsonToSNBT(jsonObj) {
  try {
    if (!jsonObj || typeof jsonObj !== 'object') {
      return JSON.stringify(jsonObj);
    }
    
    if (jsonObj.Name && jsonObj.Count !== undefined) {
      let snbtString = "{";
      const parts = [];
      
      if (jsonObj.Count !== undefined) {
        parts.push(`Count:${jsonObj.Count}b`);
      }
      
      if (jsonObj.Name) {
        parts.push(`Name:"${jsonObj.Name}"`);
      }
      
      if (jsonObj.Damage !== undefined) {
        parts.push(`Damage:${jsonObj.Damage}s`);
      }
      
      if (jsonObj.WasPickedUp !== undefined) {
        parts.push(`WasPickedUp:${jsonObj.WasPickedUp}b`);
      }
      
      if (jsonObj.tag && typeof jsonObj.tag === 'object') {
        parts.push(`tag:${convertObjectToSNBT(jsonObj.tag)}`);
      }
      
      snbtString += parts.join(',') + "}";
      return snbtString;
    }
    
    return convertObjectToSNBT(jsonObj);
  } catch (e) {
    log(`JSON转SNBT失败: ${e.message}`);
    return JSON.stringify(jsonObj);
  }
}

function convertObjectToSNBT(obj) {
  if (obj === null || obj === undefined) {
    return '""';
  }
  
  if (typeof obj === 'string') {
    return `"${obj}"`;
  }
  
  if (typeof obj === 'number') {
    return obj.toString();
  }
  
  if (typeof obj === 'boolean') {
    return obj ? '1b' : '0b';
  }
  
  if (Array.isArray(obj)) {
    const items = obj.map(item => convertObjectToSNBT(item));
    return `[${items.join(',')}]`;
  }
  
  if (typeof obj === 'object') {
    const parts = [];
    for (const [key, value] of Object.entries(obj)) {
      if (value !== undefined) {
        parts.push(`${key}:${convertObjectToSNBT(value)}`);
      }
    }
    return `{${parts.join(',')}}`;
  }
  
  return '""';
}

function getEnchantmentName(enchId, level) {
  const enchNames = {
    0: '保护',
    1: '火焰保护',
    2: '摔落保护',
    3: '爆炸保护',
    4: '弹射物保护',
    5: '荆棘',
    6: '水下呼吸',
    7: '深海探索者',
    8: '水下速掘',
    9: '锋利',
    10: '亡灵杀手',
    11: '节肢杀手',
    12: '击退',
    13: '火焰附加',
    14: '抢夺',
    15: '效率',
    16: '精准采集',
    17: '耐久',
    18: '时运',
    19: '力量',
    20: '冲击',
    21: '火矢',
    22: '无限',
    23: '海之眷顾',
    24: '饵钓',
    25: '冰霜行者',
    26: '经验修补',
    27: '绑定诅咒',
    28: '消失诅咒',
    29: '穿刺',
    30: '激流',
    31: '忠诚',
    32: '引雷',
    33: '多重射击',
    34: '穿透',
    35: '快速装填',
    36: '灵魂疾行',
    37: '迅捷潜行',
    38: '风暴',
    39: '密度',
    40: '突袭'
  };
  
  const romanNumerals = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'];
  const enchName = enchNames[enchId] || `未知附魔${enchId}`;
  const romanLevel = romanNumerals[level] || level.toString();
  return `${enchName} ${romanLevel}`;
}



function getItemCustomNameFromNBT(item) {
  try {
    const nbt = item.getNbt();
    if (nbt && nbt.getKeys().includes('tag')) {
      const tag = nbt.getTag('tag');
      if (tag && tag.getKeys().includes('display')) {
        const display = tag.getTag('display');
        if (display && display.getKeys().includes('Name')) {
          return display.getString('Name');
        }
      }
    }
  } catch (e) {
    return null;
  }
  return null;
}
const default_icon_path = "textures/ui/promo_gift_small_green";
let textureData = new JsonConfigFile(`./plugins/ShoppingMall/FinalTexture/config/texture_path.json`, JSON.stringify({}, null, 4));
function getTextureData(name) {
  return textureData.get(name);
}
function getTexture(name) {
  let path = getTextureData(name);
  if (path == 'null') return default_icon_path;
  if (!path) {
    if (name.includes(':')) {
      textureData.set(name, 'null');
    }
    return default_icon_path;
  }
  return path;
}

function getShopIconTexture(shop) {
  if (!shop.iconName || shop.iconName.trim() === "") {
    return 'textures/ui/store_home_icon';
  }
  return shop.iconName.startsWith("textures/") ? shop.iconName : `textures/ui/${shop.iconName}`;
}

function addReturnButton(form) {
  form.addButton('§c§l返回上一页', 'textures/ui/icon_import');
}

let ITEM_CATEGORY = config.get("itemCategories") || ["全部"];
let PAGE_SIZE = config.get("pageSizeLimit") || 30;

const shop_cmd = mc.newCommand(config.get("cmd"), config.get("cmdDescription"), PermType.Any);
shop_cmd.overload([]);
shop_cmd.setCallback((cmd, ori, out, res) => {
  if (!ori.player) return out.error(`此命令仅限玩家执行!`);
  recordPlayerData(ori.player);
  return showMainMenu(ori.player);
});
shop_cmd.setup();

const smgf_cmd = mc.newCommand("smgf", "打开官方商店", PermType.Any);
smgf_cmd.overload([]);
smgf_cmd.setCallback((cmd, ori, out, res) => {
  if (!ori.player) return out.error(`此命令仅限玩家执行!`);
  recordPlayerData(ori.player);
  return showOfficialShopMenu(ori.player, 1, "");
});
smgf_cmd.setup();

const smdp_cmd = mc.newCommand("smdp", "打开我的店铺", PermType.Any);
smdp_cmd.overload([]);
smdp_cmd.setCallback((cmd, ori, out, res) => {
  if (!ori.player) return out.error(`此命令仅限玩家执行!`);
  recordPlayerData(ori.player);
  return handleMyShop(ori.player);
});
smdp_cmd.setup();

const smsc_cmd = mc.newCommand("smsc", "打开市场", PermType.Any);
smsc_cmd.overload([]);
smsc_cmd.setCallback((cmd, ori, out, res) => {
  if (!ori.player) return out.error(`此命令仅限玩家执行!`);
  recordPlayerData(ori.player);
  return showShoppingCenter(ori.player, 1, "", false);
});
smsc_cmd.setup();

const smop_cmd = mc.newCommand("smop", "打开管理市场", PermType.GameMasters);
smop_cmd.overload([]);
smop_cmd.setCallback((cmd, ori, out, res) => {
  if (!ori.player) return out.error(`此命令仅限玩家执行!`);
  if (!ori.player.isOP()) return out.error(`此命令仅限OP执行!`);
  recordPlayerData(ori.player);
  return showAdminMenu(ori.player);
});
smop_cmd.setup();

const smss_cmd = mc.newCommand("smss", "打开搜索页面", PermType.Any);
smss_cmd.overload([]);
smss_cmd.setCallback((cmd, ori, out, res) => {
  if (!ori.player) return out.error(`此命令仅限玩家执行!`);
  recordPlayerData(ori.player);
  return showGlobalSearch(ori.player, "", 1);
});
smss_cmd.setup();

const smpr_cmd = mc.newCommand("smpr", "打开求购页面", PermType.Any);
smpr_cmd.overload([]);
smpr_cmd.setCallback((cmd, ori, out, res) => {
  if (!ori.player) return out.error(`此命令仅限玩家执行!`);
  recordPlayerData(ori.player);
  return showPurchaseRequestMenu(ori.player);
});
smpr_cmd.setup();

function getEconomyInterface() {
  const system = config.get('economySystem');
  if (system === 'llmoney') {
    return {
      get: (player) => {
        if (!player || !player.xuid) return 0;
        return money.get(player.xuid);
      },
      getMoney: (player) => {
        if (!player || !player.xuid) return 0;
        return money.get(player.xuid);
      },
      reduce: (player, amount) => {
        if (!player || !player.xuid) return false;
        return money.reduce(player.xuid, amount);
      },
      reduceMoney: (player, amount) => {
        if (!player || !player.xuid) return false;
        return money.reduce(player.xuid, amount);
      },
      add: (player, amount) => {
        if (!player || !player.xuid) return false;
        return money.add(player.xuid, amount);
      },
      name: '§3§l金币§f',
    };
  } else if (system === 'scoreboard') {
    const objectiveName = config.get('scoreboardObjective');
    let objective = mc.getScoreObjective(objectiveName);
    if (!objective) {
      objective = mc.newScoreObjective(objectiveName, objectiveName);
    }
    return {
      get: (player) => {
        let score = player.getScore(objectiveName);
        if (typeof score !== 'number' || isNaN(score)) {
          player.setScore(objectiveName, 0);
          return 0;
        }
        return score;
      },
      getMoney: (player) => {
        let score = player.getScore(objectiveName);
        if (typeof score !== 'number' || isNaN(score)) {
          player.setScore(objectiveName, 0);
          return 0;
        }
        return score;
      },
      reduce: (player, amount) => {
        let score = player.getScore(objectiveName);
        if (typeof score !== 'number' || isNaN(score)) {
          player.setScore(objectiveName, 0);
          score = 0;
        }
        if (score < amount) {
          return false;
        }
        player.setScore(objectiveName, score - amount);
        return true;
      },
      reduceMoney: (player, amount) => {
        let score = player.getScore(objectiveName);
        if (typeof score !== 'number' || isNaN(score)) {
          player.setScore(objectiveName, 0);
          score = 0;
        }
        if (score < amount) {
          return false;
        }
        player.setScore(objectiveName, score - amount);
        return true;
      },
      add: (player, amount) => {
        let score = player.getScore(objectiveName);
        if (typeof score !== 'number' || isNaN(score)) {
          player.setScore(objectiveName, amount);
        } else {
          player.setScore(objectiveName, score + amount);
        }
      },
      name: `§3§l${objectiveName}§f`,
    };
  } else {
    throw new Error('经济系统配置错误！');
  }
}

mc.listen('onServerStarted', () => {
  if (!File.exists("./resource_packs/vanilla/texts/en_US.langbackup")) {
    File.rename("./resource_packs/vanilla/texts/en_US.lang", "./resource_packs/vanilla/texts/en_US.langbackup");
    File.copy("./resource_packs/vanilla/texts/zh_CN.lang", "./resource_packs/vanilla/texts/en_US.lang");
          log("已替换为中文");
  }
  if (config.get('economySystem') === 'scoreboard') {
    const objective = config.get('scoreboardObjective');
    if (!mc.getScoreObjective(objective)) {
      mc.newScoreObjective(objective, objective);
    }
  }  
  
  migrateShopLevelData();
  
  clearPurchaseRequestLocks();
  
  checkDiscounts();
  checkExpiredPurchaseRequests();
  
  try {
    if (typeof mc.setInterval === 'function') {
      mc.setInterval(() => {
        checkDiscounts();
        checkExpiredPurchaseRequests();
        checkExpiredWarehouse();
      }, 60000); 
    } else {
      function scheduleChecks() {
        setTimeout(() => {
          checkDiscounts();
          checkExpiredPurchaseRequests();
          checkExpiredWarehouse();
          scheduleChecks(); 
        }, 60000);
      }
      scheduleChecks();
    }
  } catch (e) {
          log(`设置定时检查任务失败: ${e.message}`);
  }
});

function migrateShopLevelData() {
  let migrationNeeded = false;
  for (const xuid in shopsData) {
    const shop = shopsData[xuid];
    if (!shop.hasOwnProperty('shopLevel')) {
      shop.shopLevel = 1;
      shop.maxItemTypes = config.get('shopDefaultItemTypes');
      shop.maxTotalItems = config.get('shopDefaultTotalItems');
      migrationNeeded = true;
    }
  }
  
  if (migrationNeeded) {
    saveShopsData();
    log("已为现有店铺添加等级系统数据");
  }
}

function clearPurchaseRequestLocks() {
  let clearedCount = 0;
  purchaseRequests.requests.forEach(request => {
    if (request.locked) {
      delete request.locked;
      clearedCount++;
    }
  });
  
  if (clearedCount > 0) {
    savePurchaseRequests();
    log(`已清理 ${clearedCount} 个求购订单的锁定状态`);
  }
}

function checkExpiredPurchaseRequests() {
  const now = Date.now();
  const expiryInMs = config.get('purchaseRequestExpiry') * 3600 * 1000;
  
  const activeRequests = purchaseRequests.requests;
  const expiredRequests = [];
  
  for (let i = activeRequests.length - 1; i >= 0; i--) {
    const request = activeRequests[i];
    if (now > request.createdTime + expiryInMs) {
      const expiredRequest = activeRequests.splice(i, 1)[0];
      expiredRequest.status = "expired";
      expiredRequests.push(expiredRequest);
      
      const player = mc.getPlayer(expiredRequest.requesterXuid);
      if (player) {
        const economy = getEconomyInterface();
        economy.add(player, expiredRequest.totalAmount);
        player.tell(`§e您的求购订单 §a${expiredRequest.itemName} x${expiredRequest.quantity}§e 已过期，已退还 §a${expiredRequest.totalAmount} ${economy.name}`);
      } else {
        if (!shopsData[expiredRequest.requesterXuid]) {
          shopsData[expiredRequest.requesterXuid] = {
            name: expiredRequest.requesterName,
            owner: expiredRequest.requesterName,
            ownerXuid: expiredRequest.requesterXuid,
            pendingEarnings: 0,
            items: {}
          };
        }
        shopsData[expiredRequest.requesterXuid].pendingEarnings = 
          (shopsData[expiredRequest.requesterXuid].pendingEarnings || 0) + expiredRequest.totalAmount;
        saveShopsData();
      }
    }
  }
  
  if (expiredRequests.length > 0) {
    purchaseRequests.history = [...purchaseRequests.history, ...expiredRequests];
    savePurchaseRequests();
  }
}

function checkDiscounts() {
  const now = Date.now();
  let shopChanged = false;
  let officialChanged = false;
  
  for (const xuid in shopsData) {
    const shop = shopsData[xuid];
    for (const itemKey in shop.items) {
      const item = shop.items[itemKey];
      if (item.discount !== undefined && item.discountEndTime !== undefined) {
        if (now > item.discountEndTime) {
          if (item.originalPrice !== undefined) {
            item.price = item.originalPrice;
            delete item.originalPrice;
          }
          delete item.discount;
          delete item.discountEndTime;
          shopChanged = true;
          const player = mc.getPlayer(xuid);
          if (player) {
            const tmpItem = safeNewItem(item.itemData);
            if (!tmpItem) continue;
            const itemName = getItemDisplayName(tmpItem, false);
            player.sendToast("§e折扣结束", `${itemName} 折扣已到期，已恢复原价`);
          }
        }
      }
    }
  }
  
  for (const itemKey in officialShopData.purchaseItems) {
    const item = officialShopData.purchaseItems[itemKey];
    
    if (item.discount !== undefined && item.discountEndTime !== undefined) {
      if (now > item.discountEndTime) {
        if (item.originalPrice !== undefined) {
          item.price = item.originalPrice;
          delete item.originalPrice;
        }
        delete item.discount;
        delete item.discountEndTime;
        officialChanged = true;
      }
    }
  }
  
  if (shopChanged) {
    saveShopsData();
  }
  
  if (officialChanged) {
    saveOfficialShopData();
  }
}

function checkExpiredWarehouse() {
  const mode = config.get('warehouseMode') || 0;
  
  if (mode !== 2) return;
  
  let expiredCount = 0;
  const now = Date.now();
  
  for (const xuid in warehouseData) {
    const userData = warehouseData[xuid];
    if (userData.expireTime && now > userData.expireTime && !userData.notified) {
      userData.notified = true;
      expiredCount++;
      
      const player = mc.getPlayer(xuid);
      if (player) {
        player.tell('§c§l您的仓库已到期！请续费后继续使用。');
        player.sendToast('§c仓库到期', '请前往续费');
      }
    }
  }
  
  if (expiredCount > 0) {
    saveWarehouseData();
  }
}

mc.listen('onJoin', function(player) {
  const shop = shopsData[player.xuid];
  if (shop) {
    if (shop.pendingEarnings && shop.pendingEarnings > 0) {
      const economy = getEconomyInterface();
      economy.add(player, shop.pendingEarnings);
      player.tell(`§a§l您的店铺在您离线期间售出了物品，获得了 ${shop.pendingEarnings} ${economy.name}`);
      shop.pendingEarnings = 0;
    }
    
    if (shop.pendingItems && shop.pendingItems.length > 0) {
      let migratedCount = 0;
      
      for (const pendingItem of shop.pendingItems) {
        try {
          let itemNbt = null;
          
          if (pendingItem.itemNbt) {
            try {
              itemNbt = NBT.parseSNBT(pendingItem.itemNbt);
            } catch (e) {
              log(`解析离线物品NBT失败: ${e.message}`);
              const testItem = safeNewItem(pendingItem.itemType || pendingItem.itemName);
              if (testItem) {
                itemNbt = testItem.getNbt();
              }
            }
          } else if (pendingItem.itemType) {
          const testItem = safeNewItem(pendingItem.itemType);
            if (testItem) {
              itemNbt = testItem.getNbt();
            }
          }
          
          if (itemNbt) {
            const itemName = pendingItem.itemName || pendingItem.source || "未知物品";
            const description = `${pendingItem.source || "求购订单"} (${new Date(pendingItem.time).toLocaleString()})`;
            
            const warehouseSuccess = addItemToWarehouse(player.xuid, player.realName, itemNbt, pendingItem.amount, description, true);
            if (warehouseSuccess) {
              migratedCount++;
              player.tell(`§a物品已迁移到仓库: §b${itemName} x${pendingItem.amount}`);
            } else {
              player.tell(`§c物品迁移失败: §b${itemName} x${pendingItem.amount}，请联系管理员`);
            }
          }
        } catch (e) {
          log(`迁移离线物品到仓库失败: ${e.message}`);
        }
      }
      
      shop.pendingItems = [];
      saveShopsData();
      
      if (migratedCount > 0) {
        player.tell(`§a§l已将 ${migratedCount} 组离线物品迁移到您的仓库中，请前往仓库查看！`);
      }
    }
    
    saveShopsData();
  }
});

function getEnchantmentsInfoFromItem(item){
  let enchantmentsLength=0, enchantmentsString=[], durable="", itemName="";
  if(item && item.isNull && !item.isNull()){
    itemName = getItemNameFromType(item);
    let nbt=item.getNbt();
    let tag = nbt.getKeys().includes("tag")? nbt.getTag("tag"):null;
    
    let enchList = tag? tag.getTag("ench"):null;
    if(nbt && tag && enchList && tag.getType("ench")==NBT.Compound){
      for(const ench of JSON.parse(enchList)){
        enchantmentsLength++;
        let itemEnc=getEnchantmentName(ench.id,ench.lvl);
        enchantmentsString.push(`${itemEnc}§f`);
      }
    }
    
    let storedEnchList = tag? tag.getTag("StoredEnchantments"):null;
    if(nbt && tag && storedEnchList && tag.getType("StoredEnchantments")==NBT.Compound){
      for(const ench of JSON.parse(storedEnchList)){
        enchantmentsLength++;
        let itemEnc=getEnchantmentName(ench.id,ench.lvl);
        enchantmentsString.push(`${itemEnc}§f`);
      }
    }
    
    if(item.isDamageableItem && item.isDamaged){
      durable=`-§3(耐久:${item.maxDamage-item.damage}/${item.maxDamage})§f`;
    } else if(item.isDamageableItem && !item.isDamaged){
      durable=`-§3(满耐久)§f`;
    } else {
      durable=`§f`;
    }
  } else {
    return [0, [], "§f", "未知物品"];
  }
  return [enchantmentsLength,enchantmentsString,durable,itemName];
}

function getShulkerBoxItemCount(item){
  try {
    if (!item || item.isNull() || !item.type.endsWith("_shulker_box")) {
      return [0, []];
    }
    const nbt = item.getNbt();
    if (!nbt) return [0, []];
    const tagData = nbt.getData("tag");
    if (!tagData) return [0, []];

    let parsed;
    try {
      parsed = JSON.parse(tagData);
    } catch (e) {
      log(`潜影盒NBT解析失败: ${e.message}`);
      return [0, []];
    }

    const items = parsed.Items || [];
    return Array.isArray(items) ? [items.length, items] : [0, []];
  } catch (e) {
    log(`潜影盒物品统计失败: ${e.message}`);
    return [0, []];
  }
}

function getBundleItemCount(item){
  try {
    if (!item || item.isNull() || (!item.type.endsWith("_bundle") && item.type !== "minecraft:bundle")) {
      return [0, []];
    }
    const nbt = item.getNbt();
    if (!nbt) return [0, []];
    const tagData = nbt.getData("tag");
    if (!tagData) return [0, []];

    let parsed;
    try {
      parsed = JSON.parse(tagData);
    } catch (e) {
      log(`捆绑袋NBT解析失败: ${e.message}`);
      return [0, []];
    }

    const items = parsed.storage_item_component_content || [];
    const validItems = Array.isArray(items) ? items.filter(it => it && it.Name && it.Name !== "" && it.Count > 0) : [];
    return [validItems.length, validItems];
  } catch (e) {
    log(`捆绑袋物品统计失败: ${e.message}`);
    return [0, []];
  }
}

function getDecoratedPotInfo(item) {
  try {
    if (!item || item.isNull() || item.type !== "minecraft:decorated_pot") {
      return null;
    }
    const nbt = item.getNbt();
    if (!nbt) return null;
    
    const result = { decorations: [], storedItem: null, storedCount: 0 };
    
    const tagData = nbt.getData("tag");
    if (tagData) {
      let parsed;
      try {
        parsed = JSON.parse(tagData);
      } catch (e) {
        return result;
      }
      
      if (parsed.sherds && Array.isArray(parsed.sherds)) {
        result.decorations = parsed.sherds.map(s => {
          const name = s.replace("minecraft:", "").replace("_pottery_sherd", "").replace(/_/g, " ");
          return name === "brick" ? "砖块" : name;
        });
      }
      
      if (parsed.item && parsed.item.Name) {
        result.storedItem = parsed.item.Name.replace("minecraft:", "");
        result.storedCount = parsed.item.Count || 1;
      }
    }
    
    const blockTag = nbt.getKeys().includes("BlockEntityTag") ? nbt.getTag("BlockEntityTag") : null;
    if (blockTag) {
      try {
        const blockData = JSON.parse(blockTag);
        if (blockData.sherds && Array.isArray(blockData.sherds)) {
          result.decorations = blockData.sherds.map(s => {
            const name = s.replace("minecraft:", "").replace("_pottery_sherd", "").replace(/_/g, " ");
            return name === "brick" ? "砖块" : name;
          });
        }
        if (blockData.item && blockData.item.Name) {
          result.storedItem = blockData.item.Name.replace("minecraft:", "");
          result.storedCount = blockData.item.Count || 1;
        }
      } catch (e) {}
    }
    
    return result;
  } catch (e) {
    log(`装饰花盆NBT解析失败: ${e.message}`);
    return null;
  }
}

function getBeehiveInfo(item) {
  try {
    if (!item || item.isNull() || (item.type !== "minecraft:beehive" && item.type !== "minecraft:bee_nest")) {
      return null;
    }
    const nbt = item.getNbt();
    if (!nbt) return null;
    
    const result = { beeCount: 0, honeyLevel: 0, shouldSpawnBees: false };
    
    const blockTag = nbt.getKeys().includes("BlockEntityTag") ? nbt.getTag("BlockEntityTag") : null;
    if (blockTag) {
      try {
        const blockData = JSON.parse(blockTag);
        result.beeCount = (blockData.Occupants && Array.isArray(blockData.Occupants)) ? blockData.Occupants.length : 0;
        result.shouldSpawnBees = blockData.ShouldSpawnBees || false;
      } catch (e) {}
    }
    
    const tagData = nbt.getData("tag");
    if (tagData) {
      try {
        const parsed = JSON.parse(tagData);
        if (parsed.Occupants && Array.isArray(parsed.Occupants)) {
          result.beeCount = parsed.Occupants.length;
        }
        if (parsed.ShouldSpawnBees !== undefined) {
          result.shouldSpawnBees = parsed.ShouldSpawnBees;
        }
      } catch (e) {}
    }
    
    return result;
  } catch (e) {
    log(`蜂箱NBT解析失败: ${e.message}`);
    return null;
  }
}

function getVaultInfo(item) {
  try {
    if (!item || item.isNull() || item.type !== "minecraft:vault") {
      return null;
    }
    const nbt = item.getNbt();
    if (!nbt) return null;
    
    const result = { isOminous: false, ejecting: false };
    
    const tagData = nbt.getData("tag");
    if (tagData) {
      try {
        const parsed = JSON.parse(tagData);
        result.isOminous = parsed.ominous || false;
      } catch (e) {}
    }
    
    return result;
  } catch (e) {
    return null;
  }
}

function getPotionInfo(item) {
  if (!item || item.isNull()) {
    return null;
  }
  
  try {
    const itemName = getItemNameFromType(item);
    
    if (item.aux !== undefined) {
      const auxEffect = getPotionEffectFromAux(item.aux);
      if (auxEffect && auxEffect.name !== "无效果" && auxEffect.name !== "粗制" && auxEffect.name !== "浓稠") {
        return [auxEffect];
      }
    }
    
    const nameEffect = getPotionEffectFromName(itemName);
    if (nameEffect) {
      return [nameEffect];
    }
    
    const nbt = item.getNbt();
    if (!nbt) {
      return null;
    }
    
    const potionEffects = [];
    
    const tag = nbt.getKeys().includes("tag") ? nbt.getTag("tag") : null;
    if (tag) {
      if (tag.getKeys().includes("CustomPotionEffects")) {
        const customEffects = JSON.parse(tag.getTag("CustomPotionEffects"));
        if (Array.isArray(customEffects)) {
          for (const effect of customEffects) {
            const effectInfo = {
              id: effect.Id || 0,
              amplifier: (effect.Amplifier || 0) + 1,
              duration: effect.Duration || 0,
              name: getPotionEffectName(effect.Id || 0)
            };
            potionEffects.push(effectInfo);
          }
        }
      }
      
      if (tag.getKeys().includes("Potion")) {
        const potionType = tag.getString("Potion");
        const defaultEffect = getDefaultPotionEffect(potionType);
        if (defaultEffect) {
          potionEffects.push(defaultEffect);
        }
      }
    }
    
    if (potionEffects.length === 0) {
      return [{
        id: 0,
        amplifier: 1,
        duration: 0,
        name: "未知效果"
      }];
    }
    
    return potionEffects;
  } catch (e) {
    return null;
  }
}

function getPotionEffectName(effectId) {
  const effectNames = {
    1: "速度",
    2: "缓慢",
    3: "急迫",
    4: "挖掘疲劳",
    5: "力量",
    6: "瞬间治疗",
    7: "瞬间伤害",
    8: "跳跃提升",
    9: "反胃",
    10: "生命恢复",
    11: "神龟",
    12: "抗火",
    13: "水下呼吸",
    14: "隐身",
    15: "失明",
    16: "夜视",
    17: "饥饿",
    18: "虚弱",
    19: "中毒",
    20: "凋零",
    21: "生命提升",
    22: "伤害吸收",
    23: "饱和",
    24: "发光",
    25: "漂浮",
    26: "衰变",
    27: "虫蚀",
    28: "缓降",
    29: "潮涌能量",
    30: "海豚的恩惠",
    31: "渗透",
    32: "编织",
    33: "黑暗",
    34: "试炼之兆",
    35: "风涌",
    36: "不祥之兆",
    37: "村庄英雄",
    38: "袭击之兆"
  };
  return effectNames[effectId] || `未知效果${effectId}`;
}

function getDefaultPotionEffect(potionType) {
  const potionEffects = {
    "minecraft:swiftness": { id: 1, amplifier: 1, duration: 3600, name: "速度" },
    "minecraft:long_swiftness": { id: 1, amplifier: 1, duration: 9600, name: "速度" },
    "minecraft:strong_swiftness": { id: 1, amplifier: 2, duration: 1800, name: "速度" },
    "swiftness": { id: 1, amplifier: 1, duration: 3600, name: "速度" },
    "long_swiftness": { id: 1, amplifier: 1, duration: 9600, name: "速度" },
    "strong_swiftness": { id: 1, amplifier: 2, duration: 1800, name: "速度" },
    "minecraft:slowness": { id: 2, amplifier: 1, duration: 1800, name: "缓慢" },
    "minecraft:long_slowness": { id: 2, amplifier: 1, duration: 4800, name: "缓慢" },
    "minecraft:strong_slowness": { id: 2, amplifier: 2, duration: 400, name: "缓慢" },
    "slowness": { id: 2, amplifier: 1, duration: 1800, name: "缓慢" },
    "long_slowness": { id: 2, amplifier: 1, duration: 4800, name: "缓慢" },
    "strong_slowness": { id: 2, amplifier: 2, duration: 400, name: "缓慢" },
    "minecraft:strength": { id: 5, amplifier: 1, duration: 3600, name: "力量" },
    "minecraft:long_strength": { id: 5, amplifier: 1, duration: 9600, name: "力量" },
    "minecraft:strong_strength": { id: 5, amplifier: 2, duration: 1800, name: "力量" },
    "strength": { id: 5, amplifier: 1, duration: 3600, name: "力量" },
    "long_strength": { id: 5, amplifier: 1, duration: 9600, name: "力量" },
    "strong_strength": { id: 5, amplifier: 2, duration: 1800, name: "力量" },
    "minecraft:healing": { id: 6, amplifier: 1, duration: 1, name: "瞬间治疗" },
    "minecraft:strong_healing": { id: 6, amplifier: 2, duration: 1, name: "瞬间治疗" },
    "healing": { id: 6, amplifier: 1, duration: 1, name: "瞬间治疗" },
    "strong_healing": { id: 6, amplifier: 2, duration: 1, name: "瞬间治疗" },
    "minecraft:harming": { id: 7, amplifier: 1, duration: 1, name: "瞬间伤害" },
    "minecraft:strong_harming": { id: 7, amplifier: 2, duration: 1, name: "瞬间伤害" },
    "harming": { id: 7, amplifier: 1, duration: 1, name: "瞬间伤害" },
    "strong_harming": { id: 7, amplifier: 2, duration: 1, name: "瞬间伤害" },
    "minecraft:leaping": { id: 8, amplifier: 1, duration: 3600, name: "跳跃提升" },
    "minecraft:long_leaping": { id: 8, amplifier: 1, duration: 9600, name: "跳跃提升" },
    "minecraft:strong_leaping": { id: 8, amplifier: 2, duration: 1800, name: "跳跃提升" },
    "leaping": { id: 8, amplifier: 1, duration: 3600, name: "跳跃提升" },
    "long_leaping": { id: 8, amplifier: 1, duration: 9600, name: "跳跃提升" },
    "strong_leaping": { id: 8, amplifier: 2, duration: 1800, name: "跳跃提升" },
    "minecraft:regeneration": { id: 10, amplifier: 1, duration: 900, name: "生命恢复" },
    "minecraft:long_regeneration": { id: 10, amplifier: 1, duration: 1800, name: "生命恢复" },
    "minecraft:strong_regeneration": { id: 10, amplifier: 2, duration: 450, name: "生命恢复" },
    "regeneration": { id: 10, amplifier: 1, duration: 900, name: "生命恢复" },
    "long_regeneration": { id: 10, amplifier: 1, duration: 1800, name: "生命恢复" },
    "strong_regeneration": { id: 10, amplifier: 2, duration: 450, name: "生命恢复" },
    "minecraft:fire_resistance": { id: 12, amplifier: 1, duration: 3600, name: "防火" },
    "minecraft:long_fire_resistance": { id: 12, amplifier: 1, duration: 9600, name: "防火" },
    "fire_resistance": { id: 12, amplifier: 1, duration: 3600, name: "防火" },
    "long_fire_resistance": { id: 12, amplifier: 1, duration: 9600, name: "防火" },
    "minecraft:water_breathing": { id: 13, amplifier: 1, duration: 3600, name: "水下呼吸" },
    "minecraft:long_water_breathing": { id: 13, amplifier: 1, duration: 9600, name: "水下呼吸" },
    "water_breathing": { id: 13, amplifier: 1, duration: 3600, name: "水下呼吸" },
    "long_water_breathing": { id: 13, amplifier: 1, duration: 9600, name: "水下呼吸" },
    "minecraft:invisibility": { id: 14, amplifier: 1, duration: 3600, name: "隐身" },
    "minecraft:long_invisibility": { id: 14, amplifier: 1, duration: 9600, name: "隐身" },
    "invisibility": { id: 14, amplifier: 1, duration: 3600, name: "隐身" },
    "long_invisibility": { id: 14, amplifier: 1, duration: 9600, name: "隐身" },
    "minecraft:night_vision": { id: 16, amplifier: 1, duration: 3600, name: "夜视" },
    "minecraft:long_night_vision": { id: 16, amplifier: 1, duration: 9600, name: "夜视" },
    "night_vision": { id: 16, amplifier: 1, duration: 3600, name: "夜视" },
    "long_night_vision": { id: 16, amplifier: 1, duration: 9600, name: "夜视" },
    "minecraft:weakness": { id: 18, amplifier: 1, duration: 1800, name: "虚弱" },
    "minecraft:long_weakness": { id: 18, amplifier: 1, duration: 4800, name: "虚弱" },
    "weakness": { id: 18, amplifier: 1, duration: 1800, name: "虚弱" },
    "long_weakness": { id: 18, amplifier: 1, duration: 4800, name: "虚弱" },
    "minecraft:poison": { id: 19, amplifier: 1, duration: 900, name: "中毒" },
    "minecraft:long_poison": { id: 19, amplifier: 1, duration: 1800, name: "中毒" },
    "minecraft:strong_poison": { id: 19, amplifier: 2, duration: 450, name: "中毒" },
    "poison": { id: 19, amplifier: 1, duration: 900, name: "中毒" },
    "long_poison": { id: 19, amplifier: 1, duration: 1800, name: "中毒" },
    "strong_poison": { id: 19, amplifier: 2, duration: 450, name: "中毒" }
  };
  return potionEffects[potionType] || null;
}

function getPotionEffectFromAux(aux) {
  const auxEffects = {
    0: { id: 0, amplifier: 0, duration: 0, name: "无效果" },
    1: { id: 0, amplifier: 0, duration: 0, name: "粗制" },
    2: { id: 0, amplifier: 0, duration: 0, name: "粗制" },
    3: { id: 0, amplifier: 0, duration: 0, name: "浓稠" },
    4: { id: 0, amplifier: 0, duration: 0, name: "粗制" },
    5: { id: 16, amplifier: 1, duration: 3600, name: "夜视" },
    6: { id: 16, amplifier: 1, duration: 9600, name: "夜视" },
    7: { id: 14, amplifier: 1, duration: 3600, name: "隐身" },
    8: { id: 14, amplifier: 1, duration: 9600, name: "隐身" },
    9: { id: 8, amplifier: 1, duration: 3600, name: "跳跃提升" },
    10: { id: 8, amplifier: 1, duration: 9600, name: "跳跃提升" },
    11: { id: 8, amplifier: 2, duration: 1800, name: "跳跃提升" },
    12: { id: 12, amplifier: 1, duration: 3600, name: "抗火" },
    13: { id: 12, amplifier: 1, duration: 9600, name: "抗火" },
    14: { id: 1, amplifier: 1, duration: 3600, name: "速度" },
    15: { id: 1, amplifier: 1, duration: 9600, name: "速度" },
    16: { id: 1, amplifier: 2, duration: 1800, name: "速度" },
    17: { id: 2, amplifier: 1, duration: 1800, name: "缓慢" },
    18: { id: 2, amplifier: 1, duration: 4800, name: "缓慢" },
    19: { id: 13, amplifier: 1, duration: 3600, name: "水下呼吸" },
    20: { id: 13, amplifier: 1, duration: 9600, name: "水下呼吸" },
    21: { id: 6, amplifier: 1, duration: 1, name: "瞬间治疗" },
    22: { id: 6, amplifier: 2, duration: 1, name: "瞬间治疗" },
    23: { id: 7, amplifier: 1, duration: 1, name: "瞬间伤害" },
    24: { id: 7, amplifier: 2, duration: 1, name: "瞬间伤害" },
    25: { id: 19, amplifier: 1, duration: 900, name: "中毒" },
    26: { id: 19, amplifier: 1, duration: 1800, name: "中毒" },
    27: { id: 19, amplifier: 2, duration: 450, name: "中毒" },
    28: { id: 10, amplifier: 1, duration: 900, name: "生命恢复" },
    29: { id: 10, amplifier: 1, duration: 1800, name: "生命恢复" },
    30: { id: 10, amplifier: 2, duration: 450, name: "生命恢复" },
    31: { id: 5, amplifier: 1, duration: 3600, name: "力量" },
    32: { id: 5, amplifier: 1, duration: 9600, name: "力量" },
    33: { id: 5, amplifier: 2, duration: 1800, name: "力量" },
    34: { id: 18, amplifier: 1, duration: 1800, name: "虚弱" },
    35: { id: 18, amplifier: 1, duration: 4800, name: "虚弱" },
    36: { id: 20, amplifier: 1, duration: 800, name: "凋零" },
    37: { id: 11, amplifier: 1, duration: 400, name: "神龟" },
    38: { id: 11, amplifier: 1, duration: 800, name: "神龟" },
    39: { id: 11, amplifier: 2, duration: 400, name: "神龟" },
    40: { id: 28, amplifier: 1, duration: 1800, name: "缓降" },
    41: { id: 28, amplifier: 1, duration: 4800, name: "缓降" },
    42: { id: 2, amplifier: 4, duration: 400, name: "缓慢" },
    43: { id: 31, amplifier: 1, duration: 3600, name: "渗透" },
    44: { id: 27, amplifier: 1, duration: 3600, name: "虫蚀" },
    45: { id: 35, amplifier: 1, duration: 3600, name: "风涌" },
    46: { id: 32, amplifier: 1, duration: 3600, name: "编织" }
  };
  return auxEffects[aux] || null;
}

function formatPotionDuration(ticks) {
  const seconds = Math.floor(ticks / 20);
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  
  if (minutes > 0) {
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
  } else {
    return `0:${remainingSeconds.toString().padStart(2, '0')}`;
  }
}

function getPotionEffectFromName(itemName) {
  const nameEffects = {
    "迅捷药水": { id: 1, amplifier: 1, duration: 3600, name: "速度" },
    "速度药水": { id: 1, amplifier: 1, duration: 3600, name: "速度" },
    "延长版迅捷药水": { id: 1, amplifier: 1, duration: 9600, name: "速度" },
    "迅捷药水II": { id: 1, amplifier: 2, duration: 1800, name: "速度" },
    "缓慢药水": { id: 2, amplifier: 1, duration: 1800, name: "缓慢" },
    "延长版缓慢药水": { id: 2, amplifier: 1, duration: 4800, name: "缓慢" },
    "缓慢药水II": { id: 2, amplifier: 2, duration: 400, name: "缓慢" },
    "力量药水": { id: 5, amplifier: 1, duration: 3600, name: "力量" },
    "延长版力量药水": { id: 5, amplifier: 1, duration: 9600, name: "力量" },
    "力量药水II": { id: 5, amplifier: 2, duration: 1800, name: "力量" },
    "治疗药水": { id: 6, amplifier: 1, duration: 1, name: "瞬间治疗" },
    "治疗药水II": { id: 6, amplifier: 2, duration: 1, name: "瞬间治疗" },
    "伤害药水": { id: 7, amplifier: 1, duration: 1, name: "瞬间伤害" },
    "伤害药水II": { id: 7, amplifier: 2, duration: 1, name: "瞬间伤害" },
    "跳跃药水": { id: 8, amplifier: 1, duration: 3600, name: "跳跃提升" },
    "延长版跳跃药水": { id: 8, amplifier: 1, duration: 9600, name: "跳跃提升" },
    "跳跃药水II": { id: 8, amplifier: 2, duration: 1800, name: "跳跃提升" },
    "生命恢复药水": { id: 10, amplifier: 1, duration: 900, name: "生命恢复" },
    "延长版生命恢复药水": { id: 10, amplifier: 1, duration: 1800, name: "生命恢复" },
    "生命恢复药水II": { id: 10, amplifier: 2, duration: 450, name: "生命恢复" },
    "防火药水": { id: 12, amplifier: 1, duration: 3600, name: "防火" },
    "延长版防火药水": { id: 12, amplifier: 1, duration: 9600, name: "防火" },
    "水下呼吸药水": { id: 13, amplifier: 1, duration: 3600, name: "水下呼吸" },
    "延长版水下呼吸药水": { id: 13, amplifier: 1, duration: 9600, name: "水下呼吸" },
    "隐身药水": { id: 14, amplifier: 1, duration: 3600, name: "隐身" },
    "延长版隐身药水": { id: 14, amplifier: 1, duration: 9600, name: "隐身" },
    "夜视药水": { id: 16, amplifier: 1, duration: 3600, name: "夜视" },
    "延长版夜视药水": { id: 16, amplifier: 1, duration: 9600, name: "夜视" },
    "虚弱药水": { id: 18, amplifier: 1, duration: 1800, name: "虚弱" },
    "延长版虚弱药水": { id: 18, amplifier: 1, duration: 4800, name: "虚弱" },
    "中毒药水": { id: 19, amplifier: 1, duration: 900, name: "中毒" },
    "延长版中毒药水": { id: 19, amplifier: 1, duration: 1800, name: "中毒" },
    "中毒药水II": { id: 19, amplifier: 2, duration: 450, name: "中毒" },
    "虫蚀药水": { id: 27, amplifier: 1, duration: 1800, name: "虫蚀" },
    "渗浆药水": { id: 31, amplifier: 1, duration: 3600, name: "渗透" },
    "延长版渗浆药水": { id: 31, amplifier: 1, duration: 9600, name: "渗透" },
    "渗浆药水II": { id: 31, amplifier: 2, duration: 1800, name: "渗透" },
    "盘丝药水": { id: 32, amplifier: 1, duration: 3600, name: "编织" },
    "延长版盘丝药水": { id: 32, amplifier: 1, duration: 9600, name: "编织" },
    "盘丝药水II": { id: 32, amplifier: 2, duration: 1800, name: "编织" },
    "蓄风药水": { id: 35, amplifier: 1, duration: 3600, name: "风涌" },
    "延长版蓄风药水": { id: 35, amplifier: 1, duration: 9600, name: "风涌" },
    "蓄风药水II": { id: 35, amplifier: 2, duration: 1800, name: "风涌" },
    "迟缓药水": { id: 2, amplifier: 1, duration: 1800, name: "缓慢" },
    "神龟药水": { id: 11, amplifier: 1, duration: 3600, name: "神龟" },
    "衰变药水": { id: 26, amplifier: 1, duration: 3600, name: "衰变" },
    "再生药水": { id: 10, amplifier: 1, duration: 900, name: "生命恢复" },
    "剧毒药水": { id: 19, amplifier: 2, duration: 450, name: "中毒" },
    "水肺药水": { id: 13, amplifier: 1, duration: 3600, name: "水下呼吸" },
    "抗火药水": { id: 12, amplifier: 1, duration: 3600, name: "抗火" },
    "喷溅型虫蚀药水": { id: 27, amplifier: 1, duration: 1800, name: "虫蚀" },
    "喷溅型盘丝药水": { id: 32, amplifier: 1, duration: 3600, name: "编织" },
    "喷溅型虚弱药水": { id: 18, amplifier: 1, duration: 1800, name: "虚弱" },
    "喷溅型剧毒药水": { id: 19, amplifier: 2, duration: 450, name: "中毒" },
    "喷溅型隐身药水": { id: 14, amplifier: 1, duration: 3600, name: "隐身" },
    "喷溅型水肺药水": { id: 13, amplifier: 1, duration: 3600, name: "水下呼吸" },
    "喷溅型衰变药水": { id: 26, amplifier: 1, duration: 3600, name: "衰变" },
    "喷溅型粗制药水": { id: 19, amplifier: 1, duration: 900, name: "中毒" },
    "喷溅型迅捷药水": { id: 1, amplifier: 1, duration: 3600, name: "速度" },
    "喷溅型力量药水": { id: 5, amplifier: 1, duration: 3600, name: "力量" },
    "喷溅型治疗药水": { id: 6, amplifier: 1, duration: 1, name: "瞬间治疗" },
    "喷溅型伤害药水": { id: 7, amplifier: 1, duration: 1, name: "瞬间伤害" },
    "喷溅型中毒药水": { id: 19, amplifier: 1, duration: 900, name: "中毒" }
  };
  
  return nameEffects[itemName] || null;
}

function getItemCustomName(item) {
  try {
    const nbt = item.getNbt();
    if (nbt && nbt.getKeys().includes('tag')) {
      const tag = nbt.getTag('tag');
      if (tag && tag.getKeys().includes('display')) {
        const display = tag.getTag('display');
        if (display && display.getKeys().includes('Name')) {
          const customName = display.getString('Name');
          
          try {
            const parsed = JSON.parse(customName);
            if (parsed && typeof parsed === 'object') {
              return parsed.text || parsed.translate || customName;
            }
          } catch (e) {
            
          }
          
          return customName;
        }
      }
    }
  } catch (e) {
    log(`获取物品自定义名称失败: ${e.message}`);
  }
  return null;
}

function getItemDisplayName(item, displayDetails){
  if (!item) {
    return "未知物品";
  }
  
  const customName = getItemCustomNameFromNBT(item);
  
  const itemInfo = getEnchantmentsInfoFromItem(item);
  if(Array.isArray(itemInfo)&&itemInfo.length===4){
    const [enchLength,enchStrArr,durable,originalItemName]=itemInfo;
    const itemName = customName || originalItemName;
    const tempStr = displayDetails?"\n":"";
    let enchString=tempStr;
    for(const enc of enchStrArr){
      enchString += enc+tempStr;
    }
    if(itemName.includes("药水") || item.type === "minecraft:potion" || 
       item.type === "minecraft:splash_potion" || 
       item.type === "minecraft:lingering_potion" || 
       item.isPotionItem){
  
      if (itemName.includes("水瓶") || itemName.includes("粗制") || 
          itemName.includes("平凡") || itemName.includes("浓稠") ||
          itemName.includes("长久平凡")) {
        return `${itemName}§f`;
      }
      
      const potionInfo = getPotionInfo(item);
      if (potionInfo && potionInfo.length > 0) {
        let potionDetails = "";
        for (const effect of potionInfo) {
          const roman = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'];
          const amplifierStr = effect.amplifier >= 1 ? ` ${roman[effect.amplifier] || effect.amplifier}` : '';
          const durationStr = effect.duration > 1 ? ` (${formatPotionDuration(effect.duration)})` : '';
          potionDetails += `§a${effect.name}${amplifierStr}${durationStr}§f `;
        }
        return `${itemName}§f - ${potionDetails.trim()}`;
      } else {
        return `${itemName}§f`;
      }
    } else if(item.type.endsWith("_shulker_box")){
      let [cnt, boxItems] = getShulkerBoxItemCount(item);
      if(displayDetails && cnt>0){
        let detail="\n";
        for(const it of boxItems){
          let tmp=safeCreateItem(it);
          if (tmp) {
            detail+=`-${getItemDisplayName(tmp,displayDetails)} * ${it.Count}\n`;
          }
        }
        return `${itemName}§f- (${detail.trimEnd()})`;
      }else{
        return `${itemName}§f- (${cnt<=0?'空盒':cnt+'项物品'})`;
      }
    } else if(item.type.endsWith("_bundle")||item.type==="minecraft:bundle"){
      let [cnt, bundleItems] = getBundleItemCount(item);
      if(displayDetails && cnt>0){
        let detail="\n";
        for(const it of bundleItems){
          let tmp=safeCreateItem(it);
          if (tmp) {
            detail+=`-${getItemDisplayName(tmp,displayDetails)} * ${it.Count}\n`;
          }
        }
        return `${itemName}§f- (${detail.trimEnd()})`;
      }else{
        return `${itemName}§f- (${cnt<=0?'空袋':cnt+'项物品'})`;
      }
    } else if(item.type === "minecraft:tropical_fish_bucket"){
      try {
        const nbt = item.getNbt();
        const tag = nbt.getKeys().includes("tag") ? nbt.getTag("tag") : null;
        if(tag && tag.getKeys().includes("Variant")) {
          const variant = JSON.parse(tag.getTag("Variant"));
          const size = variant & 0xFF;
          const pattern = (variant >> 8) & 0xFF;
          const bodyColor = (variant >> 16) & 0xFF;
          const patternColor = (variant >> 24) & 0xFF;
          
          const sizeNames = {0: "小型", 1: "大型"};
          const patternNames = {0: "Kob", 1: "Sunstreak", 2: "Snooper", 3: "Dasher", 4: "Brinely", 5: "Spotty"};
          const colorNames = {
            0: "白色", 1: "橙色", 2: "品红色", 3: "淡蓝色", 4: "黄色", 5: "黄绿色",
            6: "粉红色", 7: "灰色", 8: "淡灰色", 9: "青色", 10: "紫色", 11: "蓝色",
            12: "棕色", 13: "绿色", 14: "红色", 15: "黑色"
          };
          
          const sizeStr = sizeNames[size] || "未知";
          const patternStr = patternNames[pattern] || "普通";
          const bodyColorStr = colorNames[bodyColor] || "未知色";
          const patternColorStr = colorNames[patternColor] || "未知色";
          
          return `${itemName}§f - §e${sizeStr}${patternStr} (${bodyColorStr}-${patternColorStr})§f`;
        }
      } catch(e) {
        log(`热带鱼桶NBT解析失败: ${e.message}`);
      }
      return `${itemName}§f`;
    } else if(item.type === "minecraft:axolotl_bucket"){
      try {
        const nbt = item.getNbt();
        const tag = nbt.getKeys().includes("tag") ? nbt.getTag("tag") : null;
        if(tag && tag.getKeys().includes("Variant")) {
          const variant = JSON.parse(tag.getTag("Variant"));
          const variantNames = {
            0: "粉色", 1: "棕色", 2: "金色", 3: "青色", 4: "蓝色"
          };
          const variantStr = variantNames[variant] || "未知变种";
          return `${itemName}§f - §b${variantStr}美西螈§f`;
        }
      } catch(e) {
        log(`美西螈桶NBT解析失败: ${e.message}`);
      }
      return `${itemName}§f`;
    } else if(item.type === "minecraft:beehive" || item.type === "minecraft:bee_nest"){
      const beeInfo = getBeehiveInfo(item);
      if (beeInfo) {
        if (beeInfo.beeCount > 0) {
          return `${itemName}§f - §3含有 ${beeInfo.beeCount} 只蜜蜂§f`;
        } else if (beeInfo.shouldSpawnBees) {
          return `${itemName}§f - §e可生成蜜蜂§f`;
        } else {
          return `${itemName}§f - §7空置§f`;
        }
      }
      return `${itemName}§f`;
    } else if(item.type === "minecraft:decorated_pot"){
      const potInfo = getDecoratedPotInfo(item);
      if (potInfo) {
        let info = "";
        if (potInfo.storedItem) {
          info = `§a含有: ${potInfo.storedItem} x${potInfo.storedCount}§f`;
        }
        if (potInfo.decorations.length > 0 && potInfo.decorations.some(d => d !== "砖块")) {
          const decoStr = potInfo.decorations.filter(d => d !== "砖块").join(", ");
          info += info ? ` §7[${decoStr}]§f` : `§7[${decoStr}]§f`;
        }
        return info ? `${itemName}§f - ${info}` : `${itemName}§f`;
      }
      return `${itemName}§f`;
    } else if(item.type === "minecraft:vault"){
      const vaultInfo = getVaultInfo(item);
      if (vaultInfo && vaultInfo.isOminous) {
        return `${itemName}§f - §c不祥宝库§f`;
      }
      return `${itemName}§f`;
    } else if(item.type === "minecraft:filled_map"){
      try {
        const nbt = item.getNbt();
        const tag = nbt.getKeys().includes("tag") ? nbt.getTag("tag") : null;
        if(tag) {
          const mapUuid = tag.getKeys().includes("map_uuid") ? JSON.parse(tag.getTag("map_uuid")) : null;
          const mapNameIndex = tag.getKeys().includes("map_name_index") ? JSON.parse(tag.getTag("map_name_index")) : null;
          const displayPlayers = tag.getKeys().includes("map_display_players") ? JSON.parse(tag.getTag("map_display_players")) : true;
          const mapScale = tag.getKeys().includes("map_scale") ? JSON.parse(tag.getTag("map_scale")) : 0;
          
          let mapInfo = "";
          if(mapNameIndex !== null) {
            mapInfo += `§a地图 #${mapNameIndex}§f`;
          }
          if(mapScale !== undefined) {
            const scaleNames = {0: "1:1", 1: "1:2", 2: "1:4", 3: "1:8", 4: "1:16"};
            const scaleStr = scaleNames[mapScale] || `1:${Math.pow(2, mapScale)}`;
            mapInfo += mapInfo ? ` §3(${scaleStr})§f` : `§3比例 ${scaleStr}§f`;
          }
          if(!displayPlayers) {
            mapInfo += " §c无玩家标记§f";
          }
          
          return mapInfo ? `${itemName}§f - ${mapInfo}` : `${itemName}§f`;
        }
      } catch(e) {
        log(`地图NBT解析失败: ${e.message}`);
      }
      return `${itemName}§f`;
    } else if(item.type==="minecraft:ominous_bottle"){
      const auxObj={
        0:'§a凶兆 I (100:00)§f',
        1:'§a凶兆 II (100:00)§f',
        2:'§a凶兆 III (100:00)§f',
        3:'§a凶兆 IV (100:00)§f',
        4:'§a凶兆 V (100:00)§f'
      };
      return `${itemName} §f${auxObj[item.aux]}`;
    } else {
      const ench=(displayDetails&&enchLength>0)
        ?enchString.trimEnd()
        :(enchLength===0?"§f":`-§c(${enchLength}§d附魔)${enchString.trimEnd()}§f`);
      return `${itemName}§f${durable}§f${ench}`;
    }
  } else return `该物品信息获取失败!`;
}

function isSameItemIgnoringCount(nbtA, nbtB){
  try {
    let na, nb;
    if (typeof nbtA === 'string') {
      na = NBT.parseSNBT(nbtA);
    } else {
      try {
        na = NBT.parseSNBT(nbtA.toSNBT());
      } catch(e) {
        log(`NBT转换SNBT失败(A): ${e.message}`);
        return false;
      }
    }
    if (typeof nbtB === 'string') {
      nb = NBT.parseSNBT(nbtB);
    } else {
      try {
        nb = NBT.parseSNBT(nbtB.toSNBT());
      } catch(e) {
        log(`NBT转换SNBT失败(B): ${e.message}`);
        return false;
      }
    }
    na.setByte('Count', 1);
    nb.setByte('Count', 1);
    const itemA = safeNewItem(na);
    const itemB = safeNewItem(nb);
    if (!itemA || !itemB) {
      return false;
    }
    if(itemA.type.endsWith("_shulker_box") && itemB.type.endsWith("_shulker_box")) {
      if(itemA.type !== itemB.type) return false;
      const tagA = na.getData("tag");
      const tagB = nb.getData("tag");
      if(!tagA && !tagB) return true;
      if(!tagA || !tagB) return false;
      
      const parsedTagA = JSON.parse(tagA);
      const parsedTagB = JSON.parse(tagB);
      
      const itemsA = parsedTagA.Items || [];
      const itemsB = parsedTagB.Items || [];
      if(itemsA.length !== itemsB.length) return false;
      const sortedItemsA = JSON.stringify(itemsA.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))));
      const sortedItemsB = JSON.stringify(itemsB.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))));
      
      return sortedItemsA === sortedItemsB;
    }
    
    if((itemA.type.endsWith("_bundle")||itemA.type==="minecraft:bundle") && 
       (itemB.type.endsWith("_bundle")||itemB.type==="minecraft:bundle")) {
      if(itemA.type !== itemB.type) return false;
      const tagA = na.getData("tag");
      const tagB = nb.getData("tag");
      if(!tagA && !tagB) return true;
      if(!tagA || !tagB) return false;
      
      const parsedTagA = JSON.parse(tagA);
      const parsedTagB = JSON.parse(tagB);
      
      const itemsA = (parsedTagA.storage_item_component_content || []).filter(item=>item.Name&&item.Name!=""&&item.Count>0);
      const itemsB = (parsedTagB.storage_item_component_content || []).filter(item=>item.Name&&item.Name!=""&&item.Count>0);
      if(itemsA.length !== itemsB.length) return false;
      
      const normalizeItem = (item) => {
        const normalized = {...item};
        if (normalized.Slot !== undefined) delete normalized.Slot;
        return normalized;
      };
      
      const normalizedItemsA = itemsA.map(normalizeItem).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
      const normalizedItemsB = itemsB.map(normalizeItem).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
      
      return JSON.stringify(normalizedItemsA) === JSON.stringify(normalizedItemsB);
    }
    
    if(na.getData("Block") && nb.getData("Block")) {
      try {
        let blockA = JSON.parse(na.getData("Block"));
        let blockB = JSON.parse(nb.getData("Block"));
        
        if(blockA.version !== undefined) delete blockA.version;
        if(blockB.version !== undefined) delete blockB.version;
        
        na.setTag("Block", NBT.parseSNBT(JSON.stringify(blockA)));
        nb.setTag("Block", NBT.parseSNBT(JSON.stringify(blockB)));
      } catch(e) {
        log(`处理Block标签时出错: ${e.message}`);
      }
    }
    const fieldsToRemove = ["WasPickedUp", "Damage", "RepairCost", "keepOnDeath"];
    for(const field of fieldsToRemove) {
      if(na.getKeys().includes(field)) na.removeTag(field);
      if(nb.getKeys().includes(field)) nb.removeTag(field);
    }
    

    if(itemA.type === itemB.type) {
      if(itemA.type === "minecraft:potion" ||
        itemA.type === "minecraft:splash_potion" ||
        itemA.type === "minecraft:lingering_potion" ||
        itemA.type === "minecraft:tipped_arrow") {
        return itemA.aux === itemB.aux;
      }
      
      if(itemA.type === "minecraft:enchanted_book") {
        try {
          const enchA = JSON.stringify(getEnchantmentsFromItem(itemA).sort((a,b) => JSON.stringify(a).localeCompare(JSON.stringify(b))));
          const enchB = JSON.stringify(getEnchantmentsFromItem(itemB).sort((a,b) => JSON.stringify(a).localeCompare(JSON.stringify(b))));
          return enchA === enchB;
        } catch(e) {
          log(`比较附魔书时出错: ${e.message}`);
          return false;
        }
      }
      
      if(itemA.isEnchanted && itemB.isEnchanted) {
        try {
          const enchA = getEnchantmentsFromItem(itemA);
          const enchB = getEnchantmentsFromItem(itemB);
          if(JSON.stringify(enchA) === JSON.stringify(enchB)) {
            return true;
          }
        } catch(e) {
          log(`比较附魔时出错: ${e.message}`);
        }
      }
      
      if(!itemA.isEnchanted && !itemB.isEnchanted) {
        return true;
      }
    }
    
    if(itemA.type === itemB.type && getItemDisplayName(itemA, false) === getItemDisplayName(itemB, false)) {
      return true;
    }
    
    return false;
  } catch(e) {
    log(`物品比较出错: ${e.message}`);
    try {
      let itemA, itemB;
      if (typeof nbtA === 'string') {
        itemA = safeNewItem(NBT.parseSNBT(nbtA));
      } else {
        itemA = safeNewItem(nbtA);
      }
      if (typeof nbtB === 'string') {
        itemB = safeNewItem(NBT.parseSNBT(nbtB));
      } else {
        itemB = safeNewItem(nbtB);
      }
      return itemA && itemB && itemA.type === itemB.type;
    } catch(e2) {
      log(`物品类型比较失败: ${e2.message}`);
      return false;
    }
  }
}

function isSameItemForRestock(nbtA, nbtB){
  try {
    let na, nb;
    if (typeof nbtA === 'string') {
      na = NBT.parseSNBT(nbtA);
    } else {
      try {
        na = NBT.parseSNBT(nbtA.toSNBT());
      } catch(e) {
        log(`补货NBT转换SNBT失败(A): ${e.message}`);
        return false;
      }
    }
    if (typeof nbtB === 'string') {
      nb = NBT.parseSNBT(nbtB);
    } else {
      try {
        nb = NBT.parseSNBT(nbtB.toSNBT());
      } catch(e) {
        log(`补货NBT转换SNBT失败(B): ${e.message}`);
        return false;
      }
    }
    na.setByte('Count', 1);
    nb.setByte('Count', 1);
    const itemA = safeNewItem(na);
    const itemB = safeNewItem(nb);
    if (!itemA || !itemB) {
      return false;
    }
    
    if(itemA.type !== itemB.type) {
      return false;
    }
    
    if(itemA.type.endsWith("_shulker_box") && itemB.type.endsWith("_shulker_box")) {
      const tagA = na.getData("tag");
      const tagB = nb.getData("tag");
      if(!tagA && !tagB) return true;
      if(!tagA || !tagB) return false;
      
      const parsedTagA = JSON.parse(tagA);
      const parsedTagB = JSON.parse(tagB);
      
      const itemsA = parsedTagA.Items || [];
      const itemsB = parsedTagB.Items || [];
      if(itemsA.length !== itemsB.length) return false;
      const sortedItemsA = JSON.stringify(itemsA.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))));
      const sortedItemsB = JSON.stringify(itemsB.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))));
      
      return sortedItemsA === sortedItemsB;
    }
    
    if((itemA.type.endsWith("_bundle")||itemA.type==="minecraft:bundle") && 
       (itemB.type.endsWith("_bundle")||itemB.type==="minecraft:bundle")) {
      const tagA = na.getData("tag");
      const tagB = nb.getData("tag");
      if(!tagA && !tagB) return true;
      if(!tagA || !tagB) return false;
      
      const parsedTagA = JSON.parse(tagA);
      const parsedTagB = JSON.parse(tagB);
      
      const itemsA = (parsedTagA.storage_item_component_content || []).filter(item=>item.Name&&item.Name!=""&&item.Count>0);
      const itemsB = (parsedTagB.storage_item_component_content || []).filter(item=>item.Name&&item.Name!=""&&item.Count>0);
      if(itemsA.length !== itemsB.length) return false;
      
      const normalizeItem = (item) => {
        const normalized = {...item};
        if (normalized.Slot !== undefined) delete normalized.Slot;
        return normalized;
      };
      
      const normalizedItemsA = itemsA.map(normalizeItem).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
      const normalizedItemsB = itemsB.map(normalizeItem).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
      
      return JSON.stringify(normalizedItemsA) === JSON.stringify(normalizedItemsB);
    }
    
    if(na.getData("Block") && nb.getData("Block")) {
      try {
        let blockA = JSON.parse(na.getData("Block"));
        let blockB = JSON.parse(nb.getData("Block"));
        
        const blockIgnoreFields = ["version", "data_version"];
        blockIgnoreFields.forEach(field => {
          if(blockA[field] !== undefined) delete blockA[field];
          if(blockB[field] !== undefined) delete blockB[field];
        });
        
        na.setTag("Block", NBT.parseSNBT(JSON.stringify(blockA)));
        nb.setTag("Block", NBT.parseSNBT(JSON.stringify(blockB)));
      } catch(e) {
        log(`处理Block标签时出错: ${e.message}`);
      }
    }
    
    const fieldsToRemove = [
      "WasPickedUp", "RepairCost", "keepOnDeath", 
      "PickupDelay", "Age", "FireTime", "FallTime",
      "Item", "ItemDropChance", "ItemRotation", "PushReaction",
      "UpdateBit", "TicksUntilDrop", "Owner", "Thrower",
      "variant", "data_version", "format_version"
    ];
    
    for(const field of fieldsToRemove) {
      if(na.getKeys().includes(field)) na.removeTag(field);
      if(nb.getKeys().includes(field)) nb.removeTag(field);
    }
    
    if(itemA.type === "minecraft:potion" ||
      itemA.type === "minecraft:splash_potion" ||
      itemA.type === "minecraft:lingering_potion" ||
      itemA.type === "minecraft:tipped_arrow") {
      return itemA.aux === itemB.aux;
    }
    
    if(itemA.type === "minecraft:enchanted_book") {
      try {
        const enchA = JSON.stringify(getEnchantmentsFromItem(itemA).sort((a,b) => JSON.stringify(a).localeCompare(JSON.stringify(b))));
        const enchB = JSON.stringify(getEnchantmentsFromItem(itemB).sort((a,b) => JSON.stringify(a).localeCompare(JSON.stringify(b))));
        return enchA === enchB;
      } catch(e) {
        log(`比较附魔书时出错: ${e.message}`);
        return false;
      }
    }
    
    if(itemA.isEnchanted && itemB.isEnchanted) {
      try {
        const enchA = getEnchantmentsFromItem(itemA);
        const enchB = getEnchantmentsFromItem(itemB);
        return JSON.stringify(enchA.sort((a,b) => JSON.stringify(a).localeCompare(JSON.stringify(b)))) === 
               JSON.stringify(enchB.sort((a,b) => JSON.stringify(a).localeCompare(JSON.stringify(b))));
      } catch(e) {
        log(`比较附魔时出错: ${e.message}`);
        return false;
      }
    }
    
    if(!itemA.isEnchanted && !itemB.isEnchanted) {
      if(itemA.aux !== undefined && itemB.aux !== undefined && itemA.aux !== itemB.aux) {
        return false;
      }
      
      const hasTag = na.getData("tag") || nb.getData("tag");
      if(!hasTag) {
        return true;
      }
      
      try {
        const tagA = na.getData("tag");
        const tagB = nb.getData("tag");
        
        if(!tagA && !tagB) return true;
        if(!tagA || !tagB) return false;
        
        let parsedTagA, parsedTagB;
        try {
          parsedTagA = JSON.parse(tagA);
          parsedTagB = JSON.parse(tagB);
        } catch(e) {
          return tagA === tagB;
        }
        
        const ignoreTagFields = [
          "Damage", "RepairCost", "ench", "StoredEnchantments",
          "display", "HideFlags", "Unbreakable", "CanDestroy", "CanPlaceOn"
        ];
        
        for(const field of ignoreTagFields) {
          if(parsedTagA[field] !== undefined && parsedTagB[field] !== undefined) {
            if(field === "Damage") {
              if(parsedTagA[field] !== parsedTagB[field]) {
                return false;
              }
            } else if(field === "ench" || field === "StoredEnchantments") {
              const enchAStr = JSON.stringify((parsedTagA[field] || []).sort((a,b) => JSON.stringify(a).localeCompare(JSON.stringify(b))));
              const enchBStr = JSON.stringify((parsedTagB[field] || []).sort((a,b) => JSON.stringify(a).localeCompare(JSON.stringify(b))));
              if(enchAStr !== enchBStr) {
                return false;
              }
            } else {
              if(JSON.stringify(parsedTagA[field]) !== JSON.stringify(parsedTagB[field])) {
                return false;
              }
            }
          } else if((parsedTagA[field] !== undefined) !== (parsedTagB[field] !== undefined)) {
            return false;
          }
        }
        
        return true;
      } catch(e) {
        try {
          const naStr = na.toSNBT();
          const nbStr = nb.toSNBT();
          return naStr === nbStr;
        } catch(snbtError) {
          log(`NBT转换SNBT时出现UTF-8编码错误: ${snbtError.message}`);
          return itemA.type === itemB.type && itemA.aux === itemB.aux;
        }
      }
    }
    
    return false;
  } catch(e) {
    log(`补货物品比较出错: ${e.message}`);
    return false;
  }
}

function getPlayerItemCountForRestock(player, nbtString){
  let total=0;
  const inv=player.getInventory();
  
  let searchItem;
  searchItem = safeCreateItem(nbtString);
  if (!searchItem) {
    return 0;
  }
  
  const searchNbt = NBT.parseSNBT(nbtString);
  
  for(let i=0;i<inv.size;i++){
    let it=inv.getItem(i);
    if(it&&it.type!=='' && searchItem.type === it.type){
      try {
        const itemNbt = it.getNbt();
        if(itemNbt && isSameItemForRestock(searchNbt, itemNbt)) {
          if(it.count <= 0 || it.count > 64) {
            continue;
          }
          total+=it.count;
        }
      } catch(e) {
        log(`检查物品匹配时出错: ${e.message}, 槽位: ${i}`);
      }
    }
  }
  
  if(total < 0 || total > 2304) {
    return 0;
  }
  
  return total;
}

function debugRestockItemComparison(player, shopItemNbt) {
  if (!player.isOP()) return;
  
  const inv = player.getInventory();
  const searchNbt = NBT.parseSNBT(shopItemNbt);
  const searchItem = safeCreateItem(shopItemNbt);
  if (!searchItem) return;
  
  player.tell("§6§l[调试]补货物品比较分析：");
  player.tell(`§e目标物品：${searchItem.type}`);
  player.tell(`§e目标NBT：§7${shopItemNbt}`);
  player.tell("§6背包匹配分析：");
  
  for(let i=0;i<inv.size;i++){
    const it=inv.getItem(i);
    if(it&&it.type!=='' && searchItem.type === it.type){
      const itemNbt = it.getNbt();
      const matches = isSameItemForRestock(searchNbt, itemNbt);
      let nbtStr = "";
      try {
        nbtStr = itemNbt.toSNBT();
      } catch(e) {
        nbtStr = `[UTF-8编码错误: ${e.message}]`;
      }
      
      player.tell(`§3槽位${i}：${matches ? '§a匹配' : '§c不匹配'} §f数量:${it.count}`);
      player.tell(`§7NBT: ${nbtStr.length > 100 ? nbtStr.substring(0, 100) + '...' : nbtStr}`);
    }
  }
}

function removeItemsFromPlayerForRestock(player, nbtString, count){
  let remaining = count;
  const inv = player.getInventory();
  let searchItem;
  searchItem = safeNewItem(nbtString);
  if (!searchItem) {
    log(`创建查找物品失败`);
    return false;
  }
  
  const searchNbt = NBT.parseSNBT(nbtString);
  
  const matchingItems = [];
  for(let i = 0; i < inv.size; i++) {
    const it = inv.getItem(i);
    if(it && it.type !== '') {
      try {
        if(searchItem.type === it.type) {
          const itemNbt = it.getNbt();
          if(itemNbt && isSameItemForRestock(searchNbt, itemNbt)) {
            matchingItems.push({
              slot: i,
              count: it.count
            });
          }
        }
      } catch(e) {
        log(`检查物品匹配时出错: ${e.message}, 槽位: ${i}`);
      }
    }
  }
  
  let totalAvailable = 0;
  matchingItems.forEach(m => totalAvailable += m.count);
  
  if(totalAvailable < count) {
    log(`精确匹配物品数量不足: 需要 ${count}, 实际只有 ${totalAvailable}`);
    return false;
  }
  
  const processedSlots = new Set();
  
  for(const match of matchingItems) {
    if(remaining <= 0) break;
    
    if(processedSlots.has(match.slot)) {
      continue;
    }
    
    const currentItem = inv.getItem(match.slot);
    if(!currentItem || currentItem.type === '' || currentItem.count <= 0) {
      continue;
    }
    
    const currentNbt = currentItem.getNbt();
    if(!currentNbt || !isSameItemForRestock(searchNbt, currentNbt)) {
      continue;
    }
    
    if(currentItem.count > 64 || currentItem.count !== match.count) {
      continue;
    }
    
    const removeCount = Math.min(match.count, remaining);
    if(removeCount <= 0) break;
    
    try {
      const preCount = currentItem.count;
      inv.removeItem(match.slot, removeCount);
      
      const postItem = inv.getItem(match.slot);
      const postCount = postItem ? postItem.count : 0;
      const actualRemoved = preCount - postCount;
      
      if(actualRemoved !== removeCount) {
        log(`移除数量不匹配 - 槽位: ${match.slot}, 预期: ${removeCount}, 实际: ${actualRemoved}`);
        return false;
      }
      
      remaining -= actualRemoved;
      processedSlots.add(match.slot);
    } catch(e) {
      log(`移除物品时出错: ${e.message}, 槽位: ${match.slot}, 数量: ${removeCount}`);
      return false;
    }
  }
  
  player.refreshItems();
  return remaining <= 0;
}

function getEnchantmentsFromItem(item) {
  const enchantments = [];
  if(!item.isNull() && item.isEnchanted) {
    try {
      const nbt = item.getNbt();
      const tag = nbt.getKeys().includes("tag") ? nbt.getTag("tag") : null;
      
      if(tag) {
        if(tag.getKeys().includes("ench")) {
          const enchList = JSON.parse(tag.getTag("ench"));
          if(Array.isArray(enchList)) {
            enchantments.push(...enchList);
          }
        }
        if(tag.getKeys().includes("StoredEnchantments")) {
          const storedEnch = JSON.parse(tag.getTag("StoredEnchantments"));
          if(Array.isArray(storedEnch)) {
            enchantments.push(...storedEnch);
          }
        }
      }
    } catch(e) {
      log(`读取附魔信息出错: ${e.message}`);
    }
  }
  return enchantments;
}

function removeItemsFromPlayer(player, nbtString, count){
  let remaining = count;
  const inv = player.getInventory();
  let searchItem;
  searchItem = safeNewItem(nbtString);
  if (!searchItem) {
    log(`创建查找物品失败`);
    return false;
  }
  
  const searchNbt = NBT.parseSNBT(nbtString);
  
  const matchingItems = [];
  for(let i = 0; i < inv.size; i++) {
    const it = inv.getItem(i);
    if(it && it.type !== '') {
      try {
        if(searchItem.type === it.type) {
          const itemNbt = it.getNbt();
          if(itemNbt && isSameItemIgnoringCount(searchNbt, itemNbt)) {
            matchingItems.push({
              slot: i,
              count: it.count
            });
          }
        }
      } catch(e) {
        log(`检查物品匹配时出错: ${e.message}, 槽位: ${i}`);
      }
    }
  }
  
  let totalAvailable = 0;
  matchingItems.forEach(m => totalAvailable += m.count);
  
  if(totalAvailable < count) {
    log(`精确匹配物品数量不足: 需要 ${count}, 实际只有 ${totalAvailable}`);
    return false;
  }
  
  for(const match of matchingItems) {
    if(remaining <= 0) break;
    
    const removeCount = Math.min(match.count, remaining);
    try {
      inv.removeItem(match.slot, removeCount);
      remaining -= removeCount;
    } catch(e) {
      log(`移除物品时出错: ${e.message}, 槽位: ${match.slot}, 数量: ${removeCount}`);
    }
  }
  
  player.refreshItems();
  return remaining <= 0;
}

function getPlayerInventoryItems(player, excludeForbidden = false){
  const invItems = {};
  const inv = player.getInventory().getAllItems();
  
  for(let i = 0; i < inv.length; i++) {
    const item = inv[i];
    if(item && item.type !== '') {
      try {
        let nbts;
        try {
          nbts = item.getNbt().toSNBT();
        } catch(nbtError) {
          log(`获取物品NBT字符串失败(槽位${i}): ${nbtError.message}`);
          continue;
        }
        if(excludeForbidden && forbiddenItems.includes(item.type)) continue;
        
        let foundKey = null;
        for(const existingKey in invItems) {
          try {
            const existingItem = safeNewItem(existingKey);
            if(existingItem.type === item.type) {
              foundKey = existingKey;
              break;
            }
          } catch(e) {
            continue;
          }
        }
        
        if(foundKey) {
          invItems[foundKey].count += item.count;
        } else {
          invItems[nbts] = {item, count: item.count};
        }
      } catch(e) {
        log(`处理物品NBT时出错: ${e.message}, 槽位: ${i}`);
      }
    }
  }
  
  return invItems;
}


function getPlayerInventoryItems(player, excludeForbidden=false){
  const invItems={};
  const inv = player.getInventory().getAllItems();
  for(let i=0;i<inv.length;i++){
    const item=inv[i];
    if(item && item.type!==''){
      let nbts;
      try {
        nbts = item.getNbt().toSNBT();
      } catch(e) {
        log(`获取物品NBT字符串失败(槽位${i}): ${e.message}`);
        continue;
      }
      if(excludeForbidden&&forbiddenItems.includes(item.type)) continue;
      if(!invItems[nbts]){
        invItems[nbts]={item, count:item.count};
      } else {
        invItems[nbts].count+=item.count;
      }
    }
  }
  return invItems;
}

function addSales(xuid, qty){
  if(!rankingData[xuid]){
    rankingData[xuid] = { salesCount:0, totalEarnings:0 };
  }
  rankingData[xuid].salesCount += qty;
  saveRankingData();
}

function addEarnings(xuid, val){
  if(!rankingData[xuid]){
    rankingData[xuid] = { salesCount:0, totalEarnings:0 };
  }
  rankingData[xuid].totalEarnings += val;
  saveRankingData();
}

function distributeItemsToPlayer(player, itemNbt, totalQuantity){
  if (!canPlayerReceiveItem(player, itemNbt, totalQuantity)) {
    player.tell('§c§l背包空间不足!');
    return false;
  }
  
  const testItem = safeNewItem(itemNbt);
  if (!testItem) return false;
  const maxStack = testItem.maxStackSize;
  let remain = totalQuantity;
  
  const inv = player.getInventory();
  
  for(let i = 0; i < inv.size && remain > 0; i++){
    const slotItem = inv.getItem(i);
    if(slotItem && !slotItem.isNull() && slotItem.type !== 'minecraft:air'){
      try {
        if(typeof slotItem.getNbt !== 'function'){
          continue;
        }
        const slotNbt = slotItem.getNbt();
        if(slotNbt && isSameItemIgnoringCount(itemNbt, slotNbt)){
          const canAdd = maxStack - slotItem.count;
          if(canAdd > 0){
            const addCount = Math.min(canAdd, remain);
            slotItem.setCount(slotItem.count + addCount);
            inv.setItem(i, slotItem);
            remain -= addCount;
          }
        }
      } catch(e) {
        
      }
    }
  }
  
  while(remain > 0){
    let giveCount = Math.min(remain, maxStack);
    const newNbt = NBT.parseSNBT(itemNbt.toSNBT());
    newNbt.setByte('Count', giveCount);
    let item = safeNewItem(newNbt);
    if (!item) return false;
    
    let ok = player.giveItem(item);
    if(!ok){
      player.tell('§c§l背包空间发生异常!');
      return false;
    }
    remain -= giveCount;
  }
  return true;
}

function canPlayerReceiveItem(player, itemNbt, totalQuantity){
  const inv = player.getInventory();
  const testItem = safeNewItem(itemNbt);
  if (!testItem) return false;
  const maxStack = testItem.maxStackSize;
  
  let totalAvailableSpace = 0;
  
  for(let i = 0; i < inv.size; i++){
    const slotItem = inv.getItem(i);
    if(!slotItem || slotItem.type === 'minecraft:air' || slotItem.isNull()){
      totalAvailableSpace += maxStack;
    } else if(slotItem && !slotItem.isNull() && slotItem.type !== 'minecraft:air'){
      try {
        if(typeof slotItem.getNbt === 'function'){
          const slotNbt = slotItem.getNbt();
          if(slotNbt && isSameItemIgnoringCount(itemNbt, slotNbt)){
            const canAdd = maxStack - slotItem.count;
            if(canAdd > 0){
              totalAvailableSpace += canAdd;
            }
          }
        }
      } catch(e) {
        
      }
    }
  }
  
  return totalAvailableSpace >= totalQuantity;
}


function showMainMenu(player) {
  recordPlayerData(player);
  const economy = getEconomyInterface();
  const balance = economy.get(player);
  PAGE_SIZE = config.get("pageSizeLimit") || 30;
  
  const showStatistics = config.get('showMainMenuStatistics');
  
  let content = '';
  let shopCount = 0;
  let itemCount = 0;
  let requestCount = 0;
  let officialSellCount = 0;
  let officialBuyCount = 0;
  
  requestCount = (purchaseRequests && purchaseRequests.requests) ? purchaseRequests.requests.filter(r => !r.locked).length : 0;
  for (const xuid in shopsData) {
    const shop = shopsData[xuid];
    if (shop.isOpen) {
      shopCount++;
      const shopItems = Object.keys(shop.items || {}).length;
      itemCount += shopItems;
    }
  }
  officialSellCount = Object.keys(officialShopData.purchaseItems || {}).length; 
  officialBuyCount = Object.keys(officialShopData.recycleItems || {}).length;
  
  let taxInfo = "";
  if(config.get('enableTaxSystem')){
    const taxRate = config.get('taxRate') || 0;
    const taxOnlyOfficial = config.get('taxOnlyOfficialShop');
    if(taxRate > 0){
      const taxScope = taxOnlyOfficial ? "官方商店" : "全局";
      taxInfo = ` §c(税率:${(taxRate*100).toFixed(1)}% ${taxScope})`;
    }
  }
  
  let latestTradeRecord = "暂无交易";
  let latestTradeSimple = "暂无交易";
  if (purchaseLogs && purchaseLogs.global && purchaseLogs.global.length > 0) {
    const latestTrade = purchaseLogs.global[purchaseLogs.global.length - 1];
    latestTradeRecord = `§a${latestTrade.buyerName} §f向 §a${latestTrade.sellerName} §f购买了 §b${latestTrade.itemName} x${latestTrade.quantity}`;
    if (latestTradeRecord.length > 60) {
      latestTradeRecord = latestTradeRecord.substring(0, 57) + "...";
    }
    
    latestTradeSimple = `${latestTrade.buyerName} 购买了 ${latestTrade.itemName}`;
    if (latestTradeSimple.length > 30) {
      latestTradeSimple = latestTradeSimple.substring(0, 27) + "...";
    }
  }
  
  if (showStatistics) {
    const myShop = shopsData[player.xuid];
    const myShopItemCount = myShop ? Object.keys(myShop.items || {}).length : 0;
    const myShopStatus = myShop ? (myShop.isOpen ? "§a营业中" : "§c已关闭") : "§c无店铺";
    let myTotalEarnings = 0;
    if (rankingData[player.xuid] && rankingData[player.xuid].totalEarnings) {
      myTotalEarnings = rankingData[player.xuid].totalEarnings;
    }
    
    content = `§e§l您的余额：${balance} ${economy.name}${taxInfo}\n` +
              `§3§l商城数据统计:\n` +
              `§b官方在售商品: §a${officialSellCount}§f | §b官方回收物品: §a${officialBuyCount}\n` +
              `§b玩家店铺: §a${shopCount}§f | §b在售物品: §a${itemCount}§f | §b求购订单: §a${requestCount}\n` +
              `§b我的店铺: ${myShopStatus}§f | §b店铺物品: §a${myShopItemCount}§f | §b我的交易总额: §a${myTotalEarnings} ${economy.name}\n` +
              `§d§l新交易: §f${latestTradeRecord}\n` +
              `§b§l请选择一个操作：`;
  } else {
    content = `§e§l您的余额：${balance} ${economy.name}${taxInfo}\n` +
              `§b§l请选择一个操作：`;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle('§3§l商店菜单');
  form.setContent(content);
  
  const buttonsConfig = config.get('mainMenuButtons') || {
    chatLobby: { enabled: true, order: 1 },
    globalSearch: { enabled: true, order: 2 },
    shoppingCenter: { enabled: true, order: 3 },
    myShop: { enabled: true, order: 4 },
    officialShop: { enabled: true, order: 5 },
    purchaseRequests: { enabled: true, order: 6 },
    warehouse: { enabled: true, order: 7 },
    shopRanking: { enabled: true, order: 8 },
    tradeLogs: { enabled: true, order: 9 }
  };
  
  const myShop = shopsData[player.xuid];
  const myShopItemCount = myShop ? Object.keys(myShop.items || {}).length : 0;
  const myShopStatus = myShop ? (myShop.isOpen ? "营业中" : "已关闭") : "无店铺";

  const playerRankInfo = getPlayerShopRank(player.xuid);
  let rankDisplay = "未上榜";
  if (playerRankInfo.rank > 0) {
    rankDisplay = `第${playerRankInfo.rank}名`;
  }

  const buttonDefs = {
    chatLobby: {
      title: `§a§lSM大厅\n§f最新消息:${getLatestChatMessage()}`,
      icon: 'textures/ui/mute_off.png',
      condition: config.get('enableChatLobby'),
      action: (pl) => showChatLobby(pl)
    },
    globalSearch: {
      title: `§d§l全局搜索\n§f全服: ${itemCount}个物品`,
      icon: 'textures/ui/magnifyingGlass',
      condition: true,
      action: (pl) => showGlobalSearch(pl, "", 1)
    },
    shoppingCenter: {
      title: `§a§l购物中心\n§f店铺:${shopCount} 在售:${itemCount}`,
      icon: 'textures/ui/crafting_table',
      condition: true,
      action: (pl) => showShoppingCenter(pl, 1, "", false)
    },
    myShop: {
      title: `§b§l我的店铺\n§f${myShopStatus} 物品:${myShopItemCount}`,
      icon: 'textures/ui/store_home_icon',
      condition: true,
      action: (pl) => handleMyShop(pl)
    },
    officialShop: {
      title: `§e§l官方商店\n§f出售:${officialSellCount} 回收:${officialBuyCount}`,
      icon: 'textures/ui/title',
      condition: true,
      action: (pl) => showOfficialShopDirectMenu(pl)
    },
    purchaseRequests: {
      title: `§3§l悬赏&求购\n§f当前: ${requestCount}条订单`,
      icon: 'textures/ui/MCoin',
      condition: config.get('enablePurchaseRequests'),
      action: (pl) => showPurchaseRequestMenu(pl)
    },
    warehouse: {
      title: `§3§l个人仓库\n§f存储和管理物品`,
      icon: 'textures/ui/crafting_table',
      condition: config.get('enableGiftSystem'),
      action: (pl) => showPlayerWarehouse(pl)
    },
    shopRanking: {
      title: `§d§l店铺排行榜\n§f我的排名: ${rankDisplay}`,
      icon: 'textures/ui/move',
      condition: config.get('enableShopRanking'),
      action: (pl) => showShopRanking(pl)
    },
    tradeLogs: {
      title: `§s§l交易动态信息\n§f${latestTradeSimple}`,
      icon: 'textures/ui/message',
      condition: true,
      action: (pl) => showGlobalPurchaseLogs(pl)
    }
  };
  
  const adminButton = {
    title: '§c§l管理市场',
    icon: 'textures/ui/op',
    condition: player.isOP(),
    action: (pl) => showAdminMenu(pl)
  };
  
  const buttonMapping = {};
  const sortedButtons = Object.entries(buttonsConfig)
    .filter(([key, config]) => config.enabled && buttonDefs[key] && buttonDefs[key].condition)
    .sort((a, b) => a[1].order - b[1].order);
  
  sortedButtons.forEach(([key, config], index) => {
    const buttonDef = buttonDefs[key];
    form.addButton(buttonDef.title, buttonDef.icon);
    buttonMapping[index] = key;
  });
  
  if (adminButton.condition) {
    form.addButton(adminButton.title, adminButton.icon);
    buttonMapping[Object.keys(buttonMapping).length] = 'admin';
  }
  
  const mentionInfo = mentionData[player.xuid] || { unread: false, count: 0 };
  if (mentionInfo.unread) {
    form.setContent(`${content}\n§c§l你有 ${mentionInfo.count} 条未读@消息!`);
  }
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    
    const buttonKey = buttonMapping[id];
    if (!buttonKey) return;
    
    if (buttonKey === 'admin') {
      adminButton.action(pl);
    } else {
      buttonDefs[buttonKey].action(pl);
    }
  });
}

function showGlobalPurchaseLogs(player){
  if(!purchaseLogs.global || purchaseLogs.global.length === 0){
    player.tell("§c暂无交易动态信息。");
    return;
  }
  let content = "§3最近30条全服交易动态：\n\n";
  const reversedLogs = [...purchaseLogs.global].reverse();
  reversedLogs.forEach((rec, i)=>{
    content += `§e${i+1}. §a时间:${rec.time}\n` +
               `  §b[${rec.buyerName}] §a向 §b[${rec.sellerName}] §s(店铺:${rec.shopName})\n` +
               `  §a购买 §g${rec.itemName} §a数量：§g${rec.quantity} §a单价:§g${rec.priceEach} §a总价:§g${rec.totalPrice}\n\n`;
  });

  const form = mc.newCustomForm();
  form.setTitle("§s全服交易动态");
  form.addLabel(content);
  player.sendForm(form,(pl,data)=>{
    if(data !== null) {
      showMainMenu(pl);
    }
  });
}
function showGlobalSearch(player, keyword, page) {
  const form = mc.newCustomForm();
  form.setTitle("§d全局搜索");
  form.addInput("§e输入搜索关键字:", "关键字", keyword || "");
  form.addDropdown("§e搜索类型:", ["物品", "店铺或店主"], 0); 
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    const searchKeyword = data[0]?.trim() || "";
    if (searchKeyword === "") {
      pl.tell("§c搜索关键字不能为空！");
      return;
    }
    const searchType = data[1]; 
    
    if (searchType === 0) {
      showGlobalSearchResults(pl, searchKeyword, 1);
    } else {
      showShoppingCenter(pl, 1, searchKeyword, false);
    }
  });
}

function showGlobalSearchResults(player, keyword, page) {
  if (!keyword || keyword.trim() === "") {
    player.tell("§c搜索关键字不能为空！");
    return;
  }

  let allItems = [];
  const kw = keyword.toLowerCase();
  for (const xuid in shopsData) {
    const shop = shopsData[xuid];
    if (!shop.isOpen) continue;

    for (const itemKey in shop.items) {
      const item = shop.items[itemKey];
      if (item.name.toLowerCase().includes(kw)) {
        allItems.push({
          itemKey,
          item,
          shop,
          isOfficial: false,
          price: item.price
        });
      }
    }
  }
  for (const itemKey in officialShopData.purchaseItems) {
    const item = officialShopData.purchaseItems[itemKey];
    if (item.name.toLowerCase().includes(kw) || 
        (item.displayName && item.displayName.toLowerCase().includes(kw))) {
      allItems.push({
        itemKey,
        item,
        shop: { name: "官方商店", ownerXuid: "OFFICIAL" },
        isOfficial: true,
        price: item.price
      });
    }
  }

  if (allItems.length === 0) {
    player.tell(`§c未找到包含 "${keyword}" 的物品！`);
    return;
  }

  allItems.sort((a, b) => a.price - b.price);

  const total = allItems.length;
  const totalPages = Math.ceil(total / PAGE_SIZE);
  if (page < 1) page = 1;
  if (page > totalPages) page = totalPages;
  
  const startIndex = (page - 1) * PAGE_SIZE;
  const endIndex = Math.min(startIndex + PAGE_SIZE, total);
  const pageItems = allItems.slice(startIndex, endIndex);

  const form = mc.newSimpleForm();
  form.setTitle(`§d全局搜索结果: ${keyword}`);
  form.setContent(`§e找到 ${total} 个物品匹配 "${keyword}"\n§a(按单价从低到高排序)`);
  
  addReturnButton(form);
  
  if (page > 1) {
    form.addButton("§a<< 上一页", "textures/ui/arrow_left");
  }
  if (page < totalPages) {
    form.addButton("§a下一页 >>", "textures/ui/arrow_right");
  }
  
  form.addButton("§a搜索物品","textures/ui/magnifyingGlass");
  
  pageItems.forEach(({ item, shop, isOfficial }) => {
    const tmpItem = safeNewItem(item.itemData);
    const displayName = item.displayName || getItemDisplayName(tmpItem, false);
    
    let qtyStr = (item.quantity === -1) ? "∞" : item.quantity.toString();
    
    let tx = JSON.parse(textureData.read());
    let icon = default_icon_path;
    if (tx[tmpItem.type] && tx[tmpItem.type] !== 'null') {
      icon = tx[tmpItem.type];
    }
    
    form.addButton(
      `§3单价: ${item.price} §f| §a库存: ${qtyStr}\n§s${displayName} §f| §b${shop.name}`,
      icon
    );
  });

  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    
    if (id === 0) {
      showMainMenu(pl);
      return;
    }
    
    let btnIdx = 1;
    const hasPrev = page > 1;
    const hasNext = page < totalPages;
    
    if (hasPrev && id === btnIdx) {
      showGlobalSearchResults(pl, keyword, page - 1);
      return;
    }
    if (hasPrev) btnIdx++;
    
    if (hasNext && id === btnIdx) {
      showGlobalSearchResults(pl, keyword, page + 1);
      return;
    }
    if (hasNext) btnIdx++;
    
    if (id === btnIdx) {
      showGlobalSearch(pl, keyword, 1);
      return;
    }
    btnIdx++; 
    
    const itemIdx = id - btnIdx;
    if (itemIdx >= 0 && itemIdx < pageItems.length) {
      const { itemKey, item, shop, isOfficial } = pageItems[itemIdx];
      confirmPurchase(pl, shop, itemKey, item, isOfficial);
    }
  });
}

function handleMyShop(player) {
  const xuid = player.xuid;
  if(!shopsData[xuid]){
    promptCreateShop(player);
  }else{
    showMyShopMenu(player);
  }
}

function promptCreateShop(player){
  const economy = getEconomyInterface();
  const creationCost = config.get('shopCreationCost');
  const form = mc.newCustomForm();
  form.setTitle('§b§l创建店铺');
  form.addInput('§e§l请输入您的店铺名称（最多10个字符）：', '店铺名称');
  form.addLabel(`§e§l创建店铺需要花费：§3§l${creationCost}§f ${economy.name}`);
  form.addLabel('§a（提交后将扣除相应的经济）');
  player.sendForm(form,(pl,data)=>{
    if(!data) return;
    const shopName = data[0]?.trim();
    if(!shopName){
      pl.tell('§c§l店铺名称不能为空！');
      return;
    }
    if(shopName.length>10){
      pl.tell('§c§l店铺名称不能超过10个字符！');
      return;
    }
    if(economy.get(pl)<creationCost){
      pl.tell('§c§l您的经济不足，无法创建店铺！');
      return;
    }
    if(!economy.reduce(pl,creationCost)){
      pl.tell('§c§l您的经济不足，无法创建店铺！');
      return;
    }
    shopsData[pl.xuid] = {
      name: shopName,
      owner: pl.realName,
      ownerXuid: pl.xuid,
      createdAt: Date.now(),
      lastNameChange: Date.now(),
      items:{},
      pendingEarnings:0,
      isOpen:true,
      advertSlot:0,
      advertExpire:0,
      iconName: "",
      lastIconChange: 0,
      shopLevel: 1,
      maxItemTypes: config.get('shopDefaultItemTypes'),
      maxTotalItems: config.get('shopDefaultTotalItems')
    };
    if(!rankingData[pl.xuid]){
      rankingData[pl.xuid] = { salesCount:0, totalEarnings:0 };
      saveRankingData();
    }
    saveShopsData();
    pl.tell(`§a§l店铺创建成功！店铺名称：§3§l${shopName}`);
  });
}

function showMyShopMenu(player){
  const shop = shopsData[player.xuid];
  const form = mc.newSimpleForm();
  form.setTitle('§b§l我的店铺');
  const itemCount = Object.keys(shop.items).length;
  let totalItemsCount = 0;
  for (const key in shop.items) {
    const item = shop.items[key];
    totalItemsCount += (item.quantity === -1) ? 0 : item.quantity;
  }
  
  let content = '';
  if (config.get('enableShopLevelSystem')) {
    content = `§e§l店铺等级: §3Lv.${shop.shopLevel}§f\n§e在售物品: §a${itemCount}/${shop.maxItemTypes}件§f | 总数量: §a${totalItemsCount}/${shop.maxTotalItems}§f\n§e§l请选择一个操作：`;
  } else {
    content = `§e§l在售物品: §a${itemCount}件§f | 总数量: §a${totalItemsCount}§f\n§e§l请选择一个操作：`;
  }
  form.setContent(content);
  
  addReturnButton(form);
  form.addButton('§a§l编辑店铺物品','textures/ui/Scaffolding');
  form.addButton('§b§l管理店铺','textures/ui/video_glyph');
  form.addButton('§d§l购买广告位','textures/ui/MCoin');
  form.addButton('§b§l修改店铺图标', 'textures/ui/emote_wheel_select_4');
  form.addButton('§e§l查看交易记录', 'textures/ui/backup_replace');
  form.addButton('§3§l详细财务报表', 'textures/ui/book_frame');
  form.addButton('§d§l市场趋势分析', 'textures/ui/magnifyingGlass');
  
  if (config.get('enableShopLevelSystem')) {
    form.addButton('§3§l升级店铺', 'textures/ui/up_chevron');
  }
  
  player.sendForm(form,(pl,id)=>{
    if(id==null) return;
    if(id===0){
      showMainMenu(pl);
      return;
    }
    let idx=1;
    if(id===idx++){
      showEditShopItemsMenu(pl);
    } else if(id===idx++){
      showManageShopMenu(pl);
    } else if(id===idx++){
      showBuyAdvertSlotMenu(pl);
    } else if(id===idx++){
      showChangeShopIconMenu(pl);
    } else if(id===idx++){
      showMyTradeRecords(pl);
    } else if(id===idx++){
      showDetailedFinancialReport(pl);
    } else if(id===idx++){
      showMarketTrendAnalysis(pl);
    } else if(config.get('enableShopLevelSystem') && id===idx){
      showShopUpgradeMenu(pl, shop);
    }
  });
}

function showShopUpgradeMenu(player, shop) {
  const enableBatchUpgrade = config.get('enableBatchShopUpgrade');
  
  if (enableBatchUpgrade) {
    const form = mc.newSimpleForm();
    form.setTitle('§3§l升级店铺');
    
    const itemCount = Object.keys(shop.items).length;
    let totalItemsCount = 0;
    for (const key in shop.items) {
      const item = shop.items[key];
      totalItemsCount += (item.quantity === -1) ? 0 : item.quantity;
    }
    
    form.setContent(`§e§l当前店铺等级: §3Lv.${shop.shopLevel}§f\n§e在售物品: §a${itemCount}/${shop.maxItemTypes}件 §f| 总数量: §a${totalItemsCount}/${shop.maxTotalItems}§f\n\n§e请选择升级方式：`);
    
    addReturnButton(form);
    form.addButton('§a§l普通升级 (升1级)', 'textures/ui/up_chevron');
    form.addButton('§3§l批量升级 (升多级)', 'textures/ui/smithing_material_slot_overlay');
    
    player.sendForm(form, (pl, id) => {
      if (id == null) return;
      if (id === 0) {
        showMyShopMenu(pl);
        return;
      }
      let idx = 1;
      if (id === idx++) {
        showSingleShopUpgradeMenu(pl, shop);
      } else if (id === idx++) {
        showBatchShopUpgradeMenu(pl, shop);
      }
    });
  } else {
    showSingleShopUpgradeMenu(player, shop);
  }
}

function showSingleShopUpgradeMenu(player, shop) {
  const economy = getEconomyInterface();
  const basePrice = config.get('shopUpgradeBasePrice');
  const increment = config.get('shopUpgradePriceIncrement');
  const itemTypeIncrement = config.get('shopUpgradeItemTypeIncrement');
  const totalIncrement = config.get('shopUpgradeTotalIncrement');
  const nextLevelPrice = basePrice + (shop.shopLevel * increment);
  const itemCount = Object.keys(shop.items).length;
  let totalItemsCount = 0;
  for (const key in shop.items) {
    const item = shop.items[key];
    totalItemsCount += (item.quantity === -1) ? 0 : item.quantity;
  }
  
  const form = mc.newCustomForm();
  form.setTitle('§3§l普通升级店铺');
  form.addLabel(`§e§l当前店铺等级: §3Lv.${shop.shopLevel}§f\n§e在售物品: §a${itemCount}/${shop.maxItemTypes}件 §f| 总数量: §a${totalItemsCount}/${shop.maxTotalItems}§f\n`);
  form.addLabel(`§e§l升级后可获得:\n§a● 可上架物品件数 +${itemTypeIncrement}件\n§a● 可上架物品总数 +${totalIncrement}§f\n`);
  form.addLabel(`§e§l升级费用: §3${nextLevelPrice} ${economy.name}§f\n§c(您当前余额: ${economy.get(player)} ${economy.name})`);
  form.addSwitch('§a§l确认升级', false);
  
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showShopUpgradeMenu(pl, shop);
      return;
    }
    
    const confirmUpgrade = data[3];
    if (!confirmUpgrade) {
      pl.tell('§c已取消店铺升级。');
      showShopUpgradeMenu(pl, shop);
      return;
    }
    
    if (economy.get(pl) < nextLevelPrice) {
      pl.tell(`§c您的余额不足，需要 §3${nextLevelPrice} ${economy.name}§c 才能升级店铺！`);
      return;
    }
    
    if (!economy.reduce(pl, nextLevelPrice)) {
      pl.tell('§c扣款失败，无法升级店铺，请重试！');
      return;
    }
    shop.shopLevel++;
    shop.maxItemTypes += itemTypeIncrement;
    shop.maxTotalItems += totalIncrement;
    
    saveShopsData();
    
    pl.tell(`§a§l店铺升级成功！当前等级: §3Lv.${shop.shopLevel}§a, 可上架物品件数: §3${shop.maxItemTypes}件§a, 可上架物品总数: §3${shop.maxTotalItems}`);
    pl.sendToast("§a店铺升级成功", `当前等级: Lv.${shop.shopLevel}`);
    mc.runcmdEx(`playsound random.levelup @a[name="${pl.name}"]`);
  });
}

function showBatchShopUpgradeMenu(player, shop) {
  const economy = getEconomyInterface();
  const basePrice = config.get('shopUpgradeBasePrice');
  const increment = config.get('shopUpgradePriceIncrement');
  const itemTypeIncrement = config.get('shopUpgradeItemTypeIncrement');
  const totalIncrement = config.get('shopUpgradeTotalIncrement');
  const currentBalance = economy.get(player);
  
  const itemCount = Object.keys(shop.items).length;
  let totalItemsCount = 0;
  for (const key in shop.items) {
    const item = shop.items[key];
    totalItemsCount += (item.quantity === -1) ? 0 : item.quantity;
  }
  
  const form = mc.newCustomForm();
  form.setTitle('§3§l批量升级店铺');
  form.addLabel(`§e§l当前店铺等级: §3Lv.${shop.shopLevel}§f\n§e在售物品: §a${itemCount}/${shop.maxItemTypes}件 §f| 总数量: §a${totalItemsCount}/${shop.maxTotalItems}§f\n§c您当前余额: §3${currentBalance} ${economy.name}§f\n`);
  form.addInput('§e§l目标等级 (当前等级+1以上):', '数字', (shop.shopLevel + 1).toString());
  form.addLabel('§a§l将根据您输入的目标等级自动计算所需费用和升级收益');
  
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showShopUpgradeMenu(pl, shop);
      return;
    }
    
    const targetLevel = parseInt(data[1]);
    
    if (isNaN(targetLevel) || targetLevel <= shop.shopLevel) {
      pl.tell('§c目标等级必须大于当前等级！');
      showBatchShopUpgradeMenu(pl, shop);
      return;
    }
    
    if (targetLevel > shop.shopLevel + 100) {
      pl.tell('§c一次最多只能升级100级！');
      showBatchShopUpgradeMenu(pl, shop);
      return;
    }
    
    showBatchUpgradeConfirmation(pl, shop, targetLevel);
  });
}

function showBatchUpgradeConfirmation(player, shop, targetLevel) {
  const economy = getEconomyInterface();
  const basePrice = config.get('shopUpgradeBasePrice');
  const increment = config.get('shopUpgradePriceIncrement');
  const itemTypeIncrement = config.get('shopUpgradeItemTypeIncrement');
  const totalIncrement = config.get('shopUpgradeTotalIncrement');
  
  const currentLevel = shop.shopLevel;
  const levelDiff = targetLevel - currentLevel;
  
  let totalCost = 0;
  for (let i = currentLevel; i < targetLevel; i++) {
    totalCost += basePrice + (i * increment);
  }
  
  const totalItemTypeIncrease = levelDiff * itemTypeIncrement;
  const totalItemIncrease = levelDiff * totalIncrement;
  const newMaxItemTypes = shop.maxItemTypes + totalItemTypeIncrease;
  const newMaxTotalItems = shop.maxTotalItems + totalItemIncrease;
  const currentBalance = economy.get(player);
  
  const form = mc.newCustomForm();
  form.setTitle('§3§l确认批量升级');
  form.addLabel(`§e§l升级详情:\n§a当前等级: §3Lv.${currentLevel} §a→ 目标等级: §3Lv.${targetLevel}§f\n§a升级级数: §3${levelDiff}级§f\n`);
  form.addLabel(`§e§l升级收益:\n§a可上架物品件数: §3${shop.maxItemTypes} §a→ §3${newMaxItemTypes} §a(+${totalItemTypeIncrease})§f\n§a可上架物品总数: §3${shop.maxTotalItems} §a→ §3${newMaxTotalItems} §a(+${totalItemIncrease})§f\n`);
  form.addLabel(`§e§l费用详情:\n§a总费用: §3${totalCost} ${economy.name}§f\n§a当前余额: §3${currentBalance} ${economy.name}§f\n§a升级后余额: §${currentBalance >= totalCost ? '6' : 'c'}${currentBalance - totalCost} ${economy.name}§f\n`);
  
  if (currentBalance < totalCost) {
    form.addLabel('§c§l余额不足，无法进行升级！');
  } else {
    form.addSwitch('§a§l确认批量升级', false);
  }
  
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showBatchShopUpgradeMenu(pl, shop);
      return;
    }
    
    if (currentBalance < totalCost) {
      pl.tell(`§c您的余额不足，需要 §3${totalCost} ${economy.name}§c 才能升级到等级 ${targetLevel}！`);
      return;
    }
    
    const confirmUpgrade = data[3];
    if (!confirmUpgrade) {
      pl.tell('§c已取消批量升级。');
      showBatchShopUpgradeMenu(pl, shop);
      return;
    }
    
    if (!economy.reduce(pl, totalCost)) {
      pl.tell('§c扣款失败，无法升级店铺，请重试！');
      return;
    }
    
    shop.shopLevel = targetLevel;
    shop.maxItemTypes = newMaxItemTypes;
    shop.maxTotalItems = newMaxTotalItems;
    
    saveShopsData();
    
    pl.tell(`§a§l批量升级成功！店铺已从 §3Lv.${currentLevel} §a升级到 §3Lv.${targetLevel}§a！`);
    pl.tell(`§a可上架物品件数: §3${newMaxItemTypes}件§a, 可上架物品总数: §3${newMaxTotalItems}§a, 共花费: §3${totalCost} ${economy.name}`);
    pl.sendToast("§a批量升级成功", `Lv.${currentLevel} → Lv.${targetLevel}`);
    mc.runcmdEx(`playsound random.levelup @a[name="${pl.name}"]`);
  });
}
function showMyTradeRecords(player) {
  const f = mc.newSimpleForm();
  f.setTitle("§a查看交易记录");
  f.setContent("请选择要查看的记录类型：");
  addReturnButton(f);
  f.addButton("§e我的购买记录", "textures/ui/MCoin");
  f.addButton("§b我的售出记录", "textures/ui/hanging_sign");
  player.sendForm(f, (pl, id) => {
    if (id == null) return;
    if (id === 0) {
      showMyShopMenu(pl);
      return;
    }
    let idx=1;
    if (id===idx++) {
      showMyBuyRecords(pl);
    } else if (id===idx) {
      showMySaleRecords(pl);
    }
  });
}

function showMyBuyRecords(player){
  const xuid = player.xuid;
  if (!purchaseLogs.players || !purchaseLogs.players[xuid]) {
    player.tell("§c暂无任何记录。");
    return;
  }
  const myBuy = purchaseLogs.players[xuid].buy || [];
  if (myBuy.length === 0) {
    player.tell("§c暂无任何购买记录。");
    return;
  }

  let content = "§a最近30条购买记录：\n\n";
  const reversedBuyLogs = [...myBuy].reverse();
  reversedBuyLogs.forEach((rec, i) => {
    content += `§e${i+1}. §a时间:${rec.time}\n` +
               `  §a向§b[${rec.sellerName}] §s(店铺:${rec.shopName})\n` +
               `  §a购买了§g${rec.itemName} \n§a数量：§g${rec.quantity} §a单价:§g${rec.priceEach} §a总价§g:${rec.totalPrice}\n\n`;
  });

  const form = mc.newCustomForm();
  form.setTitle("§a我的购买记录");
  form.addLabel(content);
  player.sendForm(form, (pl, data)=>{});
}

function showMySaleRecords(player){
  const xuid = player.xuid;
  if (!purchaseLogs.players || !purchaseLogs.players[xuid]) {
    player.tell("§c暂无任何记录。");
    return;
  }
  const mySell = purchaseLogs.players[xuid].sell || [];
  if (mySell.length === 0) {
    player.tell("§c暂无任何售出记录。");
    return;
  }

  let content = "§a最近30条售出记录：\n\n";
  const reversedSellLogs = [...mySell].reverse();
  reversedSellLogs.forEach((rec, i) => {
    content += `§e${i+1}. §a时间:${rec.time}\n` +
               `  §a卖给了§b[${rec.buyerName}] §s(店铺:${rec.shopName})\n` +
               `  §a物品：§g${rec.itemName} §a数量：${rec.quantity} §a单价:§g${rec.priceEach} §a总价:§g${rec.totalPrice}\n\n`;
  });

  const form = mc.newCustomForm();
  form.setTitle("§a我的售出记录");
  form.addLabel(content);
  player.sendForm(form, (pl, data)=>{});
}



function showChangeShopIconMenu(player){
  const shop = shopsData[player.xuid];
  if(!shop){
    player.tell("§c您尚未创建店铺，无法修改图标!");
    return;
  }
  let localEnabled = config.get("enableLocalIcon");
  let customEnabled = config.get("enableCustomPathIcon");
  let form = mc.newSimpleForm();
  form.setTitle("§a§l更改店铺图标");
  form.setContent("§e请选择图标类型:");
  addReturnButton(form);
  if(localEnabled) form.addButton("§b本地图标","textures/ui/color_picker");
  if(customEnabled) form.addButton("§5自定义路径图标","textures/ui/equipped_item_border");

  player.sendForm(form,(pl,id)=>{
    if(id==null)return;
    if(id===0){
      showMyShopMenu(pl);
      return;
    }
    let idx=1;
    let localSlot = localEnabled?idx++:-1;
    let customSlot = customEnabled?idx++:-1;
    if(id===localSlot){
      showChangeShopIconLocal(pl,shop);
      return;
    }
    if(id===customSlot){
      showChangeShopIconCustom(pl, shop);
      return;
    }
  });
}

function showChangeShopIconCustom(player, shop) {
  let cost = config.get("customPathIconChangeCost") || 200;
  let cd = config.get("customPathIconChangeCooldown") || 72;
  let now = Date.now();
  let cdMs = cd * 3600000;
  if(now - (shop.lastIconChange||0) < cdMs){
      let remainHr = (( cdMs - (now - shop.lastIconChange)) / 3600000).toFixed(1);
      player.tell(`§c距离下次修改店铺图标还有 ${remainHr} 小时!`);
      return;
  }

  const form = mc.newCustomForm();
  form.setTitle("§5自定义图标路径");
  form.addInput("§e请输入自定义路径（例如 textures/ui/... ）", "");
  player.sendForm(form, (pl, data) => {
      if (!data) return;
      const pathStr = data[0]?.trim();
      if (!pathStr) {
          pl.tell("§c路径不能为空！");
          return;
      }
      let economy = getEconomyInterface();
      if(economy.get(pl) < cost){
          pl.tell(`§c余额不足!修改图标需${cost}${economy.name}`);
          return;
      }
      let check = economy.reduce(pl, cost);
      if(!check){
          pl.tell('§c扣费失败,请重试');
          return;
      }
      shop.iconName = pathStr;
      shop.lastIconChange = Date.now();
      saveShopsData();
      pl.tell(`§a成功更改店铺图标为: ${pathStr}`);
  });
}


function showChangeShopIconLocal(player, shop){
  let cost = config.get("localIconChangeCost") || 200;
  let cd = config.get("localIconChangeCooldown") || 72;
  let now = Date.now();
  let cdMs = cd*3600000;
  if(now - (shop.lastIconChange||0) < cdMs){
    let remainHr = (( cdMs - (now - shop.lastIconChange)) / 3600000).toFixed(1);
    player.tell(`§c距离下次修改店铺图标还有 ${remainHr} 小时!`);
    return;
  }
  let files = [];
  try{
    let raw = File.readFrom(uiIconsPath);
    if(raw){
      if(raw.charCodeAt(0)===0xFEFF) raw = raw.slice(1);
      files = JSON.parse(raw);
    }
  }catch(e){}
  if(!Array.isArray(files) || files.length===0){
    player.tell('§c暂无可用的本地图标(请检查 ui_icons.json)');
    return;
  }
  showShopIconSelectPage(player, shop, files, 1, cost, cdMs, "local");
}

function showShopIconSelectPage(player, shop, files, page, cost, cdMs, iconType){
  let total=files.length;
  let totalPages=Math.ceil(total/PAGE_SIZE);
  if(page<1) page=1;
  if(page>totalPages && totalPages>0) page=totalPages;
  let start=(page-1)*PAGE_SIZE;
  let end=start+PAGE_SIZE;
  let list=files.slice(start,end);
  const form=mc.newSimpleForm();
  form.setTitle(`§a选择店铺图标 - 第${page}/${totalPages}页`);
  form.setContent(`§e选中图标后将花费${cost}, 并进入${cdMs/3600000}小时冷却.\n(点击图标会跳出确认界面预览)`);
  if(page>1) form.addButton('§a<< 上一页','textures/ui/arrow_dark_left_stretch');
  if(page<totalPages) form.addButton('§a下一页 >>','textures/ui/arrow_dark_right');
  list.forEach(iconName=>{
    form.addButton(iconName, `textures/ui/${iconName}`);
  });
  player.sendForm(form,(pl,id)=>{
    if(id==null)return;
    let idx=0;
    let hasPrev=(page>1), hasNext=(page<totalPages);
    if(hasPrev && id===idx){
      showShopIconSelectPage(pl,shop,files,page-1,cost,cdMs,iconType);
      return;
    }
    if(hasPrev) idx++;
    if(hasNext && id===idx){
      showShopIconSelectPage(pl,shop,files,page+1,cost,cdMs,iconType);
      return;
    }
    if(hasNext) idx++;
    let selectIndex = id - idx;
    if(selectIndex<0||selectIndex>=list.length){
      pl.tell('§c选择无效!');
      return;
    }
    let realFilename=list[selectIndex];
    let nameNoExt=realFilename.replace(/\.png$/i,'');
    confirmLocalIconBuy(pl, shop, nameNoExt, cost, cdMs);
  });
}

function confirmLocalIconBuy(player, shop, iconName, cost, cdMs){
  const economy = getEconomyInterface();
  if(economy.get(player)<cost){
    player.tell(`§c余额不足!修改图标需${cost}${economy.name}`);
    return;
  }
  const f=mc.newSimpleForm();
  f.setTitle('§a确认购买图标');
  f.setContent(`§e是否花费 ${cost}${economy.name} 购买图标\n§btextures/ui/${iconName} ?\n点击下方预览按钮即可确认。`);
  f.addButton("§a预览并确认","textures/ui/icon_import");
  player.sendForm(f,(pl,id)=>{
    if(id==null)return;
    if(economy.get(pl)<cost){
      pl.tell(`§c余额不足!修改图标需${cost}${economy.name}`);
      return;
    }
    let ok = economy.reduce(pl,cost);
    if(!ok){
      pl.tell('§c扣费失败,请重试');
      return;
    }
    shop.iconName=`textures/ui/${iconName}`;
    shop.lastIconChange=Date.now();
    saveShopsData();
    pl.tell(`§a成功更改店铺图标为: textures/ui/${iconName}`);
  });
}

function showEditShopItemsMenu(player){
  const form = mc.newSimpleForm();
  form.setTitle('§a§l编辑店铺物品');
  form.setContent('§e§l请选择一个操作：');
  addReturnButton(form);
  form.addButton('§a§l上架物品','textures/ui/backup_replace');
  form.addButton('§b§l编辑物品','textures/ui/anvil_icon');
  form.addButton('§d§l设置折扣','textures/ui/store_sort_icon');
  form.addButton('§3§l调整物品顺序','textures/ui/hammer_r');
  if(config.get('enableBatchOperations')){
    form.addButton('§3§l批量操作','textures/ui/copy');
  }
  player.sendForm(form,(pl,id)=>{
    if(id==null) return;
    if(id===0){
      showMyShopMenu(pl);
      return;
    }
    let idx=1;
    if(id===idx++){
      listPlayerItems(pl,false);
    } else if(id===idx++){
      editShopItems(pl);
    } else if(id===idx++){
      showShopDiscountMenu(pl, shopsData[pl.xuid]);
    } else if(id===idx++){
      showShopItemOrderMenu(pl);
    } else if(config.get('enableBatchOperations') && id===idx){
      showBatchOperationsMenu(pl);
    }
  });
}

function listPlayerItems(player, isOfficialShop){
  const invItems=getPlayerInventoryItems(player,!isOfficialShop);
  

  const itemKeys=Object.keys(invItems);
  if(itemKeys.length===0){
    player.tell('§c§l您的背包中没有物品！');
    return;
  }
  if (!isOfficialShop) {
    const shop = shopsData[player.xuid];
    const currentItemCount = Object.keys(shop.items).length;
    
    if (config.get('enableShopLevelSystem') && currentItemCount >= shop.maxItemTypes) {
      player.tell(`§c§l您的店铺已达到最大物品件数限制(${shop.maxItemTypes}件)，请先下架部分物品或升级店铺！`);
      return;
    }
  }
  
  const form=mc.newCustomForm();
  form.setTitle(isOfficialShop?'§a§l官方商店上架物品（购买）':'§a§l上架物品');
  const itemNames=itemKeys.map((k,idx)=>{
    const {item,count}=invItems[k];
    const dn=getItemDisplayName(item,false);
    let cloneNbt = item.getNbt();
    cloneNbt.setByte('Count',1);
    let nbtString = cloneNbt.toSNBT();
    
    let statusText = '';
    if (isOfficialShop && isItemAlreadyInOfficialPurchase(nbtString)) {
      statusText = ' §3(已上架)';
    }
    
    return `${idx+1}. ${dn} §ax ${count}${statusText}`;
  });
  form.addDropdown('§e§l请选择要上架的物品：', itemNames);
  form.addInput('§e§l请输入出售价格（每个）：','数字');
  if(isOfficialShop){
    form.addInput('§e§l请输入库存数量（0为无限）：','数字','0');
    form.addInput('§e§l自定义显示名称（可选）：','留空则使用默认名称','');
  } else {
    form.addInput('§e§l请输入要上架的数量：','数字');
  }
  form.addInput('§e§l请输入物品备注（可选，最多50字符）：','备注信息','');
  if(config.get('enableItemCategories')){
    const categories = config.get('itemCategories') || ["全部"];
    form.addDropdown('§e§l请选择物品分类：', categories);
  }
  player.sendForm(form,(pl,data)=>{
    if(!data)return;
    
    const selectedIndex=data[0];
    const price=parseInt(data[1]);
    let quantity=parseInt(data[2]);
    
    let fieldIndex = 3; 
    let displayName = '';
    let remark = '';
    let categoryValue = 0; 
    
    if(isOfficialShop){
      displayName = data[fieldIndex++]?.trim() || '';
    }
    
    remark = data[fieldIndex++]?.trim() || '';
    
    if(config.get('enableItemCategories')){
      categoryValue = data[fieldIndex];
    }
    
    if(isOfficialShop){
      if(isNaN(quantity)||quantity<0){pl.tell('§c§l库存数量必须是非负整数！');return;}
      if(quantity===0) quantity=-1;
    } else {
      if(isNaN(quantity)||quantity<=0){pl.tell('§c§l数量必须是正整数！');return;}
      if(quantity>invItems[itemKeys[selectedIndex]].count){pl.tell('§c§l您没有足够的物品！');return;}
      const shop = shopsData[pl.xuid];
      let currentTotalItems = 0;
      for (const key in shop.items) {
        const item = shop.items[key];
        currentTotalItems += (item.quantity === -1) ? 0 : item.quantity;
      }
      
      if (config.get('enableShopLevelSystem') && currentTotalItems + quantity > shop.maxTotalItems) {
        pl.tell(`§c§l超出店铺物品总数限制！当前总数: ${currentTotalItems}, 上限: ${shop.maxTotalItems}, 尝试添加: ${quantity}`);
        return;
      }
    }
    
    if(isNaN(price)||price<=0){pl.tell('§c§l价格必须是正整数！');return;}
    if(remark.length>50){pl.tell('§c§l备注信息不能超过50字符！');return;}
    
    let selectedCategory = "全部";
    if(config.get('enableItemCategories')){
      const categories = config.get('itemCategories') || ["全部"];
      if(categoryValue !== undefined && categoryValue !== null && categories[categoryValue] !== undefined) {
        selectedCategory = categories[categoryValue];
      }
    }
    
    const selKey=itemKeys[selectedIndex];
    const {item}=invItems[selKey];
    const nbtString=item.getNbt().toSNBT();
    
    if(!isOfficialShop){
      const currentInvItems = getPlayerInventoryItems(pl, true);
      const currentItemData = currentInvItems[selKey];
      if(!currentItemData || currentItemData.count < quantity) {
        pl.tell('§c§l物品数量发生变化，请重新操作！');
        return;
      }
      
      const currentNbt = currentItemData.item.getNbt().toSNBT();
      const originalItem = safeNewItem(nbtString);
      const currentItem = currentItemData.item;
      
      if (!originalItem || !currentItem) {
        pl.tell('§c§l物品验证失败，请重试！');
        return;
      }
      
      if (originalItem.type !== currentItem.type || 
          getItemDisplayName(originalItem, false) !== getItemDisplayName(currentItem, false)) {
        pl.tell('§c§l物品类型已发生变化，请重新操作！');
        return;
      }
      
      let ok = removeItemsFromPlayer(pl, nbtString, quantity);
      if(!ok){
        pl.tell('§c§l扣除物品失败，请重试！');
        return;
      }
    }
    
    const tmp=safeNewItem(nbtString);
    const itemInfo=getItemDisplayName(tmp,true).replace(/§[a-zA-Z0-9]/g,'');
    const notifyItemListingToAll = config.get('notifyItemListingToAll');
    
    if(isOfficialShop){
      officialShopData.purchaseItems[nbtString]={
        itemData: nbtString,
        name: itemInfo,
        displayName: displayName,
        price,
        quantity,
        remark,
        category: selectedCategory
      };
      recordPriceHistory(nbtString, "OFFICIAL", price, true);
      saveOfficialShopData();
      
      pl.sendToast("§a上架成功", `${displayName || itemInfo} 已上架至官方商店`);
      
      if (notifyItemListingToAll) {
        const onlinePlayers = mc.getOnlinePlayers();
        onlinePlayers.forEach(p => {
          if (p.xuid !== pl.xuid) {
            p.sendToast(`§a官方商店新商品`, `${displayName || itemInfo} 价格:${price} ${quantity === -1 ? '库存:无限' : `数量:${quantity}`}`);
          }
        });
      }
      
      const listingMsg = {
        sender: "§a商店系统",
        content: `§e官方商店§f上架了新商品: §a${displayName || itemInfo} §f价格:§c${price}§f ${quantity === -1 ? '库存:无限' : `数量:${quantity}`}`,
        timestamp: Date.now(),
        mentions: []
      };
      chatMessages.push(listingMsg);
      if (chatMessages.length > config.get('chatHistoryLimit')) {
        chatMessages.shift();
      }
      saveChatData();
      
      pl.tell(`§a§l已上架到官方商店 §d${displayName || getItemDisplayName(tmp,true)}\n§f数量:${quantity===-1?'无限':quantity}，售价:§3${price}§f(每个)`);
      manageOfficialShop(pl); 
    } else {
      const shop=shopsData[pl.xuid];
      if(!shop.items[nbtString]){
        if (config.get('enableShopLevelSystem') && Object.keys(shop.items).length >= shop.maxItemTypes) {
          pl.tell(`§c§l您的店铺已达到最大物品件数限制(${shop.maxItemTypes}件)！请先下架部分物品或升级店铺。`);
          const returnSuccess = giveItemToPlayer(pl, nbtString, quantity);
          if (!returnSuccess) {
            pl.tell('§c§l物品返还失败！请清理背包空间后联系管理员！');
            log(`警告：玩家 ${pl.realName} 店铺上架失败且物品返还失败！物品：${nbtString}，数量：${quantity}`);
          }
          return;
        }
        
        shop.items[nbtString]={
          itemData: nbtString,
          name: itemInfo,
          price,
          quantity,
          remark,
          category: selectedCategory
        };
        recordPriceHistory(nbtString, pl.xuid, price, false);
      } else {
        let old=shop.items[nbtString];
        old.quantity+=quantity;
        if(old.price !== price){
          recordPriceHistory(nbtString, pl.xuid, price, false);
        }
        old.price=price;
        old.remark=remark;
        old.category=selectedCategory;
      }
      saveShopsData();
      
      pl.sendToast("§a上架成功", `${itemInfo} x${quantity} 已上架`);
      
      if (notifyItemListingToAll) {
        const onlinePlayers = mc.getOnlinePlayers();
        onlinePlayers.forEach(p => {
          if (p.xuid !== pl.xuid) { 
            p.sendToast(`§a${shop.name} 店铺新商品`, `${itemInfo} 价格:${price} 数量:${quantity}`);
          }
        });
      }
      
      const listingMsg = {
        sender: "§a商店系统",
        content: `§e${shop.name} §f店铺上架了新商品: §a${itemInfo} §f价格:§c${price}§f 数量:§c${quantity}`,
        timestamp: Date.now(),
        mentions: []
      };
      chatMessages.push(listingMsg);
      if (chatMessages.length > config.get('chatHistoryLimit')) {
        chatMessages.shift();
      }
      saveChatData();
      
      pl.tell(`§a§l成功上架 §d${getItemDisplayName(tmp,true)}\n§f数量:${quantity}，售价:§3${price}§f(每个)`);
      showEditShopItemsMenu(pl); 
    }
  });
}

function showBatchOperationsMenu(player) {
  const shop = shopsData[player.xuid];
  if (!shop || Object.keys(shop.items).length === 0) {
    player.tell("§c店铺中没有物品可进行批量操作！");
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle("§3§l批量操作");
  form.setContent("§e请选择批量操作类型：");
  addReturnButton(form);
  form.addButton("§a批量调价", "textures/ui/MCoin");
  form.addButton("§b批量设置分类", "textures/ui/recipe_book_icon");
  form.addButton("§c批量下架", "textures/ui/trash");
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === 0) {
      showEditShopItemsMenu(pl);
      return;
    }
    
    if (id === 1) {
      showBatchPriceAdjustment(pl);
    } else if (id === 2) {
      showBatchCategoryChange(pl);
    } else if (id === 3) {
      showBatchRemoveItems(pl);
    }
  });
}

function showBatchPriceAdjustment(player) {
  const shop = shopsData[player.xuid];
  const form = mc.newCustomForm();
  form.setTitle("§a§l批量调价");
  form.addLabel("§e对所有商品进行批量调价");
  form.addDropdown("§e调价方式：", ["按百分比调整", "按固定金额调整", "设置统一价格"], 0);
  form.addInput("§e调整值（百分比输入0-200，金额输入正负数）：", "数值", "10");
  form.addSwitch("§e仅对选定分类的物品生效", false);
  
  if (config.get('enableItemCategories')) {
    const categories = config.get('itemCategories') || ["全部"];
    form.addDropdown("§e选择分类：", categories, 0);
  }
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    const adjustType = data[1];
    const adjustValue = parseFloat(data[2]);
    const categoryFilter = data[3];
    const selectedCategoryIndex = config.get('enableItemCategories') ? data[4] : 0;
    const categories = config.get('itemCategories') || ["全部"];
    const targetCategory = categories[selectedCategoryIndex];
    
    if (isNaN(adjustValue)) {
      pl.tell("§c请输入有效的数值！");
      return;
    }
    
    let count = 0;
    for (const key in shop.items) {
      const item = shop.items[key];
      
      if (categoryFilter && item.category !== targetCategory) {
        continue;
      }
      
      let newPrice = item.price;
      
      if (adjustType === 0) {
        newPrice = Math.round(item.price * (adjustValue / 100));
      } else if (adjustType === 1) {
        newPrice = item.price + adjustValue;
      } else if (adjustType === 2) {
        newPrice = adjustValue;
      }
      
      if (newPrice <= 0) newPrice = 1;
      
      if (item.price !== newPrice) {
        recordPriceHistory(key, pl.xuid, newPrice, false);
        item.price = newPrice;
        count++;
      }
    }
    
    saveShopsData();
    pl.tell(`§a成功调整了 ${count} 个物品的价格！`);
    pl.sendToast("§a批量调价完成", `已调整 ${count} 个物品`);
  });
}

function showBatchCategoryChange(player) {
  if (!config.get('enableItemCategories')) {
    player.tell("§c物品分类功能未启用！");
    return;
  }
  
  const shop = shopsData[player.xuid];
  const categories = config.get('itemCategories') || ["全部"];
  
  const form = mc.newCustomForm();
  form.setTitle("§b§l批量设置分类");
  form.addLabel("§e选择要批量设置的分类");
  form.addDropdown("§e目标分类：", categories, 0);
  form.addSwitch("§e应用到所有物品", true);
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    const targetCategoryIndex = data[1];
    const applyToAll = data[2];
    const targetCategory = categories[targetCategoryIndex];
    
    if (applyToAll) {
      let count = 0;
      for (const key in shop.items) {
        shop.items[key].category = targetCategory;
        count++;
      }
      saveShopsData();
      pl.tell(`§a成功将所有 ${count} 个物品设置为"${targetCategory}"分类！`);
    } else {
      showItemSelectionForCategory(pl, targetCategory);
    }
  });
}

function showBatchRemoveItems(player) {
  const shop = shopsData[player.xuid];
  if (!shop || Object.keys(shop.items).length === 0) {
    player.tell("§c店铺中没有物品可进行批量操作！");
    return;
  }
  
  showBatchRemoveItemsSelection(player, shop);
}

function showBatchRemoveItemsSelection(player, shop) {
  const form = mc.newCustomForm();
  form.setTitle("§c§l批量下架物品");
  form.addLabel("§e选择要下架的物品：");
  
  const txMap = JSON.parse(textureData.read());
  const itemKeys = Object.keys(shop.items);
  
  itemKeys.forEach((key) => {
    const shopItem = shop.items[key];
    const tmpItem = safeNewItem(shopItem.itemData);
    const showName = getItemDisplayName(tmpItem, false);
    form.addSwitch(`§b${showName}§f (价格: §a${shopItem.price}§f | 库存: §a${shopItem.quantity === -1 ? '∞' : shopItem.quantity}§f)`, false);
  });
  
  form.addSwitch("§c确认下架选中物品", false);
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    const confirmRemove = data[data.length - 1];
    if (!confirmRemove) {
      pl.tell("§c已取消批量下架操作！");
      return;
    }
    
    let itemsToRemove = [];
    for (let i = 0; i < itemKeys.length; i++) {
      if (data[i + 1] === true) {
        const key = itemKeys[i];
        const item = shop.items[key];
        itemsToRemove.push({ key, item });
      }
    }
    
    if (itemsToRemove.length === 0) {
      pl.tell("§c未选择任何物品！");
      return;
    }
    
    let successCount = 0;
    let failCount = 0;
    
    for (const { key, item } of itemsToRemove) {
      if (item.quantity !== -1) {
        const itemNbt = NBT.parseSNBT(item.itemData);
        if (!canPlayerReceiveItem(pl, itemNbt, item.quantity)) {
          failCount++;
          continue;
        }
        let returnSuccess = distributeItemsToPlayer(pl, itemNbt, item.quantity);
        if(!returnSuccess){
          pl.tell(`§c§l物品返还失败！请清理背包空间后联系管理员！`);
          failCount++;
          continue;
        }
      }
      delete shop.items[key];
      successCount++;
    }
    
    saveShopsData();
    
    if (failCount > 0) {
      pl.tell(`§a成功下架 ${successCount} 个物品，§c${failCount} 个物品因背包空间不足未能下架！`);
    } else {
      pl.tell(`§a成功批量下架 ${successCount} 个物品！`);
    }
  });
}

function showItemSelectionForCategory(player, targetCategory) {
  const shop = shopsData[player.xuid];
  const form = mc.newCustomForm();
  form.setTitle(`§b设置分类为: ${targetCategory}`);
  form.addLabel("§e选择要设置分类的物品：");
  
  const itemKeys = Object.keys(shop.items);
  itemKeys.forEach((key, idx) => {
    const item = shop.items[key];
    const tmpItem = safeNewItem(item.itemData);
    const showName = getItemDisplayName(tmpItem, false);
    const currentCategory = item.category || "全部";
    form.addSwitch(`${showName} (当前: ${currentCategory})`, false);
  });
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    let count = 0;
    for (let idx = 0; idx < itemKeys.length; idx++) {
      if (data[idx + 1] === true) {
        const key = itemKeys[idx];
        shop.items[key].category = targetCategory;
        count++;
      }
    }
    
    saveShopsData();
    pl.tell(`§a成功将 ${count} 个物品设置为"${targetCategory}"分类！`);
  });
}

function editShopItems(player){
  const shop = shopsData[player.xuid];
  const shopItemKeys = getSortedShopItemKeys(shop);
  if(shopItemKeys.length === 0){
    player.tell('§c§l您的店铺中没有物品！');
    return;
  }
  const form = mc.newSimpleForm();
  form.setTitle('§b§l编辑店铺物品');
  form.setContent('§e§l请选择要编辑的物品：');
  addReturnButton(form);

  const txMap = JSON.parse(textureData.read());

  shopItemKeys.forEach((key, index) => {
    const shopItem = shop.items[key];
    const tmpItem = safeNewItem(shopItem.itemData);
    const show = getItemDisplayName(tmpItem, false);
    let icon = default_icon_path;
    const typeKey = tmpItem.type;
    if(txMap.hasOwnProperty(typeKey) && txMap[typeKey] && txMap[typeKey] !== 'null'){
      icon = txMap[typeKey];
    }
    form.addButton(
      `§s${show}\n§s库存: ${shopItem.quantity} | 价格: ${shopItem.price}`,
      icon
    );
  });

  player.sendForm(form, (pl, id) => {
    if(id == null) return;
    if(id === 0){
      showEditShopItemsMenu(pl);
      return;
    }
    const selectedKey = shopItemKeys[id - 1];
    const shopItem = shop.items[selectedKey];
    showEditShopItemForm(pl, selectedKey, shopItem);
  });
}

function showEditShopItemForm(player, itemKey, shopItem){
  const itemNbtStr = shopItem.itemData;
  const invCount = getPlayerItemCountForRestock(player, itemNbtStr);
  const form = mc.newCustomForm();
  form.setTitle('§b§l编辑物品');
  form.addLabel(`§e§l物品名称：${shopItem.name}`);
  form.addLabel(`§e§l店铺库存数量：${shopItem.quantity === -1 ? '∞(无限)' : shopItem.quantity}`);
  form.addLabel(`§a您背包中可用于补货的数量：§3${invCount}${invCount === 0 && player.isOP() ? ' §c(点击补货时查看详情)' : ''}`);
  form.addInput('§e§l补充数量(0 表示不补货):', '数字', '0');
  form.addInput('§e§l修改价格（每个）：','数字', shopItem.price.toString());
  form.addInput('§e§l修改备注信息（可选，最多50字符）：','备注信息', shopItem.remark || '');
  if(config.get('enableItemCategories')){
    const categories = config.get('itemCategories') || ["全部"];
    const currentCatIndex = categories.indexOf(shopItem.category || "全部");
    form.addDropdown('§e§l修改分类：', categories, currentCatIndex >= 0 ? currentCatIndex : 0);
  }
  form.addSwitch('§e§l是否下架此物品？', false);
  if(config.get('enablePriceHistory')){
    form.addSwitch('§e§l查看价格历史？', false);
  }
  player.sendForm(form, (pl, data) => {
    if(!data) return;
    const currentShop = shopsData[pl.xuid];
    if (!currentShop) {
      pl.tell("§c店铺数据异常，请稍后重试。");
      return;
    }
    const restockCount = parseInt(data[3]) || 0;  
    const newPrice = parseInt(data[4]);
    const newRemark = (data[5] || '').trim();
    let dataIndex = 6;
    let newCategory = shopItem.category || "全部";
    if(config.get('enableItemCategories')){
      const categories = config.get('itemCategories') || ["全部"];
      newCategory = categories[data[dataIndex]];
      dataIndex++;
    }
    const isRemove = data[dataIndex];
    const viewHistory = config.get('enablePriceHistory') ? data[dataIndex + 1] : false;
    if(isNaN(newPrice) || newPrice <= 0){
      pl.tell('§c§l价格必须是正整数！');
      return;
    }
    if(newRemark.length > 50){
      pl.tell('§c§l备注信息不能超过50字符！');
      return;
    }
    const shop = shopsData[pl.xuid];
    if(!shop){
      pl.tell('§c店铺数据异常，请稍后重试。');
      return;
    }
    
    if(viewHistory){
      showPriceHistory(pl, itemKey, pl.xuid, false);
      return;
    }
    
    if(isRemove){
      const itemNbt = NBT.parseSNBT(itemNbtStr);
      if(shopItem.quantity === -1){
        delete shop.items[itemKey];
        pl.sendToast("§e物品下架", "无限库存物品已下架");
        pl.tell('§a物品已下架(原为无限库存)，无需返还。');
        saveShopsData();
        editShopItems(pl); 
      } else {
        if(!canPlayerReceiveItem(pl, itemNbt, shopItem.quantity)){
          const confirmForm = mc.newCustomForm();
          confirmForm.setTitle('§c背包空间不足警告');
          confirmForm.addLabel(`§c警告：您的背包空间不足以容纳所有下架物品！\n\n§e物品名称：§b${shopItem.name}\n§e下架数量：§b${shopItem.quantity}\n\n§c如果您继续下架，多余的物品将会掉落到地上！\n§e请确保周围安全且有足够时间捡拾物品。\n\n§3建议：先清理背包空间再下架物品。`);
          confirmForm.addSwitch('§c我理解风险并确认下架物品', false);
          pl.sendForm(confirmForm, (pl2, confirmData) => {
            if(!confirmData) return;
            const confirmRemove = confirmData[1];
            if(confirmRemove){
              let returnSuccess = distributeItemsToPlayer(pl2, itemNbt, shopItem.quantity);
              if(returnSuccess) {
                delete shop.items[itemKey];
                pl2.sendToast("§e物品下架", `${shopItem.name} x${shopItem.quantity} 已返还`);
                pl2.tell('§a物品已下架并返还到您的背包。');
              } else {
                pl2.tell('§c§l物品下架失败！背包空间不足，请清理背包后重试！');
              }
              saveShopsData();
              editShopItems(pl2); 
            } else {
              pl2.tell('§c下架操作已取消。');
            }
          });
          return;
      } else {
        let returnSuccess = distributeItemsToPlayer(pl, itemNbt, shopItem.quantity);
        if(returnSuccess) {
          delete shop.items[itemKey];
          pl.sendToast("§e物品下架", `${shopItem.name} x${shopItem.quantity} 已返还`);
          pl.tell('§a物品已下架并返还到您的背包。');
        } else {
          pl.tell('§c§l物品下架失败！背包空间不足，请清理背包后重试！');
        }
          saveShopsData();
          editShopItems(pl); 
        }
      }
    }
    else {
      if(restockCount > 0){
        if(restockCount > invCount){
          pl.tell(`§c§l背包中此物品数量不足，仅有 ${invCount} 可补货！`);
          return;
        }
        
        const now = Date.now();
        const cooldownKey = `${pl.xuid}_${itemKey}`;
        const lastRestock = restockCooldowns[cooldownKey] || 0;
        if(now - lastRestock < 3000) {
          pl.tell(`§c§l补货操作过于频繁，请3秒后重试！`);
          return;
        }
        
        const preRestockInvCount = getPlayerItemCountForRestock(pl, itemNbtStr);
        if(preRestockInvCount < restockCount) {
          pl.tell(`§c§l验证失败：背包中可补货数量为 ${preRestockInvCount}，需要 ${restockCount}`);
          if(pl.isOP()) {
            pl.tell("§6§l[管理员]正在分析物品匹配问题...");
            debugRestockItemComparison(pl, itemNbtStr);
          }
          return;
        }
        
        const ok = removeItemsFromPlayerForRestock(pl, itemNbtStr, restockCount);
        if(!ok){
          pl.tell('§c§l从背包扣除物品失败，请重试！');
          return;
        }
        
        const postRestockInvCount = getPlayerItemCountForRestock(pl, itemNbtStr);
        const actualRemoved = preRestockInvCount - postRestockInvCount;
        
        if(actualRemoved !== restockCount) {
          pl.tell(`§c§l补货验证失败：预期扣除 ${restockCount}，实际扣除 ${actualRemoved}！`);
          log(`补货异常 - 玩家: ${pl.realName}, 预期扣除: ${restockCount}, 实际扣除: ${actualRemoved}`);
          return;
        }
        
        if(shopItem.quantity !== -1){
          shopItem.quantity += restockCount;
        }
        restockCooldowns[cooldownKey] = now;
        pl.tell(`§a§l已成功补充 ${restockCount} 份到库存！`);
      }
      if(shopItem.price !== newPrice){
        recordPriceHistory(itemKey, pl.xuid, newPrice, false);
      }
      shopItem.price = newPrice;
      shopItem.remark = newRemark;
      shopItem.category = newCategory;

      pl.tell('§a§l物品信息已更新。');
    }
    if(!isRemove){
    saveShopsData();
    editShopItems(pl); 
    }
  });
}

function showPriceHistory(player, itemKey, shopXuid, isOfficial) {
  const historyKey = isOfficial ? `official_${itemKey}` : `${shopXuid}_${itemKey}`;
  const history = priceHistory[historyKey];
  
  if (!history || !history.records || history.records.length === 0) {
    player.tell("§c该物品暂无价格历史记录！");
    return;
  }
  
  const form = mc.newCustomForm();
  form.setTitle("§3§l价格历史");
  
  const item = safeNewItem(itemKey);
  const itemName = getItemDisplayName(item, false);
  
  let content = `§e物品: §b${itemName}\n\n`;
  content += `§e当前价格: §a${history.currentPrice}\n`;
  content += `§e历史最低价: §a${history.minPrice}\n`;
  content += `§e历史最高价: §c${history.maxPrice}\n`;
  content += `§e平均价格: §b${history.avgPrice}\n\n`;
  content += `§e最近价格变化记录 (最多显示20条):\n`;
  
  const recentRecords = history.records.slice(-20).reverse();
  recentRecords.forEach((record, idx) => {
    const time = new Date(record.timestamp).toLocaleString();
    content += `§3${idx + 1}. §f${time} - §3${record.price}\n`;
  });
  
  form.addLabel(content);
  
  player.sendForm(form, (pl, data) => {});
}

function showShoppingCenter(player, page, keyword, searchingItem){
  clearExpiredAdvertSlots();
  PAGE_SIZE = config.get("pageSizeLimit") || 30;
  let shopList = Object.values(shopsData).filter(s=>s.isOpen);
  
  if(keyword && keyword.trim()!==""){
    const lowKey = keyword.toLowerCase();
    if(searchingItem){
      shopList = shopList.filter(s=>{
        let items = Object.values(s.items||{});
        for(let it of items){
          if(it.name && it.name.toLowerCase().includes(lowKey)){
            return true;
          }
        }
        return false;
      });
    } else {
      shopList = shopList.filter(s=>
        (s.name && s.name.toLowerCase().includes(lowKey)) ||
        (s.owner && s.owner.toLowerCase().includes(lowKey))
      );
    }
  }
  
  let advShops = [];
  for(let i=1; i<=10; i++){
    let occupant = getShopByAdvertSlot(i);
    if(occupant && occupant.isOpen){
      let found = shopList.find(s=>s.ownerXuid===occupant.ownerXuid);
      if(found) advShops.push(found);
    }
  }
  let advXuids = advShops.map(s=>s.ownerXuid);
  let normalShops = shopList.filter(s=> !advXuids.includes(s.ownerXuid));
  let mode = config.get("shopSortMode") || "随机";
  let sortedNormal = sortShopsByMode(normalShops, mode, rankingData);
  let mergedShops = [...advShops, ...sortedNormal];
  const total = mergedShops.length;
  const totalPages = Math.ceil(total / PAGE_SIZE);
  if(page<1) page=1;
  if(page>totalPages && totalPages>0) page=totalPages;
  const startIndex = (page-1)*PAGE_SIZE;
  const endIndex = startIndex + PAGE_SIZE;
  const currentShops = mergedShops.slice(startIndex,endIndex);
  const form = mc.newSimpleForm();
  form.setTitle(`§3§l购物中心 - 第${page}页 / 共${totalPages}页`);
  form.addButton('§c返回主菜单', 'textures/ui/icon_import');
  let content = '';
  
  if (searchingItem) {
    content = `§e包含关键词"${keyword || "无"}"的物品的店铺\n`;
  } else {
    content = `§e搜索关键字:§f ${keyword||"无"}\n`;
  }
  
  content += `§a(每页最多 ${PAGE_SIZE} 条)\n§f请选择要查看的店铺：`;
  form.setContent(content);
  let hasPrev = (page>1);
  let hasNext = (page<totalPages);
  if(hasPrev){
    form.addButton('§a<< 上一页','textures/ui/icon_import');
  }
  if(hasNext){
    form.addButton('§a下一页 >>','textures/ui/share_microsoft');
  }
  form.addButton('§b浏览全部店铺物品','textures/ui/inventory_icon');
  form.addButton('§a搜索','textures/ui/magnifyingGlass');
  currentShops.forEach(s=>{
    let itemCount = Object.keys(s.items||{}).length;
    let xuid = s.ownerXuid;
    let sc = rankingData[xuid]? rankingData[xuid].salesCount||0 : 0;
    let line1 = `${s.name} §f| §b${s.owner}`;
    let line2 = `§e在售物品: ${itemCount} | 销量: ${sc}`;
    if(s.advertSlot>=1 && s.advertSlot<=10){
      line1 = `§d(推荐)§f ${line1}`;
    }
    let iconPath = getShopIconTexture(s);
    form.addButton(`${line1}\n${line2}`, iconPath);
  });
  player.sendForm(form, (pl,id)=>{
    if(id==null) return;
    let index = 0;
    if(id===index){
      showMainMenu(pl);
      return;
    }
    index++;
    if(hasPrev){
      if(id===index){
        showShoppingCenter(pl,page-1,keyword,searchingItem);
        return;
      }
      index++;
    }
    if(hasNext){
      if(id===index){
        showShoppingCenter(pl,page+1,keyword,searchingItem);
        return;
      }
      index++;
    }
    if(id===index){
      showAllShopItems(pl, 1);
      return;
    }
    index++;
    if(id===index){
      showShopSearchForm(pl,page,keyword);
      return;
    }
    index++;
    const shopIndex = id - index;
    if(shopIndex<0 || shopIndex>=currentShops.length){
      pl.tell('§c选择无效!');
      return;
    }
    const selectedShop = currentShops[shopIndex];
    showShopItems(pl, selectedShop, 1, "", "全部");
  });
}

function showAllShopItems(player, page, keyword = "") {
  PAGE_SIZE = config.get("pageSizeLimit") || 30;
  
  let shopList = Object.values(shopsData).filter(s => s.isOpen);
  
  let advShops = [];
  for(let i = 1; i <= 10; i++) {
    let occupant = getShopByAdvertSlot(i);
    if(occupant && occupant.isOpen) {
      let found = shopList.find(s => s.ownerXuid === occupant.ownerXuid);
      if(found) advShops.push(found);
    }
  }
  
  let advXuids = advShops.map(s => s.ownerXuid);
  let normalShops = shopList.filter(s => !advXuids.includes(s.ownerXuid));
  let mode = config.get("shopSortMode") || "随机";
  let sortedNormal = sortShopsByMode(normalShops, mode, rankingData);
  let mergedShops = [...advShops, ...sortedNormal];
  
  let allItems = [];
  
  for(const shop of mergedShops) {
    const shopItemKeys = getSortedShopItemKeys(shop);
    for(const itemKey of shopItemKeys) {
      const shopItem = shop.items[itemKey];
      if(shopItem && shopItem.quantity !== 0) {
        const tmp = safeNewItem(shopItem.itemData);
        const itemName = shopItem.name || getItemDisplayName(tmp, false);
        
        if(!keyword || keyword.trim() === "" || 
           itemName.toLowerCase().includes(keyword.toLowerCase()) ||
           (shopItem.remark && shopItem.remark.toLowerCase().includes(keyword.toLowerCase()))) {
          
          allItems.push({
            itemKey: itemKey,
            shopItem: shopItem,
            shop: shop,
            item: tmp,
            displayName: itemName,
            finalPrice: shopItem.price
          });
        }
      }
    }
  }
  
  allItems.sort((a, b) => {
    if(a.shop.advertSlot && !b.shop.advertSlot) return -1;
    if(!a.shop.advertSlot && b.shop.advertSlot) return 1;
    return a.finalPrice - b.finalPrice;
  });
  
  const totalItems = allItems.length;
  const totalPages = Math.ceil(totalItems / PAGE_SIZE);
  if(page < 1) page = 1;
  if(page > totalPages && totalPages > 0) page = totalPages;
  
  const startIndex = (page - 1) * PAGE_SIZE;
  const endIndex = startIndex + PAGE_SIZE;
  const currentItems = allItems.slice(startIndex, endIndex);
  
  const form = mc.newSimpleForm();
  form.setTitle(`§b§l全部店铺物品 - 第${page}页 / 共${totalPages}页`);
  
  let content = `§e搜索关键字: §f${keyword || "无"}\n`;
  content += `§e共找到 §a${totalItems} §e件物品 §7(按推荐店铺优先、价格排序)\n`;
  content += `§f(每页最多 ${PAGE_SIZE} 项)\n请选择要购买的物品：`;
  form.setContent(content);
  
  let buttonIndex = 0;
  const RETURN_BUTTON = buttonIndex++;
  form.addButton('§c返回购物中心', 'textures/ui/icon_import');
  
  let hasPrev = (page > 1);
  let hasNext = (page < totalPages);
  let PREV_BUTTON = -1, NEXT_BUTTON = -1, SEARCH_BUTTON = -1;
  
  if(hasPrev) {
    PREV_BUTTON = buttonIndex++;
    form.addButton('§a<< 上一页', 'textures/ui/icon_import');
  }
  
  if(hasNext) {
    NEXT_BUTTON = buttonIndex++;
    form.addButton('§a下一页 >>', 'textures/ui/share_microsoft');
  }
  
  SEARCH_BUTTON = buttonIndex++;
  form.addButton('§a搜索物品', 'textures/ui/magnifyingGlass');
  
  const ITEMS_START = buttonIndex;
  
  currentItems.forEach(itemData => {
    const shopItem = itemData.shopItem;
    const shop = itemData.shop;
    const tmp = itemData.item;
    const displayName = itemData.displayName;
    
    let tx = JSON.parse(textureData.read());
    let icon = (tx.hasOwnProperty(tmp.type) && tx[tmp.type] && tx[tmp.type] !== 'null')
      ? tx[tmp.type] : default_icon_path;
    
    let priceDisplay = shopItem.price.toString();
    if(shopItem.discount && shopItem.originalPrice) {
      const endTime = new Date(shopItem.discountEndTime);
      const remainMinutes = Math.max(0, Math.floor((shopItem.discountEndTime - Date.now()) / 60000));
      priceDisplay = `§c${shopItem.price}§f(${shopItem.discount}折 原价:${shopItem.originalPrice} 剩余:${remainMinutes}分钟)`;
    }
    
    let shopPrefix = "";
    if(shop.advertSlot >= 1 && shop.advertSlot <= 10) {
      shopPrefix = "§d(推荐)§f ";
    }
    
    form.addButton(
      `§s${displayName}\n§s${shopPrefix}店铺: ${shop.name} | 库存: ${shopItem.quantity} | 价格: ${priceDisplay}`,
      icon
    );
  });
  
  player.sendForm(form, (pl, id) => {
    if(id == null) return;
    
    if(id === RETURN_BUTTON) {
      showShoppingCenter(pl, 1, "", false);
      return;
    }
    
    if(hasPrev && id === PREV_BUTTON) {
      showAllShopItems(pl, page - 1, keyword);
      return;
    }
    
    if(hasNext && id === NEXT_BUTTON) {
      showAllShopItems(pl, page + 1, keyword);
      return;
    }
    
    if(id === SEARCH_BUTTON) {
      showAllItemsSearchForm(pl, keyword);
      return;
    }
    
    const itemIndex = id - ITEMS_START;
    if(itemIndex < 0 || itemIndex >= currentItems.length) {
      pl.tell('§c选择无效!');
      return;
    }
    
    const selectedItemData = currentItems[itemIndex];
    const shop = selectedItemData.shop;
    const itemKey = selectedItemData.itemKey;
    const shopItem = selectedItemData.shopItem;
    
    confirmPurchase(pl, shop, itemKey, shopItem, false);
  });
}

function showAllItemsSearchForm(player, currentKeyword) {
  const form = mc.newCustomForm();
  form.setTitle('§a搜索全部店铺物品');
  form.addInput('§e搜索关键字(物品名/备注):', '关键字', currentKeyword || "");
  
  player.sendForm(form, (pl, data) => {
    if(!data) return;
    const newKeyword = data[0]?.trim() || "";
    showAllShopItems(pl, 1, newKeyword);
  });
}

function clearExpiredAdvertSlots() {
  const now = Date.now();
  let changed = false;
  for (let xuid in shopsData) {
    let shop = shopsData[xuid];
    if (shop.advertSlot && shop.advertSlot >= 1 && shop.advertSlot <= 10) {
      if (shop.advertExpire && now > shop.advertExpire) {
        shop.advertSlot = 0;
        shop.advertExpire = 0;
        changed=true;
      }
    }
  }
  if(changed) saveShopsData();
}

function getShopByAdvertSlot(slotNumber) {
  const now = Date.now();
  for (let xuid in shopsData) {
    let shop = shopsData[xuid];
    if (shop.advertSlot === slotNumber) {
      if (shop.advertExpire && now > shop.advertExpire) {
        shop.advertSlot = 0;
        shop.advertExpire = 0;
        saveShopsData();
        continue;
      }
      return shop;
    }
  }
  return null;
}

function showShopSearchForm(player, page, keyword) {
  const form = mc.newCustomForm();
  form.setTitle('§a搜索店铺');
  form.addInput('§e输入关键字:', '关键字', keyword || "");
  form.addDropdown('§e搜索类型:', ['物品', '店铺或店主'], 0);
  
  player.sendForm(form, (pl, data) => {
    if(!data) return;
    const newKeyword = data[0]?.trim() || "";
    const searchType = data[1];
    const isItemSearch = searchType === 0;
    
    showShoppingCenter(pl, 1, newKeyword, isItemSearch);
  });
}

function showShopItems(player, shop, page, keyword, categoryFilter = "全部"){
  if(!shop){
    player.tell('§c§l无法获取店铺信息！');
    return;
  }
  PAGE_SIZE = config.get("pageSizeLimit") || 30;
  let shopItemKeys = getSortedShopItemKeys(shop);
  if(shopItemKeys.length===0){
    player.tell('§c§l该店铺暂无物品出售。');
    return;
  }
  if(keyword && keyword.trim()!==""){
    const lowKey=keyword.toLowerCase();
    shopItemKeys=shopItemKeys.filter(k=>{
      const it=shop.items[k];
      return (it.name.toLowerCase().includes(lowKey)||
              (it.remark&&it.remark.toLowerCase().includes(lowKey)));
    });
  }
  
  if(config.get('enableItemCategories') && categoryFilter !== "全部"){
    shopItemKeys = shopItemKeys.filter(k => {
      const it = shop.items[k];
      return it.category === categoryFilter;
    });
  }

  const totalItems=shopItemKeys.length;
  const totalPages=Math.ceil(totalItems/PAGE_SIZE);
  if(page<1) page=1;
  if(page>totalPages && totalPages>0) page=totalPages;
  const start=(page-1)*PAGE_SIZE;
  const end=start+PAGE_SIZE;
  const currentKeys=shopItemKeys.slice(start,end);
  const form=mc.newSimpleForm();
  form.setTitle(`§b§l店铺：${shop.name} §r- 第${page}页 / 共${totalPages}页`);
  
  let headerContent = "";
  const xuid = shop.ownerXuid;
  const sales = rankingData[xuid]?.salesCount || 0;
  const earnings = rankingData[xuid]?.totalEarnings || 0;
  let totalItemsCount = 0;
  for (const key in shop.items) {
    const item = shop.items[key];
    totalItemsCount += (item.quantity === -1) ? 0 : item.quantity;
  }
  
  headerContent += `§e店主: §b${shop.owner} §3(Lv.${shop.shopLevel})§e | 物品: §b${Object.keys(shop.items).length}/${shop.maxItemTypes}件\n`;
  headerContent += `§e总销量: §b${sales} §e| 总收入: §b${earnings}\n`;
  
  if (shop.announcement) {
    headerContent += `§d店铺公告: §f${shop.announcement}\n`;
  }
  
  headerContent += `\n§e搜索关键字:§f${keyword}\n§f(每页最多${PAGE_SIZE}项)\n请选择要购买的物品：`;
  
  form.setContent(headerContent);
  
  let buttonIndex = 0;
  const RETURN_BUTTON = buttonIndex++;
  form.addButton('§c返回上一页','textures/ui/icon_import');
  
  let hasPrev=(page>1), hasNext=(page<totalPages);
  let PREV_BUTTON = -1, NEXT_BUTTON = -1, SEARCH_BUTTON = -1;
  
  if(hasPrev){
    PREV_BUTTON = buttonIndex++;
    form.addButton('§a<< 上一页','textures/ui/icon_import');
  }
  if(hasNext){
    NEXT_BUTTON = buttonIndex++;
    form.addButton('§a下一页 >>','textures/ui/share_microsoft');
  }
  
  SEARCH_BUTTON = buttonIndex++;
  form.addButton('§a搜索物品','textures/ui/magnifyingGlass');
  
  let CATEGORY_BUTTON = -1;
  if(config.get('enableItemCategories')){
    CATEGORY_BUTTON = buttonIndex++;
    form.addButton(`§b分类筛选: ${categoryFilter}`,'textures/ui/recipe_book_icon');
  }
  
  const ITEMS_START = buttonIndex;
  
  currentKeys.forEach(k=>{
    const it=shop.items[k];
    const tmp=safeNewItem(it.itemData);
    const show=getItemDisplayName(tmp,false);
    let tx=JSON.parse(textureData.read());
    let icon= (tx.hasOwnProperty(tmp.type)&&tx[tmp.type]&&tx[tmp.type]!=='null')
      ? tx[tmp.type] : default_icon_path;
    
    let priceDisplay = it.price.toString();
    if (it.discount && it.originalPrice) {
      const endTime = new Date(it.discountEndTime);
      const remainMinutes = Math.max(0, Math.floor((it.discountEndTime - Date.now()) / 60000));
      priceDisplay = `§c${it.price}§f(${it.discount}折 原价:${it.originalPrice} 剩余:${remainMinutes}分钟)`;
    }
    
    form.addButton(`§s${show}\n§s库存: ${it.quantity} | 价格: ${priceDisplay}`, icon);
  });
  
  player.sendForm(form,(pl,id)=>{
    if(id==null)return;
    
    if(id===RETURN_BUTTON){
      showShoppingCenter(pl,1,"",false);
      return;
    }
    
    if(hasPrev && id===PREV_BUTTON){
      showShopItems(pl,shop,page-1,keyword,categoryFilter);
      return;
    }
    
    if(hasNext && id===NEXT_BUTTON){
      showShopItems(pl,shop,page+1,keyword,categoryFilter);
      return;
    }
    
    if(id===SEARCH_BUTTON){
      showItemSearchForm(pl,shop,page,keyword);
      return;
    }
    
    if(config.get('enableItemCategories') && CATEGORY_BUTTON !== -1 && id === CATEGORY_BUTTON){
      showCategorySelectMenu(pl, shop, page, keyword, categoryFilter);
      return;
    }
    
    const itemIndex=id-ITEMS_START;
    if(itemIndex<0||itemIndex>=currentKeys.length){
      pl.tell('§c选择无效!');
      return;
    }
    const selectedKey=currentKeys[itemIndex];
    const shopItem=shop.items[selectedKey];
    confirmPurchase(pl, shop, selectedKey, shopItem, false);
  });
}

function showCategorySelectMenu(player, shop, page, keyword, currentCategory){
  const categories = config.get('itemCategories') || ["全部"];
  const form = mc.newSimpleForm();
  form.setTitle("§b§l选择分类");
  form.setContent(`§e当前分类: §a${currentCategory}`);
  addReturnButton(form);
  
  categories.forEach(cat => {
    const isSelected = cat === currentCategory;
    const itemCount = Object.values(shop.items).filter(item => cat === "全部" || item.category === cat).length;
    form.addButton(`${isSelected ? "§a" : "§f"}${cat} §3(${itemCount}件)`, 'textures/ui/recipe_book_icon');
  });
  
  player.sendForm(form, (pl, id) => {
    if(id === null) return;
    if(id === 0){
      showShopItems(pl, shop, page, keyword, currentCategory);
      return;
    }
    
    const selectedCategory = categories[id - 1];
    showShopItems(pl, shop, 1, keyword, selectedCategory);
  });
}

function showItemSearchForm(player, shop, page, keyword){
  const form=mc.newCustomForm();
  form.setTitle('§a搜索物品');
  form.addInput('§e搜索关键字(物品名/备注):','关键字',keyword);
  player.sendForm(form,(pl,data)=>{
    if(!data)return;
    const newKey=data[0]?.trim()||"";
    showShopItems(pl,shop,1,newKey);
  });
}

function confirmPurchase(player, shop, itemKey, shopItem, isOfficial){
  const economy=getEconomyInterface();
  const isSelfPurchase = !isOfficial && player.xuid === shop.ownerXuid;
  
  if (isSelfPurchase && !config.get('allowSelfPurchase')) {
    player.tell("§c§l当前服务器不允许购买自己店铺的物品！");
    return;
  }
  
  if (isOfficial) {
    if (!officialShopData.purchaseItems[itemKey]) {
      player.tell("§c该物品已下架，购买失败！");
      return;
    }
  } else {
    const currentShop = shopsData[shop.ownerXuid];
    if (!currentShop?.items?.[itemKey]) {
      player.tell("§c该物品已下架，购买失败！");
      return;
    }
    shopItem = currentShop.items[itemKey]; 
  }

  const tmp=safeNewItem(NBT.parseSNBT(shopItem.itemData));
  const shopItemName = isOfficial && shopItem.displayName ? 
                      shopItem.displayName : 
                      (shopItem.name || getItemDisplayName(tmp, false));
  
  const form=mc.newCustomForm();
  form.setTitle('§a§l确认购买');
  form.addLabel(`§e§l物品名称:§a${shopItemName}\n§s最大堆叠:${tmp.maxStackSize} §r|§9 附魔:${tmp.isEnchanted?'§a已附魔§f':'§a无附魔§f'}\n§3自定义名:${getItemCustomNameFromNBT(tmp)||'暂无命名'}`);
  const itemLore = tmp.lore;
  if(itemLore && itemLore.length > 0){
    form.addLabel(`§d§l物品描述:\n§f${itemLore.join('\n')}`);
  }
  form.addLabel(`§e§l剩余数量:§a${shopItem.quantity===-1?'无限':shopItem.quantity}`);
  let taxInfo = "";
  if(!isSelfPurchase && config.get('enableTaxSystem')){
    const taxRate = config.get('taxRate') || 0;
    const taxOnlyOfficial = config.get('taxOnlyOfficialShop');
    const shouldApplyTax = taxOnlyOfficial ? isOfficial : true;
    if(taxRate > 0 && shouldApplyTax){
      taxInfo = ` §c(+${(taxRate*100).toFixed(1)}%税)`;
    }
  }
  form.addLabel(`§e§l价格:§3${shopItem.price}§f(每个)` + taxInfo + (isSelfPurchase ? " §c(自购免费)" : ""));
  if(shopItem.remark) form.addLabel(`§e§l备注:${shopItem.remark}`);
  form.addInput('§e§l请输入购买数量:','数字','1');
  if (config.get('enableGiftSystem') && !isSelfPurchase) {
    form.addSwitch('§3§l为朋友购买 §e(礼物功能)', false);
  }
  player.sendForm(form,(pl,data)=>{
    if(!data)return;
    if (isOfficial) {
      if (!officialShopData.purchaseItems[itemKey]) {
        pl.tell("§c该物品已下架，购买失败！");
        return;
      }
    } else {
      const currentShop = shopsData[shop.ownerXuid];
      if (!currentShop?.items?.[itemKey]) {
        pl.tell("§c该物品已下架，购买失败！");
        return;
      }
    }
    const hasGiftSwitch = config.get('enableGiftSystem') && !isSelfPurchase;
    const qtyIndex = (shopItem.remark?4:3);
    const giftIndex = hasGiftSwitch ? qtyIndex + 1 : -1;
    const qty=parseInt(data[qtyIndex]);
    const isGift = hasGiftSwitch ? data[giftIndex] : false;
    
    if(isNaN(qty)||qty<=0){pl.tell('§c§l购买数量必须正整数！');return;}
    if(shopItem.quantity!==-1 && qty>shopItem.quantity){pl.tell('§c§l库存不足！');return;}
    
    if (isGift) {
      showGiftPlayerSelection(pl, shop, itemKey, shopItem, isOfficial, qty);
      return;
    }
    
    let totalPrice=shopItem.price*qty;
    let taxAmount = 0;
    let finalPrice = totalPrice;
    
    if(!isSelfPurchase && config.get('enableTaxSystem')){
      const taxRate = config.get('taxRate') || 0;
      const taxOnlyOfficial = config.get('taxOnlyOfficialShop');
      const shouldApplyTax = taxOnlyOfficial ? isOfficial : true;
      if(taxRate > 0 && shouldApplyTax){
        taxAmount = Math.floor(totalPrice * taxRate);
        finalPrice = totalPrice + taxAmount;
      }
    }
    
    if(!isSelfPurchase && economy.get(pl)<finalPrice){
      pl.tell(`§c§l余额不足！需${finalPrice}${economy.name}（含税${taxAmount}），当前:${economy.get(pl)}`);
      return;
    }
    const nbt=NBT.parseSNBT(shopItem.itemData);
    
    if(!canPlayerReceiveItem(pl,nbt,qty)){
      pl.tell('§c§l背包空间不足!');
      return;
    }
    
    if(!isSelfPurchase) {
      economy.reduce(pl,finalPrice);
      if(taxAmount > 0){
        recordTaxCollection(pl.xuid, taxAmount, shopItem.name);
      }
    }
    
    let ok=distributeItemsToPlayer(pl,nbt,qty);
    if(!ok){
      if(!isSelfPurchase) {
        economy.add(pl,finalPrice);
        if(taxAmount > 0){
          pl.tell('§c§l物品分发失败！已退还费用和税费！');
        } else {
          pl.tell('§c§l物品分发失败！已退还费用！');
        }
      }
      return;
    }
    
    if(isOfficial){
      if(shopItem.quantity!==-1){
        shopItem.quantity-=qty;
        if(shopItem.quantity<=0){
          delete officialShopData.purchaseItems[itemKey];
        }
        saveOfficialShopData();
      }
    } else {
      if(!isSelfPurchase) {
        const sellerXuid=shop.ownerXuid;
        const sp=mc.getPlayer(sellerXuid);
        if(sp){
          economy.add(sp,totalPrice);
          sp.tell(`§a§l店铺售出 §d${shopItem.name} x${qty}, 获得${totalPrice} ${economy.name}`);
          sp.sendToast("§a店铺销售", `售出 ${shopItem.name} x${qty}`);
        } else {
          shop.pendingEarnings=(shop.pendingEarnings||0)+totalPrice;
        }
        addSales(sellerXuid, qty);
        addEarnings(sellerXuid, totalPrice);
      }
      
      if(shopItem.quantity!==-1){
        shopItem.quantity-=qty;
        if(shopItem.quantity<=0){
          delete shop.items[itemKey];
        }
      }
      saveShopsData();
    }
    if(!isSelfPurchase) {
      logPurchase(pl, shop, shopItem, qty, isOfficial);
    }
    if (isSelfPurchase) {
      pl.sendToast("§a自购成功", `获得 ${shopItem.name} x${qty}`);
    } else {
      pl.sendToast("§a购买成功", `获得 ${shopItem.name} x${qty}，支付 ${finalPrice}${economy.name}`);
    }
    
    pl.tell(`§a§l购买成功！获得 §d${shopItem.name} x${qty}`);
    if(!isSelfPurchase) {
      if(taxAmount > 0){
        pl.tell(`§e已扣除 ${finalPrice} ${economy.name} (含税 ${taxAmount}), 余额:${economy.get(pl)}`);
      } else {
        pl.tell(`§e已扣除 ${totalPrice} ${economy.name}, 余额:${economy.get(pl)}`);
      }
    } else {
      pl.tell(`§e自己店铺的物品，不收取费用，不计入销量！`);
    }
  });
}

function showGiftPlayerSelection(player, shop, itemKey, shopItem, isOfficial, qty) {
  const form = mc.newSimpleForm();
  form.setTitle('§3§l选择礼物接收者');
  form.setContent('§e请选择要送礼的玩家:');
  
  form.addButton('§a在线玩家\n§f当前在线的玩家', 'textures/ui/multiplayer_glyph_color');
  form.addButton('§b模糊搜索\n§f搜索所有玩家（支持离线）', 'textures/ui/magnifyingGlass');
  form.addButton('§c取消', 'textures/ui/cancel');
  
  player.sendForm(form, (pl, id) => {
    if (id === null || id === 2) {
      confirmPurchase(pl, shop, itemKey, shopItem, isOfficial);
      return;
    }
    
    if (id === 0) {
      showOnlinePlayersForGift(pl, shop, itemKey, shopItem, isOfficial, qty);
    } else if (id === 1) {
      showSearchPlayerForGift(pl, shop, itemKey, shopItem, isOfficial, qty);
    }
  });
}

function showOnlinePlayersForGift(player, shop, itemKey, shopItem, isOfficial, qty) {
  const onlinePlayers = mc.getOnlinePlayers();
  const availablePlayers = onlinePlayers.filter(p => p.xuid !== player.xuid);
  
  if (availablePlayers.length === 0) {
    player.tell('§c当前没有其他在线玩家！');
    showGiftPlayerSelection(player, shop, itemKey, shopItem, isOfficial, qty);
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle('§a§l选择在线玩家');
  form.setContent('§e请选择要送礼的在线玩家:');
  
  availablePlayers.forEach(p => {
    form.addButton(`§b${p.realName}`, 'textures/ui/Friend1');
  });
  form.addButton('§c返回', 'textures/ui/arrow_dark_left_stretch');
  
  player.sendForm(form, (pl, id) => {
    if (id === null || id === availablePlayers.length) {
      showGiftPlayerSelection(pl, shop, itemKey, shopItem, isOfficial, qty);
      return;
    }
    
    const selectedPlayer = availablePlayers[id];
    confirmGiftPurchase(pl, selectedPlayer, shop, itemKey, shopItem, isOfficial, qty);
  });
}

function showSearchPlayerForGift(player, shop, itemKey, shopItem, isOfficial, qty) {
  const form = mc.newCustomForm();
  form.setTitle('§b§l模糊搜索玩家');
  form.addLabel('§e输入玩家名称的部分字符进行搜索:\n§f支持模糊匹配，输入1个字母即可搜索');
  form.addInput('§e搜索关键字:', '输入关键字', '');
  
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showGiftPlayerSelection(pl, shop, itemKey, shopItem, isOfficial, qty);
      return;
    }
    
    const keyword = data[1]?.trim();
    if (!keyword) {
      pl.tell('§c请输入搜索关键字！');
      showSearchPlayerForGift(pl, shop, itemKey, shopItem, isOfficial, qty);
      return;
    }
    
    if (keyword.length < 1) {
      pl.tell('§c关键字至少需要1个字符！');
      showSearchPlayerForGift(pl, shop, itemKey, shopItem, isOfficial, qty);
      return;
    }
    
    const searchResults = searchPlayersByName(keyword);
    
    if (searchResults.length === 0) {
      pl.tell(`§c未找到包含"${keyword}"的玩家！`);
      showSearchPlayerForGift(pl, shop, itemKey, shopItem, isOfficial, qty);
      return;
    }
    
    showPlayerSearchResults(pl, searchResults, keyword, shop, itemKey, shopItem, isOfficial, qty);
  });
}

function showPlayerSearchResults(player, results, keyword, shop, itemKey, shopItem, isOfficial, qty) {
  const form = mc.newSimpleForm();
  form.setTitle(`§a§l搜索结果: ${keyword}`);
  form.setContent(`§e找到 ${results.length} 个匹配的玩家：`);
  
  form.addButton('§c返回搜索', 'textures/ui/arrow_dark_left_stretch');
  
  results.forEach(result => {
    const onlinePlayer = mc.getPlayer(result.xuid);
    const statusText = onlinePlayer ? '§a在线' : '§3离线';
    const lastSeenText = onlinePlayer ? '' : ` §f(${getTimeAgo(result.lastSeen)}前活跃)`;
    
    let displayText = `§b${result.name} ${statusText}${lastSeenText}`;
    if (!result.isCurrentName && result.historyName) {
      displayText += `\n§3曾用名: ${result.historyName}`;
    }
    
    form.addButton(displayText, 'textures/ui/Friend1');
  });
  
  player.sendForm(form, (pl, id) => {
    if (id === null) {
      showGiftPlayerSelection(pl, shop, itemKey, shopItem, isOfficial, qty);
      return;
    }
    
    if (id === 0) {
      showSearchPlayerForGift(pl, shop, itemKey, shopItem, isOfficial, qty);
      return;
    }
    
    const selectedResult = results[id - 1];
    if (!selectedResult) return;
    
    if (selectedResult.xuid === pl.xuid) {
      pl.tell('§c不能给自己送礼！');
      showPlayerSearchResults(pl, results, keyword, shop, itemKey, shopItem, isOfficial, qty);
      return;
    }
    
    const targetPlayer = mc.getPlayer(selectedResult.xuid);
    if (targetPlayer) {
      confirmGiftPurchase(pl, targetPlayer, shop, itemKey, shopItem, isOfficial, qty);
    } else {
      confirmOfflineGiftPurchase(pl, selectedResult.name, shop, itemKey, shopItem, isOfficial, qty);
    }
  });
}

function confirmGiftPurchase(buyer, recipient, shop, itemKey, shopItem, isOfficial, qty) {
  const economy = getEconomyInterface();
  const tmp = safeNewItem(NBT.parseSNBT(shopItem.itemData));
  const shopItemName = isOfficial && shopItem.displayName ? 
                      shopItem.displayName : 
                      (shopItem.name || getItemDisplayName(tmp, false));
  
  let totalPrice = shopItem.price * qty;
  let taxAmount = 0;
  let finalPrice = totalPrice;
  
  if (config.get('enableTaxSystem')) {
    const taxRate = config.get('taxRate') || 0;
    const taxOnlyOfficial = config.get('taxOnlyOfficialShop');
    const shouldApplyTax = taxOnlyOfficial ? isOfficial : true;
    if (taxRate > 0 && shouldApplyTax) {
      taxAmount = Math.floor(totalPrice * taxRate);
      finalPrice = totalPrice + taxAmount;
    }
  }
  
  const form = mc.newSimpleForm();
  form.setTitle('§3§l确认礼物购买');
  
  let content = `§e您即将为 §b${recipient.realName} §e购买礼物:\n\n` +
                `§a${shopItemName} §fx${qty}\n\n` +
                `§e单价: §a${shopItem.price} ${economy.name}\n` +
                `§e总价: §a${finalPrice} ${economy.name}`;
  
  if (taxAmount > 0) {
    content += ` §c(含税 ${taxAmount})`;
  }
  
  content += `\n\n§c确认购买？物品将直接送给接收者。`;
  
  form.setContent(content);
  form.addButton('§c取消', 'textures/ui/cancel');
  form.addButton('§a确认购买', 'textures/ui/confirm');
  
  buyer.sendForm(form, (pl, id) => {
    if (id === null || id === 0) {
      showGiftPlayerSelection(pl, shop, itemKey, shopItem, isOfficial, qty);
      return;
    }
    
    if (id === 1) {
      processGiftPurchase(pl, recipient, shop, itemKey, shopItem, isOfficial, qty, finalPrice, taxAmount, totalPrice);
    }
  });
}

function confirmOfflineGiftPurchase(buyer, recipientName, shop, itemKey, shopItem, isOfficial, qty) {
  const economy = getEconomyInterface();
  const tmp = safeNewItem(NBT.parseSNBT(shopItem.itemData));
  const shopItemName = isOfficial && shopItem.displayName ? 
                      shopItem.displayName : 
                      (shopItem.name || getItemDisplayName(tmp, false));
  
  let totalPrice = shopItem.price * qty;
  let taxAmount = 0;
  let finalPrice = totalPrice;
  
  if (config.get('enableTaxSystem')) {
    const taxRate = config.get('taxRate') || 0;
    const taxOnlyOfficial = config.get('taxOnlyOfficialShop');
    const shouldApplyTax = taxOnlyOfficial ? isOfficial : true;
    if (taxRate > 0 && shouldApplyTax) {
      taxAmount = Math.floor(totalPrice * taxRate);
      finalPrice = totalPrice + taxAmount;
    }
  }
  
  const form = mc.newSimpleForm();
  form.setTitle('§3§l确认离线礼物购买');
  
  let content = `§e您即将为 §b${recipientName} §e购买礼物:\n\n` +
                `§a${shopItemName} §fx${qty}\n\n` +
                `§e单价: §a${shopItem.price} ${economy.name}\n` +
                `§e总价: §a${finalPrice} ${economy.name}`;
  
  if (taxAmount > 0) {
    content += ` §c(含税 ${taxAmount})`;
  }
  
  content += `\n\n§e§l注意：\n§f- 玩家当前不在线\n§f- 物品将直接存入其仓库\n§f- 下次上线时会收到通知\n\n§c确认购买？`;
  
  form.setContent(content);
  form.addButton('§c取消', 'textures/ui/cancel');
  form.addButton('§a确认购买', 'textures/ui/confirm');
  
  buyer.sendForm(form, (pl, id) => {
    if (id === null || id === 0) {
      showGiftPlayerSelection(pl, shop, itemKey, shopItem, isOfficial, qty);
      return;
    }
    
    if (id === 1) {
      const totalPriceWithoutTax = shopItem.price * qty;
      processOfflineGiftPurchase(pl, recipientName, shop, itemKey, shopItem, isOfficial, qty, finalPrice, taxAmount, totalPriceWithoutTax);
    }
  });
}

function processOfflineGiftPurchase(buyer, recipientName, shop, itemKey, shopItem, isOfficial, qty, finalPrice, taxAmount, totalPrice) {
  const economy = getEconomyInterface();
  
  if (economy.get(buyer) < finalPrice) {
    buyer.tell(`§c§l余额不足！需 ${finalPrice} ${economy.name}（含税 ${taxAmount}），当前: ${economy.get(buyer)}`);
    return;
  }
  
  economy.reduce(buyer, finalPrice);
  if (taxAmount > 0) {
    recordTaxCollection(buyer.xuid, taxAmount, shopItem.name);
  }
  
  if (isOfficial) {
    if (shopItem.quantity !== -1) {
      shopItem.quantity -= qty;
      if (shopItem.quantity <= 0) {
        delete officialShopData.purchaseItems[itemKey];
      }
      saveOfficialShopData();
    }
  } else {
    const sellerXuid = shop.ownerXuid;
    const sp = mc.getPlayer(sellerXuid);
    if (sp) {
      economy.add(sp, totalPrice);
      sp.tell(`§a§l店铺售出 §d${shopItem.name} x${qty}§a，获得 ${totalPrice} ${economy.name} §3(离线礼物交易)`);
      sp.sendToast("§a店铺销售", `售出 ${shopItem.name} x${qty} (离线礼物)`);
    } else {
      shop.pendingEarnings = (shop.pendingEarnings || 0) + totalPrice;
    }
    addSales(sellerXuid, qty);
    addEarnings(sellerXuid, totalPrice);
    
    if (shopItem.quantity !== -1) {
      shopItem.quantity -= qty;
      if (shopItem.quantity <= 0) {
        delete shop.items[itemKey];
      }
    }
    saveShopsData();
  }
  
  const recipientXuid = getPlayerXuidByName(recipientName);
  if (recipientXuid) {
    const warehouseSuccess = addItemToWarehouse(recipientXuid, recipientName, shopItem.itemData, qty, `来自 ${buyer.realName} 的礼物`, true);
    if (!warehouseSuccess) {
      economy.add(buyer, finalPrice);
      if (taxAmount > 0) {
        recordTaxCollection(buyer.xuid, -taxAmount, shopItem.name);
      }
      buyer.tell(`§c§l送礼失败！§e物品存储失败，已退款。`);
      return;
    }
    buyer.tell(`§a§l礼物已送达！§e${recipientName} §a的礼物已存入其仓库，下次上线时会收到通知。`);
  } else {
    economy.add(buyer, finalPrice);
    if (taxAmount > 0) {
      recordTaxCollection(buyer.xuid, -taxAmount, shopItem.name);
    }
    buyer.tell(`§c§l送礼失败！§e玩家 ${recipientName} 不存在，已退款。`);
    return;
  }
  
  buyer.sendToast("§a礼物已送出", `给 ${recipientName}: ${shopItem.name} x${qty}`);
  
  addGiftRecord(buyer.xuid, buyer.realName, recipientXuid, recipientName, shopItem.name, qty, finalPrice, true);
  
  logOfflineGiftPurchase(buyer, recipientName, recipientXuid, shop, shopItem, qty, isOfficial, finalPrice);
  
  if (taxAmount > 0) {
    buyer.tell(`§e已扣除 ${finalPrice} ${economy.name} (含税 ${taxAmount})，余额: ${economy.get(buyer)}`);
  } else {
    buyer.tell(`§e已扣除 ${totalPrice} ${economy.name}，余额: ${economy.get(buyer)}`);
  }
}

function getPlayerXuidByName(playerName) {
  for (const xuid in playerRecords) {
    const record = playerRecords[xuid];
    if (record.name === playerName) {
      return xuid;
    }
    if (record.nameHistory && record.nameHistory.includes(playerName)) {
      return xuid;
    }
  }
  
  for (const xuid in shopsData) {
    const shop = shopsData[xuid];
    if (shop.owner === playerName) {
      return xuid;
    }
  }
  
  for (const xuid in warehouseData) {
    const warehouse = warehouseData[xuid];
    if (warehouse.playerName === playerName) {
      return xuid;
    }
  }
  
  if (rankingData) {
    for (const xuid in rankingData) {
      const data = rankingData[xuid];
      if (data.playerName === playerName) {
        return xuid;
      }
    }
  }
  
  return null;
}

function logOfflineGiftPurchase(buyer, recipientName, recipientXuid, shop, shopItem, qty, isOfficial, finalPrice) {
  const buyerName = buyer.realName;
  const buyerXuid = buyer.xuid;
  let sellerName = "官方商店";
  let sellerXuid = "OFFICIAL";
  let shopName = "官方商店";
  
  if (!isOfficial && shop) {
    sellerName = shop.owner;
    sellerXuid = shop.ownerXuid;
    shopName = shop.name;
  }
  
  const itemName = shopItem.name;
  const priceEach = shopItem.price;
  const timeNow = new Date().toLocaleString();
  
  const record = {
    buyerName,
    buyerXuid,
    recipientName,
    recipientXuid,
    sellerName,
    sellerXuid,
    shopName,
    itemName,
    quantity: qty,
    priceEach,
    totalPrice: finalPrice,
    time: timeNow,
    isGift: true,
    isOfflineGift: true
  };
  
  if (!purchaseLogs.global) purchaseLogs.global = [];
  purchaseLogs.global.push(record);
  if (purchaseLogs.global.length > 30) {
    purchaseLogs.global.shift();
  }
  
  if (!purchaseLogs.players) purchaseLogs.players = {};
  if (!purchaseLogs.players[buyerXuid]) {
    purchaseLogs.players[buyerXuid] = { buy: [], sell: [] };
  }
  purchaseLogs.players[buyerXuid].buy.push(record);
  if (purchaseLogs.players[buyerXuid].buy.length > 30) {
    purchaseLogs.players[buyerXuid].buy.shift();
  }
  
  if (!isOfficial && sellerXuid !== buyerXuid && sellerXuid !== "OFFICIAL") {
    if (!purchaseLogs.players[sellerXuid]) {
      purchaseLogs.players[sellerXuid] = { buy: [], sell: [] };
    }
    purchaseLogs.players[sellerXuid].sell.push(record);
    if (purchaseLogs.players[sellerXuid].sell.length > 30) {
      purchaseLogs.players[sellerXuid].sell.shift();
    }
  }
  
  savePurchaseLogs();
}

function processGiftPurchase(buyer, recipient, shop, itemKey, shopItem, isOfficial, qty, finalPrice, taxAmount, totalPrice) {
  const economy = getEconomyInterface();
  
  if (economy.get(buyer) < finalPrice) {
    buyer.tell(`§c§l余额不足！需 ${finalPrice} ${economy.name}（含税 ${taxAmount}），当前: ${economy.get(buyer)}`);
    return;
  }
  
  const nbt = NBT.parseSNBT(shopItem.itemData);
  if (!canPlayerReceiveItem(recipient, nbt, qty)) {
    buyer.tell(`§c§l礼物购买失败！接收者 §b${recipient.realName} §c的背包空间不足！`);
    return;
  }
  
  economy.reduce(buyer, finalPrice);
  if (taxAmount > 0) {
    recordTaxCollection(buyer.xuid, taxAmount, shopItem.name);
  }
  
  if (isOfficial) {
    if (shopItem.quantity !== -1) {
      shopItem.quantity -= qty;
      if (shopItem.quantity <= 0) {
        delete officialShopData.purchaseItems[itemKey];
      }
      saveOfficialShopData();
    }
  } else {
    const sellerXuid = shop.ownerXuid;
    const sp = mc.getPlayer(sellerXuid);
    if (sp) {
      economy.add(sp, totalPrice);
      sp.tell(`§a§l店铺售出 §d${shopItem.name} x${qty}§a，获得 ${totalPrice} ${economy.name} §3(礼物交易)`);
      sp.sendToast("§a店铺销售", `售出 ${shopItem.name} x${qty} (礼物)`);
    } else {
      shop.pendingEarnings = (shop.pendingEarnings || 0) + totalPrice;
    }
    addSales(sellerXuid, qty);
    addEarnings(sellerXuid, totalPrice);
    
    if (shopItem.quantity !== -1) {
      shopItem.quantity -= qty;
      if (shopItem.quantity <= 0) {
        delete shop.items[itemKey];
      }
    }
    saveShopsData();
  }
  
  const success = giveItemToPlayer(recipient, shopItem.itemData, qty);
  if (!success) {
    const warehouseSuccess = addItemToWarehouse(recipient.xuid, recipient.realName, shopItem.itemData, qty, `来自 ${buyer.realName} 的礼物`, true);
    if (!warehouseSuccess) {
      economy.add(buyer, finalPrice);
      if (taxAmount > 0) {
        recordTaxCollection(buyer.xuid, -taxAmount, shopItem.name);
      }
      buyer.tell(`§c§l送礼失败！§e物品存储失败，已退款。`);
      return;
    }
    recipient.tell(`§3§l收到礼物！§a来自 §b${buyer.realName} §a的 §d${shopItem.name} x${qty} §a已存入仓库！使用 §e/smck §a查看。`);
    buyer.tell(`§a§l礼物已送达！§e${recipient.realName} §a的背包已满，物品已存入其仓库。`);
  } else {
    recipient.tell(`§3§l收到礼物！§a来自 §b${buyer.realName} §a的 §d${shopItem.name} x${qty} §a已添加到背包！`);
    buyer.tell(`§a§l礼物已送达！§e${recipient.realName} §a已收到您的礼物。`);
  }
  
  recipient.sendToast("§3收到礼物", `来自 ${buyer.realName}: ${shopItem.name} x${qty}`);
  buyer.sendToast("§a礼物已送出", `给 ${recipient.realName}: ${shopItem.name} x${qty}`);
  
  addGiftRecord(buyer.xuid, buyer.realName, recipient.xuid, recipient.realName, shopItem.name, qty, finalPrice, false);
  
  logGiftPurchase(buyer, recipient, shop, shopItem, qty, isOfficial, finalPrice);
  
  if (taxAmount > 0) {
    buyer.tell(`§e已扣除 ${finalPrice} ${economy.name} (含税 ${taxAmount})，余额: ${economy.get(buyer)}`);
  } else {
    buyer.tell(`§e已扣除 ${totalPrice} ${economy.name}，余额: ${economy.get(buyer)}`);
  }
}

function giveItemToPlayer(player, nbtData, quantity) {
  try {
    if (!nbtData || !player) {
      return false;
    }
    
    let nbt;
    if (typeof nbtData === 'string') {
      if (!nbtData.startsWith('{')) {
        return false;
      }
      nbt = NBT.parseSNBT(nbtData);
    } else {
      nbt = nbtData;
    }
    
    if (!nbt) {
      return false;
    }
    
    return distributeItemsToPlayer(player, nbt, quantity);
  } catch (e) {
    return false;
  }
}

function hasWarehousePurchased(playerXuid) {
  return hasWarehouseAccess(playerXuid);
}



function addItemToWarehouse(playerXuid, playerName, nbtOrKey, quantity, description = "", isGift = false) {
  if (!warehouseData[playerXuid]) {
    warehouseData[playerXuid] = {
      playerName: playerName,
      items: [],
      purchased: false
    };
  }
  
  const maxSlots = config.get('maxWarehouseSlots') || 50;
  const currentItems = warehouseData[playerXuid].items.length;
  
  if (!isGift && currentItems >= maxSlots) {
    const player = mc.getPlayer(playerXuid);
    if (player) {
      player.tell(`§c§l仓库已满！当前容量：${currentItems}/${maxSlots}`);
    }
    return false;
  }
  
  let nbtString = nbtOrKey;
  if (typeof nbtOrKey === 'string' && nbtOrKey.startsWith('{')) {
    nbtString = nbtOrKey;
  } else if (typeof nbtOrKey === 'object' && nbtOrKey !== null) {
    if (typeof nbtOrKey.toSNBT === 'function') {
      try {
        nbtString = nbtOrKey.toSNBT();
      } catch(e) {
        log(`仓库NBT转换失败: ${e.message}`);
        return false;
      }
    } else if (typeof nbtOrKey.getNbt === 'function') {
      try {
        nbtString = nbtOrKey.getNbt().toSNBT();
      } catch(e) {
        log(`仓库物品NBT转换失败: ${e.message}`);
        return false;
      }
    } else {
      try {
        nbtString = nbtOrKey.toString();
      } catch(e) {
        log(`仓库对象转换字符串失败: ${e.message}`);
        return false;
      }
    }
  } else {
    nbtString = nbtOrKey;
  }
  
  const itemData = {
    itemData: nbtString,
    quantity: quantity,
    description: description,
    timestamp: Date.now(),
    id: Date.now().toString(36) + Math.random().toString(36).substr(2, 5)
  };
  
  warehouseData[playerXuid].items.push(itemData);
  saveWarehouseData();
  return true;
}

function logGiftPurchase(buyer, recipient, shop, shopItem, qty, isOfficial, finalPrice) {
  const buyerName = buyer.realName;
  const buyerXuid = buyer.xuid;
  const recipientName = recipient.realName;
  const recipientXuid = recipient.xuid;
  let sellerName = "官方商店";
  let sellerXuid = "OFFICIAL";
  let shopName = "官方商店";
  
  if (!isOfficial && shop) {
    sellerName = shop.owner;
    sellerXuid = shop.ownerXuid;
    shopName = shop.name;
  }
  
  const itemName = shopItem.name;
  const priceEach = shopItem.price;
  const timeNow = new Date().toLocaleString();
  
  const record = {
    buyerName,
    buyerXuid,
    recipientName,
    recipientXuid,
    sellerName,
    sellerXuid,
    shopName,
    itemName,
    quantity: qty,
    priceEach,
    totalPrice: finalPrice,
    time: timeNow,
    isGift: true
  };
  
  if (!purchaseLogs.global) purchaseLogs.global = [];
  purchaseLogs.global.push(record);
  if (purchaseLogs.global.length > 30) {
    purchaseLogs.global.shift();
  }
  
  if (!purchaseLogs.players) purchaseLogs.players = {};
  if (!purchaseLogs.players[buyerXuid]) {
    purchaseLogs.players[buyerXuid] = { buy: [], sell: [] };
  }
  purchaseLogs.players[buyerXuid].buy.push(record);
  if (purchaseLogs.players[buyerXuid].buy.length > 30) {
    purchaseLogs.players[buyerXuid].buy.shift();
  }
  
  if (!isOfficial && sellerXuid !== buyerXuid && sellerXuid !== "OFFICIAL") {
    if (!purchaseLogs.players[sellerXuid]) {
      purchaseLogs.players[sellerXuid] = { buy: [], sell: [] };
    }
    purchaseLogs.players[sellerXuid].sell.push(record);
    if (purchaseLogs.players[sellerXuid].sell.length > 30) {
      purchaseLogs.players[sellerXuid].sell.shift();
    }
  }
  
  savePurchaseLogs();
}

function showPlayerWarehouse(player) {
  if (!config.get('enableGiftSystem')) {
    player.tell('§c仓库功能已被管理员禁用！');
    return;
  }
  
  const mode = config.get('warehouseMode') || 0;
  const hasAccess = hasWarehouseAccess(player.xuid);
  
  if (!hasAccess && mode > 0) {
    showWarehousePurchaseMenu(player);
    return;
  }
  
  const playerData = warehouseData[player.xuid];
  const itemCount = playerData ? playerData.items.length : 0;
  const maxSlots = config.get('maxWarehouseSlots') || 50;
  
  let statusText = `§e欢迎使用个人仓库系统！\n\n§b当前状态：\n§f- 仓库物品：§a${itemCount}§f/§a${maxSlots}§f 种\n§f- 存储空间：§${itemCount === 0 ? 'c空' : itemCount >= maxSlots ? 'c满' : 'a可用'}`;
  
  if (mode === 1 && playerData && playerData.purchased) {
    statusText += `\n§f- 仓库状态：§a已永久购买`;
  } else if (mode === 2) {
    const remaining = getRemainingTime(player.xuid);
    if (remaining !== null) {
      const timeStr = formatTime(remaining);
      statusText += `\n§f- 剩余时间：§${remaining > 60000 ? 'a' : 'c'}${timeStr}`;
      
      if (remaining < 60000) {
        statusText += `\n§c§l⚠ 仓库即将到期！`;
      }
    }
  }
  
  statusText += `\n\n§a仓库功能：\n§f- 安全存储您的贵重物品\n§f- 自动保存收到的礼物\n§f- 支持批量管理操作`;
  
  const form = mc.newSimpleForm();
  form.setTitle('§3§l个人仓库中心');
  form.setContent(statusText);
  
  form.addButton(`§b我的仓库 §f(${itemCount}种物品)`, 'textures/ui/icon_steve');
  form.addButton('§a存入物品', 'textures/ui/icon_import');
  form.addButton('§3批量操作', 'textures/ui/backup_replace');
  form.addButton('§d礼物记录', 'textures/ui/comment');
  
  if (mode === 2) {
    form.addButton('§e续费仓库', 'textures/ui/MCoin');
  }
  
  form.addButton('§c关闭', 'textures/ui/cancel');
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    
    let buttonIndex = 0;
    
    if (id === buttonIndex++) {
      showWarehouseItemsList(pl);
    } else if (id === buttonIndex++) {
      showWarehouseDepositMenu(pl);
    } else if (id === buttonIndex++) {
      showWarehouseBatchOperations(pl);
    } else if (id === buttonIndex++) {
      showGiftRecords(pl);
    } else if (mode === 2 && id === buttonIndex++) {
      showWarehousePurchaseMenu(pl);
    }
  });
}

function showWarehousePurchaseMenu(player) {
  const mode = config.get('warehouseMode') || 0;
  const eco = getEconomyInterface();
  const playerData = warehouseData[player.xuid];
  const giftCount = playerData ? playerData.items.filter(item => item.description && typeof item.description === 'string' && item.description.indexOf('礼物') !== -1).length : 0;
  
  if (mode === 0) {
    showPlayerWarehouse(player);
    return;
  }
  
  const form = mc.newSimpleForm();
  
  if (mode === 1) {
    const buyoutPrice = config.get('warehouseBuyoutPrice') || 10000;
    form.setTitle('§3§l购买仓库');
    
    let content = `§e§l仓库功能需要购买后才能使用！\n\n`;
    content += `§a仓库功能包括：\n`;
    content += `§f- 安全存储您的贵重物品\n`;
    content += `§f- 主动存入/取出物品\n`;
    content += `§f- 批量管理操作\n`;
    content += `§f- 自动接收礼物\n\n`;
    content += `§b一次性购买价格：§e${buyoutPrice} ${eco.name}\n`;
    content += `§b您的余额：§e${eco.getMoney(player)} ${eco.name}\n\n`;
    
    if (giftCount > 0) {
      content += `§c§l注意：您有 §e${giftCount}§c§l 个礼物在仓库中等待领取！\n`;
      content += `§c§l购买仓库后即可正常管理这些物品。\n\n`;
    }
    
    form.setContent(content);
    
    if (giftCount > 0) {
      form.addButton('§b查看待领取礼物', 'textures/ui/icon_steve');
    }
    form.addButton(`§a永久购买仓库 §f(${buyoutPrice} ${eco.name})`, 'textures/ui/MCoin');
    form.addButton('§c暂不购买', 'textures/ui/cancel');
    
    player.sendForm(form, (pl, id) => {
      if (id === null) return;
      
      let buttonIndex = 0;
      if (giftCount > 0 && id === buttonIndex++) {
        showWarehouseGiftPreview(pl);
        return;
      }
      
      if (id === buttonIndex++) {
        confirmWarehousePurchase(pl);
      }
    });
  } else if (mode === 2) {
    const rentalPrice = config.get('warehouseRentalPrice') || 1;
    const minRental = config.get('warehouseMinRentalTime') || 60;
    
    form.setTitle('§3§l租用仓库');
    
    let content = `§e§l仓库功能需要租用后才能使用！\n\n`;
    content += `§a仓库功能包括：\n`;
    content += `§f- 安全存储您的贵重物品\n`;
    content += `§f- 主动存入/取出物品\n`;
    content += `§f- 批量管理操作\n`;
    content += `§f- 自动接收礼物\n\n`;
    content += `§b租赁价格：§e${rentalPrice} ${eco.name}/分钟\n`;
    content += `§b最低租用时间：§e${minRental}分钟\n`;
    content += `§b您的余额：§e${eco.getMoney(player)} ${eco.name}\n\n`;
    
    if (giftCount > 0) {
      content += `§c§l注意：您有 §e${giftCount}§c§l 个礼物在仓库中等待领取！\n`;
      content += `§c§l租用仓库后即可正常管理这些物品。\n\n`;
    }
    
    const remaining = getRemainingTime(player.xuid);
    if (remaining !== null && remaining > 0) {
      const timeStr = formatTime(remaining);
      content += `§e当前剩余时间：§a${timeStr}\n\n`;
    }
    
    form.setContent(content);
    
    if (giftCount > 0) {
      form.addButton('§b查看待领取礼物', 'textures/ui/icon_steve');
    }
    form.addButton('§a租用仓库', 'textures/ui/MCoin');
    form.addButton('§c暂不租用', 'textures/ui/cancel');
    
    player.sendForm(form, (pl, id) => {
      if (id === null) return;
      
      let buttonIndex = 0;
      if (giftCount > 0 && id === buttonIndex++) {
        showWarehouseGiftPreview(pl);
        return;
      }
      
      if (id === buttonIndex++) {
        showWarehouseRentalForm(pl);
      }
    });
  }
}

function showWarehouseRentalForm(player) {
  const rentalPrice = config.get('warehouseRentalPrice') || 1;
  const minRental = config.get('warehouseMinRentalTime') || 60;
  const eco = getEconomyInterface();
  
  const form = mc.newCustomForm();
  form.setTitle('§3§l租用仓库');
  form.addLabel(`§e仓库租赁价格：§a${rentalPrice} ${eco.name}/分钟\n§e最低租用时间：§a${minRental}分钟\n§e您的余额：§a${eco.getMoney(player)} ${eco.name}`);
  form.addInput('§e租用时间（分钟）：', `最少${minRental}分钟`, minRental.toString());
  
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showWarehousePurchaseMenu(pl);
      return;
    }
    
    const minutes = parseInt(data[1]);
    if (isNaN(minutes) || minutes < minRental) {
      pl.tell(`§c租用时间不能少于${minRental}分钟！`);
      showWarehouseRentalForm(pl);
      return;
    }
    
    confirmWarehouseRental(pl, minutes);
  });
}

function showWarehouseGiftPreview(player) {
  const playerData = warehouseData[player.xuid];
  
  if (!playerData || !playerData.items || playerData.items.length === 0) {
    player.tell('§c没有待领取的礼物！');
    showWarehousePurchaseMenu(player);
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle('§b§l待领取礼物预览');
  form.setContent('§e以下是您收到的礼物，购买仓库后可以正常管理：\n');
  
  playerData.items.forEach((item, index) => {
    try {
      const tmp = safeNewItem(NBT.parseSNBT(item.itemData));
      if (tmp && !tmp.isNull()) {
        const itemName = getItemDisplayName(tmp, false);
        const timeStr = new Date(item.timestamp).toLocaleString();
        const desc = item.description ? `\n§3${item.description}` : '';
        form.addButton(`§a${itemName} §fx${item.quantity}${desc}\n§3${timeStr}`, 'textures/ui/icon_setting');
      } else {
        const timeStr = new Date(item.timestamp).toLocaleString();
        const desc = item.description ? `\n§3${item.description}` : '';
        form.addButton(`§c未知物品 §fx${item.quantity}${desc}\n§3${timeStr}`, 'textures/ui/icon_setting');
      }
    } catch (e) {
      const timeStr = new Date(item.timestamp).toLocaleString();
      const desc = item.description ? `\n§3${item.description}` : '';
      form.addButton(`§c未知物品 §fx${item.quantity}${desc}\n§3${timeStr}`, 'textures/ui/icon_setting');
    }
  });
  
  form.addButton('§c返回购买页面', 'textures/ui/arrow_dark_left_stretch');
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === playerData.items.length) {
      showWarehousePurchaseMenu(pl);
    } else {
      pl.tell('§c请先购买仓库才能管理物品！');
      showWarehousePurchaseMenu(pl);
    }
  });
}

function showWarehouseItemsList(player) {
  const playerData = warehouseData[player.xuid];
  
  if (!playerData || !playerData.items || playerData.items.length === 0) {
    const form = mc.newSimpleForm();
    form.setTitle('§b§l我的仓库');
    form.setContent('§e您的仓库是空的！\n\n§a如何使用仓库：\n§f- 点击"存入物品"可以主动存储\n§f- 收到礼物时背包满会自动存入\n§f- 支持批量存取操作');
    
    form.addButton('§a存入物品', 'textures/ui/icon_import');
    form.addButton('§3批量操作', 'textures/ui/backup_replace');
    form.addButton('§c返回', 'textures/ui/arrow_dark_left_stretch');
    
    player.sendForm(form, (pl, id) => {
      if (id === null) return;
      
      switch (id) {
        case 0:
          showWarehouseDepositMenu(pl);
          break;
        case 1:
          showWarehouseBatchOperations(pl);
          break;
        case 2:
          showPlayerWarehouse(pl);
          break;
      }
    });
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle('§b§l我的仓库');
  form.setContent(`§e仓库物品：§a${playerData.items.length}§e/§a${config.get('maxWarehouseSlots') || 50}\n§f点击物品进行操作：`);
  
  playerData.items.forEach((item, index) => {
    try {
      const tmp = safeNewItem(NBT.parseSNBT(item.itemData));
      if (tmp && !tmp.isNull()) {
        const itemName = getItemDisplayName(tmp, false);
        const timeStr = new Date(item.timestamp).toLocaleString();
        const desc = item.description ? `\n§3${item.description}` : '';
        form.addButton(`§a${itemName} §fx${item.quantity}${desc}\n§3${timeStr}`, 'textures/ui/icon_setting');
      } else {
        const timeStr = new Date(item.timestamp).toLocaleString();
        const desc = item.description ? `\n§3${item.description}` : '';
        form.addButton(`§c未知物品 §fx${item.quantity}${desc}\n§3${timeStr}`, 'textures/ui/icon_setting');
      }
    } catch (e) {
      const timeStr = new Date(item.timestamp).toLocaleString();
      const desc = item.description ? `\n§3${item.description}` : '';
      form.addButton(`§c未知物品 §fx${item.quantity}${desc}\n§3${timeStr}`, 'textures/ui/icon_setting');
    }
  });
  
  form.addButton('§a存入物品', 'textures/ui/icon_import');
  form.addButton('§3批量操作', 'textures/ui/backup_replace');
  form.addButton('§c返回', 'textures/ui/arrow_dark_left_stretch');
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    
    const itemCount = playerData.items.length;
    if (id < itemCount) {
      showWarehouseItemOptions(pl, id);
    } else if (id === itemCount) {
      showWarehouseDepositMenu(pl);
    } else if (id === itemCount + 1) {
      showWarehouseBatchOperations(pl);
    } else if (id === itemCount + 2) {
      showPlayerWarehouse(pl);
    }
  });
}

function showWarehouseItemOptions(player, itemIndex) {
  const playerData = warehouseData[player.xuid];
  if (!playerData || !playerData.items || itemIndex >= playerData.items.length) {
    player.tell('§c物品不存在！');
    showWarehouseItemsList(player);
    return;
  }
  
  const item = playerData.items[itemIndex];
  let tmp, itemName;
  try {
    tmp = safeNewItem(NBT.parseSNBT(item.itemData));
    if (tmp && !tmp.isNull()) {
      itemName = getItemDisplayName(tmp, false);
    } else {
      itemName = "未知物品";
    }
  } catch (e) {
    itemName = "未知物品";
  }
  
  const form = mc.newCustomForm();
  form.setTitle('§3§l仓库物品操作');
  form.addLabel(`§e物品：§a${itemName} §fx${item.quantity}\n§e存入时间：§f${new Date(item.timestamp).toLocaleString()}\n§e描述：§f${item.description || '无'}`);
  form.addInput('§e提取数量（留空提取全部）：', '数字', '');
  
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showWarehouseItemsList(pl);
      return;
    }
    
    let withdrawAmount = parseInt(data[1]) || item.quantity;
    if (withdrawAmount <= 0 || withdrawAmount > item.quantity) {
      withdrawAmount = item.quantity;
    }
    
    const withdrawNbt = item.itemData;
    const success = giveItemToPlayer(pl, withdrawNbt, withdrawAmount);
    
    if (!success) {
      pl.tell('§c背包空间不足，无法提取物品！');
      showWarehouseItemsList(pl);
      return;
    }
    
    item.quantity -= withdrawAmount;
    if (item.quantity <= 0) {
      playerData.items.splice(itemIndex, 1);
    }
    
    saveWarehouseData();
    pl.tell(`§a已从仓库提取 §b${itemName} x${withdrawAmount}§a！`);
    pl.sendToast('§a仓库提取', `${itemName} x${withdrawAmount}`);
    
    showWarehouseItemsList(pl);
  });
}

function showWarehouseDepositMenu(player) {
  if (!hasWarehousePurchased(player.xuid)) {
    player.tell('§c请先购买仓库才能存入物品！');
    showWarehousePurchaseMenu(player);
    return;
  }
  
  const playerData = warehouseData[player.xuid];
  const currentSlots = playerData ? playerData.items.length : 0;
  const maxSlots = config.get('maxWarehouseSlots') || 50;
  
  if (currentSlots >= maxSlots) {
    player.tell('§c仓库已满，无法存入更多物品！');
    showPlayerWarehouse(player);
    return;
  }
  
  const playerItems = getPlayerInventoryItems(player, true);
  if (Object.keys(playerItems).length === 0) {
    player.tell('§c背包中没有可存入的物品！');
    showPlayerWarehouse(player);
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle('§a§l存入物品');
  form.setContent(`§e选择要存入仓库的物品：\n§f仓库空间：§a${maxSlots - currentSlots}§f个`);
  
  form.addButton('§c返回仓库', 'textures/ui/arrow_dark_left_stretch');
  
  const itemKeys = Object.keys(playerItems);
  itemKeys.forEach(key => {
    const item = playerItems[key];
    try {
      const tmp = safeNewItem(NBT.parseSNBT(key));
      if (tmp && !tmp.isNull()) {
        const itemName = getItemDisplayName(tmp, false);
        form.addButton(`§b${itemName} §fx${item.count}`, 'textures/ui/icon_setting');
      } else {
        form.addButton(`§c未知物品 §fx${item.count}`, 'textures/ui/icon_setting');
      }
    } catch (e) {
      form.addButton(`§c未知物品 §fx${item.count}`, 'textures/ui/icon_setting');
    }
  });
  
  form.addButton('§c返回仓库', 'textures/ui/arrow_dark_left_stretch');
  
  player.sendForm(form, (pl, id) => {
    if (id === null || id === 0 || id === itemKeys.length + 1) {
      showPlayerWarehouse(pl);
      return;
    }
    
    const selectedKey = itemKeys[id - 1];
    const selectedItem = playerItems[selectedKey];
    showWarehouseDepositAmount(pl, selectedKey, selectedItem);
  });
}

function showWarehouseBatchOperations(player) {
  if (!hasWarehousePurchased(player.xuid)) {
    player.tell('§c请先购买仓库才能进行批量操作！');
    showWarehousePurchaseMenu(player);
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle('§3§l仓库批量操作');
  form.setContent('§e请选择批量操作类型：');
  
  form.addButton('§a批量取出物品', 'textures/ui/arrow_left');
  form.addButton('§b批量存入物品', 'textures/ui/arrow_right');
  form.addButton('§e一键取出全部', 'textures/ui/upload_glyph');
  form.addButton('§d清理仓库', 'textures/ui/trash');
  form.addButton('§c返回仓库', 'textures/ui/cancel');
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    
    switch (id) {
      case 0:
        showBatchWithdrawSelection(pl);
        break;
      case 1:
        showBatchDepositSelection(pl);
        break;
      case 2:
        confirmWithdrawAll(pl);
        break;
      case 3:
        showWarehouseCleanup(pl);
        break;
      case 4:
        showPlayerWarehouse(pl);
        break;
    }
  });
}

function showBatchWithdrawSelection(player) {
  const playerData = warehouseData[player.xuid];
  if (!playerData || !playerData.items || playerData.items.length === 0) {
    player.tell('§c仓库中没有物品可以取出！');
    showWarehouseBatchOperations(player);
    return;
  }
  
  const form = mc.newCustomForm();
  form.setTitle('§a§l批量取出物品');
  form.addLabel('§e请选择要取出的物品：');
  
  playerData.items.forEach((item, index) => {
    try {
      const tmp = safeNewItem(NBT.parseSNBT(item.itemData));
      if (tmp && !tmp.isNull()) {
        const itemName = getItemDisplayName(tmp, false);
        const desc = item.description ? ` (${item.description})` : '';
        form.addSwitch(`§a${itemName} §fx${item.quantity}${desc}`, false);
      } else {
        const desc = item.description ? ` (${item.description})` : '';
        form.addSwitch(`§c未知物品 §fx${item.quantity}${desc}`, false);
      }
    } catch (e) {
      const desc = item.description ? ` (${item.description})` : '';
      form.addSwitch(`§c未知物品 §fx${item.quantity}${desc}`, false);
    }
  });
  
  form.addSwitch('§3全选', false);
  form.addInput('§e自定义取出数量（格式：物品1数量,物品2数量...）：', '留空按选择取出', '');
  
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showWarehouseBatchOperations(pl);
      return;
    }
    
    const allSelect = data[data.length - 2];
    const customAmounts = data[data.length - 1]?.trim();
    
    const selectedItems = [];
    playerData.items.forEach((item, index) => {
      const isSelected = allSelect || data[index + 1];
      if (isSelected) {
        let withdrawAmount = item.quantity;
        
        if (customAmounts) {
          const amounts = customAmounts.split(',').map(s => parseInt(s.trim()));
          if (amounts[selectedItems.length] && amounts[selectedItems.length] > 0) {
            withdrawAmount = Math.min(amounts[selectedItems.length], item.quantity);
          }
        }
        
        selectedItems.push({
          index: index,
          item: item,
          amount: withdrawAmount
        });
      }
    });
    
    if (selectedItems.length === 0) {
      pl.tell('§c请至少选择一个物品！');
      showBatchWithdrawSelection(pl);
      return;
    }
    
    confirmBatchWithdraw(pl, selectedItems);
  });
}

function confirmBatchWithdraw(player, selectedItems) {
  const form = mc.newSimpleForm();
  form.setTitle('§a§l确认批量取出');
  
  let content = '§e即将取出以下物品：\n\n';
  let totalItems = 0;
  
  selectedItems.forEach(selected => {
    try {
      const tmp = safeNewItem(NBT.parseSNBT(selected.item.itemData));
      if (tmp && !tmp.isNull()) {
        const itemName = getItemDisplayName(tmp, false);
        content += `§a${itemName} §fx${selected.amount}\n`;
      } else {
        content += `§c未知物品 §fx${selected.amount}\n`;
      }
    } catch (e) {
      content += `§c未知物品 §fx${selected.amount}\n`;
    }
    totalItems += selected.amount;
  });
  
  content += `\n§e总共 §a${selectedItems.length} §e种物品，§a${totalItems} §e个物品\n\n§c确认取出？`;
  form.setContent(content);
  
  form.addButton('§c取消', 'textures/ui/cancel');
  form.addButton('§a确认取出', 'textures/ui/confirm');
  
  player.sendForm(form, (pl, id) => {
    if (id === null || id === 0) {
      showBatchWithdrawSelection(pl);
      return;
    }
    
    if (id === 1) {
      processBatchWithdraw(pl, selectedItems);
    }
  });
}

function processBatchWithdraw(player, selectedItems) {
  const playerData = warehouseData[player.xuid];
  let successCount = 0;
  let failedCount = 0;
  const failedItems = [];
  
  selectedItems.sort((a, b) => b.index - a.index);
  
  for (const selected of selectedItems) {
    const success = giveItemToPlayer(player, selected.item.itemData, selected.amount);
    
    if (success) {
      selected.item.quantity -= selected.amount;
      if (selected.item.quantity <= 0) {
        playerData.items.splice(selected.index, 1);
      }
      successCount++;
    } else {
      try {
        const tmp = safeNewItem(NBT.parseSNBT(selected.item.itemData));
        if (tmp && !tmp.isNull()) {
          const itemName = getItemDisplayName(tmp, false);
          failedItems.push(`${itemName} x${selected.amount}`);
        } else {
          failedItems.push(`未知物品 x${selected.amount}`);
        }
      } catch (e) {
        failedItems.push(`未知物品 x${selected.amount}`);
      }
      failedCount++;
    }
  }
  
  saveWarehouseData();
  
  if (successCount > 0) {
    player.tell(`§a§l批量取出成功！§f取出了 ${successCount} 种物品`);
    player.sendToast('§a批量取出', `成功取出 ${successCount} 种物品`);
  }
  
  if (failedCount > 0) {
    player.tell(`§c§l部分物品取出失败（背包空间不足）：\n§f${failedItems.join(', ')}`);
  }
  
  showPlayerWarehouse(player);
}

function showBatchDepositSelection(player) {
  const invItems = getPlayerInventoryItems(player, true);
  const itemKeys = Object.keys(invItems);
  
  if (itemKeys.length === 0) {
    player.tell('§c您的背包中没有可存入的物品！');
    showWarehouseBatchOperations(player);
    return;
  }
  
  const playerData = warehouseData[player.xuid];
  const currentSlots = playerData ? playerData.items.length : 0;
  const maxSlots = config.get('maxWarehouseSlots') || 50;
  const availableSlots = maxSlots - currentSlots;
  
  if (availableSlots <= 0) {
    player.tell('§c仓库已满，无法存入更多物品！');
    showWarehouseBatchOperations(player);
    return;
  }
  
  const form = mc.newCustomForm();
  form.setTitle('§b§l批量存入物品');
  form.addLabel(`§e请选择要存入的物品（剩余容量：${availableSlots}）：`);
  
  itemKeys.forEach((itemKey, index) => {
    const {item, count} = invItems[itemKey];
    const itemName = getItemDisplayName(item, false);
    form.addSwitch(`§a${itemName} §fx${count}`, false);
  });
  
  form.addSwitch('§3全选（受容量限制）', false);
  form.addInput('§e自定义存入数量（格式：物品1数量,物品2数量...）：', '留空按选择存入', '');
  form.addInput('§e存入描述（可选）：', '批量存入', '');
  
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showWarehouseBatchOperations(pl);
      return;
    }
    
    const allSelect = data[data.length - 3];
    const customAmounts = data[data.length - 2]?.trim();
    const description = data[data.length - 1]?.trim() || '批量存入';
    
    const selectedItems = [];
    let selectedCount = 0;
    
    itemKeys.forEach((itemKey, index) => {
      const isSelected = allSelect || data[index + 1];
      if (isSelected && selectedCount < availableSlots) {
        const {item, count} = invItems[itemKey];
        let depositAmount = count;
        
        if (customAmounts) {
          const amounts = customAmounts.split(',').map(s => parseInt(s.trim()));
          if (amounts[selectedItems.length] && amounts[selectedItems.length] > 0) {
            depositAmount = Math.min(amounts[selectedItems.length], count);
          }
        }
        
        selectedItems.push({
          itemKey: itemKey,
          item: item,
          amount: depositAmount
        });
        selectedCount++;
      }
    });
    
    if (selectedItems.length === 0) {
      pl.tell('§c请至少选择一个物品！');
      showBatchDepositSelection(pl);
      return;
    }
    
    confirmBatchDeposit(pl, selectedItems, description);
  });
}

function confirmBatchDeposit(player, selectedItems, description) {
  const form = mc.newSimpleForm();
  form.setTitle('§b§l确认批量存入');
  
  let content = '§e即将存入以下物品：\n\n';
  let totalItems = 0;
  
  selectedItems.forEach(selected => {
    const itemName = getItemDisplayName(selected.item, false);
    content += `§a${itemName} §fx${selected.amount}\n`;
    totalItems += selected.amount;
  });
  
  content += `\n§e总共 §a${selectedItems.length} §e种物品，§a${totalItems} §e个物品\n`;
  content += `§e描述：§f${description}\n\n§c确认存入？`;
  form.setContent(content);
  
  form.addButton('§c取消', 'textures/ui/cancel');
  form.addButton('§a确认存入', 'textures/ui/confirm');
  
  player.sendForm(form, (pl, id) => {
    if (id === null || id === 0) {
      showBatchDepositSelection(pl);
      return;
    }
    
    if (id === 1) {
      processBatchDeposit(pl, selectedItems, description);
    }
  });
}

function processBatchDeposit(player, selectedItems, description) {
  let successCount = 0;
  let failedCount = 0;
  const failedItems = [];
  
  for (const selected of selectedItems) {
    const removed = removeItemsFromPlayer(player, selected.itemKey, selected.amount);
    
    if (removed) {
      const success = addItemToWarehouse(player.xuid, player.realName, selected.itemKey, selected.amount, description);
      
      if (success) {
        successCount++;
      } else {
        giveItemToPlayer(player, selected.itemKey, selected.amount);
        const itemName = getItemDisplayName(selected.item, false);
        failedItems.push(`${itemName} x${selected.amount}`);
        failedCount++;
      }
    } else {
      const itemName = getItemDisplayName(selected.item, false);
      failedItems.push(`${itemName} x${selected.amount}`);
      failedCount++;
    }
  }
  
  if (successCount > 0) {
    player.tell(`§a§l批量存入成功！§f存入了 ${successCount} 种物品`);
    player.sendToast('§a批量存入', `成功存入 ${successCount} 种物品`);
  }
  
  if (failedCount > 0) {
    player.tell(`§c§l部分物品存入失败：\n§f${failedItems.join(', ')}`);
  }
  
  showPlayerWarehouse(player);
}

function confirmWithdrawAll(player) {
  const playerData = warehouseData[player.xuid];
  if (!playerData || !playerData.items || playerData.items.length === 0) {
    player.tell('§c仓库中没有物品可以取出！');
    showWarehouseBatchOperations(player);
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle('§e§l一键取出全部');
  
  let content = '§e将取出仓库中的所有物品：\n\n';
  let totalItems = 0;
  
  playerData.items.forEach(item => {
    try {
      const tmp = safeNewItem(NBT.parseSNBT(item.itemData));
      if (tmp && !tmp.isNull()) {
        const itemName = getItemDisplayName(tmp, false);
        content += `§a${itemName} §fx${item.quantity}\n`;
      } else {
        content += `§c未知物品 §fx${item.quantity}\n`;
      }
    } catch (e) {
      content += `§c未知物品 §fx${item.quantity}\n`;
    }
    totalItems += item.quantity;
  });
  
  content += `\n§e总共 §a${playerData.items.length} §e种物品，§a${totalItems} §e个物品\n\n`;
  content += `§c§l警告：§f如果背包空间不足，部分物品可能无法取出！\n\n§c确认取出所有物品？`;
  form.setContent(content);
  
  form.addButton('§c取消', 'textures/ui/cancel');
  form.addButton('§a确认取出全部', 'textures/ui/confirm');
  
  player.sendForm(form, (pl, id) => {
    if (id === null || id === 0) {
      showWarehouseBatchOperations(pl);
      return;
    }
    
    if (id === 1) {
      processWithdrawAll(pl);
    }
  });
}

function processWithdrawAll(player) {
  const playerData = warehouseData[player.xuid];
  let successCount = 0;
  let failedCount = 0;
  const failedItems = [];
  
  const itemsToProcess = [...playerData.items];
  
  for (let i = itemsToProcess.length - 1; i >= 0; i--) {
    const item = itemsToProcess[i];
    const success = giveItemToPlayer(player, item.itemData, item.quantity);
    
    if (success) {
      playerData.items.splice(i, 1);
      successCount++;
    } else {
      try {
        const tmp = safeNewItem(NBT.parseSNBT(item.itemData));
        if (tmp && !tmp.isNull()) {
          const itemName = getItemDisplayName(tmp, false);
          failedItems.push(`${itemName} x${item.quantity}`);
        } else {
          failedItems.push(`未知物品 x${item.quantity}`);
        }
      } catch (e) {
        failedItems.push(`未知物品 x${item.quantity}`);
      }
      failedCount++;
    }
  }
  
  saveWarehouseData();
  
  if (successCount > 0) {
    player.tell(`§a§l一键取出成功！§f取出了 ${successCount} 种物品`);
    player.sendToast('§a一键取出', `成功取出 ${successCount} 种物品`);
  }
  
  if (failedCount > 0) {
    player.tell(`§c§l部分物品取出失败（背包空间不足）：\n§f${failedItems.join(', ')}`);
  }
  
  showPlayerWarehouse(player);
}

function showWarehouseCleanup(player) {
  const playerData = warehouseData[player.xuid];
  if (!playerData || !playerData.items || playerData.items.length === 0) {
    player.tell('§c仓库中没有物品可以清理！');
    showWarehouseBatchOperations(player);
    return;
  }
  
  const form = mc.newCustomForm();
  form.setTitle('§d§l仓库清理');
  form.addLabel('§e选择清理选项：');
  form.addSwitch('§c删除所有礼物物品', false);
  form.addSwitch('§c删除指定时间前的物品', false);
  form.addDropdown('§e时间范围：', ['7天前', '30天前', '90天前'], 1);
  form.addSwitch('§c删除所有物品（危险操作）', false);
  form.addSwitch('§3我确认要执行清理操作', false);
  
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showWarehouseBatchOperations(pl);
      return;
    }
    
    const deleteGifts = data[1];
    const deleteOld = data[2];
    const timeRange = data[3];
    const deleteAll = data[4];
    const confirmed = data[5];
    
    if (!confirmed) {
      pl.tell('§c请确认清理操作！');
      showWarehouseCleanup(pl);
      return;
    }
    
    processWarehouseCleanup(pl, deleteGifts, deleteOld, timeRange, deleteAll);
  });
}

function processWarehouseCleanup(player, deleteGifts, deleteOld, timeRange, deleteAll) {
  const playerData = warehouseData[player.xuid];
  let deletedCount = 0;
  
  if (deleteAll) {
    deletedCount = playerData.items.length;
    playerData.items = [];
  } else {
    const now = Date.now();
    const timeRanges = [7 * 24 * 60 * 60 * 1000, 30 * 24 * 60 * 60 * 1000, 90 * 24 * 60 * 60 * 1000];
    const cutoffTime = now - timeRanges[timeRange];
    
    for (let i = playerData.items.length - 1; i >= 0; i--) {
      const item = playerData.items[i];
      let shouldDelete = false;
      
      if (deleteGifts && item.description && item.description.indexOf('礼物') !== -1) {
        shouldDelete = true;
      }
      
      if (deleteOld && item.timestamp < cutoffTime) {
        shouldDelete = true;
      }
      
      if (shouldDelete) {
        playerData.items.splice(i, 1);
        deletedCount++;
      }
    }
  }
  
  saveWarehouseData();
  
  if (deletedCount > 0) {
    player.tell(`§a§l仓库清理完成！§f删除了 ${deletedCount} 种物品`);
    player.sendToast('§a仓库清理', `删除了 ${deletedCount} 种物品`);
  } else {
    player.tell('§e没有符合条件的物品需要清理。');
  }
  
  showPlayerWarehouse(player);
}

function showWarehouseDepositAmount(player, itemKey, itemData) {
  let tmp;
  let itemName;
  try {
    tmp = safeNewItem(itemKey);
    if (!tmp || tmp.isNull()) {
      player.tell('§c取消操作');
      showPlayerWarehouse(player);
    return;
  }
    itemName = getItemDisplayName(tmp, false);
  } catch (e) {
    player.tell('§c取消操作');
    showPlayerWarehouse(player);
    return;
  }
  
  const form = mc.newCustomForm();
  form.setTitle('§a§l存入物品');
  form.addLabel(`§e物品：§a${itemName}\n§e拥有数量：§a${itemData.count}`);
  form.addInput('§e存入数量（留空存入全部）：', '数字', '');
  form.addInput('§e备注（可选）：', '描述', '');
  
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showWarehouseDepositMenu(pl);
      return;
    }
    
    let depositAmount = parseInt(data[1]) || itemData.count;
    const description = data[2]?.trim() || '';
    
    if (depositAmount <= 0 || depositAmount > itemData.count) {
      depositAmount = itemData.count;
    }
    
    const playerCurrentCount = getPlayerItemCount(pl, itemKey);
    if (playerCurrentCount < depositAmount) {
      pl.tell('§c您的背包中物品数量不足！');
      showWarehouseDepositAmount(pl, itemKey, itemData);
      return;
    }
    
    const removed = removeItemsFromPlayer(pl, itemKey, depositAmount);
    if (!removed) {
      pl.tell('§c扣除物品失败！');
      showWarehouseDepositAmount(pl, itemKey, itemData);
      return;
    }
    
    const success = addItemToWarehouse(pl.xuid, pl.realName, itemKey, depositAmount, description);
    if (!success) {
      const returnSuccess = giveItemToPlayer(pl, itemKey, depositAmount);
      if (!returnSuccess) {
        pl.tell('§c§l仓库空间不足且背包无法容纳返还物品！物品已丢失，请联系管理员！');
        log(`警告：玩家 ${pl.realName} 的物品返还失败，物品可能丢失！物品：${itemKey}，数量：${depositAmount}`);
      } else {
        pl.tell('§c仓库空间不足，物品已返还到背包！');
      }
      showPlayerWarehouse(pl);
      return;
    }
    
    pl.tell(`§a已将 §b${itemName} x${depositAmount}§a 存入仓库！`);
    pl.sendToast('§a仓库存入', `${itemName} x${depositAmount}`);
    
    showPlayerWarehouse(pl);
  });
}

function logPurchase(buyerPl, shop, shopItem, qty, isOfficial) {
  const buyerName = buyerPl.realName;
  const buyerXuid = buyerPl.xuid;
  let sellerName = "官方商店";
  let sellerXuid = "OFFICIAL";
  let shopName = "官方商店";
  if (!isOfficial && shop) {
    sellerName = shop.owner;
    sellerXuid = shop.ownerXuid;
    shopName = shop.name;
  }
  const itemName = shopItem.name;
  const priceEach = shopItem.price;
  const totalPrice = priceEach * qty;
  const timeNow = new Date().toLocaleString(); 
  const record = {
    buyerName,
    buyerXuid,
    sellerName,
    sellerXuid,
    shopName,
    itemName,
    quantity: qty,
    priceEach,
    totalPrice,
    time: timeNow
  };
  if (!purchaseLogs.global) purchaseLogs.global = [];
  purchaseLogs.global.push(record);
  if (purchaseLogs.global.length > 30) {
    purchaseLogs.global.shift(); 
  }
  if (!purchaseLogs.players) purchaseLogs.players = {};
  if (!purchaseLogs.players[buyerXuid]) {
    purchaseLogs.players[buyerXuid] = { buy: [], sell: [] };
  }
  purchaseLogs.players[buyerXuid].buy.push(record);
  if (purchaseLogs.players[buyerXuid].buy.length > 30) {
    purchaseLogs.players[buyerXuid].buy.shift();
  }
  if (!isOfficial && sellerXuid !== buyerXuid && sellerXuid !== "OFFICIAL") {
    if (!purchaseLogs.players[sellerXuid]) {
      purchaseLogs.players[sellerXuid] = { buy: [], sell: [] };
    }
    purchaseLogs.players[sellerXuid].sell.push(record);
    if (purchaseLogs.players[sellerXuid].sell.length > 30) {
      purchaseLogs.players[sellerXuid].sell.shift();
    }
  }
  savePurchaseLogs();
}

function getPlayerShopRank(playerXuid) {
  let arr = [];
  for(let xuid in rankingData){
    let rd = rankingData[xuid];
    let te = rd.totalEarnings||0;
    arr.push({
      xuid,
      totalEarnings: te
    });
  }
  arr.sort((a,b)=> b.totalEarnings - a.totalEarnings);
  
  const playerIndex = arr.findIndex(item => item.xuid === playerXuid);
  if (playerIndex === -1) {
    return { rank: -1, total: arr.length };
  }
  
  return { rank: playerIndex + 1, total: arr.length };
}

function showShopRanking(player){
  let arr = [];
  for(let xuid in rankingData){
    let rd = rankingData[xuid];
    let sc = rd.salesCount||0;
    let te = rd.totalEarnings||0;
    let shop = shopsData[xuid];
    let shopName = shop? shop.name : `玩家(${xuid.slice(0,5)})`;
    let ownerName = shop? shop.owner : xuid;
    let cAt = shop? shop.createdAt : 0;
    arr.push({
      xuid,
      shopName,
      ownerName,
      salesCount: sc,
      totalEarnings: te,
      createdAt: cAt
    });
  }
  arr.sort((a,b)=> b.totalEarnings - a.totalEarnings);
  let top = arr.slice(0,20);
  const form=mc.newCustomForm();
  form.setTitle('§d§l店铺排行榜(前20)');
  let content=`§b按总收入降序,最多20名.\n§e当前店铺总数:${Object.keys(shopsData).length}\n\n`;
  if(top.length===0){
    content+=`§c当前无人开店或无收益数据.\n`;
  } else {
    top.forEach((item,idx)=>{
      let rank=idx+1;
      let cTime=new Date(item.createdAt).toLocaleString();
      content+=`§3§lNO.${rank}§r\n`+
               `§b店铺:§e${item.shopName} §r| 店主:§a${item.ownerName}\n`+
               `§e总收入:§3${item.totalEarnings||0}§r | 销量:${item.salesCount||0}\n`+
               `§a创建时间:${(item.createdAt?cTime:'未知')}\n\n`;
    });
  }
  form.addLabel(content);
  player.sendForm(form,(pl,data)=>{
    if(data !== null) {
      showMainMenu(pl);
    }
  });
}

function showAdminMenu(player){
  const form=mc.newSimpleForm();
  form.setTitle('§c§l管理市场');
  form.setContent('§e§l请选择一个操作：');
  addReturnButton(form);
  form.addButton('§a§l配置市场','textures/ui/op');
  form.addButton('§b§l设置不可上架物品','textures/ui/anvil_icon');
  form.addButton('§d§l配置广告位','textures/ui/MCoin');
  form.addButton('§e§l图标配置','textures/ui/color_picker');
  form.addButton('§2§l管理玩家店铺','textures/ui/video_glyph_2x');
  form.addButton('§3§l悬赏&求购 配置', 'textures/ui/MCoin');
  form.addButton('§9§l税收系统配置', 'textures/ui/store_sort_icon');
  form.addButton('§5§l分类管理', 'textures/ui/recipe_book_icon');
  form.addButton('§3§l主菜单按钮配置', 'textures/ui/move');
  form.addButton('§8§l仓库系统配置', 'textures/ui/icon_steve');
  form.addButton('§6§l查看玩家仓库', 'textures/ui/magnifyingGlass');
  form.addButton('§3§l动态回收配置', 'textures/ui/video_glyph_color_2x');
  form.addButton('§c§l用户行为分析', 'textures/ui/dev_glyph');
  player.sendForm(form,(pl,id)=>{
    if(id==null)return;
    if(id===0){
      showMainMenu(pl);
      return;
    }
    let idx=1;
    if(id===idx++){
      showMarketConfigMenu(pl);
    } else if(id===idx++){
      setForbiddenItems(pl);
    } else if(id===idx++){
      showAdvertSlotsSettingMenu(pl);
    } else if(id===idx++){
      showIconConfigMenu(pl);
    } else if(id===idx++){
      showManagePlayerShops(pl,1,"");
    } else if(id===idx++) {
      showPurchaseRequestConfigMenu(pl);
    } else if(id===idx++) {
      showTaxSystemConfig(pl);
    } else if(id===idx++) {
      showCategoryManagement(pl);
    } else if(id===idx++) {
      showMainMenuButtonsConfig(pl);
    } else if(id===idx++) {
      showWarehouseSystemConfig(pl);
    } else if(id===idx++) {
      showAdminViewPlayerWarehouse(pl);
    } else if(id===idx++) {
      showDynamicRecycleConfig(pl);
    } else if(id===idx) {
      showEnhancedUserBehaviorAnalysis(pl);
    }
  });
}

function showPurchaseRequestConfigMenu(player) {
  const enabled = config.get('enablePurchaseRequests');
  const fee = config.get('purchaseRequestFee');
  const expiry = config.get('purchaseRequestExpiry');
  const notify = config.get('notifyPurchaseRequestToAll'); 
  const form = mc.newCustomForm();
  form.setTitle('§3§l悬赏&求购配置');
  form.addSwitch('§e是否启用悬赏&求购功能:', enabled);
  form.addInput('§e悬赏求购手续费(0为免费):', '数字', fee.toString());
  form.addInput('§e悬赏求购过期时间(小时):', '数字', expiry.toString());
  form.addSwitch('§e是否全服通知新的求购订单:', notify);
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;   
    const newEnabled = data[0];
    const newFee = parseInt(data[1]);
    const newExpiry = parseInt(data[2]);
    const newNotify = data[3];   
    if (isNaN(newFee) || newFee < 0) {
      pl.tell('§c手续费必须是非负整数!');
      return;
    }   
    if (isNaN(newExpiry) || newExpiry <= 0) {
      pl.tell('§c过期时间必须是正整数!');
      return;
    }  
    config.set('enablePurchaseRequests', newEnabled);
    config.set('purchaseRequestFee', newFee);
    config.set('purchaseRequestExpiry', newExpiry);
    config.set('notifyPurchaseRequestToAll', newNotify); 
    pl.tell('§a悬赏&求购配置已更新!');
  });
}

function showTaxSystemConfig(player) {
  const form = mc.newCustomForm();
  form.setTitle("§9§l税收系统配置");
  
  const enabled = config.get('enableTaxSystem');
  const taxRate = config.get('taxRate') || 0;
  const taxOnlyOfficial = config.get('taxOnlyOfficialShop');
  
  form.addSwitch("§e启用税收系统", enabled);
  form.addInput("§e税率（百分比，如5代表5%）", "0-100", (taxRate * 100).toString());
  form.addSwitch("§e仅对官方商店征税", taxOnlyOfficial);
  form.addSwitch("§e查看税收统计", false);
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    const newEnabled = data[0];
    const newTaxRate = parseFloat(data[1]) / 100;
    const newTaxOnlyOfficial = data[2];
    const viewStats = data[3];
    
    if (viewStats) {
      showTaxStatistics(pl);
      return;
    }
    
    if (isNaN(newTaxRate) || newTaxRate < 0 || newTaxRate > 1) {
      pl.tell("§c税率必须在0-100之间！");
      return;
    }
    
    config.set('enableTaxSystem', newEnabled);
    config.set('taxRate', newTaxRate);
    config.set('taxOnlyOfficialShop', newTaxOnlyOfficial);
    
    const taxScope = newTaxOnlyOfficial ? "仅官方商店" : "全局商店";
    pl.tell(`§a税收系统配置已更新！当前范围：${taxScope}`);
  });
}

function showTaxStatistics(player) {
  const form = mc.newCustomForm();
  form.setTitle("§9§l税收统计");
  
  let content = `§e总税收: §a${taxRecords.totalCollected} ${getEconomyInterface().name}\n\n`;
  
  content += "§e每日税收记录:\n";
  const dates = Object.keys(taxRecords.dailyRecords).slice(-7);
  dates.forEach(date => {
    const record = taxRecords.dailyRecords[date];
    content += `§3${date}: §a${record.total} §3(${record.count}笔)\n`;
  });
  
  content += "\n§e纳税排行榜（前10）:\n";
  const topPayers = Object.entries(taxRecords.playerRecords)
    .map(([xuid, data]) => ({
      xuid,
      name: mc.getPlayer(xuid)?.realName || xuid.substring(0, 8),
      total: data.totalPaid
    }))
    .sort((a, b) => b.total - a.total)
    .slice(0, 10);
  
  topPayers.forEach((payer, idx) => {
    content += `§3${idx + 1}. §b${payer.name}: §a${payer.total}\n`;
  });
  
  form.addLabel(content);
  player.sendForm(form, (pl, data) => {
    if(data !== null) {
      showTaxSystemConfig(pl);
    }
  });
}

function showCategoryManagement(player) {
  const form = mc.newSimpleForm();
  form.setTitle("§5§l分类管理");
  form.setContent("§e请选择操作：");
  addReturnButton(form);
  form.addButton("§a添加新分类", "textures/ui/color_plus");
  form.addButton("§c删除分类", "textures/ui/trash");
  form.addButton("§b查看分类统计", "textures/ui/magnifyingGlass");
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === 0) {
      showAdminMenu(pl);
      return;
    }
    
    if (id === 1) {
      showAddCategory(pl);
    } else if (id === 2) {
      showDeleteCategory(pl);
    } else if (id === 3) {
      showCategoryStatistics(pl);
    }
  });
}

function showAddCategory(player) {
  const form = mc.newCustomForm();
  form.setTitle("§a§l添加新分类");
  form.addInput("§e分类名称（最多10个字符）", "分类名", "");
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    const categoryName = data[0]?.trim();
    if (!categoryName) {
      pl.tell("§c分类名称不能为空！");
      return;
    }
    
    if (categoryName.length > 10) {
      pl.tell("§c分类名称不能超过10个字符！");
      return;
    }
    
    const categories = config.get('itemCategories') || ["全部"];
    if (categories.includes(categoryName)) {
      pl.tell("§c该分类已存在！");
      return;
    }
    
    categories.push(categoryName);
    config.set('itemCategories', categories);
    ITEM_CATEGORY = categories;
    
    pl.tell(`§a成功添加分类: ${categoryName}`);
    showCategoryManagement(pl);
  });
}

function showDeleteCategory(player) {
  const categories = config.get('itemCategories') || ["全部"];
  if (categories.length <= 1) {
    player.tell("§c至少需要保留一个分类！");
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle("§c§l删除分类");
  form.setContent("§e选择要删除的分类（全部分类不可删除）：");
  addReturnButton(form);
  
  categories.forEach(cat => {
    if (cat !== "全部") {
      form.addButton(`§c${cat}`, "textures/ui/trash");
    }
  });
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === 0) {
      showCategoryManagement(pl);
      return;
    }
    
    const deletableCategories = categories.filter(c => c !== "全部");
    const categoryToDelete = deletableCategories[id - 1];
    
    const newCategories = categories.filter(c => c !== categoryToDelete);
    config.set('itemCategories', newCategories);
    ITEM_CATEGORY = newCategories;
    
    let resetCount = 0;
    for (const xuid in shopsData) {
      const shop = shopsData[xuid];
      for (const key in shop.items) {
        if (shop.items[key].category === categoryToDelete) {
          shop.items[key].category = "全部";
          resetCount++;
        }
      }
    }
    
    for (const key in officialShopData.purchaseItems) {
      if (officialShopData.purchaseItems[key].category === categoryToDelete) {
        officialShopData.purchaseItems[key].category = "全部";
        resetCount++;
      }
    }
    
    saveShopsData();
    saveOfficialShopData();
    
    pl.tell(`§a成功删除分类: ${categoryToDelete}, 已将 ${resetCount} 个物品重置为"全部"分类`);
    showCategoryManagement(pl);
  });
}

function showCategoryStatistics(player) {
  const categories = config.get('itemCategories') || ["全部"];
  const stats = {};
  
  categories.forEach(cat => {
    stats[cat] = {
      shopCount: 0,
      officialCount: 0,
      totalValue: 0
    };
  });
  
  for (const xuid in shopsData) {
    const shop = shopsData[xuid];
    for (const key in shop.items) {
      const item = shop.items[key];
      const cat = item.category || "全部";
      if (stats[cat]) {
        stats[cat].shopCount++;
        stats[cat].totalValue += item.price * (item.quantity === -1 ? 1 : item.quantity);
      }
    }
  }
  
  for (const key in officialShopData.purchaseItems) {
    const item = officialShopData.purchaseItems[key];
    const cat = item.category || "全部";
    if (stats[cat]) {
      stats[cat].officialCount++;
      stats[cat].totalValue += item.price * (item.quantity === -1 ? 1 : item.quantity);
    }
  }
  
  const form = mc.newCustomForm();
  form.setTitle("§b§l分类统计");
  
  let content = "§e各分类物品统计:\n\n";
  categories.forEach(cat => {
    const stat = stats[cat];
    content += `§3${cat}:\n`;
    content += `  §3玩家店铺物品: §a${stat.shopCount}\n`;
    content += `  §3官方商店物品: §a${stat.officialCount}\n`;
    content += `  §3总价值: §a${stat.totalValue}\n\n`;
  });
  
  form.addLabel(content);
  player.sendForm(form, (pl, data) => {
    if(data !== null) {
      showCategoryManagement(pl);
    }
  });
}

function showMainMenuButtonsConfig(player) {
  const defaultButtons = {
    chatLobby: { enabled: true, order: 1 },
    globalSearch: { enabled: true, order: 2 },
    shoppingCenter: { enabled: true, order: 3 },
    myShop: { enabled: true, order: 4 },
    officialShop: { enabled: true, order: 5 },
    purchaseRequests: { enabled: true, order: 6 },
    warehouse: { enabled: true, order: 7 },
    shopRanking: { enabled: true, order: 8 },
    tradeLogs: { enabled: true, order: 9 }
  };
  
  const buttonsConfig = config.get('mainMenuButtons') || defaultButtons;
  
  function showButtonsList() {
    const buttonKeys = Object.keys(buttonsConfig);
    const form = mc.newSimpleForm();
    form.setTitle('§3§l主菜单按钮配置');
    form.setContent('§e选择要修改的按钮:');
    addReturnButton(form);
    
    buttonKeys.sort((a, b) => buttonsConfig[a].order - buttonsConfig[b].order)
      .forEach(key => {
        const buttonInfo = buttonsConfig[key];
        const enabledText = buttonInfo.enabled ? '§a启用' : '§c禁用';
        const buttonName = getButtonDisplayName(key);
        form.addButton(`${enabledText} §3[${buttonInfo.order}] §f${buttonName}`);
      });
    
    form.addButton('§c§l重置所有按钮');
    
    player.sendForm(form, (pl, id) => {
      if (id === null) {
        return;
      }
      
      if (id === 0) {
        showAdminMenu(pl);
        return;
      }
      
      const buttonKeys = Object.keys(buttonsConfig)
        .sort((a, b) => buttonsConfig[a].order - buttonsConfig[b].order);
      
      if (id === buttonKeys.length + 1) {
        confirmResetAllButtons(pl);
      } else if (id > 0 && id <= buttonKeys.length) {
        const keyToEdit = buttonKeys[id - 1];
        showButtonConfig(pl, keyToEdit);
      }
    });
  }
  
  function getButtonDisplayName(key) {
    const nameMap = {
      'chatLobby': 'SM大厅',
      'globalSearch': '全局搜索',
      'shoppingCenter': '购物中心',
      'myShop': '我的店铺',
      'officialShop': '官方商店',
      'purchaseRequests': '悬赏&求购',
      'warehouse': '个人仓库',
      'shopRanking': '店铺排行榜',
      'tradeLogs': '交易动态信息'
    };
    return nameMap[key] || key;
  }
  
  function showButtonConfig(pl, key) {
    const buttonInfo = buttonsConfig[key];
    if (!buttonInfo) {
      pl.tell("§c错误: 按钮配置不存在");
      return;
    }
    
    const buttonName = getButtonDisplayName(key);
    const buttonKeys = Object.keys(buttonsConfig);
    
    const form = mc.newCustomForm();
    form.setTitle(`§3§l修改按钮 - ${buttonName}`);
    form.addSwitch('§e启用此按钮:', buttonInfo.enabled);
    form.addSlider(`§e按钮顺序 (1-${buttonKeys.length}):`, 1, buttonKeys.length, 1, buttonInfo.order);
    
    pl.sendForm(form, (p, data) => {
      if (data === null) {
        p.tell("§a已取消操作");
        showButtonsList();
        return;
      }
      
      try {
        const newEnabled = data[0];
        const newOrder = data[1];
        
        buttonsConfig[key].enabled = newEnabled;
        
        if (newOrder !== buttonInfo.order) {
          const oldOrder = buttonInfo.order;
          buttonsConfig[key].order = newOrder;
          
          if (newOrder > oldOrder) {
            Object.keys(buttonsConfig).forEach(k => {
              if (k !== key && buttonsConfig[k].order > oldOrder && buttonsConfig[k].order <= newOrder) {
                buttonsConfig[k].order--;
              }
            });
          } else {
            Object.keys(buttonsConfig).forEach(k => {
              if (k !== key && buttonsConfig[k].order >= newOrder && buttonsConfig[k].order < oldOrder) {
                buttonsConfig[k].order++;
              }
            });
          }
        }
        
        config.set('mainMenuButtons', buttonsConfig);
        p.tell(`§a按钮 ${buttonName} 配置已更新！`);
      } catch (e) {
        p.tell(`§c错误: ${e.message}`);
      }
      
      showButtonsList();
    });
  }
  
  function confirmResetAllButtons(pl) {
    const form = mc.newCustomForm();
    form.setTitle('§c§l确认重置');
    form.addLabel('§e§l确定要重置所有按钮配置吗？\n这将恢复所有按钮为默认启用状态和默认顺序。');
    form.addSwitch('§c我确认要重置所有按钮配置', false);
    
    pl.sendForm(form, (p, data) => {
      if (data === null) {
        p.tell("§a已取消操作");
        showButtonsList();
        return;
      }
      
      try {
        const confirmed = data[1];
        if (confirmed) {
          config.set('mainMenuButtons', defaultButtons);
          Object.keys(defaultButtons).forEach(key => {
            buttonsConfig[key] = { ...defaultButtons[key] };
          });
          p.tell('§a所有按钮配置已重置为默认！');
        } else {
          p.tell('§a未进行重置操作。');
        }
      } catch (e) {
        p.tell(`§c重置出错: ${e.message}`);
      }
      
      showButtonsList();
    });
  }
  
  showButtonsList();
}

function showMarketConfigMenu(player){
  const economySystem=config.get('economySystem');
  const scoreboardObjective=config.get('scoreboardObjective');
  const shopCreationCost=config.get('shopCreationCost');
  const shopNameChangeCost=config.get('shopNameChangeCost');
  const shopNameChangeCooldown=config.get('shopNameChangeCooldown');
  const showOfficialPurchase=config.get('showOfficialPurchase');
  const pageSizeLimit = config.get("pageSizeLimit");
  const shopSortMode = config.get("shopSortMode");
  const officialShopSortMode = config.get("officialShopSortMode");
  const enableChatLobby = config.get("enableChatLobby");
  const notifyDiscountToAll = config.get("notifyDiscountToAll");
  const notifyItemListingToAll = config.get("notifyItemListingToAll");
  const chatHistoryLimit = config.get("chatHistoryLimit");
  const enableShopLevelSystem = config.get("enableShopLevelSystem");
  const shopDefaultItemTypes = config.get("shopDefaultItemTypes") || 15;
  const shopDefaultTotalItems = config.get("shopDefaultTotalItems") || 960;
  const shopUpgradeBasePrice = config.get("shopUpgradeBasePrice") || 1000;
  const shopUpgradePriceIncrement = config.get("shopUpgradePriceIncrement") || 500;
  const shopUpgradeItemTypeIncrement = config.get("shopUpgradeItemTypeIncrement") || 1;
  const shopUpgradeTotalIncrement = config.get("shopUpgradeTotalIncrement") || 64;
  const enableBatchShopUpgrade = config.get("enableBatchShopUpgrade");
  const mainMenuButtons = config.get('mainMenuButtons') || {
    chatLobby: { enabled: true, order: 1 },
    globalSearch: { enabled: true, order: 2 },
    shoppingCenter: { enabled: true, order: 3 },
    myShop: { enabled: true, order: 4 },
    officialShop: { enabled: true, order: 5 },
    purchaseRequests: { enabled: true, order: 6 },
    warehouse: { enabled: true, order: 7 },
    shopRanking: { enabled: true, order: 8 },
    tradeLogs: { enabled: true, order: 9 }
  };
  
  const form=mc.newCustomForm();
  form.setTitle('§c§l配置市场');
  form.addDropdown('§e选择经济系统:',['llmoney','scoreboard'], economySystem==='llmoney'?0:1);
  form.addInput('§e记分板名称(仅scoreboard时生效):','money',scoreboardObjective);
  form.addInput('§e创建店铺的费用:','数字', shopCreationCost.toString());
  form.addInput('§e修改店铺名称的费用:','数字', shopNameChangeCost.toString());
  form.addInput('§e修改店铺名称的冷却(小时):','数字',shopNameChangeCooldown.toString());
  form.addSwitch('§e是否显示官方商店的购买按钮:', showOfficialPurchase);
  form.addInput('§eSM大厅显示消息数量:', '数字', chatHistoryLimit.toString());
  form.addSwitch('§e折扣是否向全服广播:', notifyDiscountToAll);
  form.addSwitch('§e上架物品是否向全服广播:', notifyItemListingToAll);
  form.addSwitch('§e是否显示主菜单统计信息:', config.get('showMainMenuStatistics'));
  form.addInput('§e设置每页最多显示多少条:', '数字', pageSizeLimit.toString());
  const sortModeOptions = ["随机","销量","在售","销量+在售"];
  let sortIndex = sortModeOptions.indexOf(shopSortMode);
  if (sortIndex < 0) sortIndex = 0;
  form.addDropdown(
    "§e店铺显示排序逻辑:",
    [
      "随机",
      "销量",
      "在售",
      "销量+在售"
    ],
    sortIndex
  );
  const officialShopSortOptions = ["随机","名字顺序"];
  let officialIndex = officialShopSortOptions.indexOf(officialShopSortMode);
  if (officialIndex < 0) officialIndex = 0;
  form.addDropdown(
    "§e官方商店物品排序:",
    officialShopSortOptions,
    officialIndex
  );
  form.addSwitch("§3§l是否启用店铺等级系统:", enableShopLevelSystem);
  form.addLabel("§3§l店铺等级系统配置（仅在启用等级系统时生效）");
  form.addInput("§e初始可上架物品件数:", "数字", shopDefaultItemTypes.toString());
  form.addInput("§e初始可上架物品总数:", "数字", shopDefaultTotalItems.toString());
  form.addInput("§e升级基础价格:", "数字", shopUpgradeBasePrice.toString());
  form.addInput("§e每级价格递增:", "数字", shopUpgradePriceIncrement.toString());
  form.addInput("§e每次升级增加物品件数:", "数字", shopUpgradeItemTypeIncrement.toString());
  form.addInput("§e每次升级增加物品总数:", "数字", shopUpgradeTotalIncrement.toString());
  form.addSwitch("§3§l启用批量店铺升级:", enableBatchShopUpgrade);
  form.addLabel("§3§l===== SM主页按钮显示设置 =====");
  form.addSwitch("§a显示SM大厅按钮:", Boolean(mainMenuButtons.chatLobby?.enabled ?? true));
  form.addSwitch("§a显示全局搜索按钮:", Boolean(mainMenuButtons.globalSearch?.enabled ?? true));
  form.addSwitch("§a显示购物中心按钮:", Boolean(mainMenuButtons.shoppingCenter?.enabled ?? true));
  form.addSwitch("§a显示我的店铺按钮:", Boolean(mainMenuButtons.myShop?.enabled ?? true));
  form.addSwitch("§a显示官方商店按钮:", Boolean(mainMenuButtons.officialShop?.enabled ?? true));
  form.addSwitch("§a显示悬赏&求购按钮:", Boolean(mainMenuButtons.purchaseRequests?.enabled ?? true));
  form.addSwitch("§a显示个人仓库按钮:", Boolean(mainMenuButtons.warehouse?.enabled ?? true));
  form.addSwitch("§a显示店铺排行榜按钮:", Boolean(mainMenuButtons.shopRanking?.enabled ?? true));
  form.addSwitch("§a显示交易动态信息按钮:", Boolean(mainMenuButtons.tradeLogs?.enabled ?? true));
  form.addLabel("§3§l===== 礼物系统设置 =====");
  form.addSwitch("§a启用礼物系统:", config.get('enableGiftSystem'));
  form.addInput("§e仓库最大容量:", "数字", (config.get('maxWarehouseSlots') || 50).toString());
  form.addLabel("§3§l===== 购买设置 =====");
  form.addSwitch("§a允许玩家购买自己店铺的物品:", config.get('allowSelfPurchase'));
  player.sendForm(form,(pl,data)=>{
    if(!data)return;
    const selEco = data[0]===0?'llmoney':'scoreboard';
    const newObj = data[1]?.trim();
    const newCreCost = parseInt(data[2]);
    const newNameChangeCost = parseInt(data[3]);
    const newNameChangeCD = parseInt(data[4]);
    const newShowOff = data[5];
    const newChatHistoryLimit = parseInt(data[6]);
    const newNotifyDiscount = data[7];
    const newNotifyItemListing = data[8];
    const newShowMainMenuStatistics = data[9];
    const newPageSize = parseInt(data[10]);
    const newSortIndex = data[11];
    const sortModeOptions = ["随机","销量","在售","销量+在售"];
    const newSortMode = sortModeOptions[newSortIndex] || "随机";
    const newOfficialIndex = data[12];
    const officialShopSortOptions = ["随机","名字顺序"];
    const newOfficialSortMode = officialShopSortOptions[newOfficialIndex] || "随机";
    const newEnableShopLevelSystem = data[13];
    const newShopDefaultItemTypes = parseInt(data[15]);
    const newShopDefaultTotalItems = parseInt(data[16]);
    const newShopUpgradeBasePrice = parseInt(data[17]);
    const newShopUpgradePriceIncrement = parseInt(data[18]);
    const newShopUpgradeItemTypeIncrement = parseInt(data[19]);
    const newShopUpgradeTotalIncrement = parseInt(data[20]);
    const newEnableBatchShopUpgrade = data[21];
    
    const newChatLobbyButton = data[23];
    const newGlobalSearchButton = data[24];
    const newShoppingCenterButton = data[25];
    const newMyShopButton = data[26];
    const newOfficialShopButton = data[27];
    const newPurchaseRequestsButton = data[28];
    const newWarehouseButton = data[29];
    const newShopRankingButton = data[30];
    const newTradeLogsButton = data[31];
    const newEnableGiftSystem = data[33];
    const newMaxWarehouseSlots = parseInt(data[34]) || 50;
    const newAllowSelfPurchase = data[36];
    if(selEco==='scoreboard'&&!newObj){
      pl.tell('§c§l记分板名称不能为空!');
      return;
    }
    if(isNaN(newCreCost)||newCreCost<0){
      pl.tell('§c§l创建店铺费用必须非负整数!');
      return;
    }
    if(isNaN(newNameChangeCost)||newNameChangeCost<0){
      pl.tell('§c§l改名费用必须非负整数!');
      return;
    }
    if(isNaN(newNameChangeCD)||newNameChangeCD<0){
      pl.tell('§c§l改名冷却时间必须非负整数!');
      return;
    }
    if(isNaN(newPageSize)||newPageSize<=0){
      pl.tell('§c§l每页最多显示数量必须为正整数!');
      return;
    }
    if(isNaN(newShopDefaultItemTypes)||newShopDefaultItemTypes<=0){
      pl.tell('§c§l初始可上架物品件数必须为正整数!');
      return;
    }
    if(isNaN(newShopDefaultTotalItems)||newShopDefaultTotalItems<=0){
      pl.tell('§c§l初始可上架物品总数必须为正整数!');
      return;
    }
    if(isNaN(newShopUpgradeBasePrice)||newShopUpgradeBasePrice<0){
      pl.tell('§c§l升级基础价格必须非负整数!');
      return;
    }
    if(isNaN(newShopUpgradePriceIncrement)||newShopUpgradePriceIncrement<0){
      pl.tell('§c§l每级价格递增必须非负整数!');
      return;
    }
    if(isNaN(newShopUpgradeItemTypeIncrement)||newShopUpgradeItemTypeIncrement<=0){
      pl.tell('§c§l每次升级增加物品件数必须为正整数!');
      return;
    }
    if(isNaN(newShopUpgradeTotalIncrement)||newShopUpgradeTotalIncrement<=0){
      pl.tell('§c§l每次升级增加物品总数必须为正整数!');
      return;
    }    
    if(isNaN(newMaxWarehouseSlots)||newMaxWarehouseSlots<=0){
      pl.tell('§c§l仓库最大容量必须为正整数!');
      return;
    }    
    config.set('economySystem',selEco);
    config.set('scoreboardObjective',newObj);
    config.set('shopCreationCost',newCreCost);
    config.set('shopNameChangeCost',newNameChangeCost);
    config.set('shopNameChangeCooldown',newNameChangeCD);
    config.set('showOfficialPurchase',newShowOff);
    config.set('chatHistoryLimit', newChatHistoryLimit);
    config.set('notifyDiscountToAll',newNotifyDiscount);
    config.set('notifyItemListingToAll',newNotifyItemListing);
    config.set('showMainMenuStatistics', newShowMainMenuStatistics);
    config.set('pageSizeLimit', newPageSize);
    config.set("shopSortMode", newSortMode);
    config.set("officialShopSortMode", newOfficialSortMode);
    config.set("enableShopLevelSystem", newEnableShopLevelSystem);
    config.set("shopDefaultItemTypes", newShopDefaultItemTypes);
    config.set("shopDefaultTotalItems", newShopDefaultTotalItems);
    config.set("shopUpgradeBasePrice", newShopUpgradeBasePrice);
    config.set("shopUpgradePriceIncrement", newShopUpgradePriceIncrement);
    config.set("shopUpgradeItemTypeIncrement", newShopUpgradeItemTypeIncrement);
    config.set("shopUpgradeTotalIncrement", newShopUpgradeTotalIncrement);
    config.set("enableBatchShopUpgrade", newEnableBatchShopUpgrade);
    
    const updatedMainMenuButtons = {
      chatLobby: { enabled: newChatLobbyButton, order: 1 },
      globalSearch: { enabled: newGlobalSearchButton, order: 2 },
      shoppingCenter: { enabled: newShoppingCenterButton, order: 3 },
      myShop: { enabled: newMyShopButton, order: 4 },
      officialShop: { enabled: newOfficialShopButton, order: 5 },
      purchaseRequests: { enabled: newPurchaseRequestsButton, order: 6 },
      warehouse: { enabled: newWarehouseButton, order: 7 },
      shopRanking: { enabled: newShopRankingButton, order: 8 },
      tradeLogs: { enabled: newTradeLogsButton, order: 9 }
    };
    config.set('mainMenuButtons', updatedMainMenuButtons);
    
    config.set('enableChatLobby', newChatLobbyButton);
    config.set('enableShopRanking', newShopRankingButton);   
    config.set('enableGiftSystem', newEnableGiftSystem);
    config.set('maxWarehouseSlots', newMaxWarehouseSlots);
    config.set('allowSelfPurchase', newAllowSelfPurchase);
    pl.tell('§a§l配置已更新！');
  });
}

function showWarehouseSystemConfig(player) {
  const form = mc.newCustomForm();
  form.setTitle("§8§l仓库系统配置");
  
  const enabled = config.get('enableGiftSystem');
  const mode = config.get('warehouseMode') || 0;
  const buyoutPrice = config.get('warehouseBuyoutPrice') || 10000;
  const rentalPrice = config.get('warehouseRentalPrice') || 1;
  const minRentalTime = config.get('warehouseMinRentalTime') || 60;
  const maxSlots = config.get('maxWarehouseSlots') || 50;
  
  form.addSwitch("§e启用仓库系统", enabled);
  form.addDropdown("§e仓库使用模式", ["免费使用", "一次性购买", "按时间租用"], mode);
  form.addInput("§e一次性购买价格", "数字", buyoutPrice.toString());
  form.addInput("§e租赁价格(每分钟)", "数字", rentalPrice.toString());
  form.addInput("§e最低租用时间(分钟)", "数字", minRentalTime.toString());
  form.addInput("§e仓库最大容量", "数字", maxSlots.toString());
  form.addSwitch("§e查看仓库统计", false);
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    const newEnabled = data[0];
    const newMode = data[1];
    const newBuyoutPrice = parseInt(data[2]);
    const newRentalPrice = parseInt(data[3]);
    const newMinRentalTime = parseInt(data[4]);
    const newMaxSlots = parseInt(data[5]);
    const viewStats = data[6];
    
    if (viewStats) {
      showWarehouseStatistics(pl);
      return;
    }
    
    if (isNaN(newBuyoutPrice) || newBuyoutPrice < 0) {
      pl.tell("§c一次性购买价格必须是非负整数！");
      return;
    }
    
    if (isNaN(newRentalPrice) || newRentalPrice < 0) {
      pl.tell("§c租赁价格必须是非负整数！");
      return;
    }
    
    if (isNaN(newMinRentalTime) || newMinRentalTime <= 0) {
      pl.tell("§c最低租用时间必须是正整数！");
      return;
    }
    
    if (isNaN(newMaxSlots) || newMaxSlots <= 0) {
      pl.tell("§c仓库最大容量必须是正整数！");
      return;
    }
    
    config.set('enableGiftSystem', newEnabled);
    config.set('warehouseMode', newMode);
    config.set('warehouseBuyoutPrice', newBuyoutPrice);
    config.set('warehouseRentalPrice', newRentalPrice);
    config.set('warehouseMinRentalTime', newMinRentalTime);
    config.set('maxWarehouseSlots', newMaxSlots);
    
    const eco = getEconomyInterface();
    const modeNames = ["免费使用", "一次性购买", "按时间租用"];
    pl.tell(`§a仓库系统配置已更新！\n§e模式：${modeNames[newMode]}\n§e容量：${newMaxSlots}\n§e购买价格：${newBuyoutPrice} ${eco.name}\n§e租赁价格：${newRentalPrice} ${eco.name}/分钟`);
  });
}

function showWarehouseStatistics(player) {
  const form = mc.newCustomForm();
  form.setTitle("§8§l仓库系统统计");
  
  let totalUsers = 0;
  let accessUsers = 0;
  let totalItems = 0;
  let giftItems = 0;
  let warehouseRevenue = 0;
  let activeRentalUsers = 0;
  let expiredUsers = 0;
  
  const mode = config.get('warehouseMode') || 0;
  const buyoutPrice = config.get('warehouseBuyoutPrice') || 10000;
  const rentalPrice = config.get('warehouseRentalPrice') || 1;
  
  for (const xuid in warehouseData) {
    const userData = warehouseData[xuid];
    totalUsers++;
    
    if (mode === 1 && userData.purchased) {
      accessUsers++;
      warehouseRevenue += buyoutPrice;
    } else if (mode === 2) {
      if (userData.expireTime) {
        if (Date.now() < userData.expireTime) {
          accessUsers++;
          activeRentalUsers++;
        } else {
          expiredUsers++;
        }
      }
    } else if (mode === 0) {
      accessUsers++;
    }
    
    if (userData.items) {
      totalItems += userData.items.length;
      giftItems += userData.items.filter(item => 
        item.description && typeof item.description === 'string' && item.description.indexOf('礼物') !== -1
      ).length;
    }
  }
  
  let content = `§e仓库系统使用统计：\n\n`;
  const modeNames = ["免费模式", "购买模式", "租用模式"];
  content += `§b当前模式：§a${modeNames[mode]}\n`;
  content += `§b总用户数：§a${totalUsers}\n`;
  
  if (mode === 0) {
    content += `§b可用用户：§a${accessUsers} §f(全部)\n\n`;
  } else if (mode === 1) {
    content += `§b已购买用户：§a${accessUsers}§f/§a${totalUsers} §f(${totalUsers > 0 ? Math.round((accessUsers/totalUsers)*100) : 0}%)\n`;
    content += `§b未购买用户：§c${totalUsers - accessUsers}\n\n`;
  } else if (mode === 2) {
    content += `§b活跃租用用户：§a${activeRentalUsers}§f/§a${totalUsers} §f(${totalUsers > 0 ? Math.round((activeRentalUsers/totalUsers)*100) : 0}%)\n`;
    content += `§b已过期用户：§c${expiredUsers}\n`;
    content += `§b未租用用户：§e${totalUsers - activeRentalUsers - expiredUsers}\n\n`;
  }
  
  content += `§b总存储物品：§a${totalItems}§f个\n`;
  content += `§b礼物物品：§d${giftItems}§f个 §f(${totalItems > 0 ? Math.round((giftItems/totalItems)*100) : 0}%)\n`;
  content += `§b普通物品：§f${totalItems - giftItems}§f个\n\n`;
  
  if (mode === 1) {
    content += `§b仓库总收入：§e${warehouseRevenue} ${getEconomyInterface().name}\n`;
  } else if (mode === 2) {
    content += `§b租用价格：§e${rentalPrice} ${getEconomyInterface().name}/分钟\n`;
  }
  
  content += `§b平均每用户：§f${totalUsers > 0 ? Math.round(totalItems/totalUsers*100)/100 : 0}§f个物品\n`;
  
  const topUsers = Object.entries(warehouseData)
    .map(([xuid, data]) => {
      let status = '§c无权限';
      if (mode === 0) {
        status = '§a免费使用';
      } else if (mode === 1 && data.purchased) {
        status = '§a已购买';
      } else if (mode === 2 && data.expireTime) {
        if (Date.now() < data.expireTime) {
          const remaining = data.expireTime - Date.now();
          const timeStr = formatTime(remaining);
          status = `§a租用中(${timeStr})`;
        } else {
          status = '§c已过期';
        }
      }
      
      return {
        name: data.playerName || xuid.substring(0, 8),
        itemCount: data.items ? data.items.length : 0,
        status: status
      };
    })
    .sort((a, b) => b.itemCount - a.itemCount)
    .slice(0, 5);
  
  content += `\n§e仓库使用排行榜（前5）：\n`;
  topUsers.forEach((user, idx) => {
    content += `§3${idx + 1}. §b${user.name}: §a${user.itemCount}§f个 ${user.status}\n`;
  });
  
  form.addLabel(content);
  player.sendForm(form, (pl, data) => {
    if(data !== null) {
      showWarehouseSystemConfig(pl);
    }
  });
}

function showAdminViewPlayerWarehouse(player) {
  if (!player.isOP()) {
    player.tell("§c此功能仅限管理员使用！");
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle('§6§l查看玩家仓库');
  form.setContent('§e请选择查看方式：');
  addReturnButton(form);
  form.addButton('§a在线玩家\n§f查看当前在线玩家仓库', 'textures/ui/multiplayer_glyph_color');
  form.addButton('§b搜索玩家\n§f按名字搜索玩家', 'textures/ui/magnifyingGlass');
  form.addButton('§d全部玩家仓库\n§f查看所有有仓库记录的玩家', 'textures/ui/icon_steve');
  form.addButton('§e仓库物品统计\n§f查看全服仓库物品统计', 'textures/ui/book_frame');
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === 0) {
      showAdminMenu(pl);
      return;
    }
    
    switch (id) {
      case 1:
        showAdminOnlinePlayersWarehouse(pl);
        break;
      case 2:
        showAdminSearchPlayerWarehouse(pl);
        break;
      case 3:
        showAdminAllPlayersWarehouse(pl, 1, "");
        break;
      case 4:
        showAdminWarehouseGlobalStats(pl);
        break;
    }
  });
}

function showAdminOnlinePlayersWarehouse(player) {
  const onlinePlayers = mc.getOnlinePlayers();
  
  if (onlinePlayers.length === 0) {
    player.tell('§c当前没有在线玩家！');
    showAdminViewPlayerWarehouse(player);
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle('§a§l在线玩家仓库');
  form.setContent('§e选择要查看仓库的在线玩家：');
  addReturnButton(form);
  
  onlinePlayers.forEach(p => {
    const playerData = warehouseData[p.xuid];
    const itemCount = playerData && playerData.items ? playerData.items.length : 0;
    const hasAccess = hasWarehouseAccess(p.xuid);
    const statusText = hasAccess ? '§a已开通' : '§c未开通';
    form.addButton(`§b${p.realName}\n§f物品: ${itemCount}种 ${statusText}`, 'textures/ui/icon_steve');
  });
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === 0) {
      showAdminViewPlayerWarehouse(pl);
      return;
    }
    
    const selectedPlayer = onlinePlayers[id - 1];
    if (selectedPlayer) {
      showAdminPlayerWarehouseDetail(pl, selectedPlayer.xuid, selectedPlayer.realName);
    }
  });
}

function showAdminSearchPlayerWarehouse(player) {
  const form = mc.newCustomForm();
  form.setTitle('§b§l搜索玩家仓库');
  form.addLabel('§e输入玩家名称进行搜索\n§f支持模糊搜索，可搜索在线和离线玩家');
  form.addInput('§e玩家名称：', '输入玩家名...');
  
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showAdminViewPlayerWarehouse(pl);
      return;
    }
    
    const keyword = data[1]?.trim();
    if (!keyword) {
      pl.tell('§c请输入搜索关键字！');
      showAdminSearchPlayerWarehouse(pl);
      return;
    }
    
    const results = searchPlayersByName(keyword);
    
    const warehouseResults = [];
    for (const xuid in warehouseData) {
      const wData = warehouseData[xuid];
      if (wData.playerName && wData.playerName.toLowerCase().includes(keyword.toLowerCase())) {
        const exists = results.find(r => r.xuid === xuid);
        if (!exists) {
          warehouseResults.push({
            xuid: xuid,
            name: wData.playerName,
            lastSeen: 0,
            isCurrentName: true,
            fromWarehouse: true
          });
        }
      }
    }
    
    const allResults = [...results, ...warehouseResults];
    
    if (allResults.length === 0) {
      pl.tell(`§c未找到匹配 "${keyword}" 的玩家！`);
      showAdminSearchPlayerWarehouse(pl);
      return;
    }
    
    showAdminSearchWarehouseResults(pl, allResults, keyword);
  });
}

function showAdminSearchWarehouseResults(player, results, keyword) {
  const form = mc.newSimpleForm();
  form.setTitle('§b§l搜索结果');
  form.setContent(`§e找到 ${results.length} 个匹配 "${keyword}" 的玩家：`);
  addReturnButton(form);
  
  results.forEach(result => {
    const playerData = warehouseData[result.xuid];
    const itemCount = playerData && playerData.items ? playerData.items.length : 0;
    const onlinePlayer = mc.getPlayer(result.xuid);
    const onlineStatus = onlinePlayer ? '§a在线' : '§7离线';
    const historyNote = result.historyName ? `\n§3曾用名: ${result.historyName}` : '';
    form.addButton(`§b${result.name} ${onlineStatus}\n§f物品: ${itemCount}种${historyNote}`, 'textures/ui/icon_steve');
  });
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === 0) {
      showAdminSearchPlayerWarehouse(pl);
      return;
    }
    
    const selectedResult = results[id - 1];
    if (selectedResult) {
      showAdminPlayerWarehouseDetail(pl, selectedResult.xuid, selectedResult.name);
    }
  });
}

function showAdminAllPlayersWarehouse(player, page, keyword) {
  let allPlayers = [];
  
  for (const xuid in warehouseData) {
    const wData = warehouseData[xuid];
    const playerName = wData.playerName || (playerRecords[xuid] ? playerRecords[xuid].name : xuid.substring(0, 8));
    const itemCount = wData.items ? wData.items.length : 0;
    
    if (keyword && keyword.trim() !== "") {
      const lowerKeyword = keyword.toLowerCase();
      if (!playerName.toLowerCase().includes(lowerKeyword)) {
        continue;
      }
    }
    
    allPlayers.push({
      xuid: xuid,
      name: playerName,
      itemCount: itemCount,
      hasAccess: hasWarehouseAccess(xuid)
    });
  }
  
  allPlayers.sort((a, b) => b.itemCount - a.itemCount);
  
  const totalPlayers = allPlayers.length;
  const totalPages = Math.ceil(totalPlayers / PAGE_SIZE) || 1;
  if (page < 1) page = 1;
  if (page > totalPages) page = totalPages;
  
  const start = (page - 1) * PAGE_SIZE;
  const end = Math.min(start + PAGE_SIZE, totalPlayers);
  const currentPlayers = allPlayers.slice(start, end);
  
  const form = mc.newSimpleForm();
  form.setTitle(`§d§l全部玩家仓库 - 第${page}/${totalPages}页`);
  form.setContent(`§e共 ${totalPlayers} 个玩家有仓库记录${keyword ? ` (筛选: ${keyword})` : ''}\n§f按物品数量排序`);
  addReturnButton(form);
  
  const hasPrev = page > 1;
  const hasNext = page < totalPages;
  
  if (hasPrev) {
    form.addButton('§a<< 上一页', 'textures/ui/arrow_left');
  }
  if (hasNext) {
    form.addButton('§a下一页 >>', 'textures/ui/arrow_right');
  }
  
  form.addButton('§e搜索筛选', 'textures/ui/magnifyingGlass');
  
  currentPlayers.forEach(p => {
    const onlinePlayer = mc.getPlayer(p.xuid);
    const onlineStatus = onlinePlayer ? '§a在线' : '§7离线';
    const accessStatus = p.hasAccess ? '' : ' §c(未开通)';
    form.addButton(`§b${p.name} ${onlineStatus}\n§f物品: ${p.itemCount}种${accessStatus}`, 'textures/ui/icon_steve');
  });
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === 0) {
      showAdminViewPlayerWarehouse(pl);
      return;
    }
    
    let buttonIndex = 1;
    
    if (hasPrev && id === buttonIndex) {
      showAdminAllPlayersWarehouse(pl, page - 1, keyword);
      return;
    }
    if (hasPrev) buttonIndex++;
    
    if (hasNext && id === buttonIndex) {
      showAdminAllPlayersWarehouse(pl, page + 1, keyword);
      return;
    }
    if (hasNext) buttonIndex++;
    
    if (id === buttonIndex) {
      showAdminAllPlayersWarehouseSearch(pl);
      return;
    }
    buttonIndex++;
    
    const playerIndex = id - buttonIndex;
    if (playerIndex >= 0 && playerIndex < currentPlayers.length) {
      const selectedPlayer = currentPlayers[playerIndex];
      showAdminPlayerWarehouseDetail(pl, selectedPlayer.xuid, selectedPlayer.name);
    }
  });
}

function showAdminAllPlayersWarehouseSearch(player) {
  const form = mc.newCustomForm();
  form.setTitle('§e§l筛选玩家');
  form.addInput('§e输入玩家名称筛选：', '留空显示全部');
  
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showAdminAllPlayersWarehouse(pl, 1, "");
      return;
    }
    
    const keyword = data[0]?.trim() || "";
    showAdminAllPlayersWarehouse(pl, 1, keyword);
  });
}

function showAdminPlayerWarehouseDetail(player, targetXuid, targetName) {
  const playerData = warehouseData[targetXuid];
  
  const form = mc.newSimpleForm();
  form.setTitle(`§6§l${targetName} 的仓库`);
  
  let statusContent = `§e玩家：§b${targetName}\n§eXUID：§f${targetXuid}\n\n`;
  
  const onlinePlayer = mc.getPlayer(targetXuid);
  statusContent += `§e状态：${onlinePlayer ? '§a在线' : '§7离线'}\n`;
  
  const mode = config.get('warehouseMode') || 0;
  const modeNames = ["免费模式", "购买模式", "租用模式"];
  statusContent += `§e仓库模式：§f${modeNames[mode]}\n`;
  
  if (mode === 1) {
    const purchased = playerData && playerData.purchased;
    statusContent += `§e购买状态：${purchased ? '§a已购买' : '§c未购买'}\n`;
    if (purchased && playerData.purchaseTime) {
      statusContent += `§e购买时间：§f${new Date(playerData.purchaseTime).toLocaleString()}\n`;
    }
  } else if (mode === 2) {
    if (playerData && playerData.expireTime) {
      const remaining = playerData.expireTime - Date.now();
      if (remaining > 0) {
        statusContent += `§e租用状态：§a有效\n`;
        statusContent += `§e剩余时间：§f${formatTime(remaining)}\n`;
        statusContent += `§e到期时间：§f${new Date(playerData.expireTime).toLocaleString()}\n`;
      } else {
        statusContent += `§e租用状态：§c已过期\n`;
        statusContent += `§e过期时间：§f${new Date(playerData.expireTime).toLocaleString()}\n`;
      }
    } else {
      statusContent += `§e租用状态：§c未租用\n`;
    }
  }
  
  const itemCount = playerData && playerData.items ? playerData.items.length : 0;
  const maxSlots = config.get('maxWarehouseSlots') || 50;
  statusContent += `\n§e仓库物品：§a${itemCount}§f/§a${maxSlots}§f 种\n`;
  
  if (playerData && playerData.items && playerData.items.length > 0) {
    let giftCount = 0;
    let normalCount = 0;
    playerData.items.forEach(item => {
      if (item.description && item.description.indexOf('礼物') !== -1) {
        giftCount++;
      } else {
        normalCount++;
      }
    });
    statusContent += `§f- 礼物物品：§d${giftCount}§f 种\n`;
    statusContent += `§f- 普通物品：§f${normalCount}§f 种\n`;
  }
  
  form.setContent(statusContent);
  
  form.addButton('§c返回玩家列表', 'textures/ui/arrow_dark_left_stretch');
  
  if (itemCount > 0) {
    form.addButton(`§a查看仓库物品 §f(${itemCount}种)`, 'textures/ui/icon_steve');
  }
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === 0) {
      showAdminViewPlayerWarehouse(pl);
      return;
    }
    
    if (id === 1 && itemCount > 0) {
      showAdminPlayerWarehouseItems(pl, targetXuid, targetName, 1);
    }
  });
}

function showAdminPlayerWarehouseItems(player, targetXuid, targetName, page) {
  const playerData = warehouseData[targetXuid];
  
  if (!playerData || !playerData.items || playerData.items.length === 0) {
    player.tell('§c该玩家仓库中没有物品！');
    showAdminPlayerWarehouseDetail(player, targetXuid, targetName);
    return;
  }
  
  const items = playerData.items;
  const totalItems = items.length;
  const totalPages = Math.ceil(totalItems / PAGE_SIZE) || 1;
  if (page < 1) page = 1;
  if (page > totalPages) page = totalPages;
  
  const start = (page - 1) * PAGE_SIZE;
  const end = Math.min(start + PAGE_SIZE, totalItems);
  const currentItems = items.slice(start, end);
  
  const form = mc.newSimpleForm();
  form.setTitle(`§6§l${targetName} 的仓库物品 - 第${page}/${totalPages}页`);
  form.setContent(`§e共 ${totalItems} 种物品\n§f点击物品查看详情`);
  
  form.addButton('§c返回玩家信息', 'textures/ui/arrow_dark_left_stretch');
  
  const hasPrev = page > 1;
  const hasNext = page < totalPages;
  
  if (hasPrev) {
    form.addButton('§a<< 上一页', 'textures/ui/arrow_left');
  }
  if (hasNext) {
    form.addButton('§a下一页 >>', 'textures/ui/arrow_right');
  }
  
  currentItems.forEach((item, index) => {
    let itemName = "未知物品";
    let icon = 'textures/ui/icon_setting';
    
    try {
      const tmp = safeNewItem(NBT.parseSNBT(item.itemData));
      if (tmp && !tmp.isNull()) {
        itemName = getItemDisplayName(tmp, false);
        let tx = JSON.parse(textureData.read());
        if (tx.hasOwnProperty(tmp.type) && tx[tmp.type] && tx[tmp.type] !== 'null') {
          icon = tx[tmp.type];
        }
      }
    } catch (e) {}
    
    const timeStr = new Date(item.timestamp).toLocaleString();
    const isGift = item.description && item.description.indexOf('礼物') !== -1;
    const giftTag = isGift ? '§d[礼物] ' : '';
    
    form.addButton(`${giftTag}§a${itemName} §fx${item.quantity}\n§3${timeStr}`, icon);
  });
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === 0) {
      showAdminPlayerWarehouseDetail(pl, targetXuid, targetName);
      return;
    }
    
    let buttonIndex = 1;
    
    if (hasPrev && id === buttonIndex) {
      showAdminPlayerWarehouseItems(pl, targetXuid, targetName, page - 1);
      return;
    }
    if (hasPrev) buttonIndex++;
    
    if (hasNext && id === buttonIndex) {
      showAdminPlayerWarehouseItems(pl, targetXuid, targetName, page + 1);
      return;
    }
    if (hasNext) buttonIndex++;
    
    const itemIndex = start + (id - buttonIndex);
    if (itemIndex >= 0 && itemIndex < totalItems) {
      showAdminWarehouseItemDetail(pl, targetXuid, targetName, itemIndex, page);
    }
  });
}

function showAdminWarehouseItemDetail(player, targetXuid, targetName, itemIndex, returnPage) {
  const playerData = warehouseData[targetXuid];
  
  if (!playerData || !playerData.items || itemIndex >= playerData.items.length) {
    player.tell('§c物品不存在！');
    showAdminPlayerWarehouseItems(player, targetXuid, targetName, returnPage);
    return;
  }
  
  const item = playerData.items[itemIndex];
  let itemName = "未知物品";
  let itemType = "未知";
  let isEnchanted = false;
  let itemLore = [];
  let customName = null;
  
  try {
    const tmp = safeNewItem(NBT.parseSNBT(item.itemData));
    if (tmp && !tmp.isNull()) {
      itemName = getItemDisplayName(tmp, false);
      itemType = tmp.type;
      isEnchanted = tmp.isEnchanted;
      itemLore = tmp.lore || [];
      customName = getItemCustomNameFromNBT(tmp);
    }
  } catch (e) {}
  
  const form = mc.newCustomForm();
  form.setTitle('§6§l仓库物品详情');
  
  let content = `§e玩家：§b${targetName}\n\n`;
  content += `§e物品名称：§a${itemName}\n`;
  content += `§e物品类型：§f${itemType}\n`;
  content += `§e数量：§a${item.quantity}\n`;
  content += `§e附魔：${isEnchanted ? '§a已附魔' : '§f无附魔'}\n`;
  
  if (customName) {
    content += `§e自定义名：§f${customName}\n`;
  }
  
  if (itemLore && itemLore.length > 0) {
    content += `§e物品描述：\n§f${itemLore.join('\n')}\n`;
  }
  
  content += `\n§e存入时间：§f${new Date(item.timestamp).toLocaleString()}\n`;
  content += `§e来源描述：§f${item.description || '无'}\n`;
  
  const isGift = item.description && item.description.indexOf('礼物') !== -1;
  if (isGift) {
    content += `\n§d§l[这是一个礼物物品]`;
  }
  
  form.addLabel(content);
  
  player.sendForm(form, (pl, data) => {
    showAdminPlayerWarehouseItems(pl, targetXuid, targetName, returnPage);
  });
}

function showAdminWarehouseGlobalStats(player) {
  const form = mc.newCustomForm();
  form.setTitle('§e§l全服仓库物品统计');
  
  const itemStats = {};
  let totalItems = 0;
  let totalQuantity = 0;
  let giftItems = 0;
  let giftQuantity = 0;
  
  for (const xuid in warehouseData) {
    const wData = warehouseData[xuid];
    if (!wData.items) continue;
    
    wData.items.forEach(item => {
      totalItems++;
      totalQuantity += item.quantity || 1;
      
      const isGift = item.description && item.description.indexOf('礼物') !== -1;
      if (isGift) {
        giftItems++;
        giftQuantity += item.quantity || 1;
      }
      
      let itemName = "未知物品";
      try {
        const tmp = safeNewItem(NBT.parseSNBT(item.itemData));
        if (tmp && !tmp.isNull()) {
          itemName = getItemDisplayName(tmp, false);
        }
      } catch (e) {}
      
      if (!itemStats[itemName]) {
        itemStats[itemName] = { count: 0, quantity: 0 };
      }
      itemStats[itemName].count++;
      itemStats[itemName].quantity += item.quantity || 1;
    });
  }
  
  const sortedItems = Object.entries(itemStats)
    .sort((a, b) => b[1].quantity - a[1].quantity)
    .slice(0, 20);
  
  let content = `§e§l=== 全服仓库统计 ===§r\n\n`;
  content += `§b总玩家数：§a${Object.keys(warehouseData).length}\n`;
  content += `§b物品种类数：§a${totalItems}\n`;
  content += `§b物品总数量：§a${totalQuantity}\n`;
  content += `§b礼物种类数：§d${giftItems} §f(${totalItems > 0 ? Math.round(giftItems/totalItems*100) : 0}%)\n`;
  content += `§b礼物总数量：§d${giftQuantity}\n\n`;
  
  content += `§e§l=== 物品数量排行TOP20 ===§r\n`;
  sortedItems.forEach((item, idx) => {
    const [name, stats] = item;
    content += `§3${idx + 1}. §b${name}\n`;
    content += `   §f存放次数: ${stats.count} | 总数量: ${stats.quantity}\n`;
  });
  
  form.addLabel(content);
  
  player.sendForm(form, (pl, data) => {
    showAdminViewPlayerWarehouse(pl);
  });
}

function setForbiddenItems(player){
  const invItems=getPlayerInventoryItems(player);
  const itemKeys=Object.keys(invItems);
  if(itemKeys.length===0){
    player.tell('§c§l您的背包中没有物品！');
    return;
  }
  const form=mc.newCustomForm();
  form.setTitle('§b§l设置不可上架物品');
  const itemNames=itemKeys.map((k,idx)=>{
    const {item}=invItems[k];
    return `${idx+1}. ${getItemDisplayName(item,false)}`;
  });
  form.addDropdown('§e§l请选择物品:', itemNames);
  form.addInput('§e§l请输入原因(可选):','原因','');
  player.sendForm(form,(pl,data)=>{
    if(!data)return;
    const selIdx=data[0];
    const reason=data[1]?.trim()||'未提供原因';
    const selectedKey=itemKeys[selIdx];
    const it=invItems[selectedKey].item;
    const itemTypeId = it.type;
    if(!forbiddenItems.includes(itemTypeId)){
      forbiddenItems.push(itemTypeId);
      pl.tell(`§a已将 ${getItemDisplayName(it,false)} (§b${itemTypeId}§a) 设置为不可上架。原因:${reason}`);
    } else {
      pl.tell(`§c该物品(§b${itemTypeId}§c)已被设置为不可上架。`);
    }
    saveForbiddenItems();
  });
}
function showManageShopMenu(player){
  const shop=shopsData[player.xuid];
  if(!shop){
    player.tell("§c您没有店铺可管理！");
    return;
  }
  const economy=getEconomyInterface();
  const shopNameChangeCost=config.get('shopNameChangeCost');
  const shopNameChangeCooldown=config.get('shopNameChangeCooldown')*3600*1000;
  const form=mc.newSimpleForm();
  form.setTitle('§b§l管理店铺');
  form.setContent('§e§l请选择一个操作：');
  addReturnButton(form);
  form.addButton('§a§l修改店铺名称','textures/ui/book_edit_default');
  form.addButton('§b§l设置店铺公告', 'textures/ui/creative_icon');
  const hasItems = Object.keys(shop.items).length > 0;
  form.addButton(
    hasItems ? "§c删除店铺（请先下架所有物品）" : "§c删除店铺",
    "textures/ui/trash",
    hasItems 
  );
  form.addButton(shop.isOpen?'§e§l关闭商店\n当前状态:开启':'§a§l开启商店\n当前状态:关闭', shop.isOpen?'textures/ui/crossout':'textures/ui/check');
  player.sendForm(form,(pl,id)=>{
    if(id==null)return;
    if(id===0){
      showMyShopMenu(pl);
      return;
    }
    let idx=1;
    if(id===idx++){
      const now=Date.now();
      if(now-shop.lastNameChange<shopNameChangeCooldown){
        const remain=((shopNameChangeCooldown-(now-shop.lastNameChange))/3600000).toFixed(1);
        pl.tell(`§c距离下次改名还有${remain}小时！`);
        return;
      }
      const f=mc.newCustomForm();
      f.setTitle('§a§l修改店铺名称');
      f.addInput('§e§l新的店铺名称(最多10字符):','店铺名称');
      f.addLabel(`§e需要花费:§3${shopNameChangeCost}§f${economy.name}`);
      pl.sendForm(f,(pl2,d)=>{
        if(!d)return;
        const newName=d[0]?.trim();
        if(!newName){
          pl2.tell('§c店铺名不能为空!');
          return;
        }
        if(newName.length>10){
          pl2.tell('§c店铺名不能超过10字符!');
          return;
        }
        if(economy.get(pl2)<shopNameChangeCost){
          pl2.tell('§c经济不足，无法改名！');
          return;
        }
        economy.reduce(pl2,shopNameChangeCost);
        shop.name=newName;
        shop.lastNameChange=Date.now();
        saveShopsData();
        pl2.tell(`§a店铺名称已修改为:§3${newName}`);
      });
    } else if(id===idx++){
      setShopAnnouncement(pl, shop);
    } else if(id===idx++){
      const hasItems = Object.keys(shop.items).length > 0;
      if(hasItems){
        pl.tell('§c无法删除店铺！您的店铺中还有物品，请先下架所有物品再尝试删除店铺。');
        return;
      }
      const cf=mc.newCustomForm();
      cf.setTitle('§c§l删除店铺');
      cf.addLabel('§c警告：删除店铺后将无法恢复！\n§c删除店铺不会退还任何资金（包括创建费用、升级费用等）！\n§e请确认您是否要删除店铺？');
      cf.addSwitch('§e确认删除店铺',false);
      pl.sendForm(cf,(pl2,dd)=>{
        if(!dd)return;
        const confirm=dd[1];
        if(confirm){
          const finalConfirmForm = mc.newCustomForm();
          finalConfirmForm.setTitle('§c最终确认删除店铺');
          finalConfirmForm.addLabel('§c这是最后一次确认机会！\n§c删除后店铺将永久消失，不会退还任何费用！\n§e您真的确定要删除店铺吗？');
          finalConfirmForm.addSwitch('§c我完全理解并确认删除店铺',false);
          pl2.sendForm(finalConfirmForm,(pl3,finalData)=>{
            if(!finalData)return;
            const finalConfirm=finalData[1];
            if(finalConfirm){
              delete shopsData[pl3.xuid];
            saveShopsData();
              if(rankingData[pl3.xuid]){
                delete rankingData[pl3.xuid];
              saveRankingData();
            }
              pl3.tell('§a店铺已成功删除！');
          } else {
              pl3.tell('§c操作已取消。');
          }
          });
        } else {
          pl2.tell('§c操作已取消。');
        }
      });
    } else if(id===idx){
      shop.isOpen=!shop.isOpen;
      saveShopsData();
      pl.tell(`§a店铺已${shop.isOpen?'开启':'关闭'}！`);
    }
  });
}
function setShopAnnouncement(player, shop) {
  const form = mc.newCustomForm();
  form.setTitle("§b§l设置店铺公告");
  form.addLabel("§e设置一条公告，将显示在您店铺的首页");
  form.addInput("§e输入公告内容(最多100字符):", "欢迎光临我的店铺...", shop.announcement || "");
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    const announcement = data[1]?.trim();
    if (announcement.length > 100) {
      pl.tell("§c公告内容不能超过100字符！");
      return;
    }  
    shop.announcement = announcement;
    saveShopsData();
    pl.tell("§a店铺公告设置成功！");
  });
}
function showShopDiscountMenu(player, shop) {
  const shopItems = Object.keys(shop.items);
  if (shopItems.length === 0) {
    player.tell("§c您的店铺中没有物品可以打折！");
    return;
  }
  
  const form = mc.newCustomForm();
  form.setTitle("§d§l店铺物品折扣");
  form.addLabel("§e请选择要打折的物品，所选物品将在下一步设置折扣率");
  shopItems.forEach(key => {
    const item = shop.items[key];
    const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
    const showName = getItemDisplayName(tmp, false);
    const hasDiscount = item.discount !== undefined;
    const discountInfo = hasDiscount ? 
      `§a[当前折扣: ${item.discount}折，剩余${Math.floor((item.discountEndTime - Date.now()) / 60000)}分钟]` : 
      "§3[无折扣]";
    form.addSwitch(`${showName} - 原价:${item.price} ${discountInfo}`, false);
  });
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    const selectedItems = [];
    for (let i = 0; i < shopItems.length; i++) {
      if (data[i + 1] === true) { 
        selectedItems.push({
          key: shopItems[i],
          item: shop.items[shopItems[i]]
        });
      }
    } 
    if (selectedItems.length === 0) {
      player.tell("§c未选择任何物品进行打折！");
      return;
    }
    showDiscountSettingForm(pl, shop, selectedItems);
  });
}


function showDiscountSettingForm(player, shop, selectedItems) {
  const form = mc.newCustomForm();
  form.setTitle("§d§l设置折扣");
  let itemsInfo = "§e已选物品：\n";
  selectedItems.forEach(({ item }) => {
    const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
    const showName = getItemDisplayName(tmp, false);
    itemsInfo += `§3- ${showName} (原价:${item.price})\n`;
  });
  form.addLabel(itemsInfo);
  form.addSlider("§e设置折扣率 (几折)", 1, 9, 1, 7);
  form.addInput("§e折扣持续时间 (分钟)", "输入数字", "60");
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    const discountRate = data[1]; 
    const durationMinutes = parseInt(data[2]);
    
    if (isNaN(durationMinutes) || durationMinutes <= 0) {
      pl.tell("§c折扣持续时间必须是正数！");
      return;
    }
    const discountEndTime = Date.now() + (durationMinutes * 60 * 1000);
    let broadcastMsg = `§d店铺折扣: §f${shop.name} 店铺开始促销！`;
    const notifyDiscountToAll = config.get('notifyDiscountToAll');
    selectedItems.forEach(({ key, item }) => {
      if (item.originalPrice === undefined) {
        item.originalPrice = item.price;
      }
      
      item.discount = discountRate;
      item.discountEndTime = discountEndTime;
      const discountedPrice = Math.floor(item.originalPrice * (discountRate / 10));
      item.price = discountedPrice;
      
      const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
      const showName = getItemDisplayName(tmp, false);
      pl.sendToast("§d物品折扣设置成功", `${showName} 已设置为${discountRate}折`);
      if (notifyDiscountToAll) {
        const onlinePlayers = mc.getOnlinePlayers();
        onlinePlayers.forEach(p => {
          if (p.xuid !== pl.xuid) { 
            p.sendToast(`§d${shop.name} 店铺折扣`, `${showName} ${discountRate}折 ${durationMinutes}分钟`);
          }
        });
      }
      const discountMsg = {
        sender: "§d折扣系统",
        content: `§e${shop.name} §f店铺的 §a${showName} §f打折促销！§c${discountRate}§f折，原价:§c${item.originalPrice}§f, 现价:§c${discountedPrice}§f，持续:§c${durationMinutes}§f分钟`,
        timestamp: Date.now(),
        mentions: []
      };
      chatMessages.push(discountMsg);
      if (chatMessages.length > 30) chatMessages.shift();
      saveChatData();
    });
    
    saveShopsData();
    pl.tell(`§a已成功为 ${selectedItems.length} 个物品设置${discountRate}折，持续 ${durationMinutes} 分钟`);
  });
}

function showBuyAdvertSlotMenu(player) {
  const shop = shopsData[player.xuid];
  if(!shop){
    player.tell("§c您尚未创建店铺，无法购买广告位。");
    return;
  }
  clearExpiredAdvertSlots();
  if(shop.advertSlot && shop.advertSlot>=1 && shop.advertSlot<=10){
    const now = Date.now();
    if(shop.advertExpire && now < shop.advertExpire) {
      let remainMs = shop.advertExpire - now;
      let hoursLeft = (remainMs / 3600000).toFixed(1);
      player.tell(`§e您已拥有广告位#${shop.advertSlot}，剩余时间约 ${hoursLeft} 小时。到期后才可再次购买！`);
      return;
    } else {
      shop.advertSlot = 0;
      shop.advertExpire = 0;
      saveShopsData();
    }
  }
  const form = mc.newSimpleForm();
  form.setTitle("§d§l购买广告位");
  form.setContent("§e请选择要购买的广告位：");
  addReturnButton(form);
  for(let i=1; i<=10; i++){
    let occupant = getShopByAdvertSlot(i);
    if(occupant){
      form.addButton(`§a广告位#${i}\n§c已被【${occupant.name}】占用`,"textures/ui/crossout");
    } else {
      const advConf = config.get(`advertSlotsSetting.${i}`);
      if(!advConf || advConf.price<=0 || advConf.duration<=0 ){
        form.addButton(`§e广告位#${i}\n§c(未配置不可购)`, "textures/ui/crossout");
      } else {
        form.addButton(`§a广告位#${i}\n价格:${advConf.price},时长:${advConf.duration}h`,"textures/ui/MCoin");
      }
    }
  }
  player.sendForm(form,(pl,id)=>{
    if(id==null) return;
    if(id===0){
      showMyShopMenu(pl);
      return;
    }
    const slotNumber = id;
    if(slotNumber<1 || slotNumber>10){
      pl.tell('§c无效的广告位选择!');
      return;
    }
    let occupant = getShopByAdvertSlot(slotNumber);
    if(occupant){
      pl.tell(`§c广告位#${slotNumber}已被【${occupant.name}】占用！`);
      return;
    }
    let advConf = config.get(`advertSlotsSetting.${slotNumber}`);
    if(!advConf || advConf.price<=0 || advConf.duration<=0 ){
      pl.tell("§c此广告位尚未配置(或配置无效)，无法购买！");
      return;
    }
    confirmBuyAdvertSlot(pl, shop, slotNumber, advConf);
  });
}

function confirmBuyAdvertSlot(player, shop, slotNumber, advConf){
  const price = advConf.price;
  const hours = advConf.duration;
  const economy = getEconomyInterface();
  const cf = mc.newCustomForm();
  cf.setTitle(`§a确认购买广告位#${slotNumber}`);
  cf.addLabel(`§e广告位价格:§3${price} ${economy.name}\n§e持续时长:${hours} 小时\n\n§c是否确认购买?`);
  player.sendForm(cf, (pl, data)=>{
    if(!data) return;
    doBuyAdvertSlot(pl, shop, slotNumber, advConf);
  });
}

function doBuyAdvertSlot(player, shop, slotNumber, advConf){
  let occupant = getShopByAdvertSlot(slotNumber);
  if(occupant){
    player.tell(`§c广告位#${slotNumber}已被【${occupant.name}】占用！`);
    return;
  }
  if(shop.advertSlot && shop.advertSlot >= 1 && shop.advertSlot <= 10){
    const now = Date.now();
    if(shop.advertExpire && now < shop.advertExpire){
      let remainMs = shop.advertExpire - now;
      let hoursLeft = (remainMs / 3600000).toFixed(1);
      player.tell(`§c您的广告位尚未过期，剩余时间${hoursLeft}小时！`);
      return;
    } else {
      shop.advertSlot=0; 
      shop.advertExpire=0;
    }
  }
  const economy = getEconomyInterface();
  const price = advConf.price;
  const hours = advConf.duration;
  if (economy.get(player) < price) {
    player.tell(`§c需要${price} ${economy.name}购买广告位#${slotNumber}，您余额不足！`);
    return;
  }
  if (!economy.reduce(player, price)) {
    player.tell("§c扣费失败，无法购买广告位！");
    return;
  }
  const now = Date.now();
  const durationMs = hours * 3600 * 1000;
  shop.advertSlot = slotNumber;
  shop.advertExpire = now + durationMs;
  saveShopsData();
  player.tell(`§a成功购买广告位#${slotNumber}，持续：${hours}小时！`);
}

function showAdvertSlotsSettingMenu(player) {
  const form = mc.newSimpleForm();
  form.setTitle("§c§l配置广告位");
  form.setContent("§e点击编号进入编辑：");
  addReturnButton(form);
  for (let i = 1; i <= 10; i++) {
    const advConf = config.get(`advertSlotsSetting.${i}`) || {price:0,duration:0};
    const price = advConf.price || 0;
    const duration = advConf.duration || 0;
    form.addButton(`§a广告位 #${i}\n价格: ${price} | 时长: ${duration}h`, "textures/ui/anvil_icon");
  }
  player.sendForm(form, (pl, id) => {
    if (id==null) return;
    if (id===0) {
      showAdminMenu(pl);
      return;
    }
    showEditAdvertSlotForm(pl,id);
  });
}

function showEditAdvertSlotForm(player, slotNumber) {
  const advConf = config.get(`advertSlotsSetting.${slotNumber}`) || {price:0,duration:0};
  const price = advConf.price || 0;
  const duration = advConf.duration || 0;
  const form = mc.newCustomForm();
  form.setTitle(`§c配置广告位#${slotNumber}`);
  form.addInput("§e广告位价格:", "", price.toString());
  form.addInput("§e广告位持续时长(小时):", "", duration.toString());
  player.sendForm(form, (pl, data) => {
    if(!data) return;
    const newPrice = parseInt(data[0]);
    const newDur = parseInt(data[1]);
    if(isNaN(newPrice)||newPrice<0){
      pl.tell("§c价格必须是非负整数！");
      return;
    }
    if(isNaN(newDur)||newDur<0){
      pl.tell("§c持续时长必须是非负整数！");
      return;
    }
    config.set(`advertSlotsSetting.${slotNumber}`, { price: newPrice, duration: newDur });
    pl.tell(`§a已更新广告位#${slotNumber}的价格=${newPrice},时长=${newDur}h`);
  });
}

function showOfficialShopDirectMenu(player){
  const form=mc.newSimpleForm();
  form.setTitle('§e§l官方商店');
  form.setContent('§e§l请选择一个操作：');
  addReturnButton(form);
  let idx=1;
  if(config.get('showOfficialPurchase')){
    form.addButton('§a§l购买','textures/ui/bookshelf_flat');
    idx++;
  }
  form.addButton('§b§l回收','textures/ui/recap_glyph_color_2x');
  idx++;
  if(player.isOP()){
    form.addButton('§c§l管理商店','textures/ui/op');
    idx++;
  }
  player.sendForm(form,(pl,id)=>{
    if(id==null)return;
    if(id===0){
      showMainMenu(pl);
      return;
    }
    let cId=1;
    if(config.get('showOfficialPurchase')){
      if(id===cId++){
        let allKeys = Object.keys(officialShopData.purchaseItems);
        if(allKeys.length === 0){
          pl.tell("§c官方商店暂无物品出售。");
          return;
        }
        let offSortMode = config.get("officialShopSortMode") || "随机";
        if(offSortMode === "随机"){
          for(let i=allKeys.length-1; i>0; i--){
            let j = Math.floor(Math.random()*(i+1));
            [allKeys[i], allKeys[j]] = [allKeys[j], allKeys[i]];
          }
        }
        else if(offSortMode === "名字顺序"){
          allKeys.sort((aKey, bKey)=>{
            let A = officialShopData.purchaseItems[aKey];
            let B = officialShopData.purchaseItems[bKey];
            return A.name.localeCompare(B.name);
          });
        }
        officialPurchaseAllKeys = allKeys;
        showOfficialShopItems(pl, 1, "", "全部");
        return;
      }
    }
    
    if(id===cId++){
      showRecycleItems(pl);
      return;
    }
    if(player.isOP()&&id===cId++){
      manageOfficialShop(pl);
      return;
    }
  });
}

function showOfficialShopMenu(player, page, keyword){
  const form=mc.newSimpleForm();
  form.setTitle('§e§l官方商店');
  form.setContent('§e§l请选择一个操作：');
  addReturnButton(form);
  let idx=1;
  if(config.get('showOfficialPurchase')){
    form.addButton('§a§l购买','textures/ui/bookshelf_flat');
    idx++;
  }
  form.addButton('§b§l回收','textures/ui/recap_glyph_color_2x');
  idx++;
  if(player.isOP()){
    form.addButton('§c§l管理商店','textures/ui/op');
    idx++;
  }
  player.sendForm(form,(pl,id)=>{
    if(id==null)return;
    if(id===0){
      showMainMenu(pl);
      return;
    }
    let cId=1;
    if(config.get('showOfficialPurchase')){
      if(id===cId++){
        let allKeys = Object.keys(officialShopData.purchaseItems);
        if(allKeys.length === 0){
          pl.tell("§c官方商店暂无物品出售。");
          return;
        }
        let offSortMode = config.get("officialShopSortMode") || "随机";
        if(offSortMode === "随机"){
          for(let i=allKeys.length-1; i>0; i--){
            let j = Math.floor(Math.random()*(i+1));
            [allKeys[i], allKeys[j]] = [allKeys[j], allKeys[i]];
          }
        }
        else if(offSortMode === "名字顺序"){
          allKeys.sort((aKey, bKey)=>{
            let A = officialShopData.purchaseItems[aKey];
            let B = officialShopData.purchaseItems[bKey];
            return A.name.localeCompare(B.name);
          });
        }
        officialPurchaseAllKeys = allKeys;
        showOfficialShopItems(pl, 1, "", "全部");
        return;
      }
    }
    
    if(id===cId++){
      showRecycleItems(pl);
      return;
    }
    if(player.isOP()&&id===cId++){
      manageOfficialShop(pl);
      return;
    }
  });
}

function showOfficialCategorySelectMenu(player, page, keyword, currentCategory) {
  const categories = config.get('itemCategories') || ["全部"];
  const form = mc.newSimpleForm();
  form.setTitle("§e§l选择分类");
  form.setContent(`§e请选择要浏览的商品分类:`);
  addReturnButton(form);
  
  const categoryCounts = {};
  categories.forEach(cat => {
    categoryCounts[cat] = 0;
  });
  
  let totalCount = 0;
  for(const key in officialShopData.purchaseItems) {
    totalCount++;
    const item = officialShopData.purchaseItems[key];
    if(item.category && categories.includes(item.category)) {
      categoryCounts[item.category]++;
    }
  }
  categoryCounts["全部"] = totalCount;
  
  categories.forEach(cat => {
    const isSelected = cat === currentCategory;
    const itemCount = cat === "全部" ? totalCount : categoryCounts[cat] || 0;
    form.addButton(`${isSelected ? "§a" : "§f"}${cat} §3(${itemCount}件)`, 'textures/ui/recipe_book_icon');
  });
  
  player.sendForm(form, (pl, id) => {
    if(id === null) return;
    if(id === 0){
      showOfficialShopBrowseOptions(pl);
      return;
    }
    
    const selectedCategory = categories[id - 1];
    showOfficialShopItems(pl, 1, keyword, selectedCategory);
  });
}

function showOfficialShopBrowseOptions(player) {
  const form = mc.newSimpleForm();
  form.setTitle('§e§l选择浏览方式');
  form.setContent('§e请选择如何浏览商品：');
  addReturnButton(form);
  form.addButton('§a查看全部商品', 'textures/ui/crafting_table');
  
  if(config.get('enableItemCategories')) {
    form.addButton('§b按分类浏览', 'textures/ui/recipe_book_icon');
  }
  
  player.sendForm(form, (pl, id) => {
    if(id === null) return;
    if(id === 0) {
      showOfficialShopMenu(pl, 1, "");
      return;
    }
    
    if(id === 1) {
      let allKeys = Object.keys(officialShopData.purchaseItems);
      if(allKeys.length === 0){
        pl.tell("§c官方商店暂无物品出售。");
        return;
      }
      let offSortMode = config.get("officialShopSortMode") || "随机";
      if(offSortMode === "随机"){
        for(let i=allKeys.length-1; i>0; i--){
          let j = Math.floor(Math.random()*(i+1));
          [allKeys[i], allKeys[j]] = [allKeys[j], allKeys[i]];
        }
      }
      else if(offSortMode === "名字顺序"){
        allKeys.sort((aKey, bKey)=>{
          let A = officialShopData.purchaseItems[aKey];
          let B = officialShopData.purchaseItems[bKey];
          return A.name.localeCompare(B.name);
        });
      }
      officialPurchaseAllKeys = allKeys;
      showOfficialShopItems(pl, 1, "", "全部");
      return;
    } else if(id === 2 && config.get('enableItemCategories')) {
      let allKeys = Object.keys(officialShopData.purchaseItems);
      if(allKeys.length === 0){
        pl.tell("§c官方商店暂无物品出售。");
        return;
      }
      let offSortMode = config.get("officialShopSortMode") || "随机";
      if(offSortMode === "随机"){
        for(let i=allKeys.length-1; i>0; i--){
          let j = Math.floor(Math.random()*(i+1));
          [allKeys[i], allKeys[j]] = [allKeys[j], allKeys[i]];
        }
      }
      else if(offSortMode === "名字顺序"){
        allKeys.sort((aKey, bKey)=>{
          let A = officialShopData.purchaseItems[aKey];
          let B = officialShopData.purchaseItems[bKey];
          return A.name.localeCompare(B.name);
        });
      }
      officialPurchaseAllKeys = allKeys;
      showOfficialCategorySelectMenu(pl, 1, "", "全部");
      return;
    }
  });
}

function showRecycleBrowseOptions(player) {
  const form = mc.newSimpleForm();
  form.setTitle('§e§l选择浏览方式');
  form.setContent('§e请选择如何浏览回收物品：');
  addReturnButton(form);
  form.addButton('§a查看全部回收物品', 'textures/ui/crafting_table');
  
  if(config.get('enableItemCategories')) {
    form.addButton('§b按分类浏览', 'textures/ui/recipe_book_icon');
  }
  
  player.sendForm(form, (pl, id) => {
    if(id === null) return;
    if(id === 0) {
      showOfficialShopMenu(pl, 1, "");
      return;
    }
    
    if(id === 1) {
      showRecycleItems(pl);
      return;
    } else if(id === 2 && config.get('enableItemCategories')) {
      showRecycleCategorySelectMenu(pl);
      return;
    }
  });
}

function showRecycleCategorySelectMenu(player) {
  const categories = config.get('itemCategories') || ["全部"];
  const form = mc.newSimpleForm();
  form.setTitle("§e§l选择分类");
  form.setContent(`§e请选择要浏览的回收物品分类:`);
  addReturnButton(form);
  
  const categoryCounts = {};
  categories.forEach(cat => {
    categoryCounts[cat] = 0;
  });
  
  let totalCount = 0;
  for(const key in officialShopData.recycleItems) {
    totalCount++;
    const item = officialShopData.recycleItems[key];
    if(item.category && categories.includes(item.category)) {
      categoryCounts[item.category]++;
    }
  }
  categoryCounts["全部"] = totalCount;
  
  categories.forEach(cat => {
    const itemCount = cat === "全部" ? totalCount : categoryCounts[cat] || 0;
    form.addButton(`${cat} §3(${itemCount}件)`, 'textures/ui/recipe_book_icon');
  });
  
  player.sendForm(form, (pl, id) => {
    if(id === null) return;
    if(id === 0){
      showRecycleBrowseOptions(pl);
      return;
    }
    
    const selectedCategory = categories[id - 1];
    showRecycleItemsByCategory(pl, selectedCategory);
  });
}

function showRecycleItemsByCategory(player, categoryFilter = "全部") {
  const keys = Object.keys(officialShopData.recycleItems);
  if(keys.length === 0){
    player.tell('§c官方商店暂无回收物品。');
    return;
  }
  
  const economy = getEconomyInterface();
  
  let filteredKeys = keys;
  if(categoryFilter !== "全部") {
    filteredKeys = keys.filter(key => {
      const item = officialShopData.recycleItems[key];
      return item.category === categoryFilter;
    });
    
    if(filteredKeys.length === 0) {
      player.tell(`§c${categoryFilter}分类下没有回收物品。`);
      return;
    }
  }
  
  const offSortMode = config.get("officialShopSortMode") || "随机";
  let sortedKeys = [...filteredKeys];
  if(offSortMode === "随机"){
    for(let i=sortedKeys.length-1; i>0; i--){
      let j = Math.floor(Math.random()*(i+1));
      [sortedKeys[i], sortedKeys[j]] = [sortedKeys[j], sortedKeys[i]];
    }
  } else if(offSortMode === "名字顺序"){
    sortedKeys.sort((aKey, bKey)=>{
      const aObj = officialShopData.recycleItems[aKey];
      const bObj = officialShopData.recycleItems[bKey];
      return aObj.name.localeCompare(bObj.name);
    });
  }
  
  const form = mc.newSimpleForm();
  form.setTitle('§e§l官方商店回收');
  form.setContent(`§e当前分类: §a${categoryFilter}\n§e请选择要出售的物品:`);
  addReturnButton(form);
  sortedKeys.forEach(k => {
    const it = officialShopData.recycleItems[k];
    const tmp = mc.newItem(NBT.parseSNBT(it.itemData));
    const show = getItemDisplayName(tmp, false);
    let tx = JSON.parse(textureData.read());
    let icon = (tx.hasOwnProperty(tmp.type) && tx[tmp.type] && tx[tmp.type] !== 'null')
      ? tx[tmp.type] : default_icon_path;
    
    const originalPrice = it.price;
    const perCount = it.perCount || 1;
    const currentPrice = getDynamicRecyclePrice(k, originalPrice);
    const dynamicConfig = config.get('dynamicRecycle') || {};
    
    let priceText;
    if (dynamicConfig.enabled && currentPrice !== originalPrice) {
      const changePercent = ((currentPrice - originalPrice) / originalPrice * 100).toFixed(1);
      const priceColor = currentPrice < originalPrice ? '§c' : '§a';
      priceText = `§3§l动态价格:${priceColor}${currentPrice}§f(${priceColor}${changePercent}%§f)`;
    } else {
      if (perCount > 1) {
        priceText = `§3§l${perCount}个=${currentPrice}${economy.name}`;
      } else {
        priceText = `§3§l1个=${currentPrice}${economy.name}`;
      }
    }
    
    if (config.get('enableRecycleLimits')) {
      const globalLimit = recycleLimitsData.globalLimits[k] || 0;
      const playerLimit = recycleLimitsData.playerLimits[k] || 0;
      
      if (globalLimit > 0 || playerLimit > 0) {
        const globalUsage = recycleLimitsData.globalUsage[k] || 0;
        const playerUsage = recycleLimitsData.playerUsage[player.xuid] ? 
          (recycleLimitsData.playerUsage[player.xuid][k] || 0) : 0;
        
        let limitText = '';
        
        if (globalLimit > 0) {
          const globalRemaining = globalLimit - globalUsage;
          if (globalRemaining <= 0) {
            limitText = '§c全服已满';
          } else {
            limitText = `§a${globalRemaining}`;
          }
        }
        
        if (playerLimit > 0) {
          const playerRemaining = playerLimit - playerUsage;
          if (playerRemaining <= 0) {
            if (limitText) {
              limitText += ' §c个人已满';
            } else {
              limitText = '§c个人已满';
            }
          } else {
            if (limitText) {
              const minRemaining = globalLimit > 0 ? Math.min(globalLimit - globalUsage, playerRemaining) : playerRemaining;
              limitText = `§a${Math.max(0, minRemaining)}`;
            } else {
              limitText = `§a${playerRemaining}`;
            }
          }
        }
        
        if (limitText) {
          priceText += ` §e限制余:${limitText}`;
        }
      }
    }
    
    let buttonText = `${show}\n${priceText}`;
    
    form.addButton(buttonText, icon);
  });
  
  player.sendForm(form, (pl, id) => {
    if(id == null) return;
    if(id === 0){
      showRecycleCategorySelectMenu(pl);
      return;
    }
    const itemIndex = id - 1;
    if(itemIndex < 0 || itemIndex >= sortedKeys.length){
      pl.tell('§c选择无效!');
      return;
    }
    const selectedKey = sortedKeys[itemIndex];
    const rec = officialShopData.recycleItems[selectedKey];
    confirmRecycle(pl, selectedKey, rec, () => showRecycleItemsByCategory(pl, categoryFilter));
  });
}

function showOfficialShopItems(player, page, keyword, categoryFilter = "全部"){
  if(officialPurchaseAllKeys.length === 0){
    player.tell("§c还未生成官方商店的顺序，请重新点击[官方商店 -> 购买]!");
    return;
  }
  let filtered = [];
  for(let key of officialPurchaseAllKeys){
    let itemObj = officialShopData.purchaseItems[key];
    if(!itemObj){
      continue;
    }
    if(keyword && keyword.trim()!==""){
      let kw = keyword.trim().toLowerCase();
      let nameLower = itemObj.name.toLowerCase();
      let displayNameLower = (itemObj.displayName || "").toLowerCase();
      let remarkLower = (itemObj.remark || "").toLowerCase();
      if(!(nameLower.includes(kw) || displayNameLower.includes(kw) || remarkLower.includes(kw))){
        continue;
      }
    }
    if(categoryFilter !== "全部" && itemObj.category !== categoryFilter){
      continue;
    }
    filtered.push(key);
  }
  let total = filtered.length;
  let PAGE_SIZE = config.get("pageSizeLimit") || 30;
  let totalPages = Math.ceil(total / PAGE_SIZE);
  if(page<1) page=1;
  if(page>totalPages && totalPages>0) page=totalPages;
  let startIndex = (page-1)*PAGE_SIZE;
  let endIndex = startIndex + PAGE_SIZE;
  let currKeys = filtered.slice(startIndex, endIndex);
  const form = mc.newSimpleForm();
  form.setTitle(`§e§l官方商店 - 第${page}页 / 共${totalPages}页`);
  let discountItemsCount = 0;
  for (const key in officialShopData.purchaseItems) {
    if (officialShopData.purchaseItems[key].discount) {
      discountItemsCount++;
    }
  }
  
  let info = `§e搜索: ${keyword||"无"}\n`;
  if (discountItemsCount > 0) {
    info += `§d当前有 ${discountItemsCount} 个物品正在促销中！\n`;
  }
  info += `§e共${total}项,每页${PAGE_SIZE}条.\n请选择要购买的物品:`;
  
  form.setContent(info);
  
  let hasPrev = (page>1);
  let hasNext = (page<totalPages);
  
  if(hasPrev){
    form.addButton("§a<< 上一页","textures/ui/arrow_left");
  }
  if(hasNext){
    form.addButton("§a下一页 >>","textures/ui/arrow_right");
  }
  form.addButton("§a搜索物品","textures/ui/magnifyingGlass");
  
  if(config.get('enableItemCategories')) {
    form.addButton("§b按分类浏览","textures/ui/recipe_book_icon");
  }
  
  let topNavButtonCount = (hasPrev ? 1 : 0) + (hasNext ? 1 : 0) + 1 + (config.get('enableItemCategories') ? 1 : 0); 
  
  for(let key of currKeys){
    let it = officialShopData.purchaseItems[key];
    if(!it) continue;
    let tmpItem = mc.newItem(NBT.parseSNBT(it.itemData));
    let showName = it.displayName || getItemDisplayName(tmpItem, false);
    let tx= JSON.parse(textureData.read());
    let icon = default_icon_path;
    if(tx[tmpItem.type] && tx[tmpItem.type]!=='null'){
      icon = tx[tmpItem.type];
    }
    let qtyStr = (it.quantity===-1) ? "∞" : String(it.quantity);
    let priceDisplay = it.price.toString();
    if (it.discount && it.originalPrice) {
      const endTime = new Date(it.discountEndTime);
      const remainMinutes = Math.max(0, Math.floor((it.discountEndTime - Date.now()) / 60000));
      priceDisplay = `§c${it.price}§f(${it.discount}折 原价:${it.originalPrice} 剩余:${remainMinutes}分钟)`;
    }

    form.addButton(`§s${showName}\n§s库存: ${qtyStr} | 价格: ${priceDisplay}`, icon);
  }
  
  if(hasPrev){
    form.addButton("§a<< 上一页","textures/ui/arrow_left");
  }
  if(hasNext){
    form.addButton("§a下一页 >>","textures/ui/arrow_right");
  }
  form.addButton("§a返回上级菜单", "textures/ui/icon_import");
  let bottomNavButtonCount = (hasPrev ? 1 : 0) + (hasNext ? 1 : 0) + 1; 
  
  player.sendForm(form, (pl, id)=>{
    if(id===null) return;
    if(id < topNavButtonCount){
      let idx=0;
      if(hasPrev && id===idx){
        showOfficialShopItems(pl, page-1, keyword, categoryFilter);
        return;
      }
      if(hasPrev) idx++;
      if(hasNext && id===idx){
        showOfficialShopItems(pl, page+1, keyword, categoryFilter);
        return;
      }
      if(hasNext) idx++;
      if(id===idx){
        showOfficialShopSearchForm(pl, page, keyword, categoryFilter);
        return;
      }
      idx++;
      if(config.get('enableItemCategories') && id===idx){
        showOfficialCategorySelectMenu(pl, page, keyword, categoryFilter);
        return;
      }
      return;
    }
    let itemStartIdx = topNavButtonCount;
    let itemEndIdx = itemStartIdx + currKeys.length - 1;
    
    if(id >= itemStartIdx && id <= itemEndIdx){
      let itemIndex = id - itemStartIdx;
      let pickKey = currKeys[itemIndex];
      let pickObj = officialShopData.purchaseItems[pickKey];
      if(!pickObj){
        pl.tell("§c操作取消");
        return;
      }
      confirmPurchase(pl, null, pickKey, pickObj, true);
      return;
    }
    let bottomNavStartIdx = itemEndIdx + 1;
    
    if(id >= bottomNavStartIdx){
      let bottomIdx = id - bottomNavStartIdx;
      
      if(hasPrev && bottomIdx === 0){
        showOfficialShopItems(pl, page-1, keyword, categoryFilter);
        return;
      }
      
      if(hasNext && ((hasPrev && bottomIdx === 1) || (!hasPrev && bottomIdx === 0))){
        showOfficialShopItems(pl, page+1, keyword, categoryFilter);
        return;
      }
      showOfficialShopMenu(pl, 1, "");
      return;
    }
  });
}

function showOfficialShopSearchForm(player, page, keyword, categoryFilter = "全部"){
  const form=mc.newCustomForm();
  form.setTitle('§a搜索物品(官方商店)');
  form.addInput('§e搜索关键字(物品名/备注):','关键字',keyword);
  player.sendForm(form,(pl,data)=>{
    if(!data)return;
    const newKey=data[0]?.trim()||"";
    showOfficialShopItems(pl,1,newKey, categoryFilter);
  });
}

function showRecycleItems(player){
  const keys=Object.keys(officialShopData.recycleItems);
  if(keys.length===0){
    player.tell('§c官方商店暂无回收物品。');
        return;
      }
  const economy = getEconomyInterface();
  const offSortMode = config.get("officialShopSortMode") || "随机";
  let sortedKeys = [...keys];
      if(offSortMode === "随机"){
    for(let i=sortedKeys.length-1; i>0; i--){
          let j = Math.floor(Math.random()*(i+1));
      [sortedKeys[i], sortedKeys[j]] = [sortedKeys[j], sortedKeys[i]];
    }
  } else if(offSortMode === "名字顺序"){
    sortedKeys.sort((aKey, bKey)=>{
      const aObj = officialShopData.recycleItems[aKey];
      const bObj = officialShopData.recycleItems[bKey];
      return aObj.name.localeCompare(bObj.name);
    });
  }
  
  const form=mc.newSimpleForm();
  form.setTitle('§e§l官方商店回收');
  form.setContent('§e请选择要出售的物品:');
  addReturnButton(form);
  
  if(config.get('enableItemCategories')) {
    form.addButton("§b按分类浏览","textures/ui/recipe_book_icon");
  }
  sortedKeys.forEach(k=>{
    const it=officialShopData.recycleItems[k];
    const tmp=mc.newItem(NBT.parseSNBT(it.itemData));
    const show=getItemDisplayName(tmp,false);
    let tx=JSON.parse(textureData.read());
    let icon=(tx.hasOwnProperty(tmp.type)&&tx[tmp.type]&&tx[tmp.type]!=='null')
      ?tx[tmp.type]:default_icon_path;
    
    const perCount = it.perCount || 1;
    let priceText;
    if (perCount > 1) {
      priceText = `§3§l${perCount}个=${it.price}${economy.name}`;
    } else {
      priceText = `§3§l1个=${it.price}${economy.name}`;
    }
    let limitText = '';
    
    if (config.get('enableRecycleLimits')) {
      const globalLimit = recycleLimitsData.globalLimits[k] || 0;
      const playerLimit = recycleLimitsData.playerLimits[k] || 0;
      
      if (globalLimit > 0 || playerLimit > 0) {
        const globalUsage = recycleLimitsData.globalUsage[k] || 0;
        const playerUsage = recycleLimitsData.playerUsage[player.xuid] ? 
          (recycleLimitsData.playerUsage[player.xuid][k] || 0) : 0;
        
        if (globalLimit > 0) {
          const globalRemaining = globalLimit - globalUsage;
          if (globalRemaining <= 0) {
            limitText = '§c全服已满';
          } else {
            limitText = `§a${globalRemaining}`;
          }
        }
        
        if (playerLimit > 0) {
          const playerRemaining = playerLimit - playerUsage;
          if (playerRemaining <= 0) {
            if (limitText) {
              limitText += ' §c个人已满';
            } else {
              limitText = '§c个人已满';
            }
          } else {
            if (limitText) {
              const minRemaining = globalLimit > 0 ? Math.min(globalLimit - globalUsage, playerRemaining) : playerRemaining;
              limitText = `§a${Math.max(0, minRemaining)}`;
            } else {
              limitText = `§a${playerRemaining}`;
            }
          }
        }
        
        if (limitText) {
          priceText += ` §e限制余:${limitText}`;
        }
      }
    }
    
    let buttonText = `${show}\n${priceText}`;
    
    form.addButton(buttonText, icon);
  });
  player.sendForm(form,(pl,id)=>{
    if(id==null)return;
    if(id===0){
      showOfficialShopMenu(pl,1,"");
      return;
    }
    
    let currentId = 1;
    if(config.get('enableItemCategories') && id === currentId){
      showRecycleCategorySelectMenu(pl);
      return;
    }
    if(config.get('enableItemCategories')) currentId++;
    
    const itemIndex = id - currentId;
    if(itemIndex<0||itemIndex>=sortedKeys.length){
      pl.tell('§c选择无效!');
      return;
    }
    const selectedKey = sortedKeys[itemIndex];

    const rec = officialShopData.recycleItems[selectedKey];
    confirmRecycle(pl, selectedKey, rec, () => showRecycleItems(pl));
  });
}

function getPlayerItemCount(player, nbtString){
  let total=0;
  const inv=player.getInventory();
  
  let searchItem;
  searchItem = safeCreateItem(nbtString);
  if (!searchItem) {
    return 0;
  }
  
  for(let i=0;i<inv.size;i++){
    let it=inv.getItem(i);
    if(it&&it.type!=='' && searchItem.type === it.type){
      total+=it.count;
    }
  }
  return total;
}

function confirmRecycle(player, itemKey, rec, returnCallback){
  const economy=getEconomyInterface();
  const nbtStr=rec.itemData;
  const totalItemCount=getPlayerItemCount(player,nbtStr);
  const form=mc.newCustomForm();
  form.setTitle('§a§l确认出售');
  const tmp=mc.newItem(NBT.parseSNBT(nbtStr));
  const name=rec.displayName || getItemDisplayName(tmp,false);
  
  const originalPrice = rec.price;
  const perCount = rec.perCount || 1;
  const currentPrice = getDynamicRecyclePrice(itemKey, originalPrice);
  const dynamicConfig = config.get('dynamicRecycle') || {};
  const unitLabel = perCount > 1 ? `/${perCount}个` : '(每个)';
  
  form.addLabel(`§e§l物品名称:${name}`);
  const recycleLore = tmp.lore;
  if(recycleLore && recycleLore.length > 0){
    form.addLabel(`§d§l物品描述:\n§f${recycleLore.join('\n')}`);
  }
  
  if (dynamicConfig.enabled && currentPrice !== originalPrice) {
    const changePercent = ((currentPrice - originalPrice) / originalPrice * 100).toFixed(1);
    const priceColor = currentPrice < originalPrice ? '§c' : '§a';
    form.addLabel(`§e§l原始价格: §3${originalPrice}${unitLabel}`);
    form.addLabel(`§e§l当前价格: ${priceColor}${currentPrice}${unitLabel} §f(${priceColor}${changePercent}%§f)`);
    if (currentPrice < originalPrice) {
      form.addLabel(`§3§l价格因市场饱和而下降`);
    }
  } else {
    form.addLabel(`§e§l价格:§3${currentPrice}${unitLabel}`);
  }
  
  form.addLabel(`§e§l您拥有的数量:${totalItemCount}`);
  
  if (config.get('enableRecycleLimits')) {
    const resetHours = config.get('recycleLimitResetHours') || 24;
    const timeUnit = resetHours === 24 ? '每日' : resetHours === 168 ? '每周' : `每${resetHours}小时`;
    
    const globalLimit = recycleLimitsData.globalLimits[itemKey] || 0;
    const playerLimit = recycleLimitsData.playerLimits[itemKey] || 0;
    const globalUsage = recycleLimitsData.globalUsage[itemKey] || 0;
    const playerUsage = recycleLimitsData.playerUsage[player.xuid] ? 
      (recycleLimitsData.playerUsage[player.xuid][itemKey] || 0) : 0;
    
    if (globalLimit > 0 || playerLimit > 0) {
      form.addLabel(`§b§l━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
      form.addLabel(`§d§l✦ 回收限制信息 ✦`);
      
      if (globalLimit > 0) {
        const globalRemaining = globalLimit - globalUsage;
        const globalColor = globalRemaining > 0 ? '§a' : '§c';
        const statusIcon = globalRemaining > 0 ? '§a✓' : '§c✗';
        form.addLabel(`§f${statusIcon} §e全服${timeUnit}限制:`);
        form.addLabel(`   §3已使用: ${globalColor}${globalUsage}§3/${globalColor}${globalLimit} §f| §3剩余: ${globalColor}${Math.max(0, globalRemaining)}`);
      }
      
      if (playerLimit > 0) {
        const playerRemaining = playerLimit - playerUsage;
        const playerColor = playerRemaining > 0 ? '§a' : '§c';
        const statusIcon = playerRemaining > 0 ? '§a✓' : '§c✗';
        form.addLabel(`§f${statusIcon} §e个人${timeUnit}限制:`);
        form.addLabel(`   §3已使用: ${playerColor}${playerUsage}§3/${playerColor}${playerLimit} §f| §3剩余: ${playerColor}${Math.max(0, playerRemaining)}`);
      }
      
      const nextReset = new Date(recycleLimitsData.lastReset + (resetHours * 60 * 60 * 1000));
      const now = new Date();
      const timeLeft = Math.max(0, nextReset.getTime() - now.getTime());
      const hoursLeft = Math.floor(timeLeft / (1000 * 60 * 60));
      const minutesLeft = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
      
      form.addLabel(`§f §e限制重置倒计时: §3${hoursLeft}小时${minutesLeft}分钟`);
      form.addLabel(`§b§l━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
    }
  }
  
  form.addInput(`§e§l请输入出售数量(最低${perCount}):`,'数字',totalItemCount.toString());
  player.sendForm(form,(pl,data)=>{
    if(!data){
      if(returnCallback) returnCallback();
      return;
    }
    const qtyInput=parseInt(data[data.length - 1]); 
    if(isNaN(qtyInput)||qtyInput<=0){
      pl.tell('§c出售数量必须>0!');
      if(returnCallback) returnCallback();
      return;
    }
    if(qtyInput < perCount){
      pl.tell(`§c数量不足！最少需要 ${perCount} 个物品才能回收。`);
      if(returnCallback) returnCallback();
      return;
    }
    if(qtyInput>totalItemCount){
      pl.tell('§c物品不足!');
      if(returnCallback) returnCallback();
      return;
    }
    
    const validSets = Math.floor(qtyInput / perCount);
    const realQty = validSets * perCount;
    
    const limitCheck = checkRecycleLimit(pl, itemKey, realQty);
    if (!limitCheck.allowed) {
      pl.tell(limitCheck.message);
      if(returnCallback) returnCallback();
      return;
    }
    
    let ok=removeItemsFromPlayer(pl,nbtStr,realQty);
    if(!ok){
      pl.tell('§c扣除物品失败,重试!');
      if(returnCallback) returnCallback();
      return;
    }
    
    const finalPrice = getDynamicRecyclePrice(itemKey, originalPrice);
    let totalPrice = finalPrice * validSets;
    
    recordRecycleEvent(itemKey);
    recordRecycleUsage(pl, itemKey, realQty);
    
    economy.add(pl,totalPrice);
    
    if (realQty !== qtyInput) {
        pl.tell(`§e已自动调整数量为 ${realQty} (必须是 ${perCount} 的倍数)`);
    }

    pl.sendToast("§a回收成功", `出售 ${name} x${realQty}，获得 ${totalPrice}${economy.name}`);
    
    const notifyItemListingToAll = config.get('notifyItemListingToAll');
    if (notifyItemListingToAll) {
      const onlinePlayers = mc.getOnlinePlayers();
      onlinePlayers.forEach(p => {
        if (p.xuid !== pl.xuid) { 
          p.sendToast(`§a官方商店回收`, `${pl.realName} 出售 ${name} x${realQty}`);
        }
      });
    }
    
    const recycleMsg = {
      sender: "§a商店系统",
      content: `§e${pl.realName} §f向官方商店出售了: §a${name} x${realQty} §f获得:§c${totalPrice}${economy.name}`,
      timestamp: Date.now(),
      mentions: []
    };
    chatMessages.push(recycleMsg);
    if (chatMessages.length > config.get('chatHistoryLimit')) {
      chatMessages.shift();
    }
    saveChatData();
    
    let successMsg = `§a§l出售成功!获得${totalPrice} ${economy.name}`;
    if (dynamicConfig.enabled && finalPrice !== originalPrice) {
      const changePercent = ((finalPrice - originalPrice) / originalPrice * 100).toFixed(1);
      const priceColor = finalPrice < originalPrice ? '§c' : '§a';
      successMsg += `\n§3动态价格: ${priceColor}${changePercent}%`;
    }
    
    pl.tell(successMsg);
    if(returnCallback) {
      returnCallback();
    } else {
      showOfficialShopMenu(pl, 1, "");
    } 
  });
}

function manageOfficialShop(player){
  const form=mc.newSimpleForm();
  form.setTitle('§c§l管理官方商店');
  form.setContent('§e请选择一个操作:');
  addReturnButton(form);
  form.addButton('§a§l上架物品(玩家可买)','textures/ui/backup_replace');
  form.addButton('§b§l编辑回收物品','textures/ui/anvil_icon');
  form.addButton('§e§l编辑官方购买物品','textures/ui/anvil_icon');
  form.addButton('§d§l设置物品折扣','textures/ui/store_sort_icon');
  form.addButton('§3§l批量操作','textures/ui/color_picker');
  form.addButton('§c§l回收限制管理','textures/ui/timer');
  player.sendForm(form,(pl,id)=>{
    if(id==null)return;
    if(id===0){
      showOfficialShopMenu(pl,1,"");
        return;
      }
    let idx=1;
    if(id===idx++){
      listPlayerItems(pl,true);
    } else if(id===idx++){
      editRecycleItems(pl);
    } else if(id===idx++){
      editPurchaseItems(pl);
    } else if(id===idx++){
      showOfficialShopDiscountMenu(pl);
    } else if(id===idx++){
      showOfficialBatchOperationsMenu(pl);
    } else if(id===idx++){
      showRecycleLimitsManagement(pl);
    }
  });
}

function showOfficialBatchOperationsMenu(player) {
  const form = mc.newSimpleForm();
  form.setTitle('§3§l官方商店批量操作');
  form.setContent('§e请选择一个操作:');
  addReturnButton(form);
  form.addButton('§c批量下架','textures/ui/trash');
  form.addButton('§b批量设置分类','textures/ui/anvil_icon');
  player.sendForm(form,(pl,id)=>{
    if(id==null)return;
    if(id===0){
      manageOfficialShop(pl);
      return;
    }
    let idx=1;
    if(id===idx++){
      showOfficialBatchRemoveItems(pl);
    } else if(id===idx++){
      showOfficialBatchCategoryChange(pl);
    }
  });
}

function showOfficialBatchRemoveItems(player) {
  const purchaseItems = Object.keys(officialShopData.purchaseItems);
  if (purchaseItems.length === 0) {
    player.tell("§c官方商店中没有物品可以下架！");
      return;
    }
  
  const form = mc.newCustomForm();
  form.setTitle("§c§l官方商店批量下架");
  form.addLabel("§e请选择要下架的物品");
  
  purchaseItems.forEach(key => {
    const item = officialShopData.purchaseItems[key];
    const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
    const showName = item.displayName || getItemDisplayName(tmp, false);
    
    form.addSwitch(`${showName} - 价格:${item.price}`, false);
  });
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    const selectedItems = [];
    for (let i = 0; i < purchaseItems.length; i++) {
      if (data[i + 1] === true) { 
        selectedItems.push({
          key: purchaseItems[i],
          item: officialShopData.purchaseItems[purchaseItems[i]]
        });
      }
    }
    
    if (selectedItems.length === 0) {
      player.tell("§c未选择任何物品进行下架！");
      return;
    }
    
    const cf = mc.newCustomForm();
    cf.setTitle("§c确认批量下架");
    cf.addLabel(`§e您确定要下架以下 ${selectedItems.length} 个物品吗？`);
    selectedItems.forEach(({ item }) => {
      const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
      const showName = item.displayName || getItemDisplayName(tmp, false);
      cf.addLabel(`§3- ${showName} (价格:${item.price})`);
    });
    cf.addSwitch("确认下架这些物品?", false);
    player.sendForm(cf, (pl, data) => {
      if (!data) return;
      if (data[selectedItems.length + 1]) {
        let removedCount = 0;
        selectedItems.forEach(({ key, item }) => {
          delete officialShopData.purchaseItems[key];
          removedCount++;
        });
        saveOfficialShopData();
        player.tell(`§a已成功下架 ${removedCount} 个官方商店物品`);
      } else {
        player.tell("§c操作已取消.");
      }
    });
  });
}

function showOfficialBatchCategoryChange(player) {
  const purchaseItems = Object.keys(officialShopData.purchaseItems);
  if (purchaseItems.length === 0) {
    player.tell("§c官方商店中没有物品可以设置分类！");
    return;
  }
  
  const form = mc.newCustomForm();
  form.setTitle("§b§l官方商店批量设置分类");
  form.addLabel("§e请选择要设置分类的物品");
  
  purchaseItems.forEach(key => {
    const item = officialShopData.purchaseItems[key];
    const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
    const showName = item.displayName || getItemDisplayName(tmp, false);
    
    const currentCategory = item.category || '无';
    form.addSwitch(`${showName} - 当前分类:${currentCategory}`, false);
  });
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    const selectedItems = [];
    for (let i = 0; i < purchaseItems.length; i++) {
      if (data[i + 1] === true) { 
        selectedItems.push({
          key: purchaseItems[i],
          item: officialShopData.purchaseItems[purchaseItems[i]]
        });
      }
    }
    
    if (selectedItems.length === 0) {
      player.tell("§c未选择任何物品进行分类设置！");
      return;
    }
    
    showOfficialBatchCategoryChangeForm(pl, selectedItems);
  });
}

function showOfficialBatchCategoryChangeForm(player, selectedItems) {
  const form = mc.newCustomForm();
  form.setTitle("§b§l设置官方商店分类");
  
  let itemsInfo = "§e已选物品：\n";
  selectedItems.forEach(({ item }) => {
    const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
    const showName = item.displayName || getItemDisplayName(tmp, false);
    itemsInfo += `§3- ${showName} (当前分类:${item.category || '无'})\n`;
  });
  form.addLabel(itemsInfo);
  
  form.addInput("§e设置分类 (留空则清除分类)", "分类名称", "");
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    const category = data[1]?.trim() || '';
    
    selectedItems.forEach(({ key, item }) => {
      if (category === '') {
        delete item.category;
      } else {
        item.category = category;
      }
      
      const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
      const showName = item.displayName || getItemDisplayName(tmp, false);
      pl.sendToast("§b官方商店分类设置", `${showName} 已设置为${category || '无'}`);
    });
    
    saveOfficialShopData();
    pl.tell(`§a已成功为 ${selectedItems.length} 个官方商店物品设置分类: ${category || '无'}`);
  });
}

function showOfficialShopDiscountMenu(player) {
  const purchaseItems = Object.keys(officialShopData.purchaseItems);
  if (purchaseItems.length === 0) {
    player.tell("§c官方商店中没有物品可以打折！");
    return;
  }
  
  const form = mc.newCustomForm();
  form.setTitle("§d§l官方商店物品折扣");
  form.addLabel("§e请选择要打折的物品，所选物品将在下一步设置折扣率");
  
  purchaseItems.forEach(key => {
    const item = officialShopData.purchaseItems[key];
    const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
    const showName = item.displayName || getItemDisplayName(tmp, false);
    
    const hasDiscount = item.discount !== undefined;
    const discountInfo = hasDiscount ? 
      `§a[当前折扣: ${item.discount}折，剩余${Math.floor((item.discountEndTime - Date.now()) / 60000)}分钟]` : 
      "§3[无折扣]";
    
    form.addSwitch(`${showName} - 原价:${item.price} ${discountInfo}`, false);
  });
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    const selectedItems = [];
    for (let i = 0; i < purchaseItems.length; i++) {
      if (data[i + 1] === true) { 
        selectedItems.push({
          key: purchaseItems[i],
          item: officialShopData.purchaseItems[purchaseItems[i]]
        });
      }
    }
    
    if (selectedItems.length === 0) {
      player.tell("§c未选择任何物品进行打折！");
      return;
    }
    
    showOfficialDiscountSettingForm(pl, selectedItems);
  });
}

function showOfficialDiscountSettingForm(player, selectedItems) {
  const form = mc.newCustomForm();
  form.setTitle("§d§l设置官方商店折扣");
  
  let itemsInfo = "§e已选物品：\n";
  selectedItems.forEach(({ item }) => {
    const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
    const showName = item.displayName || getItemDisplayName(tmp, false);
    itemsInfo += `§3- ${showName} (原价:${item.price})\n`;
  });
  form.addLabel(itemsInfo);
  
  form.addSlider("§e设置折扣率 (几折)", 1, 9, 1, 7);
  
  form.addInput("§e折扣持续时间 (分钟)", "输入数字", "60");
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    const discountRate = data[1]; 
    const durationMinutes = parseInt(data[2]);
    
    if (isNaN(durationMinutes) || durationMinutes <= 0) {
      pl.tell("§c折扣持续时间必须是正数！");
      return;
    }
    
    const discountEndTime = Date.now() + (durationMinutes * 60 * 1000);
    
    selectedItems.forEach(({ key, item }) => {
      if (item.originalPrice === undefined) {
        item.originalPrice = item.price;
      }
      item.discount = discountRate;
      item.discountEndTime = discountEndTime;
      const discountedPrice = Math.floor(item.originalPrice * (discountRate / 10));
      item.price = discountedPrice;
      
      const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
      const showName = item.displayName || getItemDisplayName(tmp, false);
      pl.sendToast("§d官方商店折扣", `${showName} 已设置为${discountRate}折`);
    });
    
    saveOfficialShopData();
    pl.tell(`§a已成功为 ${selectedItems.length} 个官方商店物品设置${discountRate}折，持续 ${durationMinutes} 分钟`);
  });
}

function editRecycleItems(player){
  const form=mc.newSimpleForm();
  form.setTitle('§b编辑回收物品');
  form.setContent('§e请选择一个操作:');
  addReturnButton(form);
  form.addButton('§a添加回收物品','textures/ui/backup_replace');
  form.addButton('§b编辑回收物品','textures/ui/anvil_icon');
  player.sendForm(form, (pl,id)=>{
    if(id==null)return;
    if(id===0){
      manageOfficialShop(pl);
      return;
    }
    let idx=1;
    if(id===idx++){
      listPlayerItemsForRecycle(pl);
    } else if(id===idx){
      editExistingRecycleItems(pl);
    }
  });
}

function listPlayerItemsForRecycle(player){
  const invItems = getPlayerInventoryItems(player);
  const itemKeys = Object.keys(invItems);
  if(itemKeys.length===0){
    player.tell('§c背包中没有物品！');
    return;
  }
  const form = mc.newCustomForm();
  form.setTitle('§a添加回收物品');
  const names=itemKeys.map((k,idx)=>{
    const {item,count}=invItems[k];
    let cloneNbt = item.getNbt();
    cloneNbt.setByte('Count',1);
    let nbtString = cloneNbt.toSNBT();
    
    let statusText = '';
    if (isItemAlreadyInOfficialRecycle(nbtString)) {
      statusText = ' §3(已上架)';
    }
    
    return `${idx+1}. ${getItemDisplayName(item,false)} x${count}${statusText}`;
  });
  form.addDropdown('§e请选择要添加的物品:', names);
  form.addInput('§e输入回收价格:','数字','1');
  form.addInput('§e输入回收数量单位(多少个):','数字','1');
  form.addInput('§e自定义显示名称（可选）：','留空则使用默认名称','');
  player.sendForm(form,(pl,data)=>{
    if(!data)return;
    const selIdx = data[0];
    const price = parseInt(data[1]);
    const perCount = parseInt(data[2]);
    const displayName = data[3]?.trim() || '';
    
    if(isNaN(price)||price<=0){
      pl.tell('§c价格必须是正整数!');
      return;
    }
    if(isNaN(perCount)||perCount<=0){
      pl.tell('§c数量单位必须是正整数!');
      return;
    }
    const chosenKey = itemKeys[selIdx];
    const {item} = invItems[chosenKey];
    let cloneNbt = item.getNbt();
    cloneNbt.setByte('Count',1);
    let nbtString = cloneNbt.toSNBT();
    const tmp=mc.newItem(cloneNbt);
    const info = getItemDisplayName(tmp,false);
    officialShopData.recycleItems[nbtString] = { 
      itemData: nbtString, 
      name: info,
      displayName: displayName,
      price,
      perCount
    };
    saveOfficialShopData();
    if (perCount > 1) {
      pl.tell(`§a添加回收物品: ${displayName || info}, 回收价: §3${perCount}个=${price}§f`);
    } else {
      pl.tell(`§a添加回收物品: ${displayName || info}, 回收价: §3${price}§f`);
    }
    editRecycleItems(pl); 
  });
}

function editExistingRecycleItems(player){
  const keys = Object.keys(officialShopData.recycleItems);
  if(keys.length===0){
    player.tell('§c暂无可编辑的回收物品。');
    return;
  }
  const form = mc.newSimpleForm();
  form.setTitle('§b编辑回收物品');
  form.setContent('§e请选择要编辑的物品:');
  addReturnButton(form);

  const txMap = JSON.parse(textureData.read());

  keys.forEach((k, idx) => {
    const rec = officialShopData.recycleItems[k];
    const tmpItem = mc.newItem(NBT.parseSNBT(rec.itemData));
    const showName = rec.displayName || rec.name || getItemDisplayName(tmpItem, false);
    let icon = default_icon_path;
    const typeKey = tmpItem.type;
    if(txMap.hasOwnProperty(typeKey) && txMap[typeKey] && txMap[typeKey] !== 'null'){
      icon = txMap[typeKey];
    }
    const perCount = rec.perCount || 1;
    let priceDisplay;
    if (perCount > 1) {
      priceDisplay = `${perCount}个=${rec.price}`;
    } else {
      priceDisplay = `1个=${rec.price}`;
    }
    form.addButton(`§c${idx+1}.  §s${showName}\n§3${priceDisplay}`, icon);
  });

  player.sendForm(form,(pl,id)=>{
    if(id==null)return;
    if(id===0){
      editRecycleItems(pl);
      return;
    }
    const recKey = keys[id-1];
    const rec = officialShopData.recycleItems[recKey];
    showEditRecycleItemForm(pl, recKey, rec);
  });
}


function showEditRecycleItemForm(player, itemKey, rec){
  const form=mc.newCustomForm();
  form.setTitle('§b编辑回收物品');
  form.addLabel(`§e物品名称:${rec.name}`);
  form.addInput('§e修改回收价格:','数字',rec.price.toString());
  form.addInput('§e修改回收数量单位(多少个):','数字',(rec.perCount || 1).toString());
  form.addInput('§e自定义显示名称（可选）：','留空则使用默认名称',rec.displayName || '');
  form.addSwitch('§e是否删除此回收物品?',false);
  player.sendForm(form,(pl,data)=>{
    if(!data)return;
    const newPrice=parseInt(data[1]);
    const newPerCount=parseInt(data[2]);
    const newDisplayName = data[3]?.trim() || '';
    const remove=data[4];
    if(isNaN(newPrice)||newPrice<=0){
      pl.tell('§c价格必须是正整数!');
      return;
    }
    if(isNaN(newPerCount)||newPerCount<=0){
      pl.tell('§c数量单位必须是正整数!');
      return;
    }
    if(remove){
      delete officialShopData.recycleItems[itemKey];
      pl.tell('§a回收物品已删除。');
    } else {
      rec.price=newPrice;
      rec.perCount=newPerCount;
      rec.displayName = newDisplayName;
      pl.tell('§a回收物品已更新。');
    }
    saveOfficialShopData();
    editExistingRecycleItems(pl); 
  });
}

function editPurchaseItems(player){
  const keys = Object.keys(officialShopData.purchaseItems);
  if(keys.length===0){
    player.tell('§c暂无可编辑的官方购买物品.');
    return;
  }
  const form = mc.newSimpleForm();
  form.setTitle('§b编辑官方购买物品');
  form.setContent('§e请选择要编辑的物品:');
  addReturnButton(form);
  const txMap = JSON.parse(textureData.read()); 
  keys.forEach((k, idx) => {
    const rec = officialShopData.purchaseItems[k];
    const tmpItem = mc.newItem(NBT.parseSNBT(rec.itemData));
    const showName = rec.displayName || rec.name || getItemDisplayName(tmpItem, false);
    const qtyStr = (rec.quantity === -1 ? '∞' : rec.quantity);

    let icon = default_icon_path;
    const typeKey = tmpItem.type; 
    if(txMap.hasOwnProperty(typeKey) && txMap[typeKey] && txMap[typeKey] !== 'null'){
      icon = txMap[typeKey];
    }

    form.addButton(
      `§c${idx+1}. §s${showName}\n§s(价格:${rec.price} | 库存:${qtyStr})`,
      icon
    );
  });
  
  player.sendForm(form, (pl, id) => {
    if(id==null)return;
    if(id===0){
      manageOfficialShop(pl);
      return;
    }
    const recKey = keys[id-1];
    const rec = officialShopData.purchaseItems[recKey];
    showEditPurchaseItemForm(pl, recKey, rec);
  });
}

function showEditPurchaseItemForm(player, itemKey, rec){
  const form=mc.newCustomForm();
  form.setTitle('§b编辑官方购买物品');
  form.addLabel(`§e物品名称:${rec.name}`);
  form.addInput('§e修改价格(每个):','数字', rec.price.toString());
  form.addInput('§e修改库存数量(0为无限):','数字', (rec.quantity===-1? "0": rec.quantity.toString()));
  form.addInput('§e自定义显示名称（可选）：','留空则使用默认名称',rec.displayName || '');
  form.addInput('§e修改备注(可留空):','', rec.remark||'');
  form.addSwitch('§e是否删除该购买物品?', false);
  player.sendForm(form, (pl, data) => {
    if(!data)return;
    let newP = parseInt(data[1]);
    let newQty = parseInt(data[2]);
    const newDisplayName = data[3]?.trim() || "";
    const newRemark = data[4]?.trim() || "";
    const remove = data[5];
    if(isNaN(newP) || newP<=0){
      pl.tell('§c价格必须正整数!');
      return;
    }
    if(isNaN(newQty) || newQty<0){
      pl.tell('§c库存数量必须≥0! (0为无限)');
      return;
    }
    if(remove){
      delete officialShopData.purchaseItems[itemKey];
      pl.tell('§a官方购买物品已删除。');
    } else {
      rec.price = newP;
      rec.quantity = (newQty===0 ? -1 : newQty);
      rec.displayName = newDisplayName;
      rec.remark = newRemark;
      pl.tell('§a官方购买物品已更新。');
    }
    saveOfficialShopData();
    editPurchaseItems(pl); 
  });
}

function showIconConfigMenu(player){
  const form = mc.newCustomForm();
  form.setTitle("§e图标配置");
  const enabledLocal = config.get("enableLocalIcon");
  const enabledCustom = config.get("enableCustomPathIcon");
  const localCost = config.get("localIconChangeCost");
  const localCD = config.get("localIconChangeCooldown");
  const customCost = config.get("customPathIconChangeCost");
  const customCD = config.get("customPathIconChangeCooldown");
  form.addSwitch("§c是否开启本地图标选择功能", enabledLocal);
  form.addInput("§e本地图标修改费用", "数字", String(localCost));
  form.addInput("§e本地图标冷却(小时)", "数字", String(localCD));
  form.addSwitch("§c是否开启自定义路径图标功能", enabledCustom);
  form.addInput("§e自定义路径图标修改费用", "数字", String(customCost));
  form.addInput("§e自定义路径图标冷却(小时)", "数字", String(customCD));
  player.sendForm(form,(pl, data)=>{
    if(!data)return;
    const localEnable = data[0];
    const localCostVal = parseInt(data[1]);
    const localCDVal = parseInt(data[2]);
    const customEnable = data[3];
    const customCostVal = parseInt(data[4]);
    const customCDVal = parseInt(data[5]);
    if(isNaN(localCostVal)||localCostVal<0){
      pl.tell("§c本地图标修改费用须为非负整数!");
      return;
    }
    if(isNaN(localCDVal)||localCDVal<0){
      pl.tell("§c本地图标冷却时间须为非负整数!");
      return;
    }
    if(isNaN(customCostVal)||customCostVal<0){
      pl.tell("§c自定义路径图标修改费用须为非负整数!");
      return;
    }
    if(isNaN(customCDVal)||customCDVal<0){
      pl.tell("§c自定义路径图标冷却时间须为非负整数!");
      return;
    }
    config.set("enableLocalIcon", localEnable);
    config.set("localIconChangeCost", localCostVal);
    config.set("localIconChangeCooldown", localCDVal);
    config.set("enableCustomPathIcon", customEnable);
    config.set("customPathIconChangeCost", customCostVal);
    config.set("customPathIconChangeCooldown", customCDVal);
    pl.tell("§a图标配置已更新!");
  });
}

function showManagePlayerShops(player, page, keyword){
  let shopArr = Object.values(shopsData);
  if(keyword && keyword.trim()!==""){
    let kw = keyword.toLowerCase();
    shopArr = shopArr.filter(s=>{
      if(s.name && s.name.toLowerCase().includes(kw)) return true;
      if(s.owner && s.owner.toLowerCase().includes(kw)) return true;
      return false;
    });
  }
  PAGE_SIZE = config.get("pageSizeLimit") || 30;
  const total = shopArr.length;
  const totalPages = Math.ceil(total/PAGE_SIZE);
  if(page<1) page=1;
  if(page>totalPages && totalPages>0) page=totalPages;
  const st=(page-1)*PAGE_SIZE, ed=st+PAGE_SIZE;
  const curr = shopArr.slice(st,ed);
  const form = mc.newSimpleForm();
  form.setTitle(`§2§l管理玩家店铺 - 第${page}/${totalPages}页`);
  form.addButton("§c返回上一页","textures/ui/icon_import");
  let ctt = `§e搜索关键字:${keyword||"无"}\n(每页最多${PAGE_SIZE}个)\n请选择要管理的店铺:`;
  form.setContent(ctt);
  let hasPrev = (page>1), hasNext=(page<totalPages);
  if(hasPrev){
    form.addButton("§a<< 上一页","textures/ui/arrow_left");
  }
  if(hasNext){
    form.addButton("§a下一页 >>","textures/ui/arrow_right");
  }
  form.addButton("§b搜索店铺","textures/ui/magnifyingGlass");
  curr.forEach(s=>{
    let itemCount = Object.keys(s.items||{}).length;
    form.addButton(`§s${s.name}\n§s拥有者:${s.owner} | 在售:${itemCount}`, getShopIconTexture(s));
  });
  player.sendForm(form, (pl, id)=>{
    if(id==null) return;
    let idx=0;
    if(id===idx){
      showAdminMenu(pl);
      return;
    }
    idx++;
    
    if(hasPrev){
      if(id===idx){
        showManagePlayerShops(pl,page-1,keyword);
        return;
      }
      idx++;
    }
    
    if(hasNext){
      if(id===idx){
        showManagePlayerShops(pl,page+1,keyword);
        return;
      }
      idx++;
    }
    
    if(id===idx){
      showManagePlayerShopSearchForm(pl);
      return;
    }
    idx++;
    
    let chosen = id - idx;
    if(chosen<0 || chosen>=curr.length){
      pl.tell("§c选择无效!");
      return;
    }
    let shop = curr[chosen];
    showManageSpecificPlayerShop(pl, shop);
  });
}

function showManagePlayerShopSearchForm(player){
  const f = mc.newCustomForm();
  f.setTitle("§b搜索店铺");
  f.addInput("请输入店铺名称或店主名称:","关键字","");
  player.sendForm(f,(pl,data)=>{
    if(!data)return;
    let kw = data[0]?.trim()||"";
    showManagePlayerShops(pl,1,kw);
  });
}

function showManageSpecificPlayerShop(player, shop){
  const form = mc.newSimpleForm();
  form.setTitle(`§a管理店铺: ${shop.name}`);
  form.setContent("请选择一个操作:");
  addReturnButton(form);
  form.addButton("§a强制更改店铺名称","textures/ui/book_edit_default");
  form.addButton(shop.isOpen?"§e关闭店铺":"§a开启店铺", shop.isOpen?"textures/ui/crossout":"textures/ui/check");
  const hasItems = Object.keys(shop.items).length > 0;
  form.addButton(
    hasItems ? "§c删除店铺（请先下架所有物品）" : "§c删除店铺",
    "textures/ui/trash",
    hasItems
  );
  form.addButton("§d强制更改店铺图标","textures/ui/refresh");
  form.addButton("§b查看并管理店铺物品","textures/ui/anvil_icon");
  player.sendForm(form,(pl,id)=>{
    if(id==null)return;
    if(id===0){
      showManagePlayerShops(pl,1,"");
      return;
    }
    let idx=1;
    if(id===idx++){
      forceChangeShopName(pl, shop);
    } else if(id===idx++){
      shop.isOpen = !shop.isOpen;
      saveShopsData();
      pl.tell(`§a店铺已${shop.isOpen?"开启":"关闭"}`);
    } else if(id===idx++){
      forceDeleteShop(pl, shop);
    } else if(id===idx++){
      forceChangeShopIcon(pl, shop);
    } else if(id===idx){
      showAdminEditShopItems(pl, shop);
    }
  });
}

function forceChangeShopName(player, shop){
  const f = mc.newCustomForm();
  f.setTitle("§a强制更改店铺名称");
  f.addInput("新的店铺名称(最多10字符):","店铺名称");
  player.sendForm(f,(pl,data)=>{
    if(!data)return;
    let name = data[0]?.trim();
    if(!name){
      pl.tell("§c店铺名不能为空!");
      return;
    }
    if(name.length>10){
      pl.tell("§c店铺名不能超过10字符!");
      return;
    }
    shop.name=name;
    shop.lastNameChange=Date.now();
    saveShopsData();
    pl.tell(`§a已强制修改店铺名称为: ${name}`);
  });
}

function forceDeleteShop(player, shop){
  const cf = mc.newCustomForm();
  cf.setTitle("§c强制删除店铺");
  cf.addLabel("删除后物品将返还到店主背包(若在线),否则无法返还.\n确认吗?");
  cf.addSwitch("确认删除店铺?", false);
  player.sendForm(cf,(pl,data)=>{
    if(!data)return;
    if(data[1]){
      let items=shop.items;
      let ownerXuid = shop.ownerXuid;
      let ownerPl = mc.getPlayer(ownerXuid);
      let successAll = true;
      for(const k in items){
        let it=items[k];
        let itemNbt=NBT.parseSNBT(it.itemData);
        if(ownerPl){
          if(!canPlayerReceiveItem(ownerPl,itemNbt,it.quantity)){
            successAll=false;
            pl.tell(`§c无法返还物品 ${it.name} 给店主 ${shop.owner}`);
            continue;
          }
          let succ=distributeItemsToPlayer(ownerPl,itemNbt,it.quantity);
          if(!succ) {
            successAll=false;
            ownerPl.tell(`§c§l无法返还物品 ${it.name}！背包空间不足！`);
          }
        }
      }
      delete shopsData[ownerXuid];
      saveShopsData();
      if(rankingData[ownerXuid]){
        delete rankingData[ownerXuid];
        saveRankingData();
      }
      pl.tell(`§a店铺已删除!`);
    } else {
      pl.tell("§c操作已取消.");
    }
  });
}

function forceChangeShopIcon(player, shop){
  const f = mc.newSimpleForm();
  f.setTitle("§d强制修改店铺图标");
  f.setContent("请选择操作:");
  addReturnButton(f);
  f.addButton("§b本地图标","textures/ui/color_picker");
  f.addButton("§5自定义路径图标","textures/ui/subscription_glyph_color");
  player.sendForm(f,(pl,id)=>{
    if(id==null)return;
    if(id===0){
      showManageSpecificPlayerShop(pl,shop);
      return;
    }
    let idx=1;
    if(id===idx++){
      forceChangeShopIconLocal(pl, shop);
    } else if(id===idx){
      forceChangeShopIconCustom(pl, shop);
    }
  });
}

function forceChangeShopIconLocal(player, shop){
  let files = [];
  try{
    let raw = File.readFrom(uiIconsPath);
    if(raw){
      if(raw.charCodeAt(0)===0xFEFF) raw = raw.slice(1);
      files = JSON.parse(raw);
    }
  }catch(e){}
  if(!Array.isArray(files) || files.length===0){
    player.tell('§c暂无可用的本地图标(请检查 ui_icons.json)');
    return;
  }
  showForceLocalIconPage(player, shop, files, 1);
}

function showForceLocalIconPage(player, shop, files, page){
  let total=files.length;
  PAGE_SIZE = config.get("pageSizeLimit") || 30;
  let totalPages=Math.ceil(total/PAGE_SIZE);
  if(page<1) page=1;
  if(page>totalPages && totalPages>0) page=totalPages;
  let start=(page-1)*PAGE_SIZE;
  let end=start+PAGE_SIZE;
  let list=files.slice(start,end);
  const form=mc.newSimpleForm();
  form.setTitle(`§a强制设置图标 - 第${page}/${totalPages}页`);
  form.setContent("请选择图标:");
  if(page>1) form.addButton('§a<< 上一页','textures/ui/arrow_dark_left_stretch');
  if(page<totalPages) form.addButton('§a下一页 >>','textures/ui/arrow_dark_right');
  list.forEach(iconName=>{
    form.addButton(iconName, `textures/ui/${iconName}`);
  });
  player.sendForm(form,(pl,id)=>{
    if(id==null)return;
    let idx=0;
    let hasPrev=(page>1), hasNext=(page<totalPages);
    if(hasPrev && id===idx){
      showForceLocalIconPage(pl,shop,files,page-1);
      return;
    }
    if(hasPrev) idx++;
    if(hasNext && id===idx){
      showForceLocalIconPage(pl,shop,files,page+1);
      return;
    }
    if(hasNext) idx++;
    let selectIndex = id - idx;
    if(selectIndex<0||selectIndex>=list.length){
      pl.tell('§c选择无效!');
      return;
    }
    let realFilename=list[selectIndex];
    let nameNoExt=realFilename.replace(/\.png$/i,'');
    shop.iconName=`textures/ui/${nameNoExt}`;
    shop.lastIconChange=Date.now();
    saveShopsData();
    pl.tell(`§a已强制修改店铺图标为: textures/ui/${nameNoExt}`);
  });
}



function forceChangeShopIconCustom(player, shop){
  const form = mc.newCustomForm();
  form.setTitle("§5强制自定义路径图标");
  form.addInput("自定义路径:","textures/ui/...");
  player.sendForm(form,(pl,data)=>{
    if(!data)return;
    const pth=data[0]?.trim();
    if(!pth){
      pl.tell("§c路径不能为空!");
      return;
    }
    shop.iconName=pth;
    shop.lastIconChange=Date.now();
    saveShopsData();
    pl.tell(`§a已强制修改店铺图标为: ${pth}`);
  });
}

function showAdminEditShopItems(player, shop) {
  const form = mc.newSimpleForm();
  form.setTitle(`§b管理店铺物品: ${shop.name}`);
  form.setContent("请选择一个操作:");
  addReturnButton(form);
  form.addButton("§a搜索物品","textures/ui/magnifyingGlass");
  const txMap = JSON.parse(textureData.read());
  const keys = Object.keys(shop.items);
  keys.forEach((k, idx) => {
    let it = shop.items[k];
    let tmpItem = mc.newItem(NBT.parseSNBT(it.itemData));
    const showName = it.name;

    let icon = default_icon_path;
    let typeKey = tmpItem.type;  
    if (txMap.hasOwnProperty(typeKey) && txMap[typeKey] && txMap[typeKey] !== 'null') {
      icon = txMap[typeKey];
    }

    const qtyStr = (it.quantity === -1) ? "§l§s∞" : String(it.quantity);

    form.addButton(
      `§s${showName}\n§s库存: ${qtyStr} | 价格: ${it.price}`,
      icon
    );
  });
  
  player.sendForm(form, (pl, id) => {
    if (id == null) return;
    if (id === 0) {
      showManageSpecificPlayerShop(pl, shop);
      return;
    }
    if (id === 1) {
      showAdminEditShopItemSearch(pl, shop);
      return;
    }
    let itemIdx = id - 2;
    const keys2 = Object.keys(shop.items);
    if (itemIdx < 0 || itemIdx >= keys2.length) {
      pl.tell("§c选择无效!");
      return;
    }
    let key = keys2[itemIdx];
    let item = shop.items[key];
    showAdminEditShopItemForm(pl, shop, key, item);
  });
}


function showAdminEditShopItemSearch(player, shop){
  const f = mc.newCustomForm();
  f.setTitle("§a搜索店铺内物品");
  f.addInput("请输入关键字(物品名/备注)","关键字","");
  player.sendForm(f,(pl,data)=>{
    if(!data)return;
    let kw = data[0]?.trim().toLowerCase()||"";
    let form2 = mc.newSimpleForm();
    form2.setTitle(`§a搜索结果: ${kw}`);
    form2.addButton("§c返回","textures/ui/icon_import");
    let keys = Object.keys(shop.items);
    let arr = [];
    for(let k of keys){
      let it=shop.items[k];
      if(it.name.toLowerCase().includes(kw) || (it.remark&&it.remark.toLowerCase().includes(kw))){
        arr.push({ key:k, item:it });
      }
    }
    if(arr.length===0){
      form2.setContent("§c未搜索到相关物品.");
    } else {
      arr.forEach((o,idx)=>{
        let tmp=mc.newItem(NBT.parseSNBT(o.item.itemData));
        let show=getItemDisplayName(tmp,false);
        form2.addButton(`§s${show}\n§s库存: ${o.item.quantity==="-1"?"∞":o.item.quantity} | 价格: ${o.item.price}`);
      });
    }
    player.sendForm(form2,(pl2,id2)=>{
      if(id2==null)return;
      if(id2===0){
        showAdminEditShopItems(pl2, shop);
        return;
      }
      let itemIdx = id2-1;
      if(itemIdx<0||itemIdx>=arr.length){
        pl2.tell("§c选择无效!");
        return;
      }
      let thekey = arr[itemIdx].key;
      let theitem = arr[itemIdx].item;
      showAdminEditShopItemForm(pl2, shop, thekey, theitem);
    });
  });
}

function showAdminEditShopItemForm(player, shop, itemKey, shopItem){
  const form = mc.newCustomForm();
  form.setTitle("§a管理员编辑店铺物品");
  let qtyText = (shopItem.quantity === -1) ? "无限" : String(shopItem.quantity);
  form.addLabel(`§b名称: §f${shopItem.name}\n§b数量: §f${qtyText}`);
  form.addInput("§e新的价格(正整数)", "数字", String(shopItem.price));
  form.addInput("§e备注(可留空,50字以内)", "", shopItem.remark||"");
  form.addSwitch("§c是否删除该物品?", false);
  player.sendForm(form, (pl, data)=>{
    if(!data)return;
    let newP = parseInt(data[1]);
    let newR = data[2]?.trim()||"";
    let remove = data[3];

    if(isNaN(newP)||newP<=0){
      pl.tell("§c价格必须为正整数!");
      return;
    }
    if(newR.length>50){
      pl.tell("§c备注不能超过50字!");
    return;
  }
  
    if(remove){
      delete shop.items[itemKey];
      pl.tell("§a物品已删除并下架!");
    } else {
      shopItem.price = newP;
      shopItem.remark = newR;
      pl.tell("§a已更新物品信息!");
    }
    saveShopsData();
    showAdminEditShopItems(pl, shop); 
  });
}

function showChatLobby(player) {
  if (mentionData[player.xuid]) {
    mentionData[player.xuid].unread = false;
    saveMentionData();
  }
  const form = mc.newCustomForm();
  form.setTitle('§a§lSM大厅');
  form.addInput('§a输入消息（@玩家名可通知对方）', '支持物品搜索和@玩家', '');
  const chatHistoryLimit = config.get('chatHistoryLimit') || 30;
  
  let chatHistory = `§e最近${chatHistoryLimit}条消息（可在配置中修改）：\n`;
  chatMessages.slice().reverse().forEach(msg => {
    const time = new Date(msg.timestamp).toLocaleTimeString();
    chatHistory += `§3[${time}] §r${msg.sender}§f: ${msg.content}\n`;
  });
  form.addLabel(chatHistory);
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    const message = data[0].trim();
    if (message.length === 0) return;
    const newMsg = {
      sender: pl.realName,
      content: message,
      timestamp: Date.now(),
      mentions: []
    };
    const mentionRegex = /@(\w+)/g;
    let match;
    while ((match = mentionRegex.exec(message)) !== null) {
      const targetName = match[1];
      const target = mc.getPlayer(targetName);
      if (target) {
        newMsg.mentions.push(target.xuid);
        if (!mentionData[target.xuid]) {
          mentionData[target.xuid] = {
            unread: true,
            count: 0
          };
        }
        mentionData[target.xuid].unread = true;
        mentionData[target.xuid].count += 1;
      }
    }   
    chatMessages.push(newMsg);
    if (chatMessages.length > chatHistoryLimit) chatMessages.shift();   
    saveChatData();
    saveMentionData();
    mc.broadcast(`§3[SM大厅] §r${pl.realName}§f: ${message}`);   
    showChatLobby(pl);
  });
}


function showPurchaseRequestMenu(player) {
  if (!config.get('enablePurchaseRequests')) {
    player.tell("§c悬赏&求购功能已被管理员禁用!");
      return;
  }  
  const form = mc.newSimpleForm();
  form.setTitle("§3§l悬赏&求购");
  form.setContent("§e选择一个操作:\n\n§3注意：求购获得的物品将自动存储到您的仓库中");
  
  addReturnButton(form);
  form.addButton("§a发布求购订单", "textures/ui/MCoin");
  const activeRequestsCount = purchaseRequests.requests.filter(r => !r.locked).length || 0;
  form.addButton(`§b查看求购列表\n§f当前求购: ${activeRequestsCount}条`, "textures/ui/touch_glyph");
  form.addButton("§d我的求购", "textures/ui/backup_replace");  
  
  const isAdmin = player.isOP() || player.permLevel >= 1;
  if (isAdmin) {
    form.addButton("§6§l[管理员]新增物品", "textures/ui/automation_glyph_color");
  }
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;   
    if (id === 0) {
      showMainMenu(pl);
      return;
    }    
    if (id === 1) {
      showCreatePurchaseRequest(pl);
    } else if (id === 2) {
      showActivePurchaseRequests(pl, "", 1);
    } else if (id === 3) {
      showMyPurchaseRequests(pl);
    } else if (id === 4 && isAdmin) {
      showAdminAddItemForPurchase(pl);
    }
  });
}

function showAdminAddItemForPurchase(player) {
  if (!player.isOP() && player.permLevel < 1) {
    player.tell("§c您没有权限执行此操作!");
    return;
  }
  
  const form = mc.newCustomForm();
  form.setTitle("§6§l[管理员]新增求购物品");
  form.addLabel("§e§l新增物品到求购物品库\n§7§l物品添加后将在求购功能中可选");
  form.addInput("§e物品ID:", "如: diamond, stone, minecraft:iron_ingot", "");
  form.addInput("§e物品显示名称:", "显示和搜索用的名称", "");
  form.addInput("§e物品AUX值:", "可选，留空为默认值0", "");
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    let itemId = data[1]?.trim();
    const displayName = data[2]?.trim();
    const auxValue = data[3]?.trim();
    
    if (!itemId || !displayName) {
      pl.tell("§c物品ID和显示名称不能为空!");
      return;
    }
    
    if (!itemId.includes(':')) {
      itemId = 'minecraft:' + itemId;
    }
    
    let aux = 0;
    if (auxValue && auxValue !== "") {
      aux = parseInt(auxValue);
      if (isNaN(aux)) {
        pl.tell("§cAUX值必须是数字!");
        return;
      }
    }
    
    try {
      const testItem = mc.newItem(itemId, 1, aux);
      if (!testItem || testItem.isNull()) {
        pl.tell(`§c无效的物品ID: ${itemId}`);
        return;
      }
    } catch(e) {
      pl.tell(`§c物品ID验证失败: ${itemId}`);
      return;
    }
    
    if (!itemsData) {
      itemsData = { items: [] };
    }
    if (!itemsData.items) {
      itemsData.items = [];
    }
    
    const existingItem = itemsData.items.find(item => 
      item.typeName === itemId && (item.aux || 0) === aux
    );
    
    if (existingItem) {
      pl.tell(`§c该物品已存在: §b${existingItem.name} §c(ID: ${itemId}${aux !== 0 ? `, AUX: ${aux}` : ''})`);
      return;
    }
    
    const newItem = {
      name: displayName,
      typeName: itemId
    };
    
    if (aux !== 0) {
      newItem.aux = aux;
    }
    
    const success = saveItemToJson(newItem);
    if (success) {
      pl.tell(`§a成功添加物品: §b${displayName} §a(ID: ${itemId}${aux !== 0 ? `, AUX: ${aux}` : ''})`);
      pl.sendToast("§a物品添加成功", `${displayName}`);
    } else {
      pl.tell("§c保存物品失败，请检查日志!");
    }
  });
}

function saveItemToJson(newItem) {
  try {
    if (!itemsData) {
      itemsData = { items: [] };
    }
    if (!itemsData.items) {
      itemsData.items = [];
    }
    
    itemsData.items.push(newItem);
    
    dbSet(DB_KEYS.ITEMS_DATA, itemsData);
    return true;
  } catch(e) {
    log(`保存物品数据失败: ${e.message}`);
    return false;
  }
}

function searchItemsInJson(keyword) {
  if (!keyword || keyword.trim() === "") {
    return [];
  }
  if (!itemsData || !itemsData.items || !Array.isArray(itemsData.items)) {
    log("物品数据格式不正确或未加载!");
    return [];
  }
  const kw = keyword.toLowerCase();
  const results = [];
  for (const item of itemsData.items) {
    if (!item || !item.name) continue;
    if (item.name.toLowerCase().includes(kw)) {
      results.push(item);
    }
  }
  return results;
}

function showCreatePurchaseRequest(player) {
  const form = mc.newCustomForm();
  form.setTitle("§a§l发布求购订单");
  form.addInput("§e搜索物品名称:", "输入关键字", "");
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    const searchKeyword = data[0]?.trim();
    if (!searchKeyword) {
      pl.tell("§c请输入搜索关键字!");
      return;
    }
    const results = searchItemsInJson(searchKeyword);
    if (results.length === 0) {
      pl.tell(`§c未找到匹配 "${searchKeyword}" 的物品，请尝试其他关键字!`);
      return;
    }
    
    showItemSelectionForPurchaseRequest(pl, results);
  });
}

function showItemSelectionForPurchaseRequest(player, items) {
  const form = mc.newSimpleForm();
  form.setTitle("§a§l选择求购物品");
  form.setContent("§e请选择您想求购的物品:");
  addReturnButton(form);
  items.forEach(item => {
    const itemName = item.name || "未知物品";
    const typeName = item.typeName || "minecraft:unknown";
    let icon = default_icon_path;
    if (textureData.get(typeName) && textureData.get(typeName) !== 'null') {
      icon = textureData.get(typeName);
    }
    form.addButton(`§b${itemName}\n§3${typeName}`, icon);
  });
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === 0) {
      showPurchaseRequestMenu(pl);
      return;
    }
    const selectedIndex = id - 1;
    if (selectedIndex >= 0 && selectedIndex < items.length) {
      const selectedItem = items[selectedIndex];
      showSetPurchaseRequestDetails(pl, selectedItem);
    }
  });
}

function showSetPurchaseRequestDetails(player, item) {
  const form = mc.newCustomForm();
  form.setTitle("§a§l设置求购详情");
  const itemName = item.name || "未知物品";
  const typeName = item.typeName || "minecraft:unknown";
  form.addLabel(`§e物品: §b${itemName}\n§3${typeName}`);
  form.addInput("§e单价 (每个):", "输入数字", "10");
  form.addInput("§e数量:", "输入数字", "1");
  form.addInput("§e备注 (可选):", "特殊需求说明...", "");
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    const priceEach = parseInt(data[1]);
    const quantity = parseInt(data[2]);
    const remark = data[3]?.trim() || "";
    if (isNaN(priceEach) || priceEach <= 0) {
      pl.tell("§c价格必须是正整数!");
      return;
    }
    if (isNaN(quantity) || quantity <= 0) {
      pl.tell("§c数量必须是正整数!");
      return;
    }
    const totalAmount = priceEach * quantity;
    confirmPurchaseRequest(pl, item, priceEach, quantity, totalAmount, remark);
  });
}

function confirmPurchaseRequest(player, item, priceEach, quantity, totalAmount, remark) {
  const economy = getEconomyInterface();
  const fee = config.get('purchaseRequestFee');
  const totalCost = totalAmount + fee;
  const form = mc.newCustomForm();
  form.setTitle("§a§l确认求购订单");
  const itemName = item.name || "未知物品";
  const typeName = item.typeName || "minecraft:unknown";
  let content = `§e物品: §b${itemName}\n§3${typeName}\n\n` + 
                `§e单价: §a${priceEach} ${economy.name}§f / 个\n` +
                `§e数量: §a${quantity}\n` +
                `§e总价: §a${totalAmount} ${economy.name}`;
  if (fee > 0) {
    content += `\n§e手续费: §a${fee} ${economy.name}\n§c需要支付总额: §a${totalCost} ${economy.name}`;
  }
  if (remark) {
    content += `\n\n§e备注: §f${remark}`;
  }
  content += `\n\n§3提示：求购的物品将直接存储到您的仓库中`;
  content += `\n\n§c确认后将从您的账户中扣除 §a${totalCost} ${economy.name}§c!`;
  form.addLabel(content);
  form.addSwitch("§3确认发布此求购订单", false);
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    const isConfirmed = data[1];
    if (!isConfirmed) {
      pl.tell("§c已取消发布求购订单!");
      return;
    }
    if (economy.get(pl) < totalCost) {
      pl.tell(`§c您的余额不足! 需要 ${totalCost} ${economy.name}, 当前余额: ${economy.get(pl)} ${economy.name}`);
      return;
    }
    const success = economy.reduce(pl, totalCost);
    if (!success) {
      pl.tell("§c支付失败，请稍后重试!");
      return;
    }
    const request = {
      id: generateRequestID(),
      itemName: itemName,
      itemType: typeName,
      requesterName: pl.realName,
      requesterXuid: pl.xuid,
      priceEach: priceEach,
      quantity: quantity,
      totalAmount: totalAmount,
      remark: remark,
      createdTime: Date.now(),
      status: "active"
    };
    
    purchaseRequests.requests.push(request);
    savePurchaseRequests();
    
    pl.sendToast("§a求购订单已发布", `${itemName} x${quantity}`);
    if (config.get('notifyPurchaseRequestToAll')) {
      const onlinePlayers = mc.getOnlinePlayers();
      onlinePlayers.forEach(p => {
        if (p.xuid !== pl.xuid) {
          p.sendToast("§3新求购订单", `${pl.realName} 求购 ${itemName} x${quantity}, 单价: ${priceEach}`);
        }
      });
      const newMsg = {
        sender: "§3求购系统",
        content: `§e${pl.realName} §f发布了求购订单: §a${itemName} x${quantity}§f, 单价: §c${priceEach}${economy.name}`,
        timestamp: Date.now(),
        mentions: []
      };
      chatMessages.push(newMsg);
      if (chatMessages.length > config.get('chatHistoryLimit')) {
        chatMessages.shift();
      }
      saveChatData();
    }
    pl.tell(`§a已成功发布求购订单: §b${itemName} x${quantity}§a, 总价: §3${totalAmount} ${economy.name}§a\n§3物品将直接存储到您的仓库中`);
  });
}

function generateRequestID() {
  return Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
}

function showActivePurchaseRequests(player, keyword, page) {
  if (!config.get('enablePurchaseRequests')) {
    player.tell("§c悬赏&求购功能已被管理员禁用!");
    return;
  }
  
  checkExpiredPurchaseRequests();
  let activeRequests = [...purchaseRequests.requests].filter(r => !r.locked);
  if (keyword && keyword.trim() !== "") {
    const kw = keyword.toLowerCase();
    activeRequests = activeRequests.filter(r => 
      r.itemName.toLowerCase().includes(kw) ||
      r.requesterName.toLowerCase().includes(kw) ||
      (r.remark && r.remark.toLowerCase().includes(kw))
    );
  }
  activeRequests = activeRequests.filter(r => r.requesterXuid !== player.xuid);  
  if (activeRequests.length === 0) {
    player.tell("§c当前没有可接的求购订单" + (keyword ? `，或没有匹配 "${keyword}" 的订单` : "") + "!");
    showPurchaseRequestMenu(player);
    return;
  }
  activeRequests.sort((a, b) => b.priceEach - a.priceEach);
  const totalRequests = activeRequests.length;
  const totalPages = Math.ceil(totalRequests / PAGE_SIZE);
  if (page < 1) page = 1;
  if (page > totalPages) page = totalPages;
  const startIndex = (page - 1) * PAGE_SIZE;
  const endIndex = Math.min(startIndex + PAGE_SIZE, totalRequests);
  const pageRequests = activeRequests.slice(startIndex, endIndex);
  const form = mc.newSimpleForm();
  form.setTitle(`§3§l求购列表 - 第${page}/${totalPages}页`);
  form.setContent(`§e共找到 ${totalRequests} 条求购订单${keyword ? `（关键字: ${keyword}）` : ""}\n§a(按单价从高到低排序)`);
  addReturnButton(form);
  form.addButton("§d搜索求购", "textures/ui/magnifyingGlass");
  if (page > 1) {
    form.addButton("§a<< 上一页", "textures/ui/arrow_left");
  }
  if (page < totalPages) {
    form.addButton("§a下一页 >>", "textures/ui/arrow_right");
  }
  pageRequests.forEach(request => {
    let icon = default_icon_path;
    if (request.itemType && textureData.get(request.itemType) && textureData.get(request.itemType) !== 'null') {
      icon = textureData.get(request.itemType);
    }
    const ago = getTimeAgo(request.createdTime);
    form.addButton(
      `§b${request.itemName} §fx${request.quantity}\n` +
      `§a单价: ${request.priceEach} | 发布者: ${request.requesterName} | ${ago}`, 
      icon
    );
  });
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === 0) {
      showPurchaseRequestMenu(pl);
      return;
    }
    if (id === 1) {
      showPurchaseRequestSearch(pl);
      return;
    }
    let buttonOffset = 2;
    const hasPrev = page > 1;
    const hasNext = page < totalPages;
    
    if (hasPrev && id === buttonOffset) {
      showActivePurchaseRequests(pl, keyword, page - 1);
      return;
    }
    
    if (hasPrev) buttonOffset++;
    
    if (hasNext && id === buttonOffset) {
      showActivePurchaseRequests(pl, keyword, page + 1);
      return;
    }
    if (hasNext) buttonOffset++;
    const selectedIdx = id - buttonOffset;
    if (selectedIdx >= 0 && selectedIdx < pageRequests.length) {
      const request = pageRequests[selectedIdx];
      showPurchaseRequestDetails(pl, request);
    }
  });
}

function showPurchaseRequestSearch(player) {
  const form = mc.newCustomForm();
  form.setTitle("§d搜索求购");
  form.addInput("§e请输入关键字:", "物品名称、发布者等", "");
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    const keyword = data[0]?.trim() || "";
    showActivePurchaseRequests(pl, keyword, 1);
  });
}

function getTimeAgo(timestamp) {
  const now = Date.now();
  const diffMs = now - timestamp;
  const seconds = Math.floor(diffMs / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  
  if (days > 0) {
    return `${days}天前`;
  } else if (hours > 0) {
    return `${hours}小时前`;
  } else if (minutes > 0) {
    return `${minutes}分钟前`;
  } else {
    return "刚刚";
  }
}

function showPurchaseRequestDetails(player, request) {
  const economy = getEconomyInterface();
  const form = mc.newCustomForm();
  form.setTitle("§3§l求购详情");
  
  let content = `§e物品: §b${request.itemName}\n§3${request.itemType}\n\n` +
                `§e发布者: §b${request.requesterName}\n` +
                `§e发布时间: §b${new Date(request.createdTime).toLocaleString()}\n\n` +
                `§e单价: §a${request.priceEach} ${economy.name}\n` +
                `§e数量: §a${request.quantity}\n` +
                `§e总价: §a${request.totalAmount} ${economy.name}\n`;
                
  if (request.remark) {
    content += `\n§e备注: §f${request.remark}`;
  }
  
  content += `\n\n§a如果您拥有此物品并希望出售，请选择下面要出售的数量。`;
  content += `\n§3提示：物品将直接存储到求购者的仓库中`;
  let playerHasItem = false;
  let itemCount = 0;
  
  try {
    const newItem = mc.newItem(request.itemType, 1);
    if (!newItem.isNull()) {
      itemCount = getPlayerInventoryItemCountByType(player, request.itemType);
      playerHasItem = itemCount > 0;
    }
  } catch (e) {
          log(`无法创建物品 ${request.itemType}: ${e.message}`);
  }
  
  form.addLabel(content);
  
  if (playerHasItem) {
    form.addLabel(`§a您的背包中有 §b${itemCount} §a个该物品可供出售。`);
    form.addInput(`§e请输入要出售的数量(最多${Math.min(itemCount, request.quantity)}):`, "数字", "1");
  } else {
    form.addLabel("§c您的背包中没有该物品，无法完成此交易。");
  }
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    if (!playerHasItem) {
      showActivePurchaseRequests(pl, "", 1);
      return;
    }
    const sellAmount = parseInt(data[2]);
    
    if (isNaN(sellAmount) || sellAmount <= 0) {
      pl.tell("§c请输入有效的数量!");
      return;
    }
    
    if (sellAmount > itemCount) {
      pl.tell(`§c您的背包中只有 ${itemCount} 个该物品!`);
      return;
    }
    
    if (sellAmount > request.quantity) {
      pl.tell(`§c求购订单只需要 ${request.quantity} 个物品!`);
      return;
    }
    confirmFulfillPurchaseRequest(pl, request, sellAmount);
  });
}

function getPlayerInventoryItemCountByType(player, itemType) {
  let count = 0;
  const inv = player.getInventory();
  for (let i = 0; i < inv.size; i++) {
    const item = inv.getItem(i);
    if (item && !item.isNull() && item.type === itemType) {
      count += item.count;
    }
  }
  
  return count;
}

function confirmFulfillPurchaseRequest(player, request, sellAmount) {
  const economy = getEconomyInterface();
  const form = mc.newSimpleForm();
  form.setTitle("§a§l确认交易");
  
  const totalEarnings = request.priceEach * sellAmount;
  
  let content = `§e您将向 §b${request.requesterName} §e出售:\n\n` +
                `§a${request.itemName} §fx${sellAmount}\n\n` +
                `§e单价: §a${request.priceEach} ${economy.name}\n` +
                `§e总收入: §a${totalEarnings} ${economy.name}\n\n` +
                `§c确认后将从您的背包中扣除相应物品，并获得收入。`;
  
  form.setContent(content);
  form.addButton("§c取消", "textures/ui/cancel");
  form.addButton("§a确认交易", "textures/ui/confirm");
  
  player.sendForm(form, (pl, id) => {
    if (id === null || id === 0) {
      pl.tell("§c已取消交易!");
      showActivePurchaseRequests(pl, "", 1);
      return;
    }
    
    if (id === 1) {
      let itemCount = getPlayerInventoryItemCountByType(pl, request.itemType);
      if (itemCount < sellAmount) {
        pl.tell(`§c您的背包中只有 ${itemCount} 个该物品，无法完成交易!`);
        return;
      }
      
      const activeRequest = purchaseRequests.requests.find(r => r.id === request.id);
      if (!activeRequest) {
        pl.tell("§c此求购订单已不存在，可能已被完成或已过期!");
        return;
      }
      
      if (activeRequest.locked) {
        pl.tell("§c该订单正在处理中，请稍后再试!");
        return;
      }
      
      if (activeRequest.quantity < sellAmount) {
        pl.tell(`§c求购订单现在只需要 ${activeRequest.quantity} 个物品!`);
        return;
      }
      
      activeRequest.locked = true;
      savePurchaseRequests();
      
      let removeResult = removeItemsByType(pl, request.itemType, sellAmount);
      if (!removeResult.success) {
        activeRequest.locked = false;
        savePurchaseRequests();
        pl.tell("§c从背包移除物品失败，请确保物品未被锁定!");
        return;
      }
      
      activeRequest.quantity -= sellAmount;
      
      if (activeRequest.quantity <= 0) {
        const idx = purchaseRequests.requests.findIndex(r => r.id === request.id);
        if (idx !== -1) {
          const completedRequest = purchaseRequests.requests.splice(idx, 1)[0];
          completedRequest.status = "completed";
          completedRequest.completedTime = Date.now();
          completedRequest.fulfilledBy = [{
            playerName: pl.realName,
            playerXuid: pl.xuid,
            amount: sellAmount,
            time: Date.now()
          }];
          purchaseRequests.history.push(completedRequest);
        }
      } else {
        activeRequest.totalAmount = activeRequest.priceEach * activeRequest.quantity;
        if (!activeRequest.partialFulfillments) {
          activeRequest.partialFulfillments = [];
        }
        
        activeRequest.partialFulfillments.push({
          playerName: pl.realName,
          playerXuid: pl.xuid,
          amount: sellAmount,
          time: Date.now()
        });
        activeRequest.locked = false;
      }
      savePurchaseRequests();
      
      economy.add(pl, totalEarnings);
            let sourceItemNbt = null;
      
      if (removeResult.removedItem && !removeResult.removedItem.isNull()) {
        sourceItemNbt = removeResult.removedItem.getNbt();
            } else {
        try {
          const baseItem = mc.newItem(request.itemType, 1);
          sourceItemNbt = baseItem.getNbt();
        } catch (e) {
          log(`创建基础物品失败: ${e.message}`);
          pl.tell(`§c物品处理失败，请联系管理员！`);
          return;
        }
      }
      
      const requester = mc.getPlayer(request.requesterXuid);
      
      try {
        const warehouseResult = addItemToWarehouse(request.requesterXuid, request.requesterName, sourceItemNbt, sellAmount, `来自求购订单: ${request.itemName} (出售者: ${pl.realName})`, true);
        
        if (!warehouseResult) {
          log(`§c求购仓库存储失败，正在回滚交易...`);
          economy.reduce(pl, totalEarnings);
          
          try {
            const returnItem = mc.newItem(NBT.parseSNBT(sourceItemNbt.toSNBT ? sourceItemNbt.toSNBT() : sourceItemNbt));
            returnItem.setCount(sellAmount);
            pl.giveItem(returnItem);
            pl.tell(`§c物品存储到求购者仓库失败！已将物品退还给您，收入已撤销。`);
          } catch (returnErr) {
            addItemToWarehouse(pl.xuid, pl.realName, sourceItemNbt, sellAmount, `求购交易回滚: ${request.itemName}`, true);
            pl.tell(`§c物品存储失败！物品已存入您的仓库，收入已撤销。请前往仓库领取。`);
          }
          
          activeRequest.quantity += sellAmount;
          activeRequest.locked = false;
          savePurchaseRequests();
          return;
        }
        
        pl.tell(`§a物品已成功存储到求购者的仓库中！`);
        
        if (requester) {
          requester.tell(`§a§l您的求购订单 §b${request.itemName} §a已被 §e${pl.realName} §a满足 §3${sellAmount} §a个！物品已存储到您的仓库中，请前往仓库领取！`);
          requester.sendToast("§a求购订单更新", `${request.itemName} x${sellAmount} 已到仓库`);
        }
      } catch (e) {
        log(`存储物品到仓库失败: ${e.message}`);
        economy.reduce(pl, totalEarnings);
        
        try {
          const returnItem = mc.newItem(NBT.parseSNBT(sourceItemNbt.toSNBT ? sourceItemNbt.toSNBT() : sourceItemNbt));
          returnItem.setCount(sellAmount);
          pl.giveItem(returnItem);
          pl.tell(`§c物品存储失败！已将物品退还给您，收入已撤销。`);
        } catch (returnErr) {
          addItemToWarehouse(pl.xuid, pl.realName, sourceItemNbt, sellAmount, `求购交易回滚: ${request.itemName}`, true);
          pl.tell(`§c物品存储失败！物品已存入您的仓库，收入已撤销。请前往仓库领取。`);
        }
        
        activeRequest.quantity += sellAmount;
        activeRequest.locked = false;
        savePurchaseRequests();
        return;
      }
      
        if (activeRequest.quantity <= 0) {
        if (requester) {
          requester.tell(`§a§l您的求购订单 §b${request.itemName} §a已完全满足!`);
        }
      }
      const newMsg = {
        sender: "§3求购系统",
        content: `§e${pl.realName} §f满足了 §e${request.requesterName} §f的求购: §a${request.itemName} x${sellAmount}§f, 收入: §c${totalEarnings}${economy.name}`,
        timestamp: Date.now(),
        mentions: []
      };
      chatMessages.push(newMsg);
      if (chatMessages.length > config.get('chatHistoryLimit')) {
        chatMessages.shift();
      }
      saveChatData();
      pl.sendToast("§a交易成功", `出售 ${request.itemName} x${sellAmount} 获得 ${totalEarnings} ${economy.name}`);
      pl.tell(`§a您已成功出售 §b${request.itemName} x${sellAmount} §a给 §e${request.requesterName}§a，获得 §3${totalEarnings} ${economy.name}§a!`);
      showActivePurchaseRequests(pl, "", 1);
    }
  });
}


function removeItemsByType(player, itemType, amount) {
  let remaining = amount;
  const inv = player.getInventory();
  let removedItem = null;
  
  for (let i = 0; i < inv.size; i++) {
    if (remaining <= 0) break;
    const item = inv.getItem(i);
    if (item && !item.isNull() && item.type === itemType) {
      if (!removedItem) {
        removedItem = item.clone();
      }
      const removeCount = Math.min(item.count, remaining);
      inv.removeItem(i, removeCount);
      remaining -= removeCount;
    }
  }
  player.refreshItems();
  return {
    success: remaining <= 0,
    removedItem: removedItem
  };
}
function showMyPurchaseRequests(player) {
  if (!config.get('enablePurchaseRequests')) {
    player.tell("§c悬赏&求购功能已被管理员禁用!");
    return;
  }
  const form = mc.newSimpleForm();
  form.setTitle("§d§l我的求购");
  form.setContent("§e请选择要查看的求购记录类型:");
  
  addReturnButton(form);
  form.addButton("§a活跃的求购订单", "textures/ui/MCoin");
  form.addButton("§b历史求购记录", "textures/ui/backup_replace");
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    
    if (id === 0) {
      showPurchaseRequestMenu(pl);
      return;
    }
    
    if (id === 1) {
      showMyActivePurchaseRequests(pl);
    } else if (id === 2) {
      showMyHistoryPurchaseRequests(pl);
    }
  });
}

function showMyActivePurchaseRequests(player) {
  checkExpiredPurchaseRequests();
  const myRequests = purchaseRequests.requests.filter(r => r.requesterXuid === player.xuid && !r.locked); 
  if (myRequests.length === 0) {
    player.tell("§c您当前没有活跃的求购订单!");
    showMyPurchaseRequests(player);
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle("§a§l我的活跃求购订单");
  form.setContent(`§e您当前有 ${myRequests.length} 个活跃的求购订单`);
  addReturnButton(form);
  myRequests.forEach(request => {
    let icon = default_icon_path;
    if (request.itemType && textureData.get(request.itemType) && textureData.get(request.itemType) !== 'null') {
      icon = textureData.get(request.itemType);
    }
    const ago = getTimeAgo(request.createdTime);
    form.addButton(
      `§b${request.itemName} §fx${request.quantity}\n` +
      `§a单价: ${request.priceEach} | 总价: ${request.totalAmount} | ${ago}`, 
      icon
    );
  });
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === 0) {
      showMyPurchaseRequests(pl);
      return;
    }
    const selectedIdx = id - 1;
    if (selectedIdx >= 0 && selectedIdx < myRequests.length) {
      const request = myRequests[selectedIdx];
      showMyPurchaseRequestDetails(pl, request);
    }
  });
}

function showMyPurchaseRequestDetails(player, request) {
  const economy = getEconomyInterface();
  const form = mc.newCustomForm();
  form.setTitle("§a§l我的求购订单");
  let content = `§e物品: §b${request.itemName}\n§3${request.itemType}\n\n` +
                `§e发布时间: §b${new Date(request.createdTime).toLocaleString()}\n\n` +
                `§e单价: §a${request.priceEach} ${economy.name}\n` +
                `§e剩余数量: §a${request.quantity}\n` +
                `§e剩余金额: §a${request.totalAmount} ${economy.name}\n`;
                
  if (request.remark) {
    content += `\n§e备注: §f${request.remark}`;
  }
  if (request.partialFulfillments && request.partialFulfillments.length > 0) {
    content += "\n\n§e已完成的交易:";
    request.partialFulfillments.forEach((fulfillment, idx) => {
      const time = new Date(fulfillment.time).toLocaleString();
      content += `\n§a${idx+1}. §b${fulfillment.playerName} §a提供了 §f${fulfillment.amount} §a个，时间: §f${time}`;
    });
  }
  form.addLabel(content);
  form.addSwitch("§c取消此求购订单", false);
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    const isCancelling = data[1];
    if (isCancelling) {
      confirmCancelPurchaseRequest(pl, request);
    } else {
      showMyActivePurchaseRequests(pl);
    }
  });
}

function confirmCancelPurchaseRequest(player, request) {
  const economy = getEconomyInterface();
  const form = mc.newSimpleForm();
  form.setTitle("§c§l确认取消求购");
  let content = `§e您确定要取消以下求购订单吗？\n\n` +
                `§b${request.itemName} §fx${request.quantity}\n` +
                `§a单价: ${request.priceEach} ${economy.name}\n` +
                `§a总价: ${request.totalAmount} ${economy.name}\n\n` +
                `§e取消后，未使用的金额(§3${request.totalAmount} ${economy.name}§e)将退还给您。`; 
  form.setContent(content);
  form.addButton("§c放弃取消", "textures/ui/cancel");
  form.addButton("§a确认取消", "textures/ui/confirm");
  player.sendForm(form, (pl, id) => {
    if (id === null || id === 0) {
      showMyActivePurchaseRequests(pl);
      return;
    }  
    if (id === 1) {
      const idx = purchaseRequests.requests.findIndex(r => r.id === request.id);
      if (idx === -1) {
        pl.tell("§c此求购订单已不存在!");
        return;
      }     
      const cancelledRequest = purchaseRequests.requests.splice(idx, 1)[0];
      cancelledRequest.status = "cancelled";
      cancelledRequest.cancelledTime = Date.now();
      purchaseRequests.history.push(cancelledRequest);
      economy.add(pl, cancelledRequest.totalAmount);   
      savePurchaseRequests();
      pl.sendToast("§a求购已取消", `退还金额: ${cancelledRequest.totalAmount} ${economy.name}`);
      pl.tell(`§a您已成功取消求购订单 §b${cancelledRequest.itemName}§a，剩余金额 §3${cancelledRequest.totalAmount} ${economy.name} §a已退还!`);
      showMyPurchaseRequests(pl);
    }
  });
}

function showMyHistoryPurchaseRequests(player) {
  const myHistory = purchaseRequests.history.filter(r => r.requesterXuid === player.xuid);
  if (myHistory.length === 0) {
    player.tell("§c您没有历史求购记录!");
    showMyPurchaseRequests(player);
    return;
  }
  myHistory.sort((a, b) => {
    const timeA = a.completedTime || a.cancelledTime || a.expiredTime || a.createdTime;
    const timeB = b.completedTime || b.cancelledTime || b.expiredTime || b.createdTime;
    return timeB - timeA; 
  });
  const form = mc.newCustomForm();
  form.setTitle("§b§l历史求购记录");
  let content = `§e您有 ${myHistory.length} 条历史求购记录:\n\n`;
  myHistory.forEach((record, idx) => {
    const status = record.status === "completed" ? "§a已完成" : 
                  record.status === "cancelled" ? "§c已取消" : 
                  record.status === "expired" ? "§3已过期" : "§3未知";
    const time = new Date(record.completedTime || record.cancelledTime || record.expiredTime || record.createdTime).toLocaleString();
    content += `§e${idx+1}. §b${record.itemName} §fx${record.quantity} §3(${status}§3)\n` +
               `§a单价: ${record.priceEach} | 总价: ${record.totalAmount} | 时间: ${time}\n`;
    if (record.status === "completed" && record.fulfilledBy) {
      record.fulfilledBy.forEach(fulfill => {
        content += `  §a由 §b${fulfill.playerName} §a提供了 §f${fulfill.amount} §a个\n`;
      });
    }
    if (record.partialFulfillments && record.partialFulfillments.length > 0) {
      record.partialFulfillments.forEach(fulfill => {
        content += `  §a由 §b${fulfill.playerName} §a提供了 §f${fulfill.amount} §a个\n`;
      });
    }
    content += "\n";
  });
  form.addLabel(content);
  player.sendForm(form, (pl, data) => {
    showMyPurchaseRequests(pl);
  });
}


function getSortedShopItemKeys(shop) {
  const allKeys = Object.keys(shop.items);
  if (!shop.topItems || shop.topItems.length === 0) {
    return allKeys;
  }
  const validTopItems = shop.topItems.filter(key => shop.items[key]);
  const nonTopItems = allKeys.filter(key => !validTopItems.includes(key));
  return [...validTopItems, ...nonTopItems];
}

function showShopItemOrderMenu(player) {
  const shop = shopsData[player.xuid];
  const shopItemKeys = Object.keys(shop.items);
  if (shopItemKeys.length === 0) {
    player.tell('§c店铺中没有物品可以调整顺序！');
    return;
  }
  const form = mc.newSimpleForm();
  form.setTitle('§3§l调整物品顺序');
  form.setContent('§e您可以设置前5个物品的显示顺序，这些物品将在店铺中优先显示：');
  addReturnButton(form);
  form.addButton('§a设置置顶物品', 'textures/ui/gameTipArrow_up');
  form.addButton('§b查看当前顺序', 'textures/ui/book_metatag_default');
  form.addButton('§c重置物品顺序', 'textures/ui/refresh');
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === 0) {
      showEditShopItemsMenu(pl);
      return;
    }
    if (id === 1) {
      showSetTopItemsMenu(pl);
    } else if (id === 2) {
      showCurrentItemOrder(pl);
    } else if (id === 3) {
      resetItemOrder(pl);
    }
  });
}

function showSetTopItemsMenu(player) {
  const shop = shopsData[player.xuid];
  const shopItemKeys = Object.keys(shop.items);
  if (shopItemKeys.length === 0) {
    player.tell('§c店铺中没有物品！');
    showShopItemOrderMenu(player);
    return;
  }
  if (!shop.topItems) {
    shop.topItems = [];
  }
  const form = mc.newCustomForm();
  form.setTitle('§a§l设置置顶物品');
  form.addLabel('§e请选择最多5个物品设为置顶，置顶的物品将在店铺中优先显示：');
  shopItemKeys.forEach((key) => {
    const shopItem = shop.items[key];
    const tmpItem = mc.newItem(NBT.parseSNBT(shopItem.itemData));
    const showName = getItemDisplayName(tmpItem, false);
    const isTopItem = shop.topItems.includes(key);
    form.addSwitch(`${showName} (价格: ${shopItem.price} | 库存: ${shopItem.quantity === -1 ? '∞' : shopItem.quantity})`, isTopItem);
  });
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showShopItemOrderMenu(pl);
      return;
    }
    const selectedTopItems = [];
    for (let i = 0; i < shopItemKeys.length; i++) {
      if (data[i + 1] === true) {
        selectedTopItems.push(shopItemKeys[i]);
      }
    }
    if (selectedTopItems.length > 5) {
      pl.tell('§c最多只能设置5个置顶物品！');
      showShopItemOrderMenu(pl);
      return;
    }
    shop.topItems = selectedTopItems;
    saveShopsData();
    pl.tell(`§a成功设置 ${selectedTopItems.length} 个置顶物品！`);
    if (selectedTopItems.length > 1) {
      showTopItemsOrderMenu(pl, selectedTopItems);
    } else {
      showShopItemOrderMenu(pl);
    }
  });
}

function showTopItemsOrderMenu(player, topItems) {
  const shop = shopsData[player.xuid];
  const form = mc.newCustomForm();
  form.setTitle('§3§l调整置顶物品顺序');
  form.addLabel('§e请选择下方选项来调整置顶物品的显示顺序：');
  const itemNames = topItems.map(key => {
    const shopItem = shop.items[key];
    const tmpItem = mc.newItem(NBT.parseSNBT(shopItem.itemData));
    return getItemDisplayName(tmpItem, false);
  });
  for (let i = 0; i < topItems.length; i++) {
    form.addDropdown(`§e第${i + 1}位：`, itemNames, i);
  }
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showShopItemOrderMenu(pl);
      return;
    }
    const newOrder = [];
    const usedIndices = new Set();
    for (let i = 0; i < topItems.length; i++) {
      const selectedIndex = data[i + 1];
      if (usedIndices.has(selectedIndex)) {
        pl.tell('§c不能选择重复的物品！请重新设置。');
        showShopItemOrderMenu(pl);
        return;
      }
      usedIndices.add(selectedIndex);
      newOrder.push(topItems[selectedIndex]);
    }
    shop.topItems = newOrder;
    saveShopsData();
    pl.tell('§a置顶物品顺序调整成功！');
    showShopItemOrderMenu(pl);
  });
}

function showCurrentItemOrder(player) {
  const shop = shopsData[player.xuid];
  const sortedKeys = getSortedShopItemKeys(shop);
  const form = mc.newCustomForm();
  form.setTitle('§b§l当前物品顺序');
  let content = '§e当前店铺物品显示顺序：\n\n';
  if (shop.topItems && shop.topItems.length > 0) {
    content += '§a§l置顶物品：\n';
    shop.topItems.forEach((key, index) => {
      const shopItem = shop.items[key];
      if (shopItem) {
        const tmpItem = mc.newItem(NBT.parseSNBT(shopItem.itemData));
        const showName = getItemDisplayName(tmpItem, false);
        content += `§3${index + 1}. §f${showName}\n`;
      }
    });
    content += '\n§b§l其他物品：\n';
  }
  const nonTopItems = sortedKeys.filter(key => !shop.topItems || !shop.topItems.includes(key));
  nonTopItems.forEach((key, index) => {
    const shopItem = shop.items[key];
    const tmpItem = mc.newItem(NBT.parseSNBT(shopItem.itemData));
    const showName = getItemDisplayName(tmpItem, false);
    const displayIndex = (shop.topItems ? shop.topItems.length : 0) + index + 1;
    content += `§f${displayIndex}. ${showName}\n`;
  });
  form.addLabel(content);
  player.sendForm(form, (pl, data) => {
    showShopItemOrderMenu(pl);
  });
}

function resetItemOrder(player) {
  const shop = shopsData[player.xuid];
  const form = mc.newCustomForm();
  form.setTitle('§c§l重置物品顺序');
  form.addLabel('§e确认要重置所有物品的显示顺序吗？\n§c这将清除所有置顶设置，物品将按默认顺序显示。');
  form.addSwitch('§c确认重置物品顺序', false);
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showShopItemOrderMenu(pl);
      return;
    }
    const confirm = data[1];
    if (confirm) {
      shop.topItems = [];
      saveShopsData();
      pl.tell('§a物品顺序已重置！');
    } else {
      pl.tell('§c操作已取消。');
    }
    showShopItemOrderMenu(pl);
  });
}

function showDetailedFinancialReport(player) {
  const xuid = player.xuid;
  const shop = shopsData[xuid];
  const economy = getEconomyInterface();
  
  if (!shop) {
    player.tell("§c您还没有店铺！");
    return;
  }
  
  const playerLogs = purchaseLogs.players?.[xuid] || { buy: [], sell: [] };
  const buyRecords = playerLogs.buy || [];
  const sellRecords = playerLogs.sell || [];
  
  let totalIncome = 0;
  let totalSoldItems = 0;
  let incomeToday = 0;
  let incomeThisWeek = 0;
  let incomeThisMonth = 0;
  
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
  const monthAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000);
  
  sellRecords.forEach(record => {
    const price = parseFloat(record.totalPrice) || 0;
    totalIncome += price;
    totalSoldItems += parseInt(record.quantity) || 0;
    
    const recordDate = new Date(record.time);
    if (recordDate >= today) incomeToday += price;
    if (recordDate >= weekAgo) incomeThisWeek += price;
    if (recordDate >= monthAgo) incomeThisMonth += price;
  });
  
  let totalExpense = 0;
  let totalBoughtItems = 0;
  let expenseToday = 0;
  let expenseThisWeek = 0;
  let expenseThisMonth = 0;
  
  buyRecords.forEach(record => {
    const price = parseFloat(record.totalPrice) || 0;
    totalExpense += price;
    totalBoughtItems += parseInt(record.quantity) || 0;
    
    const recordDate = new Date(record.time);
    if (recordDate >= today) expenseToday += price;
    if (recordDate >= weekAgo) expenseThisWeek += price;
    if (recordDate >= monthAgo) expenseThisMonth += price;
  });
  
  const totalProfit = totalIncome - totalExpense;
  const profitToday = incomeToday - expenseToday;
  const profitThisWeek = incomeThisWeek - expenseThisWeek;
  const profitThisMonth = incomeThisMonth - expenseThisMonth;
  
  let shopValue = 0;
  for (const itemKey in shop.items) {
    const item = shop.items[itemKey];
    const quantity = item.quantity === -1 ? 100 : item.quantity; 
    shopValue += item.price * quantity;
  }
  
  const form = mc.newCustomForm();
  form.setTitle("§3§l详细财务报表");
  
  const content = `§e§l=== 收入分析 ===§r
§a总收入: §3${totalIncome.toFixed(2)} ${economy.name}
§a今日收入: §3${incomeToday.toFixed(2)} ${economy.name}
§a本周收入: §3${incomeThisWeek.toFixed(2)} ${economy.name}
§a本月收入: §3${incomeThisMonth.toFixed(2)} ${economy.name}
§a售出物品总数: §3${totalSoldItems}件

§e§l=== 支出分析 ===§r
§c总支出: §3${totalExpense.toFixed(2)} ${economy.name}
§c今日支出: §3${expenseToday.toFixed(2)} ${economy.name}
§c本周支出: §3${expenseThisWeek.toFixed(2)} ${economy.name}
§c本月支出: §3${expenseThisMonth.toFixed(2)} ${economy.name}
§c购买物品总数: §3${totalBoughtItems}件

§e§l=== 利润分析 ===§r
§b总利润: §3${totalProfit.toFixed(2)} ${economy.name}
§b今日利润: §3${profitToday.toFixed(2)} ${economy.name}
§b本周利润: §3${profitThisWeek.toFixed(2)} ${economy.name}
§b本月利润: §3${profitThisMonth.toFixed(2)} ${economy.name}

§e§l=== 资产状况 ===§r
§d当前余额: §3${economy.get(player)} ${economy.name}
§d店铺商品估值: §3${shopValue.toFixed(2)} ${economy.name}
§d总资产: §3${(economy.get(player) + shopValue).toFixed(2)} ${economy.name}

§e§l=== 经营指标 ===§r
§s平均售价: §3${totalSoldItems > 0 ? (totalIncome / totalSoldItems).toFixed(2) : '0'} ${economy.name}/件
§s平均购价: §3${totalBoughtItems > 0 ? (totalExpense / totalBoughtItems).toFixed(2) : '0'} ${economy.name}/件
§s利润率: §3${totalIncome > 0 ? ((totalProfit / totalIncome) * 100).toFixed(1) : '0'}%`;
  
  form.addLabel(content);
  player.sendForm(form, (pl, data) => {
    showMyShopMenu(pl);
  });
}

function showMarketTrendAnalysis(player) {
  const form = mc.newCustomForm();
  form.setTitle("§d§l📈 市场趋势分析");
  
  const itemSales = {};
  const itemPrices = {};
  const itemShops = {};
  
  if (purchaseLogs.global) {
    purchaseLogs.global.forEach(record => {
      const itemName = record.itemName;
      const quantity = parseInt(record.quantity) || 0;
      const price = parseFloat(record.priceEach) || 0;
      
      if (!itemSales[itemName]) {
        itemSales[itemName] = 0;
        itemPrices[itemName] = [];
        itemShops[itemName] = new Set();
      }
      
      itemSales[itemName] += quantity;
      itemPrices[itemName].push(price);
      itemShops[itemName].add(record.shopName);
    });
  }
  
  const hotItems = Object.entries(itemSales)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 10);
  
  const currentMarket = {};
  for (const xuid in shopsData) {
    const shop = shopsData[xuid];
    if (!shop.isOpen) continue;
    
    for (const itemKey in shop.items) {
      const item = shop.items[itemKey];
      const itemName = item.name;
      
      if (!currentMarket[itemName]) {
        currentMarket[itemName] = {
          prices: [],
          shops: 0,
          totalStock: 0
        };
      }
      
      currentMarket[itemName].prices.push(item.price);
      currentMarket[itemName].shops++;
      currentMarket[itemName].totalStock += (item.quantity === -1 ? 999 : item.quantity);
    }
  }
  
  let content = `§e§l=== 热门商品TOP10 ===§r\n`;
  hotItems.forEach((item, index) => {
    const itemName = item[0];
    const sales = item[1];
    const avgPrice = itemPrices[itemName].length > 0 ? 
      (itemPrices[itemName].reduce((a, b) => a + b, 0) / itemPrices[itemName].length).toFixed(2) : '0';
    const shopCount = itemShops[itemName].size;
    
    content += `§3${index + 1}. §b${itemName}\n`;
    content += `   §a销量: ${sales}件 §f| §e均价: ${avgPrice} §f| §d店铺: ${shopCount}家\n\n`;
  });
  
  content += `§e§l=== 当前市场概况 ===§r\n`;
  const marketItems = Object.entries(currentMarket)
    .sort((a, b) => b[1].shops - a[1].shops)
    .slice(0, 8);
  
  marketItems.forEach(item => {
    const itemName = item[0];
    const data = item[1];
    const avgPrice = data.prices.length > 0 ? 
      (data.prices.reduce((a, b) => a + b, 0) / data.prices.length).toFixed(2) : '0';
    const minPrice = data.prices.length > 0 ? Math.min(...data.prices).toFixed(2) : '0';
    const maxPrice = data.prices.length > 0 ? Math.max(...data.prices).toFixed(2) : '0';
    
    content += `§b${itemName}\n`;
    content += `   §f店铺数: §a${data.shops} §f| §f库存: §e${data.totalStock}\n`;
    content += `   §f价格区间: §c${minPrice}~§a${maxPrice} §f| §f均价: §3${avgPrice}\n\n`;
  });
  
  content += `§e§l=== 市场建议 ===§r\n`;
  content += `§a● 关注热门商品，考虑进货销售\n`;
  content += `§a● 对比价格区间，找到合适定价\n`;
  content += `§a● 库存较少的热门商品有较好机会\n`;
  content += `§a● 避免过度竞争的饱和市场`;
  
  form.addLabel(content);
  player.sendForm(form, (pl, data) => {
    showMyShopMenu(pl);
  });
}

function showEnhancedUserBehaviorAnalysis(player) {
  if (!player.isOP()) {
    player.tell("§c此功能仅限管理员使用！");
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle("§c§l用户行为分析");
  form.setContent("§e请选择分析类型：");
  addReturnButton(form);
  form.addButton("§a§l活跃用户分析", "textures/ui/sidebar_icons/dressing_room_customization");
  form.addButton("§b§l购买偏好分析", "textures/ui/heart");
  form.addButton("§d§l时间活跃度分析", "textures/ui/clock");
  form.addButton("§3§l消费能力分析", "textures/ui/MCoin");
  form.addButton("§e§l店铺经营分析", "textures/ui/store_home_icon");
  form.addButton("§c§l综合数据报告", "textures/ui/book_frame");
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === 0) {
      showAdminMenu(pl);
      return;
    }
    
    switch(id) {
      case 1:
        showActiveUserAnalysis(pl);
        break;
      case 2:
        showPurchasePreferenceAnalysis(pl);
        break;
      case 3:
        showTimeActivityAnalysis(pl);
        break;
      case 4:
        showSpendingPowerAnalysis(pl);
        break;
      case 5:
        showShopBusinessAnalysis(pl);
        break;
      case 6:
        showComprehensiveDataReport(pl);
        break;
    }
  });
}

function showActiveUserAnalysis(player) {
  const form = mc.newCustomForm();
  form.setTitle("§a§l活跃用户分析");
  
  const userActivity = {};
  const userSpending = {};
  const userFirstPurchase = {};
  const userLastPurchase = {};
  
  if (purchaseLogs.global) {
    purchaseLogs.global.forEach(record => {
      const buyerName = record.buyerName;
      const totalPrice = parseFloat(record.totalPrice) || 0;
      const time = new Date(record.time);
      
      if (!userActivity[buyerName]) {
        userActivity[buyerName] = 0;
        userSpending[buyerName] = 0;
        userFirstPurchase[buyerName] = time;
        userLastPurchase[buyerName] = time;
      }
      
      userActivity[buyerName]++;
      userSpending[buyerName] += totalPrice;
      
      if (time < userFirstPurchase[buyerName]) {
        userFirstPurchase[buyerName] = time;
      }
      if (time > userLastPurchase[buyerName]) {
        userLastPurchase[buyerName] = time;
      }
    });
  }
  
  const activeUsers = Object.entries(userActivity)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 15);
  
  let content = `§e§l=== 活跃用户TOP15 ===§r\n`;
  activeUsers.forEach((user, index) => {
    const userName = user[0];
    const purchases = user[1];
    const spending = userSpending[userName] || 0;
    const avgSpending = purchases > 0 ? (spending / purchases).toFixed(2) : '0';
    const firstPurchase = userFirstPurchase[userName];
    const lastPurchase = userLastPurchase[userName];
    const daysSinceFirst = Math.floor((new Date() - firstPurchase) / (1000 * 60 * 60 * 24));
    const daysSinceLast = Math.floor((new Date() - lastPurchase) / (1000 * 60 * 60 * 24));
    
    content += `§3${index + 1}. §b${userName}\n`;
    content += `   §a交易: ${purchases}次 §f| §e总消费: ${spending.toFixed(2)} §f| §d均消费: ${avgSpending}\n`;
    content += `   §f首购: ${daysSinceFirst}天前 §f| §f末购: ${daysSinceLast}天前\n\n`;
  });
  
  const now = new Date();
  const recentUsers = Object.keys(userLastPurchase).filter(user => {
    const daysSince = (now - userLastPurchase[user]) / (1000 * 60 * 60 * 24);
    return daysSince <= 7;
  }).length;
  
  const dormantUsers = Object.keys(userLastPurchase).filter(user => {
    const daysSince = (now - userLastPurchase[user]) / (1000 * 60 * 60 * 24);
    return daysSince > 30;
  }).length;
  
  content += `§e§l=== 用户活跃度分类 ===§r\n`;
  content += `§a活跃用户(7天内): §3${recentUsers}人\n`;
  content += `§c休眠用户(30天+): §3${dormantUsers}人\n`;
  content += `§f总用户数: §3${Object.keys(userActivity).length}人`;
  
  form.addLabel(content);
  player.sendForm(form, (pl, data) => {
    showEnhancedUserBehaviorAnalysis(pl);
  });
}

function showPurchasePreferenceAnalysis(player) {
  const form = mc.newCustomForm();
  form.setTitle("§b§l购买偏好分析");
  
  const itemPopularity = {};
  const categoryPreference = {};
  const priceRangePreference = {};
  
  if (purchaseLogs.global) {
    purchaseLogs.global.forEach(record => {
      const itemName = record.itemName;
      const price = parseFloat(record.priceEach) || 0;
      const quantity = parseInt(record.quantity) || 0;
      
      if (!itemPopularity[itemName]) {
        itemPopularity[itemName] = { count: 0, totalQuantity: 0 };
      }
      itemPopularity[itemName].count++;
      itemPopularity[itemName].totalQuantity += quantity;
      
      let priceRange;
      if (price < 10) priceRange = "0-10";
      else if (price < 50) priceRange = "10-50";
      else if (price < 100) priceRange = "50-100";
      else if (price < 500) priceRange = "100-500";
      else priceRange = "500+";
      
      if (!priceRangePreference[priceRange]) {
        priceRangePreference[priceRange] = 0;
      }
      priceRangePreference[priceRange]++;
    });
  }
  
  const popularItems = Object.entries(itemPopularity)
    .sort((a, b) => b[1].count - a[1].count)
    .slice(0, 10);
  
  let content = `§e§l=== 热门商品TOP10 ===§r\n`;
  popularItems.forEach((item, index) => {
    const itemName = item[0];
    const data = item[1];
    content += `§3${index + 1}. §b${itemName}\n`;
    content += `   §a购买次数: ${data.count} §f| §e总销量: ${data.totalQuantity}件\n\n`;
  });
  
  content += `§e§l=== 价格区间偏好 ===§r\n`;
  const sortedPriceRanges = Object.entries(priceRangePreference)
    .sort((a, b) => b[1] - a[1]);
  
  sortedPriceRanges.forEach(([range, count]) => {
    content += `§3${range}币: §a${count}次购买\n`;
  });
  
  form.addLabel(content);
  player.sendForm(form, (pl, data) => {
    showEnhancedUserBehaviorAnalysis(pl);
  });
}

function showTimeActivityAnalysis(player) {
  const form = mc.newCustomForm();
  form.setTitle("§d§l时间活跃度分析");
  
  const hourlyActivity = {};
  const dailyActivity = {};
  const weeklyActivity = {};
  
  if (purchaseLogs.global) {
    purchaseLogs.global.forEach(record => {
      const time = new Date(record.time);
      const hour = time.getHours();
      const day = time.getDay();
      const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][day];
      
      if (!hourlyActivity[hour]) hourlyActivity[hour] = 0;
      if (!weeklyActivity[weekDay]) weeklyActivity[weekDay] = 0;
      
      hourlyActivity[hour]++;
      weeklyActivity[weekDay]++;
    });
  }
  
  const peakHours = Object.entries(hourlyActivity)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 6);
  
  const peakDays = Object.entries(weeklyActivity)
    .sort((a, b) => b[1] - a[1]);
  
  let content = `§e§l=== 活跃时段TOP6 ===§r\n`;
  peakHours.forEach((hour, index) => {
    const timeStr = `${hour[0]}:00-${hour[0]}:59`;
    const count = hour[1];
    const percentage = ((count / Object.values(hourlyActivity).reduce((a, b) => a + b, 0)) * 100).toFixed(1);
    content += `§3${index + 1}. §b${timeStr} §a${count}次 §f(${percentage}%)\n`;
  });
  
  content += `\n§e§l=== 每周活跃度 ===§r\n`;
  peakDays.forEach(([day, count]) => {
    const percentage = ((count / Object.values(weeklyActivity).reduce((a, b) => a + b, 0)) * 100).toFixed(1);
    content += `§3${day}: §a${count}次 §f(${percentage}%)\n`;
  });
  
  content += `\n§e§l=== 运营建议 ===§r\n`;
  content += `§a● 在 ${peakHours[0] ? peakHours[0][0] + ':00-' + peakHours[0][0] + ':59' : '暂无数据'} 推出限时活动\n`;
  content += `§a● ${peakDays[0] ? peakDays[0][0] : '暂无数据'} 是最佳营销时机\n`;
  content += `§a● 避免在低活跃时段进行重要更新`;
  
  form.addLabel(content);
  player.sendForm(form, (pl, data) => {
    showEnhancedUserBehaviorAnalysis(pl);
  });
}

function showSpendingPowerAnalysis(player) {
  const form = mc.newCustomForm();
  form.setTitle("§3§l消费能力分析");
  
  const userSpending = {};
  const spendingDistribution = {
    "0-100": 0,
    "100-500": 0,
    "500-1000": 0,
    "1000-5000": 0,
    "5000+": 0
  };
  
  if (purchaseLogs.global) {
    purchaseLogs.global.forEach(record => {
      const buyerName = record.buyerName;
      const totalPrice = parseFloat(record.totalPrice) || 0;
      
      if (!userSpending[buyerName]) {
        userSpending[buyerName] = 0;
      }
      userSpending[buyerName] += totalPrice;
    });
  }
  
  Object.values(userSpending).forEach(spending => {
    if (spending < 100) spendingDistribution["0-100"]++;
    else if (spending < 500) spendingDistribution["100-500"]++;
    else if (spending < 1000) spendingDistribution["500-1000"]++;
    else if (spending < 5000) spendingDistribution["1000-5000"]++;
    else spendingDistribution["5000+"]++;
  });
  
  const bigSpenders = Object.entries(userSpending)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 10);
  
  let content = `§e§l=== 高消费用户TOP10 ===§r\n`;
  bigSpenders.forEach((user, index) => {
    const userName = user[0];
    const spending = user[1];
    content += `§3${index + 1}. §b${userName}: §a${spending.toFixed(2)}币\n`;
  });
  
  content += `\n§e§l=== 消费能力分布 ===§r\n`;
  Object.entries(spendingDistribution).forEach(([range, count]) => {
    const percentage = userSpending && Object.keys(userSpending).length > 0 ? 
      ((count / Object.keys(userSpending).length) * 100).toFixed(1) : '0';
    content += `§3${range}币: §a${count}人 §f(${percentage}%)\n`;
  });
  
  const totalSpending = Object.values(userSpending).reduce((a, b) => a + b, 0);
  const avgSpending = Object.keys(userSpending).length > 0 ? 
    (totalSpending / Object.keys(userSpending).length).toFixed(2) : '0';
  
  content += `\n§e§l=== 消费统计 ===§r\n`;
  content += `§f总消费金额: §a${totalSpending.toFixed(2)}币\n`;
  content += `§f人均消费: §a${avgSpending}币\n`;
  content += `§f消费用户: §a${Object.keys(userSpending).length}人`;
  
  form.addLabel(content);
  player.sendForm(form, (pl, data) => {
    showEnhancedUserBehaviorAnalysis(pl);
  });
}

function showShopBusinessAnalysis(player) {
  const form = mc.newCustomForm();
  form.setTitle("§e§l店铺经营分析");
  
  const shopStats = {};
  let totalShops = 0;
  let openShops = 0;
  
  for (const xuid in shopsData) {
    const shop = shopsData[xuid];
    totalShops++;
    if (shop.isOpen) openShops++;
    
    const itemCount = Object.keys(shop.items || {}).length;
    let totalValue = 0;
    let totalStock = 0;
    
    for (const itemKey in shop.items) {
      const item = shop.items[itemKey];
      const quantity = item.quantity === -1 ? 100 : item.quantity;
      totalValue += item.price * quantity;
      totalStock += quantity;
    }
    
    shopStats[shop.name] = {
      isOpen: shop.isOpen,
      itemCount,
      totalValue,
      totalStock,
      level: shop.shopLevel || 1
    };
  }
  
  const topValueShops = Object.entries(shopStats)
    .filter(([name, stats]) => stats.isOpen)
    .sort((a, b) => b[1].totalValue - a[1].totalValue)
    .slice(0, 8);
  
  let content = `§e§l=== 店铺经营概况 ===§r\n`;
  content += `§f总店铺数: §a${totalShops} §f| §f营业中: §a${openShops} §f| §f关闭: §c${totalShops - openShops}\n`;
  content += `§f营业率: §a${totalShops > 0 ? ((openShops / totalShops) * 100).toFixed(1) : '0'}%\n\n`;
  
  content += `§e§l=== 店铺价值TOP8 ===§r\n`;
  topValueShops.forEach(([shopName, stats], index) => {
    content += `§3${index + 1}. §b${shopName}\n`;
    content += `   §a商品价值: ${stats.totalValue.toFixed(2)}币 §f| §e物品: ${stats.itemCount}种\n\n`;
  });
  
  const levelDistribution = {};
  Object.values(shopStats).forEach(stats => {
    const level = stats.level;
    if (!levelDistribution[level]) levelDistribution[level] = 0;
    levelDistribution[level]++;
  });
  
  content += `§e§l=== 店铺等级分布 ===§r\n`;
  Object.entries(levelDistribution)
    .sort((a, b) => parseInt(a[0]) - parseInt(b[0]))
    .forEach(([level, count]) => {
      content += `§3Lv.${level}: §a${count}家店铺\n`;
    });
  
  form.addLabel(content);
  player.sendForm(form, (pl, data) => {
    showEnhancedUserBehaviorAnalysis(pl);
  });
}

function showComprehensiveDataReport(player) {
  const form = mc.newCustomForm();
  form.setTitle("§c§l综合数据报告");
  
  const totalTransactions = purchaseLogs.global ? purchaseLogs.global.length : 0;
  const totalUsers = purchaseLogs.players ? Object.keys(purchaseLogs.players).length : 0;
  const totalShops = Object.keys(shopsData).length;
  const openShops = Object.values(shopsData).filter(shop => shop.isOpen).length;
  
  let totalVolume = 0;
  if (purchaseLogs.global) {
    purchaseLogs.global.forEach(record => {
      totalVolume += parseFloat(record.totalPrice) || 0;
    });
  }
  
  const now = new Date();
  const recent7Days = purchaseLogs.global ? purchaseLogs.global.filter(record => {
    const recordDate = new Date(record.time);
    const daysDiff = (now - recordDate) / (1000 * 60 * 60 * 24);
    return daysDiff <= 7;
  }).length : 0;
  
  const recent30Days = purchaseLogs.global ? purchaseLogs.global.filter(record => {
    const recordDate = new Date(record.time);
    const daysDiff = (now - recordDate) / (1000 * 60 * 60 * 24);
    return daysDiff <= 30;
  }).length : 0;
  
  let content = `§e§l=== 平台整体数据 ===§r\n`;
  content += `§f总交易量: §a${totalTransactions}笔\n`;
  content += `§f交易总额: §a${totalVolume.toFixed(2)}币\n`;
  content += `§f活跃用户: §a${totalUsers}人\n`;
  content += `§f总店铺数: §a${totalShops}家 §f(营业: §a${openShops}家§f)\n\n`;
  
  content += `§e§l=== 活跃度趋势 ===§r\n`;
  content += `§f近7天交易: §a${recent7Days}笔\n`;
  content += `§f近30天交易: §a${recent30Days}笔\n`;
  content += `§f日均交易: §a${(recent30Days / 30).toFixed(1)}笔\n\n`;
  
  content += `§e§l=== 市场健康度 ===§r\n`;
  const avgTransactionPerUser = totalUsers > 0 ? (totalTransactions / totalUsers).toFixed(1) : '0';
  const avgVolumePerTransaction = totalTransactions > 0 ? (totalVolume / totalTransactions).toFixed(2) : '0';
  const shopUtilization = totalShops > 0 ? ((openShops / totalShops) * 100).toFixed(1) : '0';
  
  content += `§f人均交易: §a${avgTransactionPerUser}笔\n`;
  content += `§f笔均金额: §a${avgVolumePerTransaction}币\n`;
  content += `§f店铺利用率: §a${shopUtilization}%\n\n`;
  
  content += `§e§l=== 系统建议 ===§r\n`;
  if (parseFloat(shopUtilization) < 70) {
    content += `§c● 店铺利用率偏低，考虑优化店铺管理\n`;
  }
  if (recent7Days < recent30Days * 0.3) {
    content += `§c● 近期活跃度下降，建议推出活动\n`;
  }
  if (parseFloat(avgTransactionPerUser) < 5) {
    content += `§c● 用户粘性较低，考虑提升用户体验\n`;
  }
  content += `§a● 持续监控市场数据，及时调整策略`;
  
  form.addLabel(content);
  player.sendForm(form, (pl, data) => {
    showEnhancedUserBehaviorAnalysis(pl);
  });
}

function showDynamicRecycleConfig(player) {
  if (!player.isOP()) {
    player.tell("§c此功能仅限管理员使用！");
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle("§3§l动态回收配置");
  form.setContent("§e请选择操作：");
  addReturnButton(form);
  form.addButton("§a§l基础配置", "textures/ui/video_glyph_2x");
  form.addButton("§b§l价格调整规则", "textures/ui/video_glyph_color");
  form.addButton("§d§l查看当前价格", "textures/ui/magnifyingGlass");
  form.addButton("§e§l重置所有价格", "textures/ui/refresh");
  form.addButton("§c§l统计数据", "textures/ui/book_frame");
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === 0) {
      showAdminMenu(pl);
      return;
    }
    
    switch(id) {
      case 1:
        showDynamicRecycleBasicConfig(pl);
        break;
      case 2:
        showDynamicRecyclePriceRules(pl);
        break;
      case 3:
        showCurrentDynamicPrices(pl);
        break;
      case 4:
        confirmResetAllDynamicPrices(pl);
        break;
      case 5:
        showDynamicRecycleStatistics(pl);
        break;
    }
  });
}

function showDynamicRecycleBasicConfig(player) {
  const form = mc.newCustomForm();
  form.setTitle("§a§l动态回收基础配置");
  
  const dynamicConfig = config.get('dynamicRecycle') || {};
  const enabled = dynamicConfig.enabled || false;
  const timeWindow = dynamicConfig.timeWindow || 60;
  const recycleThreshold = dynamicConfig.recycleThreshold || 5;
  const recoveryTime = dynamicConfig.recoveryTime || 120;
  const checkInterval = dynamicConfig.checkInterval || 30;
  
  form.addSwitch("§e启用动态回收系统", enabled);
  form.addInput("§e价格统计时间窗口(分钟)\n§3用于计算回收频率的时间范围", "60", timeWindow.toString());
  form.addInput("§e触发降价阈值(次数)\n§3在时间窗口内超过此次数开始降价", "5", recycleThreshold.toString());
  form.addInput("§e价格恢复时间(分钟)\n§3无人回收后价格开始恢复的时间", "120", recoveryTime.toString());
  form.addInput("§e价格检查间隔(分钟)\n§3多久检查一次价格恢复", "30", checkInterval.toString());
  
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showDynamicRecycleConfig(pl);
      return;
    }
    
    const newEnabled = data[0];
    const newTimeWindow = parseInt(data[1]);
    const newThreshold = parseInt(data[2]);
    const newRecoveryTime = parseInt(data[3]);
    const newCheckInterval = parseInt(data[4]);
    
    if (isNaN(newTimeWindow) || newTimeWindow <= 0) {
      pl.tell("§c时间窗口必须是正整数！");
      return;
    }
    
    if (isNaN(newThreshold) || newThreshold <= 0) {
      pl.tell("§c触发阈值必须是正整数！");
      return;
    }
    
    if (isNaN(newRecoveryTime) || newRecoveryTime <= 0) {
      pl.tell("§c恢复时间必须是正整数！");
      return;
    }
    
    if (isNaN(newCheckInterval) || newCheckInterval <= 0) {
      pl.tell("§c检查间隔必须是正整数！");
      return;
    }
    
    const updatedConfig = {
      ...dynamicConfig,
      enabled: newEnabled,
      timeWindow: newTimeWindow,
      recycleThreshold: newThreshold,
      recoveryTime: newRecoveryTime,
      checkInterval: newCheckInterval
    };
    
    config.set('dynamicRecycle', updatedConfig);
    
    try {
      if (typeof stopDynamicPriceRecoveryTimer === 'function') {
        stopDynamicPriceRecoveryTimer();
      }
      if (newEnabled && typeof startDynamicPriceRecoveryTimer === 'function') {
        startDynamicPriceRecoveryTimer();
      }
    } catch (error) {
      pl.tell("§c配置更新时出现错误：" + error.toString());
    }
    
    pl.tell("§a动态回收基础配置已更新！");
    showDynamicRecycleConfig(pl);
  });
}

function showDynamicRecyclePriceRules(player) {
  const form = mc.newCustomForm();
  form.setTitle("§b§l价格调整规则配置");
  
  const dynamicConfig = config.get('dynamicRecycle') || {};
  const priceDecayRate = dynamicConfig.priceDecayRate || 5;
  const maxPriceDecrease = dynamicConfig.maxPriceDecrease || 50;
  const maxPriceIncrease = dynamicConfig.maxPriceIncrease || 20;
  const recoveryRate = dynamicConfig.recoveryRate || 2;
  
  form.addInput("§e每次降价幅度(%)\n§3每次触发降价时的百分比", "5", priceDecayRate.toString());
  form.addInput("§e最大降价幅度(%)\n§3相对原价的最大降幅", "50", maxPriceDecrease.toString());
  form.addInput("§e最大涨价幅度(%)\n§3相对原价的最大涨幅", "20", maxPriceIncrease.toString());
  form.addInput("§e价格恢复速度(%/小时)\n§3每小时恢复的百分比", "2", recoveryRate.toString());
  
  player.sendForm(form, (pl, data) => {
    if (!data) {
      showDynamicRecycleConfig(pl);
      return;
    }
    
    const newDecayRate = parseInt(data[0]);
    const newMaxDecrease = parseInt(data[1]);
    const newMaxIncrease = parseInt(data[2]);
    const newRecoveryRate = parseInt(data[3]);
    
    if (isNaN(newDecayRate) || newDecayRate <= 0 || newDecayRate > 100) {
      pl.tell("§c降价幅度必须在1-100之间！");
      return;
    }
    
    if (isNaN(newMaxDecrease) || newMaxDecrease <= 0 || newMaxDecrease > 100) {
      pl.tell("§c最大降价幅度必须在1-100之间！");
      return;
    }
    
    if (isNaN(newMaxIncrease) || newMaxIncrease < 0 || newMaxIncrease > 100) {
      pl.tell("§c最大涨价幅度必须在0-100之间！");
      return;
    }
    
    if (isNaN(newRecoveryRate) || newRecoveryRate <= 0 || newRecoveryRate > 100) {
      pl.tell("§c恢复速度必须在1-100之间！");
      return;
    }
    
    const updatedConfig = {
      ...dynamicConfig,
      priceDecayRate: newDecayRate,
      maxPriceDecrease: newMaxDecrease,
      maxPriceIncrease: newMaxIncrease,
      recoveryRate: newRecoveryRate
    };
    
    config.set('dynamicRecycle', updatedConfig);
    
    if (updatedConfig.enabled) {
      try {
        if (typeof stopDynamicPriceRecoveryTimer === 'function') {
          stopDynamicPriceRecoveryTimer();
        }
        if (typeof startDynamicPriceRecoveryTimer === 'function') {
          startDynamicPriceRecoveryTimer();
        }
      } catch (error) {
        pl.tell("§c价格规则更新时出现错误：" + error.toString());
      }
    }
    
    pl.tell("§a价格调整规则已更新！");
    showDynamicRecycleConfig(pl);
  });
}

function showCurrentDynamicPrices(player) {
  const form = mc.newCustomForm();
  form.setTitle("§d§l当前动态价格");
  
  let content = "§e§l=== 当前动态价格列表 ===§r\n\n";
  
  if (Object.keys(dynamicRecycleData.itemPrices).length === 0) {
    content += "§3暂无动态价格数据";
  } else {
    let count = 0;
    for (const itemKey in dynamicRecycleData.itemPrices) {
      if (count >= 20) {
        content += "§3... 还有更多物品，共显示前20项";
        break;
      }
      
      const priceData = dynamicRecycleData.itemPrices[itemKey];
      const originalPrice = priceData.originalPrice || 0;
      const currentPrice = priceData.currentPrice || originalPrice;
      const changePercent = originalPrice > 0 ? 
        (((currentPrice - originalPrice) / originalPrice) * 100).toFixed(1) : '0';
      
      const itemName = getItemFriendlyName(itemKey, itemKey);
      const priceColor = currentPrice < originalPrice ? '§c' : 
                        currentPrice > originalPrice ? '§a' : '§f';
      
      content += `§b${itemName}\n`;
      content += `§f原价: §e${originalPrice} §f| §f现价: ${priceColor}${currentPrice}\n`;
      content += `§f变化: ${priceColor}${changePercent}%\n\n`;
      count++;
    }
  }
  
  form.addLabel(content);
  player.sendForm(form, (pl, data) => {
    showDynamicRecycleConfig(pl);
  });
}

function confirmResetAllDynamicPrices(player) {
  const form = mc.newSimpleForm();
  form.setTitle("§c§l确认重置");
  form.setContent("§e确定要重置所有动态回收价格吗？\n§c此操作将清除所有价格调整记录！");
  form.addButton("§a确认重置", "");
  form.addButton("§c取消", "");
  
  player.sendForm(form, (pl, id) => {
    if (id === 0) {
      try {
        stopDynamicPriceRecoveryTimer();
        
        dynamicRecycleData.itemPrices = {};
        dynamicRecycleData.recycleHistory = {};
        dynamicRecycleData.lastUpdate = {};
        saveDynamicRecycleData();
        
        const dynamicConfig = config.get('dynamicRecycle') || {};
        if (dynamicConfig.enabled) {
          startDynamicPriceRecoveryTimer();
        }
        
        pl.tell("§a所有动态回收价格已重置！");
      } catch (error) {
        pl.tell("§c重置过程中出现错误：" + error.toString());
      }
    }
    showDynamicRecycleConfig(pl);
  });
}

function showDynamicRecycleStatistics(player) {
  const form = mc.newCustomForm();
  form.setTitle("§c§l动态回收统计");
  
  let content = "§e§l=== 动态回收系统统计 ===§r\n\n";
  
  const totalItems = Object.keys(dynamicRecycleData.itemPrices).length;
  let increasedItems = 0;
  let decreasedItems = 0;
  let totalRecycles = 0;
  
  for (const itemKey in dynamicRecycleData.itemPrices) {
    const priceData = dynamicRecycleData.itemPrices[itemKey];
    const originalPrice = priceData.originalPrice || 0;
    const currentPrice = priceData.currentPrice || originalPrice;
    
    if (currentPrice > originalPrice) increasedItems++;
    else if (currentPrice < originalPrice) decreasedItems++;
  }
  
  for (const itemKey in dynamicRecycleData.recycleHistory) {
    const history = dynamicRecycleData.recycleHistory[itemKey] || [];
    totalRecycles += history.length;
  }
  
  content += `§f动态价格物品数: §a${totalItems}\n`;
  content += `§f价格上涨物品: §a${increasedItems}\n`;
  content += `§f价格下降物品: §c${decreasedItems}\n`;
  content += `§f价格稳定物品: §e${totalItems - increasedItems - decreasedItems}\n`;
  content += `§f总回收记录数: §b${totalRecycles}\n\n`;
  
  content += "§e§l=== 最近价格变动TOP5 ===§r\n";
  const recentChanges = [];
  
  for (const itemKey in dynamicRecycleData.itemPrices) {
    const priceData = dynamicRecycleData.itemPrices[itemKey];
    const lastUpdate = dynamicRecycleData.lastUpdate[itemKey] || 0;
    
    if (lastUpdate > 0) {
      recentChanges.push({
        itemKey,
        lastUpdate,
        originalPrice: priceData.originalPrice || 0,
        currentPrice: priceData.currentPrice || 0
      });
    }
  }
  
  recentChanges.sort((a, b) => b.lastUpdate - a.lastUpdate);
  recentChanges.slice(0, 5).forEach(change => {
    const itemName = getItemFriendlyName(change.itemKey, change.itemKey);
    const changePercent = change.originalPrice > 0 ? 
      (((change.currentPrice - change.originalPrice) / change.originalPrice) * 100).toFixed(1) : '0';
    const priceColor = change.currentPrice < change.originalPrice ? '§c' : 
                      change.currentPrice > change.originalPrice ? '§a' : '§f';
    
    content += `§b${itemName}: ${priceColor}${changePercent}%\n`;
  });
  
  if (recentChanges.length === 0) {
    content += "§3暂无价格变动记录";
  }
  
  form.addLabel(content);
  player.sendForm(form, (pl, data) => {
    showDynamicRecycleConfig(pl);
  });
}

function updateDynamicRecyclePrice(itemKey, originalPrice) {
  const dynamicConfig = config.get('dynamicRecycle') || {};
  
  if (!dynamicConfig.enabled) {
    return originalPrice;
  }
  
  if (!dynamicRecycleData.itemPrices[itemKey]) {
    dynamicRecycleData.itemPrices[itemKey] = {
      originalPrice: originalPrice,
      currentPrice: originalPrice,
      lastRecycleTime: 0
    };
  }
  
  if (!dynamicRecycleData.recycleHistory[itemKey]) {
    dynamicRecycleData.recycleHistory[itemKey] = [];
  }
  
  const priceData = dynamicRecycleData.itemPrices[itemKey];
  const recycleHistory = dynamicRecycleData.recycleHistory[itemKey];
  const now = Date.now();
  const timeWindow = dynamicConfig.timeWindow * 60 * 1000; 
  
  const recentRecycles = recycleHistory.filter(time => (now - time) <= timeWindow);
  
  if (recentRecycles.length >= dynamicConfig.recycleThreshold) {
    const decayRate = dynamicConfig.priceDecayRate / 100;
    const maxDecrease = dynamicConfig.maxPriceDecrease / 100;
    const minPrice = Math.ceil(originalPrice * (1 - maxDecrease));
    
    const newPrice = Math.max(minPrice, Math.ceil(priceData.currentPrice * (1 - decayRate)));
    
    if (newPrice < priceData.currentPrice) {
      priceData.currentPrice = newPrice;
      dynamicRecycleData.lastUpdate[itemKey] = now;
      saveDynamicRecycleData();
    }
  } else {
    const recoveryTime = dynamicConfig.recoveryTime * 60 * 1000; 
    const lastRecycleTime = recycleHistory.length > 0 ? 
      Math.max(...recycleHistory) : 0;
    
    if (now - lastRecycleTime >= recoveryTime) {
      const recoveryRate = dynamicConfig.recoveryRate / 100;
      const maxIncrease = dynamicConfig.maxPriceIncrease / 100;
      const maxPrice = Math.ceil(originalPrice * (1 + maxIncrease));
      
      const hoursSinceLastRecycle = (now - lastRecycleTime) / (1000 * 60 * 60);
      const recoveryAmount = Math.floor(hoursSinceLastRecycle * recoveryRate * originalPrice / 100);
      const newPrice = Math.min(maxPrice, priceData.currentPrice + recoveryAmount);
      
      if (newPrice > priceData.currentPrice) {
        priceData.currentPrice = newPrice;
        dynamicRecycleData.lastUpdate[itemKey] = now;
        saveDynamicRecycleData();
      }
    }
  }
  
  return priceData.currentPrice;
}

function recordRecycleEvent(itemKey) {
  const dynamicConfig = config.get('dynamicRecycle') || {};
  
  if (!dynamicConfig.enabled) {
    return;
  }
  
  const now = Date.now();
  
  if (!dynamicRecycleData.recycleHistory[itemKey]) {
    dynamicRecycleData.recycleHistory[itemKey] = [];
  }
  
  dynamicRecycleData.recycleHistory[itemKey].push(now);
  
  const weekAgo = now - (7 * 24 * 60 * 60 * 1000);
  dynamicRecycleData.recycleHistory[itemKey] = 
    dynamicRecycleData.recycleHistory[itemKey].filter(time => time >= weekAgo);
  
  saveDynamicRecycleData();
}

function getDynamicRecyclePrice(itemKey, originalPrice) {
  const dynamicConfig = config.get('dynamicRecycle') || {};
  
  if (!dynamicConfig.enabled) {
    return originalPrice;
  }
  
  return updateDynamicRecyclePrice(itemKey, originalPrice);
}

try {
  if (typeof startDynamicPriceRecoveryTimer === 'function') {
    startDynamicPriceRecoveryTimer();
  }
} catch (error) {
  console.log('启动动态价格恢复定时器时出现错误：' + error.toString());
}

function showRecycleLimitsManagement(player) {
  const form = mc.newSimpleForm();
  form.setTitle('§c§l回收限制管理');
  form.setContent('§e请选择一个操作:');
  addReturnButton(form);
  
  const isEnabled = config.get('enableRecycleLimits');
  form.addButton(`§${isEnabled ? 'a' : 'c'}§l${isEnabled ? '回收限制已启用' : '回收限制已禁用'}\n§f点击切换状态`, 'textures/ui/video_glyph_2x');
  form.addButton('§3§l设置全服限制', 'textures/ui/world_glyph_color_2x');
  form.addButton('§b§l设置单人限制', 'textures/ui/icon_setting');
  form.addButton('§e§l查看使用情况', 'textures/ui/magnifyingGlass');
  form.addButton('§d§l设置重置时间', 'textures/ui/clock');
  form.addButton('§c§l重置所有限制', 'textures/ui/refresh');
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === 0) {
      manageOfficialShop(pl);
      return;
    }
    
    switch(id) {
      case 1:
        config.set('enableRecycleLimits', !isEnabled);
        pl.tell(`§a回收限制功能已${!isEnabled ? '启用' : '禁用'}!`);
        showRecycleLimitsManagement(pl);
        break;
      case 2:
        showGlobalLimitsManagement(pl);
        break;
      case 3:
        showPlayerLimitsManagement(pl);
        break;
      case 4:
        showRecycleLimitsUsage(pl);
        break;
      case 5:
        showRecycleLimitsResetConfig(pl);
        break;
      case 6:
        confirmResetRecycleLimits(pl);
        break;
    }
  });
}

function showGlobalLimitsManagement(player) {
  const form = mc.newSimpleForm();
  form.setTitle("§3§l设置全服回收限制");
  
  const resetHours = config.get('recycleLimitResetHours') || 24;
  const timeUnit = resetHours === 24 ? '每日' : resetHours === 168 ? '每周' : `每${resetHours}小时`;
  
  form.setContent(`§e为回收物品设置全服${timeUnit}回收上限\n§3点击下方按钮选择要设置的物品`);
  form.addButton("§a§l搜索物品", "textures/ui/magnifyingGlass");
  form.addButton("§b§l从列表选择", "textures/ui/store_sort_icon");
  form.addButton("§3§l查看已设置限制", "textures/ui/icon_setting");
  addReturnButton(form);
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    switch(id) {
      case 0:
        showSearchRecycleItemsForLimit(pl, 'global');
        break;
      case 1:
        showSelectRecycleItemsForLimit(pl, 'global');
        break;
      case 2:
        showCurrentGlobalLimits(pl);
        break;
      case 3:
        showRecycleLimitsManagement(pl);
        break;
    }
  });
}

function showPlayerLimitsManagement(player) {
  const form = mc.newSimpleForm();
  form.setTitle("§b§l设置单人回收限制");
  
  const resetHours = config.get('recycleLimitResetHours') || 24;
  const timeUnit = resetHours === 24 ? '每日' : resetHours === 168 ? '每周' : `每${resetHours}小时`;
  
  form.setContent(`§e为回收物品设置单人${timeUnit}回收上限\n§3点击下方按钮选择要设置的物品`);
  form.addButton("§a§l搜索物品", "textures/ui/magnifyingGlass");
  form.addButton("§b§l从列表选择", "textures/ui/store_sort_icon");
  form.addButton("§3§l查看已设置限制", "textures/ui/icon_setting");
  addReturnButton(form);
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    switch(id) {
      case 0:
        showSearchRecycleItemsForLimit(pl, 'player');
        break;
      case 1:
        showSelectRecycleItemsForLimit(pl, 'player');
        break;
      case 2:
        showCurrentPlayerLimits(pl);
        break;
      case 3:
        showRecycleLimitsManagement(pl);
        break;
    }
  });
}

function showRecycleLimitsUsage(player) {
  const form = mc.newSimpleForm();
  form.setTitle("§e§l回收限制使用情况");
  
  const resetHours = config.get('recycleLimitResetHours') || 24;
  const timeUnit = resetHours === 24 ? '每日' : resetHours === 168 ? '每周' : `每${resetHours}小时`;
  
  let content = `§3全服使用情况 (${timeUnit}重置):\n`;
  
  const recycleItems = Object.keys(officialShopData.recycleItems);
  if (recycleItems.length === 0) {
    content += "§3暂无回收物品\n";
  } else {
    recycleItems.forEach(key => {
      const item = officialShopData.recycleItems[key];
      const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
      const showName = item.displayName || getItemDisplayName(tmp, false);
      const globalLimit = recycleLimitsData.globalLimits[key] || 0;
      const globalUsage = recycleLimitsData.globalUsage[key] || 0;
      const playerLimit = recycleLimitsData.playerLimits[key] || 0;
      
      if (globalLimit > 0 || playerLimit > 0) {
        content += `§a${showName}:\n`;
        content += `  §3全服: ${globalUsage}/${globalLimit === 0 ? '∞' : globalLimit}\n`;
        content += `  §3单人限制: ${playerLimit === 0 ? '无限制' : playerLimit}\n`;
      }
    });
  }
  
  const nextReset = new Date(recycleLimitsData.lastReset + (resetHours * 60 * 60 * 1000));
  const now = new Date();
  const timeLeft = Math.max(0, nextReset.getTime() - now.getTime());
  const hoursLeft = Math.floor(timeLeft / (1000 * 60 * 60));
  const minutesLeft = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
  
  content += `\n§d下次重置时间: ${nextReset.toLocaleString()}`;
  content += `\n§e剩余时间: ${hoursLeft}小时${minutesLeft}分钟`;
  
  form.setContent(content);
  addReturnButton(form);
  
  player.sendForm(form, (pl, id) => {
    showRecycleLimitsManagement(pl);
  });
}

function showRecycleLimitsResetConfig(player) {
  const currentHours = config.get('recycleLimitResetHours') || 24;
  const resetHours = currentHours;
  const timeUnit = resetHours === 24 ? '每日' : resetHours === 168 ? '每周' : `每${resetHours}小时`;
  
  const nextReset = new Date(recycleLimitsData.lastReset + (resetHours * 60 * 60 * 1000));
  const now = new Date();
  const timeLeft = Math.max(0, nextReset.getTime() - now.getTime());
  const hoursLeft = Math.floor(timeLeft / (1000 * 60 * 60));
  const minutesLeft = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
  
  const form = mc.newCustomForm();
  form.setTitle("§d§l设置重置时间");
  form.addLabel("§e设置回收限制重置的时间间隔");
  form.addLabel(`§3当前设置: ${timeUnit}重置`);
  form.addLabel(`§e下次重置时间: §a${nextReset.toLocaleString()}`);
  form.addLabel(`§e重置倒计时: §3${hoursLeft}小时${minutesLeft}分钟`);
  form.addSlider("§3重置时间间隔（小时）", 1, 72, 1, currentHours);
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    const newHours = data[4];
    const oldHours = config.get('recycleLimitResetHours') || 24;
    
    config.set('recycleLimitResetHours', newHours);
    
    if (newHours !== oldHours) {
      const now = Date.now();
      const timeSinceLastReset = now - recycleLimitsData.lastReset;
      const newResetInterval = newHours * 60 * 60 * 1000;
      
      if (timeSinceLastReset >= newResetInterval) {
        recycleLimitsData.globalUsage = {};
        recycleLimitsData.playerUsage = {};
        recycleLimitsData.lastReset = now;
        saveRecycleLimitsData();
        pl.tell(`§a重置时间已设置为 ${newHours} 小时！由于时间变更，限制记录已自动重置。`);
      } else {
        pl.tell(`§a重置时间已设置为 ${newHours} 小时！`);
      }
    }
    
    showRecycleLimitsManagement(pl);
  });
}

function confirmResetRecycleLimits(player) {
  const form = mc.newSimpleForm();
  form.setTitle("§c§l确认重置");
  form.setContent("§e确定要重置所有回收限制使用记录吗？\n§c此操作将清除所有玩家的回收使用记录！");
  form.addButton("§a确认重置", "");
  form.addButton("§c取消", "");
  
  player.sendForm(form, (pl, id) => {
    if (id === 0) {
      recycleLimitsData.globalUsage = {};
      recycleLimitsData.playerUsage = {};
      recycleLimitsData.lastReset = Date.now();
      saveRecycleLimitsData();
      pl.tell("§a所有回收限制使用记录已重置！");
    }
    showRecycleLimitsManagement(pl);
  });
}

function checkRecycleLimit(player, itemKey, quantity) {
  if (!config.get('enableRecycleLimits')) {
    return { allowed: true, message: "" };
  }
  const resetHours = config.get('recycleLimitResetHours') || 24;
  const resetInterval = resetHours * 60 * 60 * 1000;
  if (Date.now() - recycleLimitsData.lastReset >= resetInterval) {
    recycleLimitsData.globalUsage = {};
    recycleLimitsData.playerUsage = {};
    recycleLimitsData.lastReset = Date.now();
    saveRecycleLimitsData();
  }
  const globalLimit = recycleLimitsData.globalLimits[itemKey] || 0;
  if (globalLimit > 0) {
    const globalUsage = recycleLimitsData.globalUsage[itemKey] || 0;
    if (globalUsage + quantity > globalLimit) {
      const remaining = Math.max(0, globalLimit - globalUsage);
      return { 
        allowed: false, 
        message: `§c全服回收限制已达上限！今日剩余: ${remaining}个`
      };
    }
  }
  const playerLimit = recycleLimitsData.playerLimits[itemKey] || 0;
  if (playerLimit > 0) {
    if (!recycleLimitsData.playerUsage[player.xuid]) {
      recycleLimitsData.playerUsage[player.xuid] = {};
    }
    const playerUsage = recycleLimitsData.playerUsage[player.xuid][itemKey] || 0;
    if (playerUsage + quantity > playerLimit) {
      const remaining = Math.max(0, playerLimit - playerUsage);
      return { 
        allowed: false, 
        message: `§c个人回收限制已达上限！今日剩余: ${remaining}个`
      };
    }
  }
  return { allowed: true, message: "" };
}

function recordRecycleUsage(player, itemKey, quantity) {
  if (!config.get('enableRecycleLimits')) return;
  if (!recycleLimitsData.globalUsage[itemKey]) {
    recycleLimitsData.globalUsage[itemKey] = 0;
  }
  recycleLimitsData.globalUsage[itemKey] += quantity;
  if (!recycleLimitsData.playerUsage[player.xuid]) {
    recycleLimitsData.playerUsage[player.xuid] = {};
  }
  if (!recycleLimitsData.playerUsage[player.xuid][itemKey]) {
    recycleLimitsData.playerUsage[player.xuid][itemKey] = 0;
  }
  recycleLimitsData.playerUsage[player.xuid][itemKey] += quantity;
  saveRecycleLimitsData();
}

function showSearchRecycleItemsForLimit(player, type) {
  const form = mc.newCustomForm();
  form.setTitle(`§a§l搜索回收物品 - ${type === 'global' ? '全服限制' : '单人限制'}`);
  form.addLabel("§e输入物品名称关键词进行搜索");
  form.addInput("§3搜索关键词", "输入物品名称...", "");
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    const keyword = data[1].trim();
    if (!keyword) {
      pl.tell("§c请输入搜索关键词！");
      showSearchRecycleItemsForLimit(pl, type);
      return;
    }
    
    const recycleItems = Object.keys(officialShopData.recycleItems);
    const matchedItems = [];
    
    recycleItems.forEach(key => {
      const item = officialShopData.recycleItems[key];
      if (!item || !item.itemData) {
        return;
      }
      
      const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
      const showName = item.displayName || getItemDisplayName(tmp, false);
      
      if (showName.toLowerCase().includes(keyword.toLowerCase()) || 
          tmp.type.toLowerCase().includes(keyword.toLowerCase())) {
        matchedItems.push({
          key: key,
          name: showName,
          item: item
        });
      }
    });
    
    if (matchedItems.length === 0) {
      pl.tell("§c未找到匹配的回收物品！");
      if (type === 'global') {
        showGlobalLimitsManagement(pl);
      } else {
        showPlayerLimitsManagement(pl);
      }
      return;
    }
    
    showSearchResultsForLimit(pl, matchedItems, type);
  });
}

function showSearchResultsForLimit(player, items, type) {
  const form = mc.newSimpleForm();
  form.setTitle(`§a§l搜索结果 - ${type === 'global' ? '全服限制' : '单人限制'}`);
  form.setContent(`§e找到 ${items.length} 个回收物品，点击选择要设置限制的物品：`);
  
  items.forEach(itemData => {
    const currentLimit = type === 'global' ? 
      (recycleLimitsData.globalLimits[itemData.key] || 0) :
      (recycleLimitsData.playerLimits[itemData.key] || 0);
    const currentUsage = type === 'global' ? 
      (recycleLimitsData.globalUsage[itemData.key] || 0) : 0;
    
    const limitText = currentLimit === 0 ? '无限制' : currentLimit;
    const usageText = type === 'global' ? ` | 已用: ${currentUsage}` : '';
    
    form.addButton(`§a${itemData.name}\n§3当前限制: ${limitText}${usageText}`, "textures/ui/warning_sad_steve");
  });
  
  addReturnButton(form);
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === items.length) {
      if (type === 'global') {
        showGlobalLimitsManagement(pl);
      } else {
        showPlayerLimitsManagement(pl);
      }
      return;
    }
    
    const selectedItem = items[id];
    showSetItemLimitForm(pl, selectedItem.key, selectedItem.name, type);
  });
}

function showSelectRecycleItemsForLimit(player, type) {
  const recycleItems = Object.keys(officialShopData.recycleItems);
  if (recycleItems.length === 0) {
    player.tell("§c暂无回收物品可设置限制！");
    if (type === 'global') {
      showGlobalLimitsManagement(player);
    } else {
      showPlayerLimitsManagement(player);
    }
    return;
  }
  
  const form = mc.newSimpleForm();
  form.setTitle(`§b§l选择回收物品 - ${type === 'global' ? '全服限制' : '单人限制'}`);
  form.setContent("§e点击选择要设置限制的回收物品：");
  
  recycleItems.forEach(key => {
    const item = officialShopData.recycleItems[key];
    if (!item || !item.itemData) {
      return;
    }
    
    const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
    const showName = item.displayName || getItemDisplayName(tmp, false);
    const currentLimit = type === 'global' ? 
      (recycleLimitsData.globalLimits[key] || 0) :
      (recycleLimitsData.playerLimits[key] || 0);
    const currentUsage = type === 'global' ? 
      (recycleLimitsData.globalUsage[key] || 0) : 0;
    
    const limitText = currentLimit === 0 ? '无限制' : currentLimit;
    const usageText = type === 'global' ? ` | 已用: ${currentUsage}` : '';
    
    form.addButton(`§a${showName}\n§3当前限制: ${limitText}${usageText}`, "textures/ui/icon_setting");
  });
  
  addReturnButton(form);
  
  player.sendForm(form, (pl, id) => {
    if (id === null) return;
    if (id === recycleItems.length) {
      if (type === 'global') {
        showGlobalLimitsManagement(pl);
      } else {
        showPlayerLimitsManagement(pl);
      }
      return;
    }
    
    const itemKey = recycleItems[id];
    const item = officialShopData.recycleItems[itemKey];
    
    if (!item || !item.itemData) {
      pl.tell("§c该物品已不存在，请重新选择！");
      if (type === 'global') {
        showGlobalLimitsManagement(pl);
      } else {
        showPlayerLimitsManagement(pl);
      }
      return;
    }
    
    const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
    const showName = item.displayName || getItemDisplayName(tmp, false);
    
    showSetItemLimitForm(pl, itemKey, showName, type);
  });
}

function showSetItemLimitForm(player, itemKey, itemName, type) {
  const resetHours = config.get('recycleLimitResetHours') || 24;
  const timeUnit = resetHours === 24 ? '每日' : resetHours === 168 ? '每周' : `每${resetHours}小时`;
  
  const currentLimit = type === 'global' ? 
    (recycleLimitsData.globalLimits[itemKey] || 0) :
    (recycleLimitsData.playerLimits[itemKey] || 0);
  const currentUsage = type === 'global' ? 
    (recycleLimitsData.globalUsage[itemKey] || 0) : 0;
  
  const form = mc.newCustomForm();
  form.setTitle(`§3§l设置物品限制 - ${type === 'global' ? '全服' : '单人'}`);
  form.addLabel(`§e物品名称: §a${itemName}`);
  form.addLabel(`§e当前限制: §3${currentLimit === 0 ? '无限制' : currentLimit}`);
  if (type === 'global') {
    form.addLabel(`§e当前使用: §3${currentUsage}`);
  }
  form.addInput(`§3${timeUnit}回收上限 §3(0为无限制)`, "输入上限数量", currentLimit.toString());
  
  player.sendForm(form, (pl, data) => {
    if (!data) return;
    
    const inputIndex = type === 'global' ? 3 : 2;
    const limit = parseInt(data[inputIndex]) || 0;
    if (limit < 0) {
      pl.tell("§c限制数量不能为负数！");
      showSetItemLimitForm(pl, itemKey, itemName, type);
      return;
    }
    
    if (type === 'global') {
      if (limit === 0) {
        delete recycleLimitsData.globalLimits[itemKey];
      } else {
        recycleLimitsData.globalLimits[itemKey] = limit;
      }
    } else {
      if (limit === 0) {
        delete recycleLimitsData.playerLimits[itemKey];
      } else {
        recycleLimitsData.playerLimits[itemKey] = limit;
      }
    }
    
    saveRecycleLimitsData();
    pl.tell(`§a已设置 §e${itemName} §a的${type === 'global' ? '全服' : '单人'}${timeUnit}回收限制为: §3${limit === 0 ? '无限制' : limit}`);
    
    if (type === 'global') {
      showGlobalLimitsManagement(pl);
    } else {
      showPlayerLimitsManagement(pl);
    }
  });
}

function showCurrentGlobalLimits(player) {
  const form = mc.newSimpleForm();
  form.setTitle("§3§l当前全服限制");
  
  const globalLimits = Object.keys(recycleLimitsData.globalLimits);
  if (globalLimits.length === 0) {
    form.setContent("§3暂未设置任何全服回收限制");
  } else {
    const resetHours = config.get('recycleLimitResetHours') || 24;
    const timeUnit = resetHours === 24 ? '每日' : resetHours === 168 ? '每周' : `每${resetHours}小时`;
    
    let content = `§e已设置的全服${timeUnit}回收限制:\n\n`;
    
    globalLimits.forEach(key => {
      if (officialShopData.recycleItems[key]) {
        const item = officialShopData.recycleItems[key];
        const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
        const showName = item.displayName || getItemDisplayName(tmp, false);
        const limit = recycleLimitsData.globalLimits[key];
        const usage = recycleLimitsData.globalUsage[key] || 0;
        
        content += `§a${showName}: §3${limit} §3(已用: ${usage})\n`;
      }
    });
    
    form.setContent(content);
  }
  
  addReturnButton(form);
  
  player.sendForm(form, (pl, id) => {
    showGlobalLimitsManagement(pl);
  });
}

function showCurrentPlayerLimits(player) {
  const form = mc.newSimpleForm();
  form.setTitle("§b§l当前单人限制");
  
  const playerLimits = Object.keys(recycleLimitsData.playerLimits);
  if (playerLimits.length === 0) {
    form.setContent("§3暂未设置任何单人回收限制");
  } else {
    const resetHours = config.get('recycleLimitResetHours') || 24;
    const timeUnit = resetHours === 24 ? '每日' : resetHours === 168 ? '每周' : `每${resetHours}小时`;
    
    let content = `§e已设置的单人${timeUnit}回收限制:\n\n`;
    
    playerLimits.forEach(key => {
      if (officialShopData.recycleItems[key]) {
        const item = officialShopData.recycleItems[key];
        const tmp = mc.newItem(NBT.parseSNBT(item.itemData));
        const showName = item.displayName || getItemDisplayName(tmp, false);
        const limit = recycleLimitsData.playerLimits[key];
        
        content += `§a${showName}: §3${limit}\n`;
      }
    });
    
    form.setContent(content);
  }
  
  addReturnButton(form);
  
  player.sendForm(form, (pl, id) => {
    showPlayerLimitsManagement(pl);
  });
}
mc.regPlayerCmd('smck', '打开个人仓库', (pl) => {
  recordPlayerData(pl);
  showPlayerWarehouse(pl);
});

mc.regPlayerCmd('smgm', '打开官方商店购买页面', (pl) => {
  recordPlayerData(pl);
  let allKeys = Object.keys(officialShopData.purchaseItems);
  if(allKeys.length === 0){
    pl.tell("§c官方商店暂无物品出售。");
    return;
  }
  let offSortMode = config.get("officialShopSortMode") || "随机";
  if(offSortMode === "随机"){
    for(let i=allKeys.length-1; i>0; i--){
      let j = Math.floor(Math.random()*(i+1));
      [allKeys[i], allKeys[j]] = [allKeys[j], allKeys[i]];
    }
  }
  else if(offSortMode === "名字顺序"){
    allKeys.sort((aKey, bKey)=>{
      let A = officialShopData.purchaseItems[aKey];
      let B = officialShopData.purchaseItems[bKey];
      return A.name.localeCompare(B.name);
    });
  }
  officialPurchaseAllKeys = allKeys;
  showOfficialShopItems(pl, 1, "", "全部");
});

mc.regPlayerCmd('smhs', '打开官方商店回收页面', (pl) => {
  recordPlayerData(pl);
  showRecycleItems(pl);
});

mc.regPlayerCmd('smvw', '[管理员]查看玩家仓库', (pl, args) => {
  recordPlayerData(pl);
  if (!pl.isOP()) {
    pl.tell('§c此命令仅限管理员使用！');
    return;
  }
  
  if (args.length === 0) {
    showAdminViewPlayerWarehouse(pl);
    return;
  }
  
  const targetName = args.join(' ').trim();
  if (!targetName) {
    showAdminViewPlayerWarehouse(pl);
    return;
  }
  
  const onlineTarget = mc.getPlayer(targetName);
  if (onlineTarget) {
    showAdminPlayerWarehouseDetail(pl, onlineTarget.xuid, onlineTarget.realName);
    return;
  }
  
  const searchResults = searchPlayersByName(targetName);
  if (searchResults.length > 0) {
    const exactMatch = searchResults.find(r => r.name.toLowerCase() === targetName.toLowerCase());
    if (exactMatch) {
      showAdminPlayerWarehouseDetail(pl, exactMatch.xuid, exactMatch.name);
      return;
    }
    showAdminSearchWarehouseResults(pl, searchResults, targetName);
    return;
  }
  
  for (const xuid in warehouseData) {
    const wData = warehouseData[xuid];
    if (wData.playerName && wData.playerName.toLowerCase() === targetName.toLowerCase()) {
      showAdminPlayerWarehouseDetail(pl, xuid, wData.playerName);
      return;
    }
  }
  
  pl.tell(`§c未找到玩家 "${targetName}"！`);
  showAdminViewPlayerWarehouse(pl);
});

mc.listen('onJoin', (pl) => {
  recordPlayerData(pl);
  
  if (!config.get('enableGiftSystem')) return;
  
  const playerData = warehouseData[pl.xuid];
  if (playerData && playerData.items && playerData.items.length > 0) {
    const giftItems = playerData.items.filter(item => 
      item.description && item.description.indexOf('礼物') !== -1
    );
    
    if (giftItems.length > 0) {
      setTimeout(() => {
        pl.tell(`§3§l收到礼物提醒！§f您有 ${giftItems.length} 个礼物在仓库中等待领取！`);
        pl.tell(`§e使用 §a/smck §e命令打开仓库查看。`);
        pl.sendToast('§3礼物提醒', `${giftItems.length}个礼物等待领取`);
      }, 2000);
    }
  }
});

setTimeout(() => {
  colorLog("green", "  —————————————————————————————————————————————————————————");
  colorLog("green", "  ███████ ███    ███ ");
  colorLog("green", "  ██      ████  ████ ");
  colorLog("green", "  ███████ ██ ████ ██ ");
  colorLog("green", "       ██ ██  ██  ██ ");
  colorLog("green", "  ███████ ██      ██ ");
  colorLog("green", "  —————————————————————————————————————————————————————————");
  colorLog("green", `  ShoppingMall 商城插件已加载成功！`);
  colorLog("yellow", `  版本：${PLUGIN_VERSION.join('.')}`);
  colorLog("cyan", "  MineBBS 论坛：https://www.minebbs.com/resources/sm.9899/");
  colorLog("green", "  —————————————————————————————————————————————————————————");
}, 1000);
