<?php
/** AURA FARMING — Etapa 6: modo espectador */
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/match_functions.php';
requireLogin();
afRequireAgeFeature($pdo,'live');
$u=usuarioAtual();
$token=preg_replace('/[^a-f0-9]/','',strtolower((string)($_GET['s'] ?? '')));
$p=afBuscarPartidaPublicaPorToken($pdo,$token,false,(int)$u['id']);
if(!$p){setFlash('error','Transmissão não encontrada.');header('Location: '.SITE_URL.'/pages/ao_vivo.php');exit;}
afRegistrarPresencaEspectador($pdo,$p,(int)$u['id'],(int)($_SESSION['device_id'] ?? 0));
$estado=afEstadoEspectador($pdo,$p,(int)$u['id']);
$iceServers=afWebRtcIceServers();
$pageTitle='Assistindo '.$p['nome'];$showNav=false;$bodyClass='spectator-body';
$pageStyles=[SITE_URL.'/assets/css/diamonds-reactions.css?v=6.0'];
$pageScripts=[SITE_URL.'/assets/js/spectator.js?v=23.6'];
require_once __DIR__ . '/../includes/header.php';
?>
<main id="spectator-app" class="spectator-app" data-token="<?= esc($token) ?>" data-is-owner="<?= (int)$p['usuario_id']===(int)$u['id'] ? '1' : '0' ?>" data-status="<?= esc((string)$p['status']) ?>" data-webrtc="<?= WEBRTC_ENABLED ? '1' : '0' ?>" data-ice-servers="<?= esc(json_encode($iceServers,JSON_UNESCAPED_SLASHES)) ?>" data-max-viewers="<?= WEBRTC_MAX_VIEWERS ?>" data-owner-id="<?=(int)$p['usuario_id']?>" data-viewer-id="<?=(int)$u['id']?>" data-match-id="<?=(int)$p['id']?>" data-comments-enabled="<?=!empty($estado['comments_enabled'])?'1':'0'?>">
  <video id="spectator-video" class="spectator-video" autoplay playsinline muted></video>
  <div class="spectator-placeholder" id="spectator-placeholder"><div class="spectator-energy-avatar"><img src="<?= esc($estado['jogador']['avatar']) ?>" alt=""><i></i><i></i><i></i></div><strong>CONECTANDO À CÂMERA AO VIVO…</strong><span>Os dados da partida já estão sincronizados.</span></div>
  <div class="spectator-vignette"></div><div class="spectator-particles"></div>
  <header class="spectator-topbar"><a href="<?= SITE_URL ?>/pages/ao_vivo.php" class="spectator-close">✕</a><div class="spectator-live"><i></i> AO VIVO</div><div class="spectator-count">👁 <b id="live-viewers"><?= (int)$estado['espectadores'] ?></b></div></header>
  <section class="spectator-player"><img src="<?= esc($estado['jogador']['avatar']) ?>" alt=""><div><h1 id="live-name"><?= esc($estado['jogador']['nome']) ?></h1><span><?= esc($estado['jogador']['aura_id']) ?> • <?= esc($estado['jogador']['titulo']) ?></span></div></section>
  <section class="spectator-score-panel">
    <div class="spectator-timer" id="live-timer"><?= gmdate('i:s',(int)$estado['tempo_restante']) ?></div>
    <div class="spectator-aura-head"><span>AURA DO JOGADOR</span><strong><b id="live-aura"><?= number_format((float)$estado['aura'],0,',','.') ?></b> / 1.000</strong></div>
    <div class="spectator-progress"><i id="live-progress" style="width:<?= min(100,((float)$estado['aura']/AURA_MAX)*100) ?>%"></i></div>
    <div class="spectator-stats"><div><span>❤️</span><b id="live-likes"><?= (int)$estado['likes'] ?></b><small>LIKES</small></div><div><span>⚡</span><b id="live-superlikes"><?= (int)$estado['superlikes'] ?></b><small>SUPER LIKES</small></div><div><span>💎</span><b id="live-total"><?= number_format((float)$estado['pontuacao_total'],2,',','.') ?></b><small>TOTAL</small></div><div><span>🔥</span><b id="live-combo">x<?= (int)$estado['combo_atual'] ?> • <?= (int)($estado['combo_hits_atual']??0) ?></b><small>COMBO</small></div></div>
  </section>
  <?php $diamondCosts=$estado['diamond_reactions']??['like'=>['diamonds'=>2,'aura'=>2,'xp'=>5],'superlike'=>['diamonds'=>10,'aura'=>15,'xp'=>25]]; $diamondBalance=(int)($estado['diamond_balance']??0); ?>
  <section class="spectator-actions spectator-actions--diamonds">
    <div class="spectator-diamond-balance">💎 Seu saldo: <b id="viewer-diamonds"><?=number_format($diamondBalance,0,',','.')?></b> Diamantes</div>
    <button type="button" id="btn-like" class="spectator-action spectator-action--like" data-cost="<?=(int)$diamondCosts['like']['diamonds']?>" <?= !$estado['pode_interagir']||$estado['interacoes_usuario']['like']?'disabled':'' ?>><span>❤️</span><b>LIKE</b><small><?=(int)$diamondCosts['like']['diamonds']?> 💎 • +<?=number_format((float)$diamondCosts['like']['aura'],0,',','.')?> Aura • +<?=(int)$diamondCosts['like']['xp']?> XP</small></button>
    <button type="button" id="btn-superlike" class="spectator-action spectator-action--super" data-cost="<?=(int)$diamondCosts['superlike']['diamonds']?>" <?= !$estado['pode_interagir']||$estado['interacoes_usuario']['superlike']?'disabled':'' ?>><span>⚡</span><b>SUPER LIKE</b><small><?=(int)$diamondCosts['superlike']['diamonds']?> 💎 • +<?=number_format((float)$diamondCosts['superlike']['aura'],0,',','.')?> Aura • +<?=(int)$diamondCosts['superlike']['xp']?> XP</small></button>
    <a class="spectator-buy-diamonds" href="<?=SITE_URL?>/pages/comprar-diamantes.php">Comprar Diamantes</a>
  </section>
  <?php if((int)$p['usuario_id']!==(int)$u['id']):?>
  <section class="spectator-safety-actions">
    <a href="<?=SITE_URL?>/pages/denunciar.php?tipo=transmission&partida=<?=(int)$p['id']?>&usuario=<?=(int)$p['usuario_id']?>">🚩 Denunciar transmissão</a>
    <button type="button" id="btn-block-live-user">🛡️ Bloquear jogador</button>
  </section>
  <?php endif;?>
  <section class="spectator-comments" id="spectator-comments" <?=empty($estado['comments_enabled'])?'hidden':''?>>
    <header><b>Comentários</b><span>Protegidos por moderação</span></header>
    <div class="spectator-comment-list" id="spectator-comment-list"></div>
    <form id="spectator-comment-form" autocomplete="off"><input id="spectator-comment-input" maxlength="500" placeholder="Escreva um comentário seguro"><button type="submit">ENVIAR</button></form>
  </section>
  <div class="spectator-toast" id="spectator-toast"></div>
  <section class="spectator-ended" id="spectator-ended" hidden><div>🏁</div><h2>A FARMADA TERMINOU!</h2><p>Pontuação final: <strong id="ended-score">0</strong></p><a href="<?= SITE_URL ?>/pages/ao_vivo.php" class="btn btn-primary">VER OUTRAS FARMADAS</a></section>
</main>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
