<?php
// pages/leilao.php — Página individual do leilão ao vivo
// URL: /leilao/{slug}

$slug = $conn->real_escape_string($_GET['id'] ?? '');
$a    = $conn->query(
    "SELECT * FROM auction_list WHERE slug = '$slug'"
)->fetch_assoc();

if (!$a) { include '404.php'; exit(); }

// Estado do timer
$elapsed      = $a['timer_reset_at'] ? time() - strtotime($a['timer_reset_at']) : 0;
$seconds_left = ($a['phase'] == 2) ? max(0, (int)$a['timer_seconds'] - $elapsed)
                                    : (int)$a['timer_seconds'];

// Usuário
$is_logged    = !!$_settings->userdata('id');
$customer_id  = (int)($_settings->userdata('id') ?? 0);
$user_fname   = $_settings->userdata('firstname') ?? '';

// Créditos do usuário
$user_credits = 0;
if ($is_logged) {
    require_once BASE_APP . 'includes/wallet-functions.php';
    $cr = $conn->query("SELECT credits FROM bid_credits WHERE customer_id=$customer_id");
    $user_credits = (int)($cr->fetch_assoc()['credits'] ?? 0);
}

// Lances recentes (15 últimos)
$recent_bids = $conn->query(
    "SELECT b.price_at_bid, b.created_at, b.is_simulated, c.firstname
     FROM auction_bids b
     LEFT JOIN customer_list c ON b.customer_id = c.id
     WHERE b.auction_id = {$a['id']}
     ORDER BY b.created_at DESC LIMIT 15"
);

// Vencedor (se encerrado)
$winner = null;
if ($a['status'] == 3 && $a['winner_id']) {
    $winner = $conn->query("SELECT firstname, lastname FROM customer_list
                             WHERE id = {$a['winner_id']}")->fetch_assoc();
}

// Prova social — feed de "usuários digitando"
$fake_feed = $conn->query("SELECT name, city FROM social_proof_names ORDER BY RAND() LIMIT 10");
$fakes = [];
while ($f = $fake_feed->fetch_assoc()) $fakes[] = $f;
?>

<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800;900&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@700;900&display=swap');

/* ── Layout ─────────────────────────────────────────── */
.leilao-wrap { font-family:'Inter',sans-serif; max-width: 100%; }

/* ── Header do produto ─────────────────────────────── */
.product-hero {
  background: linear-gradient(160deg,#1a1a2e 0%,#16213e 60%,#0f3460 100%);
  border-radius: 20px; overflow: hidden; color: #fff; position: relative;
}
.product-img { width:100%; height:260px; object-fit:cover; opacity:.85; }
.product-overlay {
  position:absolute; bottom:0; left:0; right:0;
  background:linear-gradient(to top,rgba(0,0,0,.9) 0%,transparent 100%);
  padding:1.5rem;
}

/* ── Mega timer ─────────────────────────────────────── */
.mega-timer {
  font-family:'Orbitron',monospace; font-size:3.5rem; font-weight:900;
  letter-spacing: 4px; line-height:1;
  color: #ffd700;
  text-shadow: 0 0 30px rgba(255,215,0,.5), 0 0 60px rgba(255,215,0,.2);
  transition: color .3s;
}
.mega-timer.urgent { color:#e74c3c; text-shadow:0 0 30px rgba(231,76,60,.6); animation: pulse-red .5s infinite; }
@keyframes pulse-red { 0%,100%{opacity:1} 50%{opacity:.7} }

/* ── Preço atual ────────────────────────────────────── */
.current-price-display {
  font-size: 2.4rem; font-weight:900; color:#00cec9;
  text-shadow: 0 0 20px rgba(0,206,201,.4);
  transition: all .3s;
}
.price-bump { animation: price-bump .4s ease; }
@keyframes price-bump { 0%{transform:scale(1)} 50%{transform:scale(1.15)} 100%{transform:scale(1)} }

/* ── Botão de lance ─────────────────────────────────── */
.bid-btn {
  background: linear-gradient(135deg,#6c5ce7 0%,#a29bfe 100%);
  border: none; border-radius: 18px; color: #fff;
  padding: 1.2rem; font-size:1.2rem; font-weight:900;
  letter-spacing:.5px; transition: all .2s;
  box-shadow: 0 8px 24px rgba(108,92,231,.4);
}
.bid-btn:hover:not(:disabled) {
  transform: translateY(-3px);
  box-shadow: 0 14px 32px rgba(108,92,231,.6);
}
.bid-btn:active:not(:disabled) { transform: scale(.97); }
.bid-btn:disabled { opacity:.5; cursor:not-allowed; }

.bid-btn-success { animation: bid-success .6s ease; }
@keyframes bid-success {
  0%{ background:linear-gradient(135deg,#00b09b,#96c93d) }
  100%{ background:linear-gradient(135deg,#6c5ce7,#a29bfe) }
}

/* ── Fase badge ─────────────────────────────────────── */
.fase-badge {
  border-radius:50px; display:inline-block; font-weight:800;
  font-size:.7rem; letter-spacing:1px; padding:5px 16px;
  animation: blink-slow 2s infinite;
}
@keyframes blink-slow { 0%,100%{opacity:1} 50%{opacity:.7} }
.fase-1 { background:rgba(108,92,231,.2); color:#a29bfe; border:1px solid rgba(162,155,254,.4); }
.fase-2 { background:rgba(231,76,60,.2); color:#e74c3c; border:1px solid rgba(231,76,60,.4); }

/* ── Feed de lances ─────────────────────────────────── */
.bids-feed { max-height: 320px; overflow-y:auto; }
.bids-feed::-webkit-scrollbar { width:4px; }
.bids-feed::-webkit-scrollbar-track { background:#f0f0f0; border-radius:4px; }
.bids-feed::-webkit-scrollbar-thumb { background:#6c5ce7; border-radius:4px; }

.bid-item {
  display:flex; align-items:center; gap:.75rem;
  padding:.6rem .75rem; border-radius:10px;
  animation: slide-in .35s ease;
  border-bottom: 1px solid #f0eeff;
}
.bid-item:first-child { background:#f3f0ff; }
@keyframes slide-in { from{opacity:0;transform:translateY(-10px)} to{opacity:1;transform:none} }

.bid-avatar {
  width:34px; height:34px; border-radius:50%;
  background:linear-gradient(135deg,#6c5ce7,#a29bfe);
  display:flex; align-items:center; justify-content:center;
  color:#fff; font-weight:700; font-size:.8rem; flex-shrink:0;
}

/* ── Prova social toast ─────────────────────────────── */
.social-proof-toast {
  position:fixed; bottom:80px; right:16px; z-index:999;
  max-width: 280px;
}
.sp-toast {
  background:#fff; border-radius:12px; padding:.75rem 1rem;
  box-shadow:0 8px 24px rgba(0,0,0,.12); font-size:.82rem;
  border-left:4px solid #6c5ce7;
  animation: toast-slide .4s ease;
}
@keyframes toast-slide { from{opacity:0;transform:translateX(50px)} to{opacity:1;transform:none} }

/* ── Stats bar ──────────────────────────────────────── */
.stats-bar {
  background:rgba(255,255,255,.05); border-radius:14px;
  border:1px solid rgba(255,255,255,.1); backdrop-filter:blur(4px);
}

/* ── Encerrado overlay ──────────────────────────────── */
.ended-overlay {
  background:linear-gradient(135deg,#2d3436,#1a1a2e);
  border-radius:18px; color:#fff; text-align:center; padding:2rem;
}

/* ── Créditos widget ────────────────────────────────── */
.credits-widget {
  background:linear-gradient(135deg,#ffeaa7,#fdcb6e);
  border-radius:14px; padding:1rem;
}
</style>

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

  <!-- ── Título da seção ── -->
  <div class="app-title mb-3">
    <h1>🎯 Leilão ao Vivo</h1>
    <a href="/leiloes" class="app-title-desc text-decoration-none" style="color:#6c5ce7">← Ver todos os leilões</a>
  </div>

  <?php if ($a['status'] == 3): ?>
  <!-- ══ ENCERRADO ════════════════════════════════════ -->
  <div class="ended-overlay mb-4">
    <div style="font-size:4rem">🏆</div>
    <h3 class="fw-bold mt-2">Leilão Encerrado!</h3>
    <h4 class="fw-black" style="color:#ffd700"><?= htmlspecialchars($a['name']) ?></h4>
    <hr style="border-color:rgba(255,255,255,.2)">
    <div class="d-flex justify-content-center gap-5 my-3">
      <div>
        <div class="opacity-75 small">Vencedor</div>
        <div class="fw-bold fs-5">
          🥇 <?= $winner ? htmlspecialchars($winner['firstname'])[0].'***' : 'Anônimo' ?>
        </div>
      </div>
      <div>
        <div class="opacity-75 small">Preço Final</div>
        <div class="fw-bold fs-5" style="color:#ffd700">
          R$ <?= number_format($a['current_price'],2,',','.') ?>
        </div>
      </div>
      <div>
        <div class="opacity-75 small">Total de Lances</div>
        <div class="fw-bold fs-5"><?= number_format($a['total_bids']) ?></div>
      </div>
    </div>
    <div class="small opacity-75">Valor real do produto: R$ <?= number_format($a['real_value'],2,',','.') ?></div>
  </div>

  <?php else: ?>
  <!-- ══ LEILÃO ATIVO ═════════════════════════════════ -->

  <!-- ── Card principal ── -->
  <div class="product-hero mb-3 position-relative">
    <?php if ($a['image_path']): ?>
      <img src="<?= validate_image($a['image_path']) ?>"
           class="product-img" alt="<?= htmlspecialchars($a['name']) ?>">
    <?php else: ?>
      <div class="product-img d-flex align-items-center justify-content-center"
           style="background:linear-gradient(135deg,#6c5ce7,#0f3460)">
        <span style="font-size:5rem">🎁</span>
      </div>
    <?php endif; ?>
    <div class="product-overlay">
      <div class="fase-badge <?= $a['phase']==2 ? 'fase-2':'fase-1' ?> mb-2">
        <?= $a['phase']==2 ? '🔥 FASE REAL — Timer pode zerar!' : '🎭 FASE CRESCIMENTO' ?>
      </div>
      <h2 class="fw-black mb-1"><?= htmlspecialchars($a['name']) ?></h2>
      <div class="small opacity-75">
        Valor real: <strong>R$ <?= number_format($a['real_value'],2,',','.') ?></strong>
        &nbsp;·&nbsp;
        <?= number_format($a['total_bids']) ?> lances dados
      </div>
    </div>
  </div>

  <!-- ── Estadão central: preço + timer ── -->
  <div class="card mb-3" style="background:#1a1a2e;border:none;border-radius:20px;color:#fff">
    <div class="card-body p-4">
      <div class="text-center mb-3">
        <div class="small opacity-60 mb-1">PREÇO ATUAL</div>
        <div class="current-price-display" id="current-price">
          R$ <?= number_format($a['current_price'],2,',','.') ?>
        </div>
      </div>

      <hr style="border-color:rgba(255,255,255,.1)">

      <!-- Timer mega -->
      <div class="text-center">
        <div class="small opacity-60 mb-2">⏱ PRÓXIMO LANCE EM</div>
        <div class="mega-timer" id="mega-timer"
             data-seconds="<?= $seconds_left ?>"
             data-phase="<?= $a['phase'] ?>"
             data-timer="<?= $a['timer_seconds'] ?>">
          <?php $mm=str_pad(floor($seconds_left/60),2,'0',STR_PAD_LEFT);
                $ss=str_pad($seconds_left%60,2,'0',STR_PAD_LEFT); ?>
          <?= $mm ?>:<?= $ss ?>
        </div>
        <?php if ($a['phase'] == 1): ?>
          <div class="small opacity-50 mt-2">🎭 Timer reinicia a cada lance — acumula valor</div>
        <?php else: ?>
          <div class="small mt-2" style="color:#e74c3c">🔥 Fase Real — o timer PODE ZERAR! Último a dar lance VENCE!</div>
        <?php endif; ?>
      </div>

      <!-- Stats bar -->
      <div class="stats-bar d-flex justify-content-around text-center mt-4 p-3">
        <div>
          <div class="small opacity-60">💰 Arrecadado</div>
          <div class="fw-bold" id="stat-revenue">R$ <?= number_format($a['total_revenue'],2,',','.') ?></div>
        </div>
        <div>
          <div class="small opacity-60">⚡ Lances</div>
          <div class="fw-bold" id="stat-bids"><?= number_format($a['total_bids']) ?></div>
        </div>
        <div>
          <div class="small opacity-60">👑 Líder</div>
          <div class="fw-bold" id="stat-leader">Aguardando...</div>
        </div>
      </div>
    </div>
  </div>

  <!-- ── Botão de Lance ── -->
  <?php if ($a['status'] == 2): ?>
  <div class="mb-3">

    <?php if (!$is_logged): ?>
      <a href="/entrar?redirect=/leilao/<?= $a['slug'] ?>"
         class="d-block text-center btn rounded-4 py-3 fw-bold fs-5"
         style="background:linear-gradient(135deg,#6c5ce7,#a29bfe);color:#fff">
        🔑 Faça login para dar lance
      </a>

    <?php elseif ($user_credits < (int)$a['bid_credit_cost']): ?>
      <div class="credits-widget mb-2">
        <div class="fw-bold mb-1">⚠️ Créditos insuficientes</div>
        <div class="small mb-2">Você tem <strong><?= $user_credits ?> crédito(s)</strong>. Lance custa
          <strong><?= $a['bid_credit_cost'] ?> crédito(s)</strong>.</div>
        <a href="/creditos" class="btn w-100 fw-bold rounded-3"
           style="background:#2d3436;color:#fff">⚡ Comprar Créditos</a>
      </div>

    <?php else: ?>
      <!-- Widget de créditos -->
      <div class="d-flex align-items-center justify-content-between mb-2 px-1">
        <span class="small text-muted">⚡ Seus créditos: <strong id="user-credits"><?= $user_credits ?></strong></span>
        <a href="/creditos" class="small text-primary text-decoration-none">+ Comprar mais</a>
      </div>

      <button class="bid-btn w-100" id="btn-bid"
              onclick="placeBid()"
              data-auction="<?= $a['id'] ?>"
              data-cost="<?= $a['bid_credit_cost'] ?>">
        ⚡ DAR LANCE — <?= $a['bid_credit_cost'] ?> crédito(s)
      </button>

      <div id="bid-feedback" class="text-center mt-2 small fw-semibold" style="min-height:24px"></div>
    <?php endif; ?>
  </div>
  <?php endif; ?>

  <!-- ── Feed de Lances ── -->
  <div class="card mb-3" style="border-radius:18px;border:none;box-shadow:0 4px 20px rgba(0,0,0,.07)">
    <div class="card-body p-3">
      <div class="d-flex align-items-center justify-content-between mb-3">
        <h6 class="fw-bold mb-0">⚡ Feed de Lances ao Vivo</h6>
        <div style="width:10px;height:10px;background:#00b894;border-radius:50%;animation:blink-slow 1.5s infinite"></div>
      </div>

      <div class="bids-feed" id="bids-feed">
        <?php
        $first = true;
        while ($bid = $recent_bids->fetch_assoc()):
          $name = $bid['is_simulated']
                ? ($fakes[array_rand($fakes)]['name'] ?? 'Usuário ***')
                : ($bid['firstname'] ? $bid['firstname'][0].'***' : 'Anônimo');
          $initial = strtoupper($name[0]);
        ?>
        <div class="bid-item <?= $first ? '' : '' ?>">
          <div class="bid-avatar"><?= $initial ?></div>
          <div style="flex:1">
            <div class="fw-semibold small"><?= htmlspecialchars($name) ?></div>
            <div class="text-muted" style="font-size:.72rem">
              deu um lance às <?= date('H:i:s', strtotime($bid['created_at'])) ?>
            </div>
          </div>
          <div class="fw-bold small text-primary">
            R$ <?= number_format($bid['price_at_bid'],2,',','.') ?>
          </div>
        </div>
        <?php $first = false; endwhile; ?>
      </div>

      <?php if ($recent_bids->num_rows === 0): ?>
        <p class="text-muted text-center small py-3">Seja o primeiro a dar lance!</p>
      <?php endif; ?>
    </div>
  </div>

  <!-- ── Descrição ── -->
  <?php if ($a['description']): ?>
  <div class="card mb-3" style="border-radius:18px;border:none;box-shadow:0 4px 20px rgba(0,0,0,.07)">
    <div class="card-body p-4">
      <h6 class="fw-bold mb-2">ℹ️ Sobre o Produto</h6>
      <p class="text-muted mb-0"><?= nl2br(htmlspecialchars($a['description'])) ?></p>
    </div>
  </div>
  <?php endif; ?>

  <!-- ── Como funciona (resumo) ── -->
  <div class="card" style="border-radius:18px;border:2px solid #f0eeff;background:#f8f7ff">
    <div class="card-body p-4">
      <h6 class="fw-bold mb-3">🎯 Como funciona o Leilão de Centavos?</h6>
      <div class="d-flex flex-column gap-2">
        <div class="d-flex gap-2 align-items-start">
          <span>1️⃣</span>
          <span class="small">Cada lance custa <strong><?= $a['bid_credit_cost'] ?> crédito(s)</strong> e aumenta o preço em R$ <?= number_format($a['bid_increment'],2,',','.') ?></span>
        </div>
        <div class="d-flex gap-2 align-items-start">
          <span>2️⃣</span>
          <span class="small">Cada lance reinicia o timer para <strong><?= $a['timer_seconds'] ?> segundos</strong></span>
        </div>
        <div class="d-flex gap-2 align-items-start">
          <span>3️⃣</span>
          <span class="small">O <strong>último a dar lance</strong> quando o timer zerar <strong>GANHA o produto!</strong></span>
        </div>
        <div class="d-flex gap-2 align-items-start">
          <span>⚡</span>
          <span class="small">Compre créditos de lance e concorra a produtos incríveis por centavos!</span>
        </div>
      </div>
    </div>
  </div>

  <?php endif; // fim if status != 3 ?>

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

<!-- ── Toast de prova social ── -->
<div class="social-proof-toast" id="sp-toast-container"></div>

<script>
const AUCTION_ID     = <?= $a['id'] ?>;
const AUCTION_STATUS = <?= $a['status'] ?>;
const BID_COST       = <?= $a['bid_credit_cost'] ?>;
<?php if ($is_logged): ?>
let userCredits = <?= $user_credits ?>;
<?php endif; ?>

// ── Mega Timer ─────────────────────────────────────────
const timerEl = document.getElementById('mega-timer');
const priceEl = document.getElementById('current-price');

let timerSecs    = <?= $seconds_left ?>;
let auctionPhase = <?= $a['phase'] ?>;
let auctionStatus = AUCTION_STATUS;

if (timerEl && AUCTION_STATUS == 2) {
  setInterval(() => {
    if (auctionPhase === 2) {
      if (timerSecs > 0) {
        timerSecs--;
        const mm = String(Math.floor(timerSecs/60)).padStart(2,'0');
        const ss = String(timerSecs%60).padStart(2,'0');
        timerEl.textContent = mm + ':' + ss;
      }
      if (timerSecs <= 10) {
        timerEl.classList.add('urgent');
      }
      if (timerSecs <= 0) {
        timerEl.textContent = '00:00';
        showEnded();
      }
    } else {
      // Fase 1: timer é decorativo
      timerEl.textContent = String(<?= $a['timer_seconds'] ?>).padStart(2,'0') + 's ∞';
    }
  }, 1000);
}

// ── Polling do status real (a cada 3s) ─────────────────
let lastBidCount = <?= $a['total_bids'] ?>;
let polling;

if (AUCTION_STATUS == 2) {
  polling = setInterval(() => {
    fetch('/classes/Auction.php?f=get_status&id=' + AUCTION_ID)
      .then(r => r.json())
      .then(d => {
        if (!d || d.error) return;

        // Atualiza preço
        if (priceEl && d.current_price_fmt) {
          if (priceEl.textContent !== d.current_price_fmt) {
            priceEl.textContent = d.current_price_fmt;
            priceEl.classList.add('price-bump');
            setTimeout(() => priceEl.classList.remove('price-bump'), 400);
          }
        }

        // Timer (sincroniza com servidor)
        if (auctionPhase === 2 && typeof d.seconds_left !== 'undefined') {
          timerSecs = d.seconds_left;
        }

        // Fase mudou
        if (d.phase && d.phase !== auctionPhase) {
          auctionPhase = d.phase;
          if (d.phase === 2) showPhaseChange();
        }

        // Stats
        if (d.total_bids) {
          const statBids = document.getElementById('stat-bids');
          if (statBids) statBids.textContent = d.total_bids;
        }
        if (d.total_revenue) {
          const statRev = document.getElementById('stat-revenue');
          if (statRev) statRev.textContent = d.total_revenue;
        }
        if (d.last_bidder_name) {
          const statLeader = document.getElementById('stat-leader');
          if (statLeader) statLeader.textContent = '👑 ' + d.last_bidder_name;
        }

        // Novos lances no feed
        if (d.recent_bids && d.total_bids > lastBidCount) {
          lastBidCount = parseInt(d.total_bids.replace(/\./g,''));
          updateBidFeed(d.recent_bids);
        }

        // Encerrado
        if (d.status == 3) { clearInterval(polling); showEnded(); }
      }).catch(() => {});
  }, 3000);
}

// ── Dar um lance ───────────────────────────────────────
function placeBid() {
  const btn      = document.getElementById('btn-bid');
  const feedback = document.getElementById('bid-feedback');
  if (!btn || btn.disabled) return;

  btn.disabled = true;
  btn.textContent = '⏳ Processando...';
  feedback.textContent = '';

  const fd = new FormData();
  fd.append('auction_id', AUCTION_ID);

  fetch('/classes/Auction.php?f=place_bid', { method:'POST', body: fd })
    .then(r => r.json())
    .then(d => {
      if (d.status === 'success') {
        // Atualiza UI imediatamente
        if (priceEl && d.new_price) {
          priceEl.textContent = d.new_price;
          priceEl.classList.add('price-bump');
          setTimeout(() => priceEl.classList.remove('price-bump'), 400);
        }
        if (d.timer_reset && d.timer_seconds) {
          timerSecs = d.timer_seconds;
          if (timerEl) timerEl.classList.remove('urgent');
        }
        if (typeof d.credits_left !== 'undefined') {
          userCredits = d.credits_left;
          const credEl = document.getElementById('user-credits');
          if (credEl) credEl.textContent = userCredits;
        }
        if (d.phase_changed) showPhaseChange();

        btn.classList.add('bid-btn-success');
        setTimeout(() => btn.classList.remove('bid-btn-success'), 600);
        feedback.style.color = '#00b894';
        feedback.textContent = '✅ Lance dado com sucesso!';

      } else if (d.status === 'no_credits') {
        feedback.style.color = '#e74c3c';
        feedback.textContent = '❌ ' + d.msg;
        setTimeout(() => location.href = '/creditos', 2000);

      } else {
        feedback.style.color = '#e74c3c';
        feedback.textContent = '❌ ' + (d.msg || 'Erro ao dar lance.');
      }

      // Reabilita após 1s (anti-spam)
      setTimeout(() => {
        btn.disabled = false;
        btn.textContent = '⚡ DAR LANCE — ' + BID_COST + ' crédito(s)';
        feedback.textContent = '';
      }, 1200);
    })
    .catch(() => {
      btn.disabled = false;
      btn.textContent = '⚡ DAR LANCE — ' + BID_COST + ' crédito(s)';
      feedback.style.color = '#e74c3c';
      feedback.textContent = '❌ Erro de conexão. Tente novamente.';
    });
}

// ── Atualiza feed de lances ────────────────────────────
function updateBidFeed(bids) {
  const feed = document.getElementById('bids-feed');
  if (!feed || !bids || !bids.length) return;

  bids.slice(0,3).forEach(bid => {
    const div = document.createElement('div');
    div.className = 'bid-item';
    const initial = bid.name.charAt(0).toUpperCase();
    div.innerHTML = `
      <div class="bid-avatar">${initial}</div>
      <div style="flex:1">
        <div class="fw-semibold small">${bid.name}</div>
        <div class="text-muted" style="font-size:.72rem">às ${bid.time}</div>
      </div>
      <div class="fw-bold small text-primary">${bid.price}</div>`;
    feed.insertBefore(div, feed.firstChild);
    if (feed.children.length > 15) feed.removeChild(feed.lastChild);
  });
}

// ── Transição de fase ─────────────────────────────────
function showPhaseChange() {
  const overlay = document.createElement('div');
  overlay.style.cssText = 'position:fixed;inset:0;background:rgba(231,76,60,.85);z-index:9999;display:flex;align-items:center;justify-content:center;flex-direction:column;color:#fff';
  overlay.innerHTML = '<div style="font-size:5rem">🔥</div><h2 style="font-weight:900;letter-spacing:2px">FASE REAL ATIVADA!</h2><p>O timer agora pode zerar. Último a dar lance VENCE!</p>';
  document.body.appendChild(overlay);
  setTimeout(() => overlay.remove(), 3000);
}

// ── Leilão encerrado ──────────────────────────────────
function showEnded() {
  const overlay = document.createElement('div');
  overlay.style.cssText = 'position:fixed;inset:0;background:rgba(26,26,46,.95);z-index:9999;display:flex;align-items:center;justify-content:center;flex-direction:column;color:#fff';
  overlay.innerHTML = '<div style="font-size:5rem">🏆</div><h2 style="font-weight:900">O LEILÃO ENCERROU!</h2><p class="opacity-75">Aguarde para ver o vencedor...</p>';
  document.body.appendChild(overlay);
  setTimeout(() => location.reload(), 3500);
}

// ── Prova social: toasts aleatórios ───────────────────
const fakeData = <?= json_encode(array_map(fn($f) => $f['name'].' ('.$f['city'].')', $fakes)) ?>;
const fakeActions = [
  'acabou de dar um lance!','está acompanhando o leilão','comprou créditos de lance',
  'está no top 5 de lances','deu o último lance'
];

let spIndex = 0;
function showSocialProofToast() {
  const container = document.getElementById('sp-toast-container');
  if (!container) return;

  const name   = fakeData[spIndex % fakeData.length];
  const action = fakeActions[Math.floor(Math.random() * fakeActions.length)];
  spIndex++;

  const toast = document.createElement('div');
  toast.className = 'sp-toast mb-2';
  toast.innerHTML = `🔥 <strong>${name}</strong> ${action}`;
  container.appendChild(toast);
  setTimeout(() => toast.remove(), 4000);
}

if (AUCTION_STATUS == 2) {
  setTimeout(() => {
    showSocialProofToast();
    setInterval(showSocialProofToast, 6000);
  }, 3000);
}
</script>
