(function ($) {

  function $tbody() {
    return $('#spg_wallets_table tbody');
  }

  function nextIndex() {
    let max = -1;

    $tbody()
      .find('input[name^="spg_wallets["], select[name^="spg_wallets["], textarea[name^="spg_wallets["]')
      .each(function () {
        const name = this.name || '';
        const m = name.match(/^spg_wallets\[(\d+)\]/);
        if (m) {
          const n = parseInt(m[1], 10);
          if (!isNaN(n) && n > max) max = n;
        }
      });

    return max + 1;
  }

  function renderTemplate(i) {
    const tpl = $('#tmpl-spg-wallet-row').html() || '';
    return tpl.replace(/\{\{i\}\}/g, String(i));
  }

  function syncRow($row) {
    const $sel = $row.find('.spg-currency-select').first();
    const currencyKey = ($sel.val() || '').toString();

    const $customWrap = $row.find('.spg-custom-wrap');
    const $coinH = $row.find('.spg-hidden-coin');
    const $netH  = $row.find('.spg-hidden-net');
    const $decH  = $row.find('.spg-adv-decimals');
    const $tagWrap = $row.find('.spg-tag-wrap');

    if (currencyKey === '__CUSTOM__') {
      $customWrap.show();

      const coin = ($row.find('.spg-custom-coin').val() || '').toString().trim();
      const net  = ($row.find('.spg-custom-net').val() || '').toString().trim();

      $coinH.val(coin);
      $netH.val(net);
    } else {
      $customWrap.hide();

      const $opt = $sel.find('option:selected');
      const coin = ($opt.data('coin') || '').toString().trim();
      const net  = ($opt.data('network') || '').toString().trim();
      const dec  = ($opt.data('decimals') ?? '').toString().trim();

      if (coin) $coinH.val(coin);
      if (net)  $netH.val(net);
      if (dec !== '') $decH.val(dec);
    }

    // Tag/memo only for XRP/XLM
    const c = ($coinH.val() || '').toString().toUpperCase().trim();
    const showTag = (c === 'XRP' || c === 'XLM');
    if ($tagWrap.length) $tagWrap.toggle(showTag);
  }

  $(document).on('click', '#spg_add_wallet', function (e) {
    e.preventDefault();
    const i = nextIndex();
    $tbody().append(renderTemplate(i));
    syncRow($tbody().find('tr').last());
  });

  $(document).on('click', '.spg-remove', function (e) {
    e.preventDefault();
    $(this).closest('tr').remove();
  });

  $(document).on('change', '.spg-currency-select', function () {
    syncRow($(this).closest('tr'));
  });

  $(document).on('input change', '.spg-custom-coin, .spg-custom-net', function () {
    syncRow($(this).closest('tr'));
  });

  $(function () {
    $('#spg_wallets_table tbody tr').each(function () {
      syncRow($(this));
    });
  });

})(jQuery);
