<?php
/** AURA FARMING — Etapa 19: partida com câmera segura para menores */
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();
$u = usuarioAtual();
$sessaoId = preg_replace('/[^a-f0-9]/', '', strtolower((string)($_GET['s'] ?? '')));
if (strlen($sessaoId) !== 48) {
    setFlash('error', 'Sessão inválida.');
    header('Location: ' . SITE_URL . '/pages/farmar.php');
    exit;
}
$p = afBuscarPartidaPorSessao($pdo, (int)$u['id'], $sessaoId);
if (!$p) {
    setFlash('error', 'Partida não encontrada.');
    header('Location: ' . SITE_URL . '/pages/farmar.php');
    exit;
}
if(!empty($p['controlled_event_id'])) afMinorPolicyRequire($pdo,'controlled_event_farm',['controlled_event_id'=>(int)$p['controlled_event_id']]); else afRequireAgeFeature($pdo,'farm');
if ($p['status'] === 'finalizada') {
    header('Location: ' . SITE_URL . '/pages/resultado.php?s=' . urlencode($sessaoId));
    exit;
}
if (!in_array($p['status'], ['aguardando','em_andamento'], true)) {
    setFlash('error', 'Esta partida não está mais disponível.');
    header('Location: ' . SITE_URL . '/pages/farmar.php');
    exit;
}
if ((int)$p['dispositivo_id'] !== (int)($_SESSION['device_id'] ?? 0)) {
    setFlash('error', 'A partida foi iniciada em outro dispositivo.');
    header('Location: ' . SITE_URL . '/pages/farmar.php');
    exit;
}
if (!empty($p['batalha_id'])) { try { afValidarBatalhaParaPartida($pdo,(int)$p['batalha_id'],(int)$u['id']); } catch(Throwable $e) { setFlash('error',$e->getMessage()); header('Location: '.SITE_URL.'/pages/arena.php'); exit; } }
if (!empty($p['competicao_id'])) afRequireAgeFeature($pdo,'competition');

$publica = afPartidaPublica($p, $pdo);
$safeCamera = afSafeCameraIssueToken($pdo,$p,(int)$u['id']);
$safeProfile = $safeCamera['profile'];
$safeMinor = !empty($safeProfile['required']);
$safeToken = (string)($safeCamera['token'] ?? '');
$equipamento = afEquipamentoUsuario($pdo,(int)$u['id']);
$iceServers = afWebRtcIceServers();
$pageTitle = 'Farmando Aura';
$showNav = false;
$bodyClass = 'gameplay-body';
$pageScripts = $safeMinor ? [] : [SITE_URL . '/assets/js/live-broadcast.js?v=12.0'];
$pageModuleScripts = [SITE_URL . '/assets/js/farm-game.js?v=22.0'];
$poseModel = is_file(ROOT_PATH . '/assets/models/pose_landmarker_lite.task')
    ? SITE_URL . '/assets/models/pose_landmarker_lite.task'
    : VISION_POSE_MODEL_URL;
$handModel = is_file(ROOT_PATH . '/assets/models/hand_landmarker.task')
    ? SITE_URL . '/assets/models/hand_landmarker.task'
    : VISION_HAND_MODEL_URL;
require_once __DIR__ . '/../includes/header.php';
?>

<main id="farm-game" class="farm-game"
      data-session-id="<?= esc($sessaoId) ?>"
      data-match-id="<?=(int)$p['id']?>"
      data-mode="<?= esc((string)($p['modo'] ?? 'individual')) ?>"
      data-battle-id="<?= (int)($p['batalha_id'] ?? 0) ?>"
      data-competition-id="<?= (int)($p['competicao_id'] ?? 0) ?>"
      data-controlled-event-id="<?= (int)($p['controlled_event_id'] ?? 0) ?>"
      data-initial-aura="<?= esc((string)$publica['aura']) ?>"
      data-time-remaining="<?= (int)$publica['tempo_restante'] ?>"
      data-sequence="<?= (int)$p['ultima_sequencia'] ?>"
      data-status="<?= esc((string)$p['status']) ?>"
      data-public-token="<?= esc((string)$p['public_token']) ?>"
      data-safe-minor="<?= $safeMinor ? '1' : '0' ?>"
      data-safe-token="<?= esc($safeToken) ?>"
      data-safe-blur="<?= !empty($safeProfile['blur_enabled']) ? '1' : '0' ?>"
      data-safe-person-limit="<?= (int)($safeProfile['person_limit'] ?? 1) ?>"
      data-safe-no-person-grace="<?= (int)($safeProfile['no_person_grace_ms'] ?? 1800) ?>"
      data-safe-multiple-grace="<?= (int)($safeProfile['multiple_people_grace_ms'] ?? 700) ?>"
      data-safe-stable-ready="<?= (int)($safeProfile['stable_ready_ms'] ?? 1200) ?>"
      data-safe-lighting="<?= !empty($safeProfile['lighting_check_enabled']) ? '1' : '0' ?>"
      data-safe-lighting-min="<?= (int)($safeProfile['lighting_min_score'] ?? 28) ?>"
      data-safe-lighting-max="<?= (int)($safeProfile['lighting_max_score'] ?? 96) ?>"
      data-safe-additional-face-blur="<?= !empty($safeProfile['additional_face_blur']) ? '1' : '0' ?>"
      data-webrtc="<?= (!$safeMinor && empty($p['controlled_event_id']) && WEBRTC_ENABLED) ? '1' : '0' ?>" data-ice-servers="<?= esc(json_encode($iceServers,JSON_UNESCAPED_SLASHES)) ?>" data-max-viewers="<?= WEBRTC_MAX_VIEWERS ?>"
      data-pose-model="<?= esc($poseModel) ?>"
      data-hand-model="<?= esc($handModel) ?>"
      data-aura-color="<?= esc($equipamento['cor_aura_valor'] ?? '') ?>"
      data-aura-effect="<?= esc($equipamento['efeito_aura_valor'] ?? '') ?>">

  <video id="farm-camera" class="farm-camera" autoplay playsinline muted></video>
  <canvas id="safe-camera-canvas" class="safe-camera-canvas" aria-hidden="true"></canvas>
  <canvas id="motion-canvas" width="64" height="48" hidden></canvas>
  <canvas id="aura-canvas" class="aura-canvas" aria-hidden="true"></canvas>
  <div class="aura-atmosphere" id="aura-atmosphere" aria-hidden="true"><i></i><i></i><i></i></div>
  <canvas id="vision-overlay" class="vision-overlay" aria-hidden="true"></canvas>
  <div class="body-frame" aria-hidden="true"><span></span></div>
  <div class="camera-vignette" aria-hidden="true"></div>
  <div class="aura-field" id="aura-field" aria-hidden="true">
    <span class="aura-ring aura-ring--1"></span><span class="aura-ring aura-ring--2"></span><span class="aura-ring aura-ring--3"></span>
    <span class="aura-core"></span>
  </div>

  <header class="game-hud game-hud--top">
    <button type="button" class="game-exit" id="btn-cancel-match" aria-label="Cancelar partida">✕</button>
    <div class="game-timer" id="game-timer">03:00</div>
    <div class="game-live <?= $safeMinor ? 'game-live--private' : '' ?>"><span></span>
      <?= $safeMinor ? 'SESSÃO PRIVADA' : (!empty($p['batalha_id']) ? 'BATALHA' : (!empty($p['competicao_id']) ? 'EVENTO' : 'AO VIVO')) ?>
      <?php if (!$safeMinor): ?><b id="player-live-viewers"><?= (int)$publica['espectadores'] ?></b><?php endif; ?>
    </div><?php if(!$safeMinor):?><button type="button" class="game-moderation-button" id="btn-live-moderation" aria-label="Moderar espectadores">🛡️</button><?php endif;?>
  </header>

  <div class="ai-status" id="ai-status" data-state="loading"><i></i><span id="ai-status-text">CARREGANDO IA</span></div>
  <div class="pose-state" id="pose-state">PREPARANDO VISÃO COMPUTACIONAL</div>
  <?php if ($safeMinor): ?>
    <div class="safe-camera-badge" id="safe-camera-badge"><span>🛡️</span><strong>CÂMERA SEGURA</strong><small>AMBIENTE PROTEGIDO</small></div>
    <section class="safe-camera-guard" id="safe-camera-guard" aria-live="assertive">
      <div class="safe-camera-guard__icon" id="safe-camera-guard-icon">🛡️</div>
      <strong id="safe-camera-guard-title">VERIFICANDO ENQUADRAMENTO</strong>
      <p id="safe-camera-guard-message">Permaneça sozinho e de frente para a câmera.</p>
      <small>A pontuação fica pausada quando a proteção é acionada.</small>
    </section>
  <?php endif; ?>
  <div class="aura-level-card" id="aura-level-card" data-level="0">
    <small>NÍVEL VISUAL</small><strong id="aura-level-name">AURA LATENTE</strong><span id="aura-level-range">0–100</span>
  </div>

  <section class="game-center-message" id="game-message" aria-live="polite">
    <strong>FARME SUA AURA LIVREMENTE!</strong><span>Faça sua apresentação do seu jeito</span>
  </section>

  <aside class="vision-metrics" aria-label="Métricas da inteligência artificial">
    <div><small>PRECISÃO</small><strong id="metric-precision">0%</strong></div>
    <div><small>FLUIDEZ</small><strong id="metric-fluidity">0%</strong></div>
    <div><small>ORIGINALIDADE</small><strong id="metric-originality">0%</strong></div>
    <div><small>DIFICULDADE</small><strong id="metric-difficulty">0%</strong></div>
  </aside>

  <section class="advanced-combo-hud" id="advanced-combo-hud" data-grade="D">
    <div class="combo-badge" id="combo-badge"><small>COMBO</small><strong id="combo-value">x1</strong></div>
    <div class="combo-chain"><span><small>CORRENTE</small><strong id="combo-hits">0 MOVES</strong></span><span><small>NOTA</small><strong id="combo-grade">D</strong></span></div>
    <div class="combo-energy"><i id="combo-energy-fill"></i></div>
    <div class="combo-rhythm"><span>RITMO</span><b id="combo-rhythm">0%</b></div>
  </section>
  <div class="move-toast" id="move-toast" aria-live="polite"><b>MOVIMENTO RECONHECIDO</b><span>POSE</span></div>
  <div class="sequence-toast" id="sequence-toast" aria-live="assertive"><small>SEQUÊNCIA ESPECIAL</small><strong id="sequence-name">COMBO</strong><span id="sequence-bonus">+0 AURA</span></div>

  <section class="player-social-hud" aria-label="Interações dos espectadores" <?= $safeMinor ? 'hidden' : '' ?>>
    <div><span>👁</span><strong id="player-viewers"><?= (int)$publica['espectadores'] ?></strong><small>ASSISTINDO</small></div>
    <div><span>❤️</span><strong id="player-likes"><?= (int)$publica['likes'] ?></strong><small>LIKES</small></div>
    <div><span>⚡</span><strong id="player-superlikes"><?= (int)$publica['superlikes'] ?></strong><small>SUPER LIKES</small></div>
    <div><span>💎</span><strong id="player-total-score"><?= number_format((float)$publica['pontuacao_total'],2,',','.') ?></strong><small>TOTAL</small></div>
  </section>

  <div class="social-received-toast" id="social-received-toast" aria-live="assertive"></div>
  <?php if(!$safeMinor):?>
  <aside class="live-moderation-panel" id="live-moderation-panel" hidden>
    <header><div><small>ETAPA 22</small><b>Moderar espectadores</b></div><button type="button" id="close-live-moderation">✕</button></header>
    <p>Remova ou bloqueie quem estiver causando problemas na transmissão.</p>
    <div id="live-moderation-viewers" class="live-moderation-viewers"><span>Nenhum espectador conectado.</span></div>
  </aside>
  <?php endif;?>

  <section class="motion-meter" aria-label="Intensidade corporal">
    <div class="motion-meter__header"><span>INTENSIDADE CORPORAL</span><strong id="motion-label">CALIBRANDO</strong></div>
    <div class="motion-meter__track"><span id="motion-fill"></span></div>
  </section>

  <section class="game-hud game-hud--bottom">
    <div class="aura-score-card">
      <div class="aura-score-card__header"><span>AURA ATUAL</span><strong><b id="aura-score"><?= number_format((float)$publica['aura'], 0, ',', '.') ?></b> / 1.000</strong></div>
      <div class="aura-progress"><span id="aura-progress-fill" style="width:<?= min(100, ((float)$publica['aura'] / AURA_MAX) * 100) ?>%"></span></div>
      <div class="score-sync" id="score-sync">Preparando visão computacional…</div>
    </div>
  </section>

  <div class="aura-evolution-overlay" id="aura-evolution-overlay" aria-live="assertive" hidden>
    <span id="aura-evolution-kicker">EVOLUÇÃO DE AURA</span>
    <strong id="aura-evolution-title">AURA DESPERTA!</strong>
    <small id="aura-evolution-subtitle">Sua energia está crescendo</small>
  </div>
  <div class="aura-screen-flash" id="aura-screen-flash" aria-hidden="true"></div>

  <div class="countdown-overlay" id="countdown-overlay" aria-live="assertive"><span id="countdown-number">3</span></div>

  <div class="camera-error-panel" id="camera-error-panel" hidden>
    <span>📷</span><h2>Não foi possível abrir a câmera</h2>
    <p>Autorize a câmera no navegador. Para contas protegidas, a detecção de pessoas e o desfoque local também precisam estar disponíveis.</p>
    <button type="button" class="btn btn-primary" id="btn-retry-camera">TENTAR NOVAMENTE</button>
    <a href="<?= SITE_URL ?>/pages/farmar.php" class="btn btn-secondary">Voltar</a>
  </div>
</main>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
