/**
 * RandomGroup Pro - Tools Tambahan
 * Menambahkan tools yang belum ada tanpa mengubah logic tools existing.
 */

(function () {
  'use strict';

  function byId(id) {
    return document.getElementById(id);
  }

  function splitLines(value) {
    return (value || '')
      .split('\n')
      .map(v => v.trim())
      .filter(Boolean);
  }

  function shuffle(arr) {
    const a = [...arr];
    for (let i = a.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
  }

  function show(id, text, asHTML = false) {
    const el = byId(id);
    if (!el) return;
    if (asHTML) el.innerHTML = text;
    else el.textContent = text;
  }

  function parseNameSkill(lines) {
    // Format: Nama (skill 9) / Nama - 9 / Nama,9
    const result = [];
    lines.forEach(line => {
      let name = line;
      let skill = 0;

      const bracket = line.match(/^(.*?)\s*\(\s*skill\s*(\d+)\s*\)\s*$/i);
      const dash = line.match(/^(.*?)\s*[-:]\s*(\d+)\s*$/);
      const comma = line.match(/^(.*?)\s*,\s*(\d+)\s*$/);

      if (bracket) {
        name = bracket[1].trim();
        skill = parseInt(bracket[2], 10);
      } else if (dash) {
        name = dash[1].trim();
        skill = parseInt(dash[2], 10);
      } else if (comma) {
        name = comma[1].trim();
        skill = parseInt(comma[2], 10);
      } else {
        name = line.trim();
        skill = 0;
      }

      if (name) result.push({ name, skill: Number.isFinite(skill) ? skill : 0 });
    });

    return result;
  }

  function bindRandomLeaderPicker() {
    const btn = byId('leaderPickBtn');
    if (!btn) return;

    btn.addEventListener('click', () => {
      const names = splitLines(byId('leaderInput')?.value);
      if (names.length < 1) {
        show('leaderResult', 'Masukkan minimal 1 nama.');
        return;
      }
      const winner = names[Math.floor(Math.random() * names.length)];
      show('leaderResult', `Leader terpilih: ${winner}`);
    });
  }

  function bindTeamBalancer() {
    const btn = byId('teamBalanceBtn');
    if (!btn) return;

    btn.addEventListener('click', () => {
      const teamCount = Math.max(2, parseInt(byId('teamCount')?.value || '2', 10));
      const lines = splitLines(byId('teamInput')?.value);
      const players = parseNameSkill(lines);

      if (players.length < teamCount) {
        show('teamResult', 'Jumlah peserta harus >= jumlah tim.');
        return;
      }

      players.sort((a, b) => b.skill - a.skill);

      const teams = Array.from({ length: teamCount }, () => ({ total: 0, members: [] }));

      players.forEach(player => {
        teams.sort((a, b) => a.total - b.total);
        teams[0].members.push(player);
        teams[0].total += player.skill;
      });

      let html = '';
      teams.forEach((team, i) => {
        html += `<div class="extra-result-card"><h4>Team ${i + 1} <small>(Total Skill: ${team.total})</small></h4><ul>`;
        team.members.forEach(m => {
          html += `<li>${m.name} <span class="muted">(skill ${m.skill})</span></li>`;
        });
        html += '</ul></div>';
      });

      show('teamResult', html, true);
    });
  }

  function bindSeatGenerator() {
    const btn = byId('seatGenerateBtn');
    if (!btn) return;

    btn.addEventListener('click', () => {
      const names = shuffle(splitLines(byId('seatInput')?.value));
      const rows = Math.max(1, parseInt(byId('seatRows')?.value || '3', 10));
      const cols = Math.max(1, parseInt(byId('seatCols')?.value || '3', 10));
      const capacity = rows * cols;

      if (!names.length) {
        show('seatResult', 'Masukkan minimal 1 nama.');
        return;
      }

      const used = names.slice(0, capacity);
      let html = '<div class="seat-grid" style="display:grid;gap:8px;">';
      html += `<div class="muted" style="margin-bottom:8px;">Layout: ${rows} x ${cols} (kapasitas ${capacity})</div>`;
      html += '<ol>';
      used.forEach((name, i) => {
        html += `<li>Seat ${i + 1}: ${name}</li>`;
      });
      html += '</ol></div>';

      if (names.length > capacity) {
        html += `<div class="muted">Sisa nama (belum dapat kursi): ${names.length - capacity}</div>`;
      }

      show('seatResult', html, true);
    });
  }

  function bindTournamentBracket() {
    const btn = byId('bracketGenerateBtn');
    if (!btn) return;

    btn.addEventListener('click', () => {
      const names = shuffle(splitLines(byId('bracketInput')?.value));
      if (names.length < 2) {
        show('bracketResult', 'Masukkan minimal 2 peserta.');
        return;
      }

      const pairs = [];
      for (let i = 0; i < names.length; i += 2) {
        if (names[i + 1]) pairs.push(`${names[i]} vs ${names[i + 1]}`);
        else pairs.push(`${names[i]} vs BYE`);
      }

      let html = '<div class="extra-result-card"><h4>Bracket Round 1</h4><ol>';
      pairs.forEach(p => {
        html += `<li>${p}</li>`;
      });
      html += '</ol></div>';

      show('bracketResult', html, true);
    });
  }

  function bindRandomNumber() {
    const btn = byId('numGenerateBtn');
    if (!btn) return;

    btn.addEventListener('click', () => {
      const min = parseInt(byId('numMin')?.value || '1', 10);
      const max = parseInt(byId('numMax')?.value || '100', 10);
      if (!Number.isFinite(min) || !Number.isFinite(max) || min > max) {
        show('numResult', 'Range tidak valid.');
        return;
      }
      const val = Math.floor(Math.random() * (max - min + 1)) + min;
      show('numResult', `Hasil: ${val}`);
    });
  }

  function bindRandomColor() {
    const btn = byId('colorGenerateBtn');
    if (!btn) return;

    btn.addEventListener('click', () => {
      const hex = '#' + Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0').toUpperCase();
      const html = `<div class="color-preview" style="width:100%;height:48px;border-radius:10px;background:${hex};border:1px solid rgba(255,255,255,.2);"></div>
                    <div style="margin-top:8px;font-weight:700;">${hex}</div>`;
      show('colorResult', html, true);
    });
  }

  function bindPasswordGenerator() {
    const btn = byId('passGenerateBtn');
    if (!btn) return;

    btn.addEventListener('click', () => {
      const length = Math.max(4, Math.min(64, parseInt(byId('passwordLength')?.value || '10', 10)));
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%';
      let pass = '';
      for (let i = 0; i < length; i++) {
        pass += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      show('passResult', pass);
    });
  }

  function bindDuplicateRemover() {
    const btn = byId('dupRemoveBtn');
    if (!btn) return;

    btn.addEventListener('click', () => {
      const items = splitLines(byId('duplicateInput')?.value);
      if (!items.length) {
        show('dupResult', 'Masukkan data terlebih dahulu.');
        return;
      }
      const unique = [...new Set(items)];
      show('dupResult', unique.join('\n'));
    });
  }

  function bindListShuffler() {
    const btn = byId('shuffleBtn');
    if (!btn) return;

    btn.addEventListener('click', () => {
      const items = splitLines(byId('listInput')?.value);
      if (!items.length) {
        show('shuffleResult', 'Masukkan list terlebih dahulu.');
        return;
      }
      show('shuffleResult', shuffle(items).join('\n'));
    });
  }

  document.addEventListener('DOMContentLoaded', () => {
    bindRandomLeaderPicker();
    bindTeamBalancer();
    bindSeatGenerator();
    bindTournamentBracket();
    bindRandomNumber();
    bindRandomColor();
    bindPasswordGenerator();
    bindDuplicateRemover();
    bindListShuffler();
  });
})();

