<?php
// pages/minha-rede.php — Visualização da Rede MLM

if ($_settings->userdata('id') == '') {
    echo '<script>location.replace(\'/\');</script>'; exit();
}
$customer_id   = (int) $_settings->userdata('id');
$customer_name = trim($_settings->userdata('firstname') . ' ' . $_settings->userdata('lastname'));

require_once BASE_APP . 'classes/MLM.php';
require_once BASE_APP . 'includes/wallet-functions.php';

$mlm = new MLM();

// Link de indicação
$ref_code = $mlm->ensure_referral_code($customer_id);
$ref_link = BASE_URL . 'cadastrar?ref=' . $ref_code;

// Dados binários do usuário
$binary = $conn->query(
    "SELECT * FROM binary_tree WHERE customer_id = $customer_id"
)->fetch_assoc();

// Indicados diretos
$directs     = $mlm->get_direct_referrals($customer_id);
$depth_count = $mlm->get_network_depth_count($customer_id);
$total_rede  = array_sum($depth_count);

// Bônus histórico
$bonus_history = $conn->query(
    "SELECT * FROM binary_bonuses WHERE customer_id = $customer_id
     ORDER BY created_at DESC LIMIT 10"
);

// Comissões unilevel
$unilevel_total = (float)($conn->query(
    "SELECT COALESCE(SUM(commission_amount),0) as total
     FROM unilevel_commissions WHERE beneficiary_id = $customer_id"
)->fetch_assoc()['total'] ?? 0);

$unilevel_history = $conn->query(
    "SELECT uc.*, c.firstname as origem_nome
     FROM unilevel_commissions uc
     JOIN customer_list c ON uc.origin_customer_id = c.id
     WHERE uc.beneficiary_id = $customer_id
     ORDER BY uc.created_at DESC LIMIT 15"
);

// Totais binário
$binary_total_earned  = (float)($binary['total_binary_earned'] ?? 0);
$binary_left_volume   = (float)($binary['left_volume'] ?? 0);
$binary_right_volume  = (float)($binary['right_volume'] ?? 0);
$binary_weak_side     = min($binary_left_volume, $binary_right_volume);
$binary_bonus_next    = round($binary_weak_side * 0.10, 2); // 10%

// Equilíbrio
$total_vol  = $binary_left_volume + $binary_right_volume;
$left_pct   = $total_vol > 0 ? round(($binary_left_volume  / $total_vol) * 100) : 50;
$right_pct  = $total_vol > 0 ? round(($binary_right_volume / $total_vol) * 100) : 50;
?>

<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800;900&display=swap');
.rede-wrap { font-family:'Inter',sans-serif; }

/* ── Hero ────────────────────────────────────────────── */
.rede-hero {
  background: linear-gradient(135deg,#2d3436 0%,#1a1a2e 50%,#0f3460 100%);
  border-radius:20px; color:#fff; padding:2rem; position:relative; overflow:hidden;
}
.rede-hero::after {
  content:''; position:absolute; bottom:-40px; right:-40px;
  width:200px; height:200px; border-radius:50%;
  background:radial-gradient(circle,rgba(108,92,231,.3) 0%,transparent 70%);
}

/* ── Cards ───────────────────────────────────────────── */
.mlm-card { border-radius:18px; border:none; box-shadow:0 4px 20px rgba(0,0,0,.07); }
.stat-pill { border-radius:14px; padding:1rem 1.25rem; }

/* ── Barra binária ───────────────────────────────────── */
.binary-bar-wrap { height:14px; border-radius:50px; background:#f0eeff; overflow:hidden; }
.binary-bar-left {
  height:100%; border-radius:50px 0 0 50px; float:left;
  background:linear-gradient(90deg,#6c5ce7,#a29bfe); transition:width .6s ease;
}
.binary-bar-right {
  height:100%; border-radius:0 50px 50px 0; float:right;
  background:linear-gradient(90deg,#fd79a8,#e17055); transition:width .6s ease;
}

/* ── Árvore binária visual ───────────────────────────── */
.tree-container {
  overflow-x:auto; padding:1.5rem;
  background:linear-gradient(135deg,#f8f7ff,#f0eeff);
  border-radius:16px;
}
.tree-level { display:flex; justify-content:center; gap:1rem; margin-bottom:0; }
.tree-connector { display:flex; justify-content:center; align-items:flex-start; }

.tree-node {
  display:flex; flex-direction:column; align-items:center;
  position:relative; min-width:90px;
}
.tree-node-card {
  background:#fff; border-radius:14px; padding:.75rem;
  box-shadow:0 4px 16px rgba(108,92,231,.12);
  border:2px solid transparent; text-align:center;
  cursor:pointer; transition:all .2s; width:90px;
}
.tree-node-card:hover { border-color:#6c5ce7; transform:translateY(-2px); }
.tree-node-card.root-node { border-color:#6c5ce7; background:#f8f7ff; }
.tree-node-card.empty-slot {
  border:2px dashed #d0c8f8; background:#faf9ff;
  color:#b0a8e0; font-size:.7rem;
}
.tree-avatar {
  width:42px; height:42px; border-radius:50%; object-fit:cover;
  margin:0 auto .4rem; display:block;
  border:2px solid #a29bfe;
}
.tree-avatar-placeholder {
  width:42px; height:42px; border-radius:50%;
  background:linear-gradient(135deg,#6c5ce7,#a29bfe);
  margin:0 auto .4rem; display:flex; align-items:center; justify-content:center;
  color:#fff; font-weight:800; font-size:1rem;
}
.tree-name { font-size:.65rem; font-weight:700; color:#2d3436; line-height:1.2; }
.tree-label { font-size:.55rem; color:#636e72; }

/* ── Linhas de conexão ───────────────────────────────── */
.tree-branches {
  display:flex; justify-content:space-around;
  padding:0 45px; position:relative;
}
.tree-branches::before {
  content:''; position:absolute; top:0; left:50%;
  transform:translateX(-50%);
  width:2px; height:20px; background:#d0c8f8;
}
.tree-branch-left, .tree-branch-right {
  flex:1; height:20px; position:relative;
}
.tree-branch-left::before {
  content:''; position:absolute; top:0; right:0;
  width:50%; height:2px; background:#d0c8f8;
}
.tree-branch-left::after {
  content:''; position:absolute; top:0; right:0;
  width:2px; height:20px; background:#d0c8f8;
}
.tree-branch-right::before {
  content:''; position:absolute; top:0; left:0;
  width:50%; height:2px; background:#d0c8f8;
}
.tree-branch-right::after {
  content:''; position:absolute; top:0; left:0;
  width:2px; height:20px; background:#d0c8f8;
}

/* ── Badge de lado ───────────────────────────────────── */
.side-badge-l { background:rgba(108,92,231,.12); color:#6c5ce7;
                border-radius:50px; font-size:.6rem; font-weight:700; padding:2px 8px; }
.side-badge-r { background:rgba(253,121,168,.12); color:#fd79a8;
                border-radius:50px; font-size:.6rem; font-weight:700; padding:2px 8px; }

/* ── Indicados diretos ───────────────────────────────── */
.referral-row { border-radius:12px; transition:.15s; }
.referral-row:hover { background:#f8f7ff; }
.ref-avatar { width:44px; height:44px; border-radius:50%; object-fit:cover; }
.ref-avatar-ph {
  width:44px; height:44px; border-radius:50%;
  background:linear-gradient(135deg,#6c5ce7,#a29bfe);
  display:flex; align-items:center; justify-content:center;
  color:#fff; font-weight:800;
}

/* ── Copy link ───────────────────────────────────────── */
.link-box {
  background:#f8f7ff; border:2px solid #e8e5f5; border-radius:14px;
  padding:1rem; cursor:pointer; transition:.2s;
}
.link-box:hover { border-color:#6c5ce7; }

/* ── Tabs ────────────────────────────────────────────── */
.rede-tabs .nav-link { border-radius:50px !important; font-weight:600; }
.rede-tabs .nav-link.active { background:#6c5ce7 !important; color:#fff !important; border:none; }
.rede-tabs .nav-link:not(.active) { color:#6c5ce7; border:1px solid #6c5ce7; }

/* ── Profundidade ────────────────────────────────────── */
.depth-bar { height:8px; border-radius:50px; background:#e8e5f5; overflow:hidden; }
.depth-fill { height:100%; border-radius:50px;
              background:linear-gradient(90deg,#6c5ce7,#a29bfe); }
</style>

<div class="container app-main rede-wrap pb-5">

  <!-- ── Título ─────────────────────────────────────── -->
  <div class="app-title mb-3">
    <h1>🌐 Minha Rede</h1>
    <div class="app-title-desc" style="color:#424b58">Binário + Unilevel — Ganhos da rede</div>
  </div>

  <!-- ── Hero ──────────────────────────────────────── -->
  <div class="rede-hero mb-3">
    <div class="row align-items-center">
      <div class="col">
        <div class="small opacity-70 mb-1">🌐 Sua Rede Total</div>
        <div class="fw-black" style="font-size:2.5rem"><?= number_format($total_rede) ?></div>
        <div class="small opacity-70">membros em <?= count(array_filter($depth_count)) ?> níveis</div>
      </div>
      <div class="col-auto">
        <div class="text-center">
          <div class="small opacity-70 mb-1">💰 Total Ganho MLM</div>
          <div class="fw-bold fs-4">
            R$ <?= number_format($binary_total_earned + $unilevel_total, 2, ',', '.') ?>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- ── Stats Binário ──────────────────────────────── -->
  <div class="row g-3 mb-3">
    <div class="col-6">
      <div class="mlm-card p-3">
        <div class="small text-muted mb-1">⬅️ Volume Esquerdo</div>
        <div class="fw-bold fs-5 text-primary">
          R$ <?= number_format($binary_left_volume, 2, ',', '.') ?>
        </div>
      </div>
    </div>
    <div class="col-6">
      <div class="mlm-card p-3">
        <div class="small text-muted mb-1">Volume Direito ➡️</div>
        <div class="fw-bold fs-5" style="color:#fd79a8">
          R$ <?= number_format($binary_right_volume, 2, ',', '.') ?>
        </div>
      </div>
    </div>
  </div>

  <!-- ── Medidor de equilíbrio ──────────────────────── -->
  <div class="mlm-card p-4 mb-3">
    <div class="d-flex justify-content-between mb-2">
      <span class="side-badge-l">⬅️ Esquerda <?= $left_pct ?>%</span>
      <span class="fw-semibold small">Equilíbrio Binário</span>
      <span class="side-badge-r">Direita <?= $right_pct ?>% ➡️</span>
    </div>
    <div class="binary-bar-wrap mb-3">
      <div class="binary-bar-left"  style="width:<?= $left_pct ?>%"></div>
      <div class="binary-bar-right" style="width:<?= $right_pct ?>%"></div>
    </div>

    <div class="row g-2 text-center">
      <div class="col-4">
        <div class="stat-pill" style="background:#f0eeff">
          <div class="small text-muted">💤 Lado Fraco</div>
          <div class="fw-bold">R$ <?= number_format($binary_weak_side, 2, ',', '.') ?></div>
        </div>
      </div>
      <div class="col-4">
        <div class="stat-pill" style="background:#f0fff8">
          <div class="small text-muted">📊 Próximo Bônus</div>
          <div class="fw-bold text-success">≈ R$ <?= number_format($binary_bonus_next, 2, ',', '.') ?></div>
        </div>
      </div>
      <div class="col-4">
        <div class="stat-pill" style="background:#fff5f0">
          <div class="small text-muted">🏆 Total Ganho</div>
          <div class="fw-bold">R$ <?= number_format($binary_total_earned, 2, ',', '.') ?></div>
        </div>
      </div>
    </div>

    <div class="alert alert-info rounded-3 small mt-3 mb-0">
      💡 O bônus binário é calculado sobre o <strong>lado mais fraco</strong>. 
      Equilibre sua rede para maximizar os ganhos!
    </div>
  </div>

  <!-- ── Abas ───────────────────────────────────────── -->
  <ul class="nav rede-tabs gap-2 mb-4">
    <li class="nav-item"><a class="nav-link active" href="#arvore" data-bs-toggle="tab">🌳 Árvore Binária</a></li>
    <li class="nav-item"><a class="nav-link" href="#indicados" data-bs-toggle="tab">👥 Indicados</a></li>
    <li class="nav-item"><a class="nav-link" href="#profundidade" data-bs-toggle="tab">📊 Por Nível</a></li>
    <li class="nav-item"><a class="nav-link" href="#bonus-hist" data-bs-toggle="tab">💰 Bônus</a></li>
  </ul>

  <div class="tab-content">

    <!-- ── Árvore Binária Visual ─────────────────────── -->
    <div class="tab-pane fade show active" id="arvore">
      <div class="mlm-card p-4 mb-3">
        <div class="d-flex justify-content-between align-items-center mb-3">
          <h6 class="fw-bold mb-0">🌳 Árvore Binária (3 níveis)</h6>
          <small class="text-muted">⬅️ Esquerda &nbsp;|&nbsp; Direita ➡️</small>
        </div>
        <div class="tree-container" id="binary-tree-container">
          <!-- Árvore renderizada via JS (dados do servidor) -->
          <div class="text-center text-muted py-3">
            <div class="spinner-border spinner-border-sm text-primary me-2"></div>
            Carregando árvore...
          </div>
        </div>
      </div>
    </div>

    <!-- ── Indicados Diretos ─────────────────────────── -->
    <div class="tab-pane fade" id="indicados">
      <div class="mlm-card p-4 mb-3">
        <h6 class="fw-bold mb-3">👥 Indicados Diretos (<?= $directs->num_rows ?>)</h6>

        <?php if ($directs->num_rows === 0): ?>
          <div class="text-center text-muted py-4">
            <div style="font-size:3rem">👥</div>
            <p>Você ainda não tem indicados. <br>Compartilhe seu link abaixo!</p>
          </div>
        <?php else: ?>
          <div class="d-flex flex-column gap-2">
            <?php while ($ref = $directs->fetch_assoc()):
              $initial = strtoupper($ref['firstname'][0]);
            ?>
            <div class="d-flex align-items-center gap-3 referral-row p-2">
              <?php if ($ref['avatar']): ?>
                <img src="<?= validate_image($ref['avatar']) ?>" class="ref-avatar" alt="">
              <?php else: ?>
                <div class="ref-avatar-ph"><?= $initial ?></div>
              <?php endif; ?>
              <div style="flex:1">
                <div class="fw-semibold">
                  <?= htmlspecialchars($ref['firstname']) ?>
                  <?= substr($ref['lastname'],0,1) ?>.
                </div>
                <div class="text-muted" style="font-size:.75rem">
                  <?= date('d/m/Y', strtotime($ref['date_added'])) ?>
                  <?php if ($ref['total_invested']): ?>
                    · R$ <?= number_format($ref['total_invested'],2,',','.') ?> investidos
                  <?php endif; ?>
                </div>
              </div>
              <?php if ($ref['has_plan']): ?>
                <span class="badge rounded-pill" style="background:#f0fff8;color:#00b894;font-size:.7rem">✅ Ativo</span>
              <?php else: ?>
                <span class="badge rounded-pill" style="background:#fff5f0;color:#e17055;font-size:.7rem">⏳ Pendente</span>
              <?php endif; ?>
            </div>
            <?php endwhile; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- ── Profundidade por Nível ────────────────────── -->
    <div class="tab-pane fade" id="profundidade">
      <div class="mlm-card p-4 mb-3">
        <h6 class="fw-bold mb-3">📊 Membros por Nível</h6>
        <?php
          $max_depth_count = max($depth_count ?: [1]);
          $unilevel_rates  = $conn->query("SELECT * FROM unilevel_rates ORDER BY level");
          $rates_arr = [];
          while ($r = $unilevel_rates->fetch_assoc()) $rates_arr[$r['level']] = $r['rate'];
        ?>
        <div class="d-flex flex-column gap-2">
          <?php for ($l = 1; $l <= 10; $l++):
            $cnt  = $depth_count[$l] ?? 0;
            $pct  = $max_depth_count > 0 ? round(($cnt / $max_depth_count) * 100) : 0;
            $rate = $rates_arr[$l] ?? 0;
          ?>
          <div>
            <div class="d-flex justify-content-between small mb-1">
              <span class="fw-semibold">
                Nível <?= $l ?>
                <?php if ($rate > 0): ?>
                  <span class="ms-2 text-success" style="font-size:.7rem">↗ <?= $rate ?>% commissão</span>
                <?php endif; ?>
              </span>
              <span class="fw-bold"><?= $cnt ?> membros</span>
            </div>
            <div class="depth-bar">
              <div class="depth-fill" style="width:<?= $pct ?>%"></div>
            </div>
          </div>
          <?php endfor; ?>
        </div>

        <div class="alert alert-success rounded-3 small mt-3 mb-0">
          🔗 Total da Rede: <strong><?= $total_rede ?> membros</strong>
          · Comissão Unilevel Total: <strong>R$ <?= number_format($unilevel_total,2,',','.') ?></strong>
        </div>
      </div>
    </div>

    <!-- ── Histórico de Bônus ────────────────────────── -->
    <div class="tab-pane fade" id="bonus-hist">
      <div class="mlm-card p-4 mb-3">
        <h6 class="fw-bold mb-3">💰 Bônus Binário Recebidos</h6>
        <?php if ($bonus_history->num_rows === 0): ?>
          <p class="text-muted text-center small py-3">Nenhum bônus recebido ainda.</p>
        <?php else: ?>
          <?php while ($bh = $bonus_history->fetch_assoc()): ?>
          <div class="d-flex justify-content-between align-items-center py-2 border-bottom">
            <div>
              <div class="small fw-semibold">Bônus Binário (<?= $bh['bonus_rate'] ?>%)</div>
              <div class="text-muted" style="font-size:.72rem">
                Base: R$ <?= number_format($bh['weak_side_volume'],2,',','.') ?>
                · <?= date('d/m/Y H:i', strtotime($bh['created_at'])) ?>
              </div>
            </div>
            <div class="fw-bold text-success">+R$ <?= number_format($bh['amount'],2,',','.') ?></div>
          </div>
          <?php endwhile; ?>
        <?php endif; ?>
      </div>

      <div class="mlm-card p-4">
        <h6 class="fw-bold mb-3">🔗 Comissões Unilevel</h6>
        <?php if ($unilevel_history->num_rows === 0): ?>
          <p class="text-muted text-center small py-3">Nenhuma comissão recebida ainda.</p>
        <?php else: ?>
          <?php while ($uc = $unilevel_history->fetch_assoc()): ?>
          <div class="d-flex justify-content-between align-items-center py-2 border-bottom">
            <div>
              <div class="small fw-semibold">
                Comissão Nível <?= $uc['level'] ?>
                <span class="ms-2 text-muted" style="font-size:.7rem">
                  via <?= htmlspecialchars($uc['origem_nome'][0].'***') ?>
                </span>
              </div>
              <div class="text-muted" style="font-size:.72rem">
                <?= $uc['rate'] ?>% sobre R$ <?= number_format($uc['base_amount'],2,',','.') ?>
                · <?= date('d/m/Y H:i', strtotime($uc['created_at'])) ?>
              </div>
            </div>
            <div class="fw-bold text-success">+R$ <?= number_format($uc['commission_amount'],2,',','.') ?></div>
          </div>
          <?php endwhile; ?>
        <?php endif; ?>
      </div>
    </div>

  </div><!-- /tab-content -->

  <!-- ── Link de Indicação ──────────────────────────── -->
  <div class="mlm-card p-4 mt-3" style="background:linear-gradient(135deg,#f8f7ff,#f0eeff)">
    <h6 class="fw-bold mb-2">🔗 Seu Link de Indicação</h6>
    <p class="small text-muted mb-3">Compartilhe e construa sua rede! Você ganha comissões de até 10 níveis.</p>

    <div class="link-box" onclick="copyRefLink()">
      <div class="d-flex align-items-center gap-2">
        <input type="text" class="form-control form-control-sm border-0 bg-transparent fw-semibold"
               id="ref-link-input" value="<?= htmlspecialchars($ref_link) ?>"
               style="font-size:.85rem" readonly onclick="this.select()">
        <button class="btn btn-primary btn-sm rounded-3 fw-bold px-3" type="button">
          Copiar
        </button>
      </div>
    </div>
    <div id="copy-ok" class="text-success small mt-1 text-center" style="display:none">
      ✅ Link copiado!
    </div>

    <div class="d-flex gap-2 mt-3">
      <a href="https://wa.me/?text=<?= urlencode('🤑 Estou ganhando na '.$_settings->info('name').'! Entre pela minha indicação: '.$ref_link) ?>"
         target="_blank" class="btn btn-success btn-sm rounded-3 fw-bold w-100">
        <i class="bi bi-whatsapp"></i> Compartilhar no WhatsApp
      </a>
      <button class="btn btn-outline-primary btn-sm rounded-3" onclick="copyRefLink()">
        <i class="bi bi-clipboard"></i>
      </button>
    </div>
  </div>

</div><!-- /container -->

<script>
// ── Copiar link ─────────────────────────────────────────
function copyRefLink() {
  const el = document.getElementById('ref-link-input');
  el.select(); el.setSelectionRange(0, 99999);
  navigator.clipboard.writeText(el.value).then(() => {
    const ok = document.getElementById('copy-ok');
    ok.style.display='block';
    setTimeout(() => ok.style.display='none', 2500);
  });
}

// ── Renderizar Árvore Binária ───────────────────────────
fetch('/classes/MLM.php?f=get_network')
  .then(r => r.json())
  .then(data => {
    if (!data || data.error) {
      document.getElementById('binary-tree-container').innerHTML = '<p class="text-muted text-center">Rede ainda vazia.</p>';
      return;
    }
    const container = document.getElementById('binary-tree-container');
    container.innerHTML = '';
    container.appendChild(buildTreeHTML(data, true));
  })
  .catch(() => {
    document.getElementById('binary-tree-container').innerHTML = '<p class="text-muted text-center small">Carregue a página novamente.</p>';
  });

function buildTreeHTML(node, isRoot = false) {
  const wrap = document.createElement('div');
  wrap.style.cssText = 'display:flex;flex-direction:column;align-items:center;';

  // Nó atual
  const card = document.createElement('div');
  card.className = 'tree-node-card' + (isRoot ? ' root-node':'');
  const avatarStr = node.avatar
    ? `<img src="${node.avatar}" class="tree-avatar" alt="">`
    : `<div class="tree-avatar-placeholder">${node.name.charAt(0)}</div>`;
  card.innerHTML = `
    ${avatarStr}
    <div class="tree-name">${node.name}</div>
    <div class="tree-label">L: R$${node.left_vol.toFixed(0)} R: R$${node.right_vol.toFixed(0)}</div>`;
  wrap.appendChild(card);

  // Filhos
  if (node.left || node.right) {
    const branchRow = document.createElement('div');
    branchRow.style.cssText = 'display:flex;justify-content:center;width:100%;padding:0 20px;margin-top:2px';

    // Linha central para baixo + galhos
    const lineWrap = document.createElement('div');
    lineWrap.style.cssText = 'display:flex;width:100%;position:relative;height:24px;';
    const vLine = document.createElement('div');
    vLine.style.cssText = 'position:absolute;left:50%;width:2px;height:24px;background:#d0c8f8;transform:translateX(-50%)';
    lineWrap.appendChild(vLine);
    if (node.left && node.right) {
      const hLine = document.createElement('div');
      hLine.style.cssText = 'position:absolute;top:0;left:25%;right:25%;height:2px;background:#d0c8f8;';
      lineWrap.appendChild(hLine);
    }
    wrap.appendChild(lineWrap);

    // Container dos filhos
    const children = document.createElement('div');
    children.style.cssText = 'display:flex;gap:16px;align-items:flex-start;';

    const leftWrap = document.createElement('div');
    leftWrap.style.cssText = 'display:flex;flex-direction:column;align-items:center;';
    const leftBadge = document.createElement('span');
    leftBadge.className = 'side-badge-l mb-1';
    leftBadge.textContent = '⬅️ ESQ';
    leftWrap.appendChild(leftBadge);

    if (node.left) {
      leftWrap.appendChild(buildTreeHTML(node.left));
    } else {
      const empty = document.createElement('div');
      empty.className = 'tree-node-card empty-slot';
      empty.innerHTML = '<div style="font-size:1.5rem">➕</div><div class="tree-name">Vago</div>';
      leftWrap.appendChild(empty);
    }
    children.appendChild(leftWrap);

    const rightWrap = document.createElement('div');
    rightWrap.style.cssText = 'display:flex;flex-direction:column;align-items:center;';
    const rightBadge = document.createElement('span');
    rightBadge.className = 'side-badge-r mb-1';
    rightBadge.textContent = 'DIR ➡️';
    rightWrap.appendChild(rightBadge);

    if (node.right) {
      rightWrap.appendChild(buildTreeHTML(node.right));
    } else {
      const empty = document.createElement('div');
      empty.className = 'tree-node-card empty-slot';
      empty.innerHTML = '<div style="font-size:1.5rem">➕</div><div class="tree-name">Vago</div>';
      rightWrap.appendChild(empty);
    }
    children.appendChild(rightWrap);

    wrap.appendChild(children);
  }

  return wrap;
}
</script>
