<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width">
  <title>Gerador de JSON de Itens</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f9;
      margin: 0;
      padding: 0;
      font-size: 14px;
    }
    h1, h2, h3, h4 {
      color: #333;
      margin: 10px 0;
      font-size: 18px;
    }
    label {
      font-weight: bold;
      margin-bottom: 5px;
      font-size: 13px;
      display: block;
    }

    .container {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      max-width: 1400px;
      margin: auto;
      padding: 20px;
      background-color: #fff;
      min-height: 100vh;
      box-sizing: border-box;
    }

    .form-container, .list-container {
      flex: 1;
      min-width: 300px;
      max-width: 700px;
      background-color: #fff;
      padding: 15px;
      border-radius: 8px;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
      overflow: hidden;
    }

    .list-container {
      max-height: calc(100vh - 60px);
      display: flex;
      flex-direction: column;
    }

    .item-list {
      margin-bottom: 15px;
      flex: 1;
      overflow-y: auto;
    }

    .item {
      display: flex;
      justify-content: space-between;
      padding: 8px;
      margin-bottom: 5px;
      background-color: #fff;
      border: 1px solid #ddd;
      border-radius: 5px;
      font-size: 13px;
    }
    .item:hover {
      background-color: #f1f1f1;
    }

    .percentages {
      display: flex;
      flex-wrap: wrap;
      gap: 3px;
      margin-top: 3px;
    }
    .percentage-value {
      font-size: 11px;
      padding: 2px 4px;
      border-radius: 4px;
      background-color: #e9ecef;
    }

    #output {
      padding: 8px;
      background-color: #f8f9fa;
      border: 1px solid #ddd;
      border-radius: 5px;
      white-space: pre-wrap;
      overflow-x: auto;
      max-height: 180px;
      font-size: 13px;
    }

    .button-group {
      display: flex;
      gap: 10px;
      margin-top: 10px;
      flex-wrap: wrap;
    }
    .button-group button {
      flex: 1;
      padding: 10px;
      border: none;
      border-radius: 5px;
      color: white;
      cursor: pointer;
      transition: background-color 0.3s;
      font-size: 14px;
    }
    #generate {
      background-color: #007bff;
    }
    #generate:hover {
      background-color: #0056b3;
    }
    #clear-list {
      background-color: #dc3545;
    }
    #clear-list:hover {
      background-color: #c82333;
    }

    .copy-button-group {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 10px;
    }
    .copy-button-group button {
      padding: 6px 12px;
      background-color: #28a745;
      height: 34px;
      border: none;
      border-radius: 5px;
      color: white;
      cursor: pointer;
      transition: background-color 0.3s;
    }
    .copy-button-group button:hover {
      background-color: #218838;
    }

    .mode-indicator {
      font-weight: bold;
      margin-bottom: 10px;
      color: #007bff;
      font-size: 14px;
      text-align: right;
    }

    /* Header Flex Container */
    .header-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
    }

    /* Seletores Categoria e Item */
    .selectors-container {
      display: flex;
      gap: 20px;
      margin-bottom: 15px;
    }
    .selectors-container div {
      flex: 1;
    }
    .selectors-container select {
      width: 100%;
      padding: 6px;
      border: 1px solid #ccc;
      border-radius: 5px;
      font-size: 14px;
      box-sizing: border-box;
    }

    /* Container para os Sliders de Level e Option */
    .sliders-container {
      display: flex;
      gap: 20px;
      margin-bottom: 15px;
    }
    .slider-row {
      flex: 1;
    }
    .slider-labels {
      display: flex;
      justify-content: space-between;
      margin-bottom: 5px;
      font-size: 13px;
      color: #333;
    }
    .dual-slider {
      position: relative;
      height: 30px; /* altura total do "container" do slider */
    }
    .range-track {
      position: absolute;
      top: 14px; /* ajusta verticalmente o "trilho" */
      left: 0;
      right: 0;
      height: 2px;
      background: #ccc;
      border-radius: 2px;
    }
    /* Barra "verde" que indica o intervalo selecionado */
    .range-progress {
      position: absolute;
      top: 14px;
      height: 2px;
      background: green;
      border-radius: 2px;
    }
    /* Inputs range sobrepostos */
    .range-input {
      position: absolute;
      top: 0;
      width: 100%;
      pointer-events: none;  /* impede clique diretamente neles (mas STILL pode mover o "thumb") */
      background: none;
      -webkit-appearance: none;
    }
    .range-input::-webkit-slider-thumb {
      pointer-events: all;  /* habilita interação no thumb */
      width: 16px;
      height: 16px;
      border-radius: 50%;
      background: #666;
      border: 2px solid #ccc;
      -webkit-appearance: none;
    }
    .range-input::-webkit-slider-runnable-track {
      height: 2px;
      -webkit-appearance: none;
      background: transparent; /* a "track" fica transparente */
    }
    /* Ajuste da z-index para garantir que o thumb do max fique por cima se conflitar */
    #level-max-range,
    #opt-max-range {
      z-index: 1;
    }

    /* Inputs para exibir valores min e max (mais abaixo do slider) */
    .min-max-values {
      display: flex;
      gap: 20px;
      margin-top: 5px;
    }
    .min-max-values input {
      width: 50px;
      border: 1px solid #ccc;
      border-radius: 5px;
      font-size: 13px;
      padding: 4px;
      text-align: center;
    }

    /* Grid Container para a Tabela de Entradas VIP */
    .grid-container {
      display: grid;
      grid-template-columns: 150px repeat(3, 1fr);
      gap: 10px;
      align-items: center;
      margin-bottom: 15px;
    }
    .grid-container .header {
      font-weight: bold;
      text-align: center;
      background-color: #e9ecef;
      padding: 5px;
      border-radius: 4px;
    }
    .grid-container .attribute-label {
      text-align: right;
      padding-right: 10px;
      font-size: 13px;
    }
    .grid-container .vip-input {
      padding: 4px;
      border: 1px solid #ccc;
      border-radius: 5px;
      font-size: 13px;
      width: 100%;
      box-sizing: border-box;
    }

    /* Row para ItemTime e Chance */
    .time-chance-row {
      display: flex;
      gap: 20px;
      margin-bottom: 15px;
    }
    .time-chance-column {
      flex: 1;
    }
    .time-chance-column input {
      width: 100%;
      padding: 4px;
      border: 1px solid #ccc;
      border-radius: 5px;
      font-size: 13px;
      box-sizing: border-box;
    }

    @media (max-width: 768px) {
      .header-container {
        flex-direction: column;
        align-items: flex-start;
      }
      .mode-indicator {
        text-align: left;
        margin-top: 10px;
      }
      .selectors-container {
        flex-direction: column;
      }
      .grid-container {
        grid-template-columns: 100px repeat(3, 1fr);
      }
      .grid-container .attribute-label {
        text-align: left;
        padding-right: 0;
        margin-bottom: 5px;
      }
      .time-chance-row {
        flex-direction: column;
      }
      .time-chance-column input {
        margin-bottom: 10px;
      }
      .button-group {
        flex-direction: column;
      }
      .button-group button {
        width: 100%;
      }
      .copy-button-group {
        justify-content: center;
      }
      .sliders-container {
        flex-direction: column;
      }
    }
  </style>
</head>
<body>

<div class="container">
  <!-- Formulário -->
  <div class="form-container">
    <!-- Cabeçalho com Título e Modo -->
    <div class="header-container">
      <h1>Gerador de JSON de Itens</h1>
      <div id="mode-indicator" class="mode-indicator">Modo: Adicionar Novo Item</div>
    </div>

    <!-- Seletores de Categoria e Item -->
    <div class="selectors-container">
      <div>
        <label for="category">Categoria:</label>
        <select id="category" disabled>
          <option value="">Selecione...</option>
        </select>
      </div>
      <div>
        <label for="item">Item:</label>
        <select id="item" disabled>
          <option value="">Selecione...</option>
        </select>
      </div>
    </div>

    <!-- Container para os Sliders de Level e Option -->
    <div class="sliders-container">
      <!-- Slider para Level [0..15] -->
      <div class="slider-row">
        <div class="slider-labels">
          <span>Level (0 - 15)</span>
          <span id="level-range-values"></span>
        </div>
        <div class="dual-slider">
          <div class="range-track"></div>
          <div id="level-range-progress" class="range-progress"></div>
          <input id="level-min-range" class="range-input" type="range" min="0" max="15" value="0" step="1">
          <input id="level-max-range" class="range-input" type="range" min="0" max="15" value="15" step="1">
        </div>
      </div>

      <!-- Slider para Opt [0..7] -->
      <div class="slider-row">
        <div class="slider-labels">
          <span>Option (0 - 7)</span>
          <span id="opt-range-values"></span>
        </div>
        <div class="dual-slider">
          <div class="range-track"></div>
          <div id="opt-range-progress" class="range-progress"></div>
          <input id="opt-min-range" class="range-input" type="range" min="0" max="7" value="0" step="1">
          <input id="opt-max-range" class="range-input" type="range" min="0" max="7" value="7" step="1">
        </div>
      </div>
    </div>

    <!-- Campos de Tempo e Chance (abaixo dos sliders) -->
    <div class="time-chance-row">
      <div class="time-chance-column">
        <label for="item-time">ItemTime:</label>
        <input type="number" id="item-time" value="0" min="0">
      </div>
      <div class="time-chance-column">
        <label for="chance">Chance:</label>
        <input type="number" id="chance" value="0.5" step="0.01" min="0">
      </div>
    </div>

    <!-- Tabela de Entradas com Cabeçalhos VIP -->
    <div class="grid-container">
      <!-- Cabeçalhos das Colunas -->
      <div></div>
      <div class="header">Sem VIP</div>
      <div class="header">Vip 1</div>
      <div class="header">Vip 2</div>

      <!-- Skill -->
      <div class="attribute-label">Skill:</div>
      <input type="number" id="skill-0" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="skill-1" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="skill-2" class="vip-input" value="0" min="0" step="0.01">

      <!-- Luck -->
      <div class="attribute-label">Luck:</div>
      <input type="number" id="luck-0" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="luck-1" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="luck-2" class="vip-input" value="0" min="0" step="0.01">

      <!-- Exc 1 -->
      <div class="attribute-label">Exc 1:</div>
      <input type="number" id="exc-1-0" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="exc-1-1" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="exc-1-2" class="vip-input" value="0" min="0" step="0.01">

      <!-- Exc 2 -->
      <div class="attribute-label">Exc 2:</div>
      <input type="number" id="exc-2-0" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="exc-2-1" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="exc-2-2" class="vip-input" value="0" min="0" step="0.01">

      <!-- Exc 3 -->
      <div class="attribute-label">Exc 3:</div>
      <input type="number" id="exc-3-0" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="exc-3-1" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="exc-3-2" class="vip-input" value="0" min="0" step="0.01">

      <!-- Exc 4 -->
      <div class="attribute-label">Exc 4:</div>
      <input type="number" id="exc-4-0" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="exc-4-1" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="exc-4-2" class="vip-input" value="0" min="0" step="0.01">

      <!-- Exc 5 -->
      <div class="attribute-label">Exc 5:</div>
      <input type="number" id="exc-5-0" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="exc-5-1" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="exc-5-2" class="vip-input" value="0" min="0" step="0.01">

      <!-- Exc 6 -->
      <div class="attribute-label">Exc 6:</div>
      <input type="number" id="exc-6-0" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="exc-6-1" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="exc-6-2" class="vip-input" value="0" min="0" step="0.01">

      <!-- Socket 1 -->
      <div class="attribute-label">Socket 1:</div>
      <input type="number" id="socket-1-0" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="socket-1-1" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="socket-1-2" class="vip-input" value="0" min="0" step="0.01">

      <!-- Socket 2 -->
      <div class="attribute-label">Socket 2:</div>
      <input type="number" id="socket-2-0" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="socket-2-1" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="socket-2-2" class="vip-input" value="0" min="0" step="0.01">

      <!-- Socket 3 -->
      <div class="attribute-label">Socket 3:</div>
      <input type="number" id="socket-3-0" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="socket-3-1" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="socket-3-2" class="vip-input" value="0" min="0" step="0.01">

      <!-- Ancient -->
      <div class="attribute-label">Ancient:</div>
      <input type="number" id="ancient-0" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="ancient-1" class="vip-input" value="0" min="0" step="0.01">
      <input type="number" id="ancient-2" class="vip-input" value="0" min="0" step="0.01">

      <!-- Rate -->
      <div class="attribute-label">Rate:</div>
      <input type="number" id="rate-0" class="vip-input" value="0" min="0" max="100" step="0.01">
      <input type="number" id="rate-1" class="vip-input" value="0" min="0" max="100" step="0.01">
      <input type="number" id="rate-2" class="vip-input" value="0" min="0" max="100" step="0.01">
    </div>

    <!-- Botões de ação -->
    <div class="button-group">
      <button id="generate" disabled>Adicionar Item</button>
      <button id="clear-list">Limpar Lista</button>
    </div>
  </div>

  <!-- Lista de itens e JSON -->
  <div class="list-container">
    <h2>Itens Adicionados</h2>
    <div id="item-list" class="item-list"></div>

    <h2>JSON Gerado</h2>
    <div class="copy-button-group">
      <button id="copy-json">Copiar JSON</button>
    </div>
    <pre id="output"></pre>
  </div>
</div>

<script>
  const categories = {
    0: 'Swords',
    1: 'Axes',
    2: 'Maces',
    3: 'Spears',
    4: 'Bows',
    5: 'Staffs',
    6: 'Shields',
    7: 'Helms',
    8: 'Armors',
    9: 'Pants',
    10: 'Gloves',
    11: 'Boots',
    12: 'Wings',
    13: 'Outros',
    15: 'Powers'
  };

  const colors = ['#ff6666', '#ffcc66', '#66ff66'];

  // DOM
  const itemList = document.getElementById('item-list');
  const output = document.getElementById('output');
  const categorySelect = document.getElementById('category');
  const itemSelect = document.getElementById('item');
  const generateButton = document.getElementById('generate');
  const clearListButton = document.getElementById('clear-list');
  const copyJsonButton = document.getElementById('copy-json');
  const modeIndicator = document.getElementById('mode-indicator');

  // Range elements para Level
  const levelMinRange = document.getElementById('level-min-range');
  const levelMaxRange = document.getElementById('level-max-range');
  const levelRangeProgress = document.getElementById('level-range-progress');
  const levelRangeValues = document.getElementById('level-range-values');

  // Range elements para Opt
  const optMinRange = document.getElementById('opt-min-range');
  const optMaxRange = document.getElementById('opt-max-range');
  const optRangeProgress = document.getElementById('opt-range-progress');
  const optRangeValues = document.getElementById('opt-range-values');

  // itemTime e chance
  const itemTimeInput = document.getElementById('item-time');
  const chanceInput = document.getElementById('chance');

  let itemData = {};
  let addedItems = [];
  let currentItemIndex = null;

  // =========================
  //     Carrega item.txt
  // =========================
  window.onload = () => {
    fetch('./item.txt')
      .then(response => response.text())
      .then(data => processFile(data))
      .catch(error => console.error('Erro ao carregar o arquivo item.txt:', error));
  };

  function processFile(fileContent) {
    const lines = fileContent.split('\n');
    let currentCategory = null;
    lines.forEach(line => {
      line = line.trim();
      if (!isNaN(line) && line !== '') {
        currentCategory = line;
        itemData[currentCategory] = [];
      } else if (currentCategory && line.match(/^\d+/)) {
        const columns = line.split(/\s+/);
        const index = columns[1];
        const nameMatch = line.match(/"(.*?)"/);
        const name = nameMatch ? nameMatch[1] : `Item ${index}`;
        itemData[currentCategory].push({ Index: index, Name: name });
      }
    });
    populateCategories();
  }

  function populateCategories() {
    categorySelect.innerHTML = '<option value="">Selecione...</option>';
    Object.keys(itemData).forEach(category => {
      const option = document.createElement('option');
      option.value = category;
      option.textContent = categories[category] || `Categoria ${category}`;
      categorySelect.appendChild(option);
    });
    categorySelect.disabled = false;
  }

  categorySelect.addEventListener('change', () => {
    const selectedCategory = categorySelect.value;
    itemSelect.innerHTML = '<option value="">Selecione...</option>';
    if (selectedCategory && itemData[selectedCategory]) {
      itemData[selectedCategory].forEach(item => {
        const option = document.createElement('option');
        option.value = item.Index;
        option.textContent = item.Name;
        itemSelect.appendChild(option);
      });
      itemSelect.disabled = false;
      generateButton.disabled = true;
    } else {
      itemSelect.disabled = true;
      generateButton.disabled = true;
    }
  });

  itemSelect.addEventListener('change', () => {
    generateButton.disabled = !itemSelect.value;
  });

  // =========================
  //   Funções do Slider
  // =========================
  function updateLevelSlider() {
    let minVal = parseInt(levelMinRange.value);
    let maxVal = parseInt(levelMaxRange.value);
    if (minVal > maxVal) {
      // Se o min ultrapassou o max, ajusta
      [minVal, maxVal] = [maxVal, minVal];
    }
    levelMinRange.value = minVal;
    levelMaxRange.value = maxVal;

    const percentMin = (minVal / levelMinRange.max) * 100;
    const percentMax = (maxVal / levelMaxRange.max) * 100;

    // Ajusta a barra verde
    levelRangeProgress.style.left = percentMin + '%';
    levelRangeProgress.style.right = (100 - percentMax) + '%';

    // Exibe os valores
    levelRangeValues.textContent = `${minVal} - ${maxVal}`;
  }
  function updateOptSlider() {
    let minVal = parseInt(optMinRange.value);
    let maxVal = parseInt(optMaxRange.value);
    if (minVal > maxVal) {
      [minVal, maxVal] = [maxVal, minVal];
    }
    optMinRange.value = minVal;
    optMaxRange.value = maxVal;

    const percentMin = (minVal / optMinRange.max) * 100;
    const percentMax = (maxVal / optMaxRange.max) * 100;

    optRangeProgress.style.left = percentMin + '%';
    optRangeProgress.style.right = (100 - percentMax) + '%';

    optRangeValues.textContent = `${minVal} - ${maxVal}`;
  }

  // Eventos dos sliders
  levelMinRange.addEventListener('input', updateLevelSlider);
  levelMaxRange.addEventListener('input', updateLevelSlider);
  optMinRange.addEventListener('input', updateOptSlider);
  optMaxRange.addEventListener('input', updateOptSlider);

  // Inicia os sliders
  updateLevelSlider();
  updateOptSlider();

  // =========================
  //      Adicionar Item
  // =========================
  generateButton.addEventListener('click', () => {
    const isEditMode = currentItemIndex !== null;

    // Pega os valores do slider de Level
    const levelMin = parseInt(levelMinRange.value);
    const levelMax = parseInt(levelMaxRange.value);

    // Pega os valores do slider de Opt
    const optMin = parseInt(optMinRange.value);
    const optMax = parseInt(optMaxRange.value);

    const item = {
      Section: parseInt(categorySelect.value),
      Index: parseInt(itemSelect.value),
      Level: {
        Min: levelMin,
        Max: levelMax
      },
      Skill: [
        parseFloat(document.getElementById('skill-0').value),
        parseFloat(document.getElementById('skill-1').value),
        parseFloat(document.getElementById('skill-2').value)
      ],
      Luck: [
        parseFloat(document.getElementById('luck-0').value),
        parseFloat(document.getElementById('luck-1').value),
        parseFloat(document.getElementById('luck-2').value)
      ],
      Opt: {
        Min: optMin,
        Max: optMax
      },
      Exc: {},
      Ancient: [
        parseFloat(document.getElementById('ancient-0').value),
        parseFloat(document.getElementById('ancient-1').value),
        parseFloat(document.getElementById('ancient-2').value)
      ],
      Socket: {},
      ItemTime: parseInt(itemTimeInput.value),
      Chance: parseFloat(chanceInput.value),
      Rate: [
        parseFloat(document.getElementById('rate-0').value),
        parseFloat(document.getElementById('rate-1').value),
        parseFloat(document.getElementById('rate-2').value)
      ]
    };

    // Processa Exc fields
    for (let i = 1; i <= 6; i++) {
      item.Exc[i] = [
        parseFloat(document.getElementById(`exc-${i}-0`).value),
        parseFloat(document.getElementById(`exc-${i}-1`).value),
        parseFloat(document.getElementById(`exc-${i}-2`).value)
      ];
    }

    // Processa Socket fields
    for (let i = 1; i <= 3; i++) {
      item.Socket[i] = [
        parseFloat(document.getElementById(`socket-${i}-0`).value),
        parseFloat(document.getElementById(`socket-${i}-1`).value),
        parseFloat(document.getElementById(`socket-${i}-2`).value)
      ];
    }

    if (isEditMode) {
      addedItems[currentItemIndex] = item;
      currentItemIndex = null;
      modeIndicator.textContent = 'Modo: Adicionar Novo Item';
      generateButton.textContent = 'Adicionar Item';
    } else {
      addedItems.push(item);
    }

    refreshItemList();
    resetForm();
  });

  function refreshItemList() {
    itemList.innerHTML = '';
    addedItems.forEach((item, index) => {
      const div = document.createElement('div');
      div.className = 'item';
      div.innerHTML = `
        <div>
          <strong>${categories[item.Section]} - ${itemData[item.Section].find(i => i.Index == item.Index).Name}</strong>
          <div class="percentages">
            <span class="percentage-value" style="background-color: ${colors[0]};">Skill: ${item.Skill.join('%, ')}%</span>
            <span class="percentage-value" style="background-color: ${colors[1]};">Luck: ${item.Luck.join('%, ')}%</span>
            <span class="percentage-value" style="background-color: ${colors[2]};">Opt: Min ${item.Opt.Min}, Max ${item.Opt.Max}</span>
          </div>
        </div>
        <div>
          <button class="button-small" onclick="editItem(${index})">Editar</button>
          <button class="button-small" onclick="deleteItem(${index})">Excluir</button>
        </div>
      `;
      itemList.appendChild(div);
    });
    output.textContent = generateJsonOutput();
  }

  function editItem(index) {
    currentItemIndex = index;
    const item = addedItems[index];

    categorySelect.value = item.Section;
    categorySelect.dispatchEvent(new Event('change'));

    setTimeout(() => {
      itemSelect.value = item.Index;

      // Ajusta sliders de Level
      levelMinRange.value = item.Level.Min;
      levelMaxRange.value = item.Level.Max;
      updateLevelSlider();

      // Ajusta sliders de Opt
      optMinRange.value = item.Opt.Min;
      optMaxRange.value = item.Opt.Max;
      updateOptSlider();

      document.getElementById('skill-0').value = item.Skill[0];
      document.getElementById('skill-1').value = item.Skill[1];
      document.getElementById('skill-2').value = item.Skill[2];

      document.getElementById('luck-0').value = item.Luck[0];
      document.getElementById('luck-1').value = item.Luck[1];
      document.getElementById('luck-2').value = item.Luck[2];

      for (let i = 1; i <= 6; i++) {
        document.getElementById(`exc-${i}-0`).value = item.Exc[i][0];
        document.getElementById(`exc-${i}-1`).value = item.Exc[i][1];
        document.getElementById(`exc-${i}-2`).value = item.Exc[i][2];
      }

      document.getElementById('ancient-0').value = item.Ancient[0];
      document.getElementById('ancient-1').value = item.Ancient[1];
      document.getElementById('ancient-2').value = item.Ancient[2];

      for (let i = 1; i <= 3; i++) {
        document.getElementById(`socket-${i}-0`).value = item.Socket[i][0];
        document.getElementById(`socket-${i}-1`).value = item.Socket[i][1];
        document.getElementById(`socket-${i}-2`).value = item.Socket[i][2];
      }

      itemTimeInput.value = item.ItemTime;
      chanceInput.value = item.Chance;

      document.getElementById('rate-0').value = item.Rate[0];
      document.getElementById('rate-1').value = item.Rate[1];
      document.getElementById('rate-2').value = item.Rate[2];

      modeIndicator.textContent = 'Modo: Editar Item';
      generateButton.textContent = 'Salvar Alterações';
      generateButton.disabled = false;
    }, 100);
  }

  function deleteItem(index) {
    if (confirm('Tem certeza que deseja excluir este item?')) {
      addedItems.splice(index, 1);
      refreshItemList();
    }
  }

  function generateJsonOutput() {
    return addedItems.map(item => {
      const excEntries = Object.entries(item.Exc).map(
        ([key, value]) => `[${key}] = {[0] = ${value[0]}, [1] = ${value[1]}, [2] = ${value[2]}}`
      ).join(', ');
      const socketEntries = Object.entries(item.Socket).map(
        ([key, value]) => `[${key}] = {[0] = ${value[0]}, [1] = ${value[1]}, [2] = ${value[2]}}`
      ).join(', ');
      return `{
    Section = ${item.Section},
    Index = ${item.Index},
    Level = {Min = ${item.Level.Min}, Max = ${item.Level.Max}},
    Skill = {[0] = ${item.Skill[0]}, [1] = ${item.Skill[1]}, [2] = ${item.Skill[2]}},
    Luck = {[0] = ${item.Luck[0]}, [1] = ${item.Luck[1]}, [2] = ${item.Luck[2]}},
    Opt = {Min = ${item.Opt.Min}, Max = ${item.Opt.Max}},
    Exc = {${excEntries}},
    Ancient = {[0] = ${item.Ancient[0]}, [1] = ${item.Ancient[1]}, [2] = ${item.Ancient[2]}},
    Socket = {${socketEntries}},
    ItemTime = ${item.ItemTime},
    Chance = ${item.Chance},
    Rate = {[0] = ${item.Rate[0]}, [1] = ${item.Rate[1]}, [2] = ${item.Rate[2]}}
}`;
    }).join(',\n\n');
  }

  function resetForm() {
    if (currentItemIndex === null) {
      // Reseta sliders
      levelMinRange.value = 0;
      levelMaxRange.value = 15;
      updateLevelSlider();

      optMinRange.value = 0;
      optMaxRange.value = 7;
      updateOptSlider();

      document.getElementById('skill-0').value = 0;
      document.getElementById('skill-1').value = 0;
      document.getElementById('skill-2').value = 0;

      document.getElementById('luck-0').value = 0;
      document.getElementById('luck-1').value = 0;
      document.getElementById('luck-2').value = 0;

      for (let i = 1; i <= 6; i++) {
        document.getElementById(`exc-${i}-0`).value = 0;
        document.getElementById(`exc-${i}-1`).value = 0;
        document.getElementById(`exc-${i}-2`).value = 0;
      }

      document.getElementById('ancient-0').value = 0;
      document.getElementById('ancient-1').value = 0;
      document.getElementById('ancient-2').value = 0;

      for (let i = 1; i <= 3; i++) {
        document.getElementById(`socket-${i}-0`).value = 0;
        document.getElementById(`socket-${i}-1`).value = 0;
        document.getElementById(`socket-${i}-2`).value = 0;
      }

      itemTimeInput.value = 0;
      chanceInput.value = 0.5;

      document.getElementById('rate-0').value = 0;
      document.getElementById('rate-1').value = 0;
      document.getElementById('rate-2').value = 0;
    }
  }

  clearListButton.addEventListener('click', () => {
    if (confirm('Tem certeza que deseja limpar toda a lista de itens?')) {
      addedItems = [];
      refreshItemList();
    }
  });

  copyJsonButton.addEventListener('click', () => {
    const jsonText = output.textContent;
    navigator.clipboard.writeText(jsonText)
      .then(() => alert('JSON copiado para a área de transferência!'))
      .catch(err => alert('Falha ao copiar o JSON: ' + err));
  });

  // Funções globais para editar/excluir
  window.editItem = editItem;
  window.deleteItem = deleteItem;
</script>

</body>
</html>
