<?php require __DIR__.'/auth_guard.php'; ?>
<?php include __DIR__.'/timer_bar.php'; ?>
<?php
// Build absolute URL for assets based on project root (parent of /admin)
if (!function_exists('asset_url')) {
  function asset_url($relPath) {
    $relPath = ltrim((string)$relPath, '/');
    $scriptDir = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/'); // e.g., /roulette-admin-v5/admin
    // project root: remove trailing /admin or /api if present
    $projectRoot = preg_replace('~/(admin|api)$~', '', $scriptDir);
    if ($projectRoot === '') { $projectRoot = '/'; }
    $prefix = ($projectRoot === '/') ? '/' : ($projectRoot . '/');
    return $prefix . $relPath;
  }
}

// admin/nova_roleta.php — Bootstrap 5, layout 100%, assets e segmentos refinados
require __DIR__.'/../db/config.php';

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$roulette = [
  'id' => 0,
  'name' => '',
  'slug' => '',
  'is_active' => 1,
  'force_pattern' => 'none',
  'spin_button_text'=>'GIRAR',
  'wheel_margin_top_desktop' => 0,
  'wheel_margin_bottom_desktop' => 0,
  'wheel_margin_top_mobile' => 0,
  'wheel_margin_bottom_mobile' => 0,
  'hide_title_mobile' => 0,
  'hide_subtitle_mobile' => 0
];

$assets = [
  'music' => null,
  'tick' => null,
  'inicio' => null,
  'ganhou' => null,
  'perdeu' => null,
  'background' => null,
  'background_mobile' => null,
  'background_mobile' => null,
];

$segments = [];

/** Converte caminho salvo no BD em URL correta a partir de /admin */
function media_url(?string $p, int $rid = 0): string {
  if (!$p) return '';
  $p = trim($p);

  // já é URL absoluta ou começa na raiz → retorna
  if (preg_match('~^https?://~i', $p) || str_starts_with($p, '/')) {
    return $p;
  }

  // normaliza variantes com ../ e remove barra inicial
  $p = preg_replace('~^(?:\.\./)+~', '', $p);
  $p = ltrim($p, '/');

  // casos comuns
  if (str_starts_with($p, 'public/')) {
    return '../' . $p; // relativo a /admin
  }
  if (str_starts_with($p, 'uploads/')) {
    return '../public/' . $p; // arquivos públicos ficam em /public/uploads
  }

  // apenas o nome do arquivo? (sem /)
  if (!str_contains($p, '/')) {
    if ($rid > 0) return '../public/uploads/roulette_' . $rid . '/' . $p;
    return '../public/uploads/' . $p;
  }

  // fallback: trate como relativo a /public
  return '../public/' . $p;
}

// Carregar configurações de segurança existentes
$roulette_limits = [];
if ($id > 0) {
  $st = $pdo->prepare("SELECT * FROM roulettes WHERE id=?");
  $st->execute([$id]);
  if ($row = $st->fetch(PDO::FETCH_ASSOC)) $roulette = $row;

  $ASSET_META = [];
  $st = $pdo->prepare("SELECT id, asset_key, file_path, COALESCE(is_muted,0) AS is_muted FROM roulette_assets WHERE roulette_id=?");
  $st->execute([$id]);
  foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $a) {
    $assets[$a['asset_key']] = $a['file_path'];
    $ASSET_META[$a['asset_key']] = [
      'id' => (int)$a['id'],
      'path' => $a['file_path'],
      'is_muted' => (int)$a['is_muted'],
    ];
  }

  $st = $pdo->prepare("SELECT id, roulette_id, segment_order, type, label_primary, label_unit, spin_count, color, weight, game_name, game_url, image_path, image_fit, image_opacity, text_color, text_size, unit_text_size, hide_text_all
                       FROM roulette_segments WHERE roulette_id=? ORDER BY segment_order ASC");
  $st->execute([$id]);
  $segments = $st->fetchAll(PDO::FETCH_ASSOC);

  // Carregar configurações de segurança
  $st = $pdo->prepare("SELECT * FROM roulette_limits WHERE roulette_id = ?");
  $st->execute([$id]);
  $roulette_limits = $st->fetch(PDO::FETCH_ASSOC) ?: [];
}

// Funções para estatísticas
function getSpinCountLast24h(PDO $pdo, int $rouletteId): int {
    $st = $pdo->prepare("SELECT COUNT(*) FROM spin_logs 
                        WHERE roulette_id = ? 
                        AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)");
    $st->execute([$rouletteId]);
    return (int)$st->fetchColumn();
}

function getUniqueUsersLast24h(PDO $pdo, int $rouletteId): int {
    $st = $pdo->prepare("SELECT COUNT(DISTINCT ip_hash) FROM spin_logs 
                        WHERE roulette_id = ? 
                        AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)");
    $st->execute([$rouletteId]);
    return (int)$st->fetchColumn();
}

function getBlockedCountLast24h(PDO $pdo, int $rouletteId): int {
    $st = $pdo->prepare("SELECT COUNT(*) FROM blocked_ips 
                        WHERE roulette_id = ? 
                        AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)");
    $st->execute([$rouletteId]);
    return (int)$st->fetchColumn();
}

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

function asset_badge(?string $current): string {
  if ($current) {
    return '<span class="badge rounded-pill text-bg-secondary ms-2">Atual</span><code class="ms-2 small">'.h($current).'</code>';
  }
  return '<span class="text-muted small ms-2">Nenhum arquivo</span>';
}

/** Renderiza um card de segmento existente */
function segment_row_html(int|string $i, array $s = []): string {
  $order = $s['segment_order'] ?? ($i + 1);
  $type  = strtoupper($s['type'] ?? 'LOSE');
  $lp    = $s['label_primary'] ?? ($type==='WIN' ? '10' : 'TENTE');
  $lu    = $s['label_unit'] ?? ($type==='WIN' ? 'GIROS' : 'NOVAMENTE');
  $spins = ($type==='WIN') ? (int)($s['spin_count'] ?? 10) : 0;
  $color = $s['color'] ?? '#a5b4fc';
  $weight= (int)($s['weight'] ?? 50);
  $game  = $s['game_name'] ?? '';
  $url   = $s['game_url'] ?? '';
  $img   = $s['image_path'] ?? '';
  $fit   = $s['image_fit'] ?? 'cover';
  $op    = (int)($s['image_opacity'] ?? 95);

  // Estilos do texto do segmento
  $text_color     = $s['text_color'] ?? '#ffffff';
  $text_size      = (int)($s['text_size'] ?? 24);
  $unit_text_size = (int)($s['unit_text_size'] ?? 13);

  // NOVO: hide_text_all
  $hide_text_all = (int)($s['hide_text_all'] ?? 0);

  $idHidden   = isset($s['id']) ? '<input type="hidden" name="segments['.$i.'][id]" value="'.h($s['id']).'">' : '';
  $badgeClass = $type==='WIN' ? 'text-bg-success' : 'text-bg-danger';
  $badgeText  = $type==='WIN' ? 'WIN' : 'LOSE';
  $imgUrl     = media_url($img);

  ob_start(); 
  ?>
  <div class="card seg-card mb-4" data-index="<?= $i ?>">
    <?= $idHidden ?>
    <div class="card-header bg-body-tertiary">
      <div class="row g-2 align-items-end">
        <div class="col-3 col-sm-2 col-md-1">
          <label class="form-label form-label-sm mb-1">#</label>
          <input type="number" class="form-control form-control-sm text-center" name="segments[<?= $i ?>][segment_order]" value="<?= h($order) ?>" min="1">
        </div>
        <div class="col-9 col-sm-4 col-md-3">
          <label class="form-label form-label-sm mb-1">Tipo</label>
          <div class="d-flex align-items-center gap-2">
            <select name="segments[<?= $i ?>][type]" class="form-select form-select-sm sel-type" onchange="onTypeChange(this)">
              <option value="LOSE" <?= $type==='LOSE'?'selected':''; ?>>LOSE</option>
              <option value="WIN"  <?= $type==='WIN'?'selected':'';  ?>>WIN</option>
            </select>
            <span class="badge type-badge <?= $badgeClass ?>"><?= $badgeText ?></span>
          </div>
        </div>
        <div class="col-6 col-sm-3 col-md-2">
          <label class="form-label form-label-sm mb-1">Cor</label>
          <input type="color" class="form-control form-control-color p-0" name="segments[<?= $i ?>][color]" value="<?= h($color) ?>">
        </div>
        <div class="col-6 col-sm-3 col-md-2">
          <label class="form-label form-label-sm mb-1">Peso</label>
          <input type="number" class="form-control form-control-sm" name="segments[<?= $i ?>][weight]" min="0" value="<?= h($weight) ?>">
        </div>
        <div class="col-12 col-md text-md-end mt-2 mt-md-0">
          <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeSegment(this)">
            <i class="bi bi-trash"></i> Remover
          </button>
        </div>
      </div>
    </div>

    <div class="card-body">
      <div class="row g-4">
        <!-- Coluna esquerda -->
        <div class="col-lg-7">
          <div class="row g-3">
            <div class="col-sm-4">
              <label class="form-label fw-semibold">Primário</label>
              <input type="text" class="form-control" name="segments[<?= $i ?>][label_primary]" value="<?= h($lp) ?>">
            </div>
            <div class="col-sm-4">
              <label class="form-label fw-semibold">Unidade</label>
              <input type="text" class="form-control" name="segments[<?= $i ?>][label_unit]" value="<?= h($lu) ?>">
            </div>
            <div class="col-sm-4 giros-wrap <?= $type==='WIN'?'':'d-none' ?>">
              <label class="form-label fw-semibold">Giros</label>
              <input type="number" class="form-control" name="segments[<?= $i ?>][spin_count]" min="0" value="<?= h($spins) ?>">
            </div>

            <!-- Toggle: Ocultar texto do seguimento (D+M) -->
            <div class="col-12">
              <div class="form-check form-switch mt-1">
                <input class="form-check-input"
                       type="checkbox"
                       id="seg<?= $i ?>_hide_text_all"
                       name="segments[<?= $i ?>][hide_text_all]"
                       value="1" <?= $hide_text_all ? 'checked' : '' ?>>
                <label class="form-check-label" for="seg<?= $i ?>_hide_text_all">
                  Ocultar texto (D+M)
                </label>
              </div>
            </div>

            <!-- Estilos do texto do segmento -->
            <div class="col-md-4">
              <label class="form-label fw-semibold">Cor do texto</label>
              <input type="color" class="form-control form-control-color p-0" name="segments[<?= $i ?>][text_color]" value="<?= h($text_color) ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label fw-semibold">Tamanho texto (px)</label>
              <input type="number" class="form-control" name="segments[<?= $i ?>][text_size]" min="10" max="40" value="<?= h($text_size) ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label fw-semibold">Tamanho unidade (px)</label>
              <input type="number" class="form-control" name="segments[<?= $i ?>][unit_text_size]" min="8" max="30" value="<?= h($unit_text_size) ?>">
            </div>

            <div class="col-md-6">
              <label class="form-label fw-semibold">Jogo</label>
              <input type="text" class="form-control" name="segments[<?= $i ?>][game_name]" value="<?= h($game) ?>" placeholder="Ex.: Fortune Tiger">
            </div>
            <div class="col-md-6">
              <label class="form-label fw-semibold">URL do jogo</label>
              <input type="text" class="form-control" name="segments[<?= $i ?>][game_url]" value="<?= h($url) ?>" placeholder="https://...">
            </div>
          </div>
        </div>

        <!-- Coluna direita: imagem -->
        <div class="col-lg-5">
          <div class="row g-3">
            <div class="col-12">
              <label class="form-label fw-semibold">Imagem do segmento</label>
              <input type="file" name="segments[<?= $i ?>][image_file]" accept="image/*" class="form-control form-control-sm">
              <input type="hidden" name="segments[<?= $i ?>][image_path_existing]" value="<?= h($img) ?>">
              <div class="form-text"><?= $img ? 'Atual: <code>'.h($img).'</code>' : 'Nenhuma imagem' ?></div>
<?php if (!empty($s['id']) && !empty($img)): ?>
  <div class="mt-2">
    <button type="button"
            class="btn btn-outline-danger btn-sm"
            data-action="segimg-delete"
            data-segid="<?= (int)$s['id'] ?>">
      <i class="bi bi-trash"></i> Excluir imagem do segmento
    </button>
  </div>
<?php endif; ?>

            </div>

            <div class="col-12">
              <div class="ratio ratio-16x9 border rounded bg-dark-subtle d-flex align-items-center justify-content-center overflow-hidden seg-preview-wrap">
                <?php if ($imgUrl): ?>
                  <img src="<?= h($imgUrl) ?>" class="seg-preview" alt=""
                       style="object-fit:<?= h($fit) ?>; width:100%; height:100%; opacity:<?= max(0,min(100,$op))/100 ?>;">
                <?php else: ?>
                  <img src="" class="seg-preview d-none" alt=""
                       style="object-fit:<?= h($fit) ?>; width:100%; height:100%;">
                  <div class="text-muted small">Nenhuma imagem</div>
                <?php endif; ?>
              </div>
            </div>

            <div class="col-7">
              <label class="form-label fw-semibold">Ajuste da imagem</label>
              <select name="segments[<?= $i ?>][image_fit]" class="form-select form-select-sm seg-fit" onChange="applyFit(this)">
                <option value="cover" <?= $fit==='cover' ? 'selected' : '' ?>>Cover</option>
                <option value="contain" <?= $fit==='contain' ? 'selected' : '' ?>>Contain</option>
              </select>
            </div>
            <div class="col-5">
              <label class="form-label fw-semibold">Opacidade (%)</label>
              <input type="range" class="form-range seg-op-range" min="0" max="100" value="<?= h($op) ?>" oninput="applyOpacity(this)">
              <div class="d-flex justify-content-between small text-muted">
                <span>0</span><span class="seg-op-val"><?= h($op) ?></span><span>100</span>
              </div>
              <input type="hidden" class="seg-op-hidden" name="segments[<?= $i ?>][image_opacity]" value="<?= h($op) ?>">
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <?php return ob_get_clean();
}

// ============ GOOGLE FONTS ============
// lista inicial; pode ampliar livremente
// ============ GOOGLE FONTS ============
$GOOGLE_FONTS = [
  // Sans / Geometric
  'Poppins'            => 'wght@400;600;700;800;900',
  'Montserrat'         => 'wght@400;700;800;900',
  'Inter'              => 'wght@400;600;700;800;900',
  'Roboto'             => 'wght@400;500;700;900',
  'Open Sans'          => 'wght@400;600;700;800',
  'Lato'               => 'wght@400;700;900',
  'Nunito'             => 'wght@400;700;800;900',
  'Manrope'            => 'wght@400;600;700;800',
  'Work Sans'          => 'wght@400;600;700;800;900',
  'Urbanist'           => 'wght@400;600;700;800;900',
  'Outfit'             => 'wght@400;600;700;800;900',
  'Lexend'             => 'wght@400;700;800;900',
  'Rubik'              => 'wght@400;600;700;800;900',
  'Jost'               => 'wght@400;600;700;800',
  'DM Sans'            => 'wght@400;500;700',
  'Source Sans 3'      => 'wght@400;600;700;800;900',
  'IBM Plex Sans'      => 'wght@400;600;700',
  'Titillium Web'      => 'wght@400;600;700;900',
  'Heebo'              => 'wght@400;600;700;800;900',
  'Mulish'             => 'wght@400;600;700;800;900',
  'Exo 2'              => 'wght@400;600;700;800;900',
  'Exo'                => 'wght@400;600;700;800;900',
  'Space Grotesk'      => 'wght@400;600;700',
  'Quicksand'          => 'wght@400;600;700',
  'Sora'               => 'wght@400;600;700;800',
  'Outfit'             => 'wght@400;600;700;800;900',
  'Archivo'            => 'wght@400;600;700;800;900',
  'Prompt'             => 'wght@400;600;700;800;900',
  'Kanit'              => 'wght@400;600;700;800;900',
  'Signika'            => 'wght@400;600;700;800',
  'Dosis'              => 'wght@400;600;700;800',
  'Cuprum'             => 'wght@400;600;700;800',
  'Saira'              => 'wght@400;600;700;800;900',
  'Saira Condensed'    => 'wght@400;600;700;800;900',

  // Condensed / Display fortes (bom p/ títulos de roleta)
  'Bebas Neue'         => '',
  'Oswald'             => 'wght@400;600;700',
  'Anton'              => '',
  'Barlow Condensed'   => 'wght@400;600;700;800;900',
  'League Spartan'     => 'wght@400;600;700;800;900',
  'Archivo Black'      => '',
  'Rajdhani'           => 'wght@400;600;700',
  'Teko'               => 'wght@400;600;700',
  'Chakra Petch'       => 'wght@400;600;700',
  'Orbitron'           => 'wght@400;600;700;800',

  // Display impactantes (para campanhas especiais)
  'Alfa Slab One'      => '',
  'Black Ops One'      => '',
  'Bangers'            => '',
  'Paytone One'        => '',
  'Russo One'          => '',
];
$selectedFont = $roulette['font_family'] ?? 'Poppins';

?>
<!DOCTYPE html>
<html lang="pt-BR" data-bs-theme="dark">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Admin - Roleta</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

  <!-- Google Fonts loader (dinâmico) -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link id="gfLink" rel="stylesheet" href="">
<style>
  .page-toolbar{
    position: sticky;
    top: 0;
    z-index: 1000;
    display:flex; align-items:center; justify-content:space-between;
    gap:12px; padding:14px 18px;
    background:rgba(17,24,39,.92);
    color:#e5e7eb;
    border:1px solid rgba(255,255,255,.08);
    border-radius:12px;
    backdrop-filter:blur(6px);
    box-shadow:0 8px 24px rgba(0,0,0,.25);
    margin-bottom:14px;
  }
  .page-toolbar h1{ margin:0; font:900 18px/1.2 system-ui; letter-spacing:.2px; }
  .toolbar-actions{ display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
  .btn{ appearance:none; border:0; cursor:pointer;
       font:700 14px/1 system-ui; padding:10px 14px; border-radius:12px;
       color:#fff; box-shadow:0 8px 20px rgba(0,0,0,.18); transition:transform .08s ease; }
  .btn:active{ transform:translateY(1px) }
  .btn-secondary{ background:#374151 }
  .btn-success{ background:#10b981 }
  .btn-warning{ background:#f59e0b; color:#111827 }
  .btn-primary{ background:#3b82f6 }
  .btn-info{ background:#0ea5e9 }
  /* Mobile tweaks */
  @media (max-width:640px){
    .page-toolbar{ padding:10px 12px; border-radius:10px; gap:8px; }
    .page-toolbar h1{ font-size:16px; }
    .toolbar-actions{ gap:8px; }
    .btn{ padding:9px 10px; font-size:13px; border-radius:10px; }
    .btn span{ display:none; }
  }
</style>
<style>
/* Sticky header like index grid */
.header{
  position:sticky; top:0; z-index:1000;
  backdrop-filter:saturate(140%) blur(10px);
  background:rgba(8,12,22,.65);
  border-bottom:1px solid rgba(255,255,255,.08);
  box-shadow:0 8px 24px rgba(0,0,0,.25);
}
.container{max-width:1200px; margin:0 auto; padding:14px 16px;}
.header .row{display:flex; align-items:center; justify-content:space-between; gap:12px;}
.header .title{margin:0; font:900 18px/1.2 system-ui; letter-spacing:.2px; color:#e5e7eb;}
.toolbar-actions{display:flex; align-items:center; gap:10px; flex-wrap:wrap;}
/* Reuse .btn skins from previous patch */
.btn{ display:inline-flex; align-items:center; justify-content:center; gap:8px;
     padding:10px 14px; border-radius:12px; border:1px solid rgba(255,255,255,.08);
     background:#0f1a2f; color:#e6eefc; cursor:pointer; transition:.2s ease; font-weight:700; }
.btn:hover{transform:translateY(-1px); filter:brightness(1.05)}
.btn:active{ transform:translateY(1px) }
.btn-secondary{ background:#374151 }
.btn-success{ background:#10b981 }
.btn-warning{ background:#f59e0b; color:#111827 }
.btn-info{ background:#0ea5e9 }
@media (max-width:640px){
  .container{padding:10px 12px;}
  .header .title{ font-size:16px; }
  .btn{ padding:9px 10px; font-size:13px; border-radius:10px; }
}
</style>
</head>
<style>
  body{   background:radial-gradient(1200px 600px at 10% -10%, rgba(124,58,237,.25), transparent 60%),
              radial-gradient(1000px 600px at 110% 10%, rgba(37,99,235,.20), transparent 60%),
              linear-gradient(180deg, var(--bg1) 0%, var(--bg2) 100%); }
  .container-narrow{ max-width:1200px }
  .seg-card{ border-color:#22304e }
  .form-label-sm{ font-size:.82rem }
  code{ background:rgba(255,255,255,.05); padding:.05rem .35rem; border-radius:.35rem }
  .asset-title{ font-weight:800; letter-spacing:.02em; }

  /* Preview de fonte */
  .font-preview{
    margin-top:10px; padding:14px 16px; border-radius:12px;
    background:linear-gradient(180deg, rgba(255,255,255,.06), rgba(255,255,255,.02));
    border:1px solid rgba(255,255,255,.12);
  }
  .font-preview .title{
    text-align:center; font-weight:1000; letter-spacing:.18em; text-transform:uppercase;
    font-size:clamp(18px, 2.6vw, 30px); margin:0 0 4px;
  }
  .font-preview .subtitle{
    text-align:center; opacity:.85; font-weight:700;
    font-size:clamp(12px, 1.8vw, 16px); letter-spacing:.05em; margin:0;
  }
</style>
<style>
.cache-alert {
    animation:slideInRight 0.3s ease;
}

@keyframes slideInRight {
    from {
        transform:translateX(100%);
        opacity:0;
    }
    to {
        transform:translateX(0);
        opacity:1;
    }
}

.alert-success {
    background:linear-gradient(135deg, #10b981, #059669);
    border-color:#059669;
    color:white;
}

.alert-danger {
    background:linear-gradient(135deg, #ef4444, #dc2626);
    border-color:#dc2626;
    color:white;
}

.alert-info {
    background:linear-gradient(135deg, #3b82f6, #2563eb);
    border-color:#2563eb;
    color:white;
}
</style>
<script>
function clearCache(rouletteId, type='all') {
    const btn=document.getElementById('clearCacheBtn');
    const originalText=btn.innerHTML;
    
    btn.disabled=true;
    btn.innerHTML='<span class="spinner-border spinner-border-sm" role="status"></span> Limpando...';
    
    const url=`clear_cache.php?id=${rouletteId}&t=${Date.now()}`;
    
    fetch(url, {
        headers: {
            'X-Requested-With':'XMLHttpRequest'
        }
    })
    .then(response=>{
        if(!response.ok) {
            throw new Error('Erro na rede');
        }
        return response.json();
    })
    .then(data=>{
        console.log('Resposta:', data);
        
        if(data.success) {
            // MENSAGEM DE SUCESSO EM VERDE
            showAlert('✅ '+data.message, 'success');
            
            // Opcional: mostrar detalhes
            if(data.arquivo) {
                showAlert('📁 Arquivo: '+data.arquivo, 'info');
            }
            
            // Recarregar após 2 segundos
            setTimeout(()=>{
                window.location.reload();
            }, 2000);
        } else {
            showAlert('❌ '+data.message, 'danger');
        }
    })
    .catch(error=>{
        console.error('Erro:', error);
        showAlert('❌ Erro ao conectar com o servidor', 'danger');
    })
    .finally(()=>{
        btn.disabled=false;
        btn.innerHTML=originalText;
    });
}
// Função para mostrar alertas
function showAlert(message, type='info') {
    // Remover alertas existentes
    const existingAlerts=document.querySelectorAll('.cache-alert');
    existingAlerts.forEach(alert=>alert.remove());
    
    // Ícones para cada tipo
    const icons={
        'success':'✅',
        'danger':'❌',
        'warning':'⚠️',
        'info':'ℹ️'
    };
    
    // Criar novo alerta
    const alert=document.createElement('div');
    alert.className=`alert alert-${type} alert-dismissible fade show cache-alert mt-3`;
    alert.style.cssText=`
        position:fixed;
        top:20px;
        right:20px;
        z-index:9999;
        min-width:300px;
        box-shadow:0 4px 12px rgba(0,0,0,.15);
    `;
    
    alert.innerHTML=`
        <strong>${icons[type] || ''} ${message}</strong>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    // Adicionar à página
    document.body.appendChild(alert);
    
    // Auto-remover após 5 segundos
    setTimeout(()=>{
        if(alert.parentNode) {
            // Efeito de fade out
            alert.style.opacity='0';
            alert.style.transition='opacity 0.5s ease';
            setTimeout(()=>{
                if(alert.parentNode) {
                    alert.remove();
                }
            }, 500);
        }
    }, 5000);
}
// Mostrar mensagem de cache limpo se vier por parâmetro na URL
document.addEventListener('DOMContentLoaded', function() {
    const urlParams=new URLSearchParams(window.location.search);
    if(urlParams.get('cache_cleared')) {
        const message=urlParams.get('message') || 'Cache limpo com sucesso!';
        const type=urlParams.get('cache_cleared')==='1' ? 'success' : 'danger';
        showAlert(type==='success' ? '✅ '+message : '❌ '+message, type);
    }
    
    // Adicionar handler para os dropdown items
    document.querySelectorAll('.dropdown-item[data-type]').forEach(item=>{
        item.addEventListener('click', function(e) {
            e.preventDefault();
            const rouletteId=<?= !empty($roulette['id']) ? (int)$roulette['id'] : 0 ?>;
            const type=this.getAttribute('data-type') || 'all';
            clearCache(rouletteId, type);
        });
    });
});
</script>

<body>
<header class="header" id="pageToolbar">
    <div class="container">
        <div class="card shadow-sm p-3">
            <div class="d-flex align-items-center justify-content-between mb-2">
                <h1 class="h3 m-0"><?= $id ? "Editar roleta" : "Nova roleta" ?></h1>
                <div class="toolbar-actions">
                    <button type="button" id="btnSaveTop" class="btn btn-success">✔ Salvar roleta</button>
                    <?php if (!empty($roulette['id'])): ?>
                    <button type="button" class="btn btn-warning btn-lg ms-2" id="clearCacheBtn"
                    onclick="clearCache(<?= (int)$roulette['id'] ?>, 'all')">
                    <i class="bi bi-arrow-clockwise"></i> Limpar Cache
                    </button>
                    
                    <!-- BOTÃO DE SEGURANÇA - APENAS PARA ROLETAS JÁ CADASTRADAS -->
                    <button type="button" class="btn btn-info btn-lg ms-2" data-bs-toggle="modal" data-bs-target="#securityModal">
                        <i class="bi bi-shield-lock"></i> Segurança
                    </button>
                    <?php endif; ?>
                    
                    <?php
                    // Recupere o slug da roleta (ajuste a origem conforme seu código)
                    $slug=$roulette['slug'];

                    if($slug) {
                        $url='../public/roletas/'.rawurlencode($slug).'.php';
                        echo '<a href="'.htmlspecialchars($url, ENT_QUOTES, 'UTF-8').'" target="_blank" class="btn btn-secondary">↗ Abrir página</a>';
                    } else {
                        echo '<button type="button" class="btn btn-secondary" disabled>↗ Abrir página</button>';
                    }
                    ?>
                    <a href="index.php" class="btn btn-secondary">← Voltar</a>
                </div>
            </div>
        </div>
        </div>
    </div>
</header>

<div class="container py-4">

  <form method="post" action="roleta_salvar.php" enctype="multipart/form-data" id="formRoleta">
    <input type="hidden" name="id" value="<?= h($roulette['id']) ?>">

    <!-- Configurações principais -->
    <div class="card shadow-sm mb-3">
      <div class="card-header fw-bold"><i class="bi bi-gear me-2"></i>Configurações da Roleta</div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">Nome da Roleta</label>
            <input type="text" class="form-control" name="name" value="<?= h($roulette['name']) ?>" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Slug (URL)</label>
            <input type="text" class="form-control" name="slug" value="<?= h($roulette['slug']) ?>" required>
          </div>
          <div class="col-md-4">
            <label class="form-label">Ativa?</label>
            <select class="form-select" name="is_active">
              <option value="1" <?= $roulette['is_active'] ? 'selected' : '' ?>>Sim</option>
              <option value="0" <?= !$roulette['is_active'] ? 'selected' : '' ?>>Não</option>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label">Forçar Padrão</label>
            <select class="form-select" name="force_pattern">
              <option value="none" <?= $roulette['force_pattern']==='none' ? 'selected' : '' ?>>Nenhum</option>
                <option value="L"     <?= $roulette['force_pattern']==='L'?'selected':'' ?>>Sempre perder (L)</option>
                <option value="W"     <?= $roulette['force_pattern']==='W'?'selected':'' ?>>Sempre ganhar (W)</option>
                <option value="LW"    <?= $roulette['force_pattern']==='LW'?'selected':'' ?>>LW</option>
                <option value="WL"    <?= $roulette['force_pattern']==='WL'?'selected':'' ?>>WL</option>
                <option value="LLW"   <?= $roulette['force_pattern']==='LLW'?'selected':'' ?>>LLW</option>
                <option value="LWLW"  <?= $roulette['force_pattern']==='LWLW'?'selected':'' ?>>LWLW</option>
                <option value="LLLW"  <?= $roulette['force_pattern']==='LLLW'?'selected':'' ?>>LLLW</option>
                <option value="WWL"   <?= $roulette['force_pattern']==='WWL'?'selected':'' ?>>WWL</option>
                <option value="LLWLLW"<?= $roulette['force_pattern']==='LLWLLW'?'selected':'' ?>>LLWLLW</option>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label">Texto do Botão Girar</label>
            <input type="text" class="form-control" name="spin_button_text" value="<?= h($roulette['spin_button_text']) ?>">
          </div>
          <div class="col-12">
            <label class="form-label">Subtítulo</label>
            <input type="text" class="form-control" name="subtitle" value="<?= h($roulette['subtitle'] ?? '') ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label fw-semibold">Cor do Pointer</label>
            <input type="color" class="form-control form-control-color p-0" name="pointer_color" value="<?= h($roulette['pointer_color'] ?? '#c3cad6') ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label fw-semibold">Posição do Pointer</label>
            <select name="pointer_position" class="form-select">
              <option value="top"    <?= ($roulette['pointer_position'] ?? '')==='top'    ? 'selected' : '' ?>>Topo</option>
              <option value="right"  <?= ($roulette['pointer_position'] ?? 'right')==='right'  ? 'selected' : '' ?>>Direita</option>
              <option value="bottom" <?= ($roulette['pointer_position'] ?? '')==='bottom' ? 'selected' : '' ?>>Base</option>
              <option value="left"   <?= ($roulette['pointer_position'] ?? '')==='left'   ? 'selected' : '' ?>>Esquerda</option>
            </select>
          </div>
            <!-- Dentro do card "Configurações da Roleta" -->
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label fw-semibold">Estilo do Aro</label>
                    <select class="form-select" name="rim_style" id="rimStyleSelect" onchange="toggleRimStyle()">
                        <option value="gradient" <?= ($roulette['rim_style'] ?? 'gradient')==='gradient' ? 'selected' : '' ?>>Gradiente Metálico</option>
                        <option value="solid" <?= ($roulette['rim_style'] ?? '')==='solid' ? 'selected' : '' ?>>Cor Sólida</option>
                    </select>
                </div>
                
                <div class="col-md-6" id="solidRimColor" style="display:none;">
                    <label class="form-label fw-semibold">Cor Sólida do Aro</label>
                    <input type="color" class="form-control form-control-color p-0" name="rim_solid_color" value="<?= h($roulette['rim_solid_color'] ?? '#3b4356') ?>">
                </div>
            </div>

            <div class="row g-3 mt-2" id="gradientRimColors">
                <div class="col-md-4">
                    <label class="form-label fw-semibold">Cor Clara (Topo)</label>
                    <input type="color" class="form-control form-control-color p-0" name="rim_light_color" value="<?= h($roulette['rim_light_color'] ?? '#c3cad6') ?>">
                </div>
                <div class="col-md-4">
                    <label class="form-label fw-semibold">Cor Média</label>
                    <input type="color" class="form-control form-control-color p-0" name="rim_mid_color" value="<?= h($roulette['rim_mid_color'] ?? '#7b8396') ?>">
                </div>
                <div class="col-md-4">
                    <label class="form-label fw-semibold">Cor Escura (Base)</label>
                    <input type="color" class="form-control form-control-color p-0" name="rim_dark_color" value="<?= h($roulette['rim_dark_color'] ?? '#3b4356') ?>">
                </div>

                <div class="row g-3 mt-2">
                    <div class="col-12">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="disable_inspect" 
                                id="disable_inspect" value="1" <?= ($roulette['disable_inspect'] ?? 0) ? 'checked' : '' ?>>
                            <label class="form-check-label fw-bold" for="disable_inspect">
                                🔒 Desabilitar Console e Inspeção de Código
                            </label>
                            <div class="form-text">
                                Quando ativado: bloqueia botão direito (inspecionar), F12, Ctrl+Shift+I e acesso ao código fonte.
                            </div>
                        </div>
                    </div>
                </div>                
            </div>
        </div>
      </div>
    </div>

    <!-- Margens da Roleta -->
    <div class="card shadow-sm mb-3">
      <div class="card-header fw-bold"><i class="bi bi-arrows-expand me-2"></i>Margens da Roleta</div>
      <div class="card-body">
        
        <!-- Desktop -->
        <h6 class="fw-semibold mb-3">💻 Desktop</h6>
        <div class="row g-3 mb-4">
          <div class="col-md-6">
            <label class="form-label">Margem Superior (px)</label>
            <input type="range" class="form-range" min="0" max="250" step="1" 
                   name="wheel_margin_top_desktop" id="wheel_margin_top_desktop"
                   value="<?= h($roulette['wheel_margin_top_desktop'] ?? 0) ?>"
                   oninput="document.getElementById('wheel_margin_top_desktop_out').value=this.value+'px'">
            <input type="text" readonly class="form-control form-control-sm mt-1" id="wheel_margin_top_desktop_out"
                   value="<?= h(($roulette['wheel_margin_top_desktop'] ?? 0)) ?>px">
          </div>
          <div class="col-md-6">
            <label class="form-label">Margem Inferior (px)</label>
            <input type="range" class="form-range" min="0" max="250" step="1"
                   name="wheel_margin_bottom_desktop" id="wheel_margin_bottom_desktop"
                   value="<?= h($roulette['wheel_margin_bottom_desktop'] ?? 0) ?>"
                   oninput="document.getElementById('wheel_margin_bottom_desktop_out').value=this.value+'px'">
            <input type="text" readonly class="form-control form-control-sm mt-1" id="wheel_margin_bottom_desktop_out"
                   value="<?= h(($roulette['wheel_margin_bottom_desktop'] ?? 0)) ?>px">
          </div>
        </div>

        <!-- Mobile -->
        <h6 class="fw-semibold mb-3">📱 Mobile</h6>
        <div class="row g-3 mb-4">
          <div class="col-md-6">
            <label class="form-label">Margem Superior (px)</label>
            <input type="range" class="form-range" min="0" max="250" step="1"
                   name="wheel_margin_top_mobile" id="wheel_margin_top_mobile"
                   value="<?= h($roulette['wheel_margin_top_mobile'] ?? 0) ?>"
                   oninput="document.getElementById('wheel_margin_top_mobile_out').value=this.value+'px'">
            <input type="text" readonly class="form-control form-control-sm mt-1" id="wheel_margin_top_mobile_out"
                   value="<?= h(($roulette['wheel_margin_top_mobile'] ?? 0)) ?>px">
          </div>
          <div class="col-md-6">
            <label class="form-label">Margem Inferior (px)</label>
            <input type="range" class="form-range" min="0" max="250" step="1"
                   name="wheel_margin_bottom_mobile" id="wheel_margin_bottom_mobile"
                   value="<?= h($roulette['wheel_margin_bottom_mobile'] ?? 0) ?>"
                   oninput="document.getElementById('wheel_margin_bottom_mobile_out').value=this.value+'px'">
            <input type="text" readonly class="form-control form-control-sm mt-1" id="wheel_margin_bottom_mobile_out"
                   value="<?= h(($roulette['wheel_margin_bottom_mobile'] ?? 0)) ?>px">
          </div>
        </div>
        <!-- Ocultar em Desktop -->
        <h6 class="fw-semibold mb-3">👁️ Ocultar em Desktop</h6>
        <div class="row g-3 mb-3">
          <div class="col-md-6">
            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox"
                    name="hide_title_desktop" id="hide_title_desktop"
                    value="1" <?= ($roulette['hide_title_desktop'] ?? 0) ? 'checked' : '' ?>>
              <label class="form-check-label" for="hide_title_desktop">Ocultar Título</label>
            </div>
          </div>
          <div class="col-md-6">
            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox"
                    name="hide_subtitle_desktop" id="hide_subtitle_desktop"
                    value="1" <?= ($roulette['hide_subtitle_desktop'] ?? 0) ? 'checked' : '' ?>>
              <label class="form-check-label" for="hide_subtitle_desktop">Ocultar Subtítulo</label>
            </div>
          </div>
        </div>
        <!-- Ocultar em Mobile -->
        <h6 class="fw-semibold mb-3">👁️ Ocultar em Mobile</h6>
        <div class="row g-3">
          <div class="col-md-6">
            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" name="hide_title_mobile" id="hide_title_mobile" 
                     value="1" <?= ($roulette['hide_title_mobile'] ?? 0) ? 'checked' : '' ?>>
              <label class="form-check-label" for="hide_title_mobile">Ocultar Título</label>
            </div>
          </div>
          <div class="col-md-6">
            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" name="hide_subtitle_mobile" id="hide_subtitle_mobile"
                     value="1" <?= ($roulette['hide_subtitle_mobile'] ?? 0) ? 'checked' : '' ?>>
              <label class="form-check-label" for="hide_subtitle_mobile">Ocultar Subtítulo</label>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Tamanho da roleta -->
    <div class="card shadow-sm mb-3">
      <div class="card-header fw-bold"><i class="bi bi-aspect-ratio me-2"></i>Tamanho da roleta</div>
      <div class="card-body">
        <div class="row align-items-center g-3">
          <div class="col-md-6">
            <label class="form-label">Escala (70% a 100%)</label>
            <input type="range" class="form-range" min="70" max="100" step="1"
                   name="wheel_scale_pct" id="wheel_scale_pct"
                   value="<?= h($roulette['wheel_scale_pct'] ?? 100) ?>"
                   oninput="document.getElementById('wheel_scale_pct_out').value=this.value+'%'">
          </div>
          <div class="col-md-3">
            <label class="form-label">Valor</label>
            <input type="text" readonly class="form-control" id="wheel_scale_pct_out"
                   value="<?= h(($roulette['wheel_scale_pct'] ?? 100)) ?>%">
          </div>
          <div class="col-md-3">
            <div class="form-text">100% = tamanho atual; 70% = menor permitido.</div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Configs de Animação -->
    <div class="card shadow-sm mb-3">
      <div class="card-header fw-bold"><i class="bi bi-arrow-repeat me-2"></i>Animação</div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">Giros na Animação</label>
            <input type="number" class="form-control" name="anim_spins" min="0" max="100" value="<?= h($roulette['anim_spins'] ?? 2) ?>">
            <div class="form-text">0–20 (recomendado: 2).</div>
          </div>
          <div class="col-md-6">
            <label class="form-label">Velocidade (%)</label>
            <input type="number" class="form-control" name="anim_speed" min="20" max="300" value="<?= h($roulette['anim_speed'] ?? 100) ?>">
            <div class="form-text">100 = normal (20–300 recomendado).</div>
          </div>
        </div>
      </div>
    </div>

    <!-- ESTILOS DO TÍTULO E SUBTÍTULO -->
    <div class="card shadow-sm mb-3">
      <div class="card-header fw-bold"><i class="bi bi-palette me-2"></i>Cores, Tamanhos de Fonte e Cor de Fundo - Texto "GIRAR"</div>
      <div class="card-body">
        <div class="row g-3">
    <div class="col-md-6">
        <label class="form-label">Cor do Texto "GIRAR"</label>
        <input type="color" class="form-control form-control-color" name="spin_text_color" 
            value="<?= h($roulette['spin_text_color'] ?? '#ffffff') ?>">
    </div>
    <div class="col-md-6">
        <label class="form-label">Tamanho do Texto "GIRAR" (px)</label>
        <input type="number" class="form-control" name="spin_text_size" min="10" max="40"
            value="<?= h($roulette['spin_text_size'] ?? 24) ?>">
    </div>
    <div class="col-md-6">
        <label class="form-label">Cor da Bolinha "GIRAR"</label>
        <input type="color" class="form-control form-control-color" name="spin_button_color" 
            value="<?= h($roulette['spin_button_color'] ?? '#f59e0b') ?>">
    </div>        
        </div>
      </div>
    </div>

    <!-- ESTILOS DO TÍTULO E SUBTÍTULO -->
    <div class="card shadow-sm mb-3">
      <div class="card-header fw-bold"><i class="bi bi-palette me-2"></i>Cores e Tamanhos de Fonte - Título/Subtítulo</div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">Cor do Título</label>
            <input type="color" class="form-control form-control-color" name="title_color" 
                value="<?= h($roulette['title_color'] ?? '#ffffff') ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label">Tamanho do Título (px)</label>
            <input type="number" class="form-control" name="title_size" min="10" max="60"
                value="<?= h($roulette['title_size'] ?? 30) ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label">Cor do Subtítulo</label>
            <input type="color" class="form-control form-control-color" name="subtitle_color"
                value="<?= h($roulette['subtitle_color'] ?? '#eef3ff') ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label">Tamanho do Subtítulo (px)</label>
            <input type="number" class="form-control" name="subtitle_size" min="10" max="40"
                value="<?= h($roulette['subtitle_size'] ?? 16) ?>">
          </div>
        </div>
      </div>
    </div>

    <!-- FONTE (GOOGLE FONTS) -->
    <div class="card shadow-sm mb-3">
      <div class="card-header fw-bold"><i class="bi bi-type me-2"></i>Fonte Título e Seguimentos (Google Fonts)</div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-6">
            <label for="font_family" class="form-label">Família</label>
            <select name="font_family" id="font_family" class="form-select">
              <?php foreach ($GOOGLE_FONTS as $name=>$weights): ?>
                <option
                  value="<?= h($name) ?>"
                  data-weights="<?= h($weights) ?>"
                  <?= ($selectedFont===$name) ? 'selected' : '' ?>
                ><?= h($name) ?></option>
              <?php endforeach; ?>
            </select>
            <div class="form-text">A fonte escolhida vai ser aplicada no título / subtítulo e nos seguimentos da roleta.</div>
          </div>
          <div class="col-md-6">
            <label class="form-label">Preview</label>
            <div class="font-preview" id="fontPreview">
              <div class="title">TÍTULO DA ROLETA</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- FONTE Subtítulo (GOOGLE FONTS) -->
    <div class="card shadow-sm mb-3">
      <div class="card-header fw-bold"><i class="bi bi-type me-2"></i>Fonte Subtítulo (Google Fonts)</div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-6">
            <label for="font_family" class="form-label">Família</label>
            <select name="font_family-subtitulo" id="font_family" class="form-select">
              <?php foreach ($GOOGLE_FONTS as $name=>$weights): ?>
                <option
                  value="<?= h($name) ?>"
                  data-weights="<?= h($weights) ?>"
                  <?= ($selectedFont===$name) ? 'selected' : '' ?>
                ><?= h($name) ?></option>
              <?php endforeach; ?>
            </select>
            <div class="form-text">A fonte escolhida vai ser aplicada no subtítulo da roleta.</div>
          </div>
          <div class="col-md-6">
            <label class="form-label">Preview</label>
            <div class="font-preview" id="fontPreview">
              <div class="subtitle">Subtítulo de exemplo</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- ASSETS — 100% largura -->
    <div class="card shadow-sm mb-3">
      <div class="card-header asset-title"><i class="bi bi-volume-up me-2"></i>Áudios</div>
      <div class="card-body">
        <div class="mb-3">
          <label class="form-label fw-semibold">Música de Fundo <?= asset_badge($assets['music']) ?></label>
          <input type="file" name="music" class="form-control form-control-sm">
            <?php if (!empty($ASSET_META['music']['path'])):
                $meta=$ASSET_META['music'];
                $muted=(int)($meta['is_muted'] ?? 0)===1;
                $url=asset_url((string)($meta['path'] ?? ''));
            ?>
            <div class="mt-2 border rounded p-2">
            <div class="d-flex justify-content-between align-items-center mb-2">
                <div class="small">MUSICA <?php if ($muted): ?><span class="badge bg-secondary ms-2">Mutado</span><?php endif; ?></div>
            <!-- /* MUSIC PREVIEW v4 */ -->
            <?php if (!empty($ASSET_META['music']['path'])):
            $p=(string)($ASSET_META['music']['path'] ?? '');
            // Constrói URL absoluta da aplicação apontando para /public/uploads/...
            if(preg_match('~^(?:https?:)?//~i', $p)) {
                $url=$p; // já é URL absoluta
            } else {
                $path=ltrim($p, "/\\");                        // remove / inicial se houver
                if(stripos($path, 'uploads/') !==0) {          // garante prefixo uploads/
                $path='uploads/'.$path;
                }
                $appBase=rtrim(dirname(dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/\\'); // ex.: /roulette-admin-v5
                $url=$appBase.'/public/'.$path;
            }
            // MIME inline por extensão (sem dependências)
            $__mime=(function($u){
            $path=parse_url($u, PHP_URL_PATH);
            $ext =strtolower(pathinfo((string)$path, PATHINFO_EXTENSION));
            $map=[
                'mp3'=>'audio/mpeg',
                'wav'=>'audio/wav',
                'ogg'=>'audio/ogg',
                'm4a'=>'audio/mp4',
                'aac'=>'audio/aac',
            ];
            return $map[$ext] ?? 'audio/mpeg';
            })($url);
            $muted=(int)($ASSET_META['music']['is_muted'] ?? 0)===1;
            ?>
            <?php endif; ?>
            <!-- /* /MUSIC PREVIEW v4 */ -->

                <div class="d-flex gap-2">
                <button type="button" class="btn btn-sm btn-danger"
                        data-aid="<?= (int)$meta['id'] ?>"
                        data-action="delete">Excluir</button>
                </div>
            </div>
            <audio controls <?= $muted?'muted':'' ?> preload="none" style="width:100%">
                <source src="<?= htmlspecialchars($url, ENT_QUOTES) ?>" type="audio/mpeg">
                Seu navegador não suporta áudio.
            </audio>
            </div>
            <?php endif; ?>
        </div>

        <div class="mb-3">
          <label class="form-label fw-semibold">Áudio de Ínicio <?= asset_badge($assets['inicio']) ?></label>
          <input type="file" name="inicio" class="form-control form-control-sm">
            <?php if (!empty($ASSET_META['inicio']['path'])):
                $meta=$ASSET_META['inicio'];
                $muted=(int)($meta['is_muted'] ?? 0)===1;
                $url=asset_url((string)($meta['path'] ?? ''));
            ?>
            <div class="mt-2 border rounded p-2">
            <div class="d-flex justify-content-between align-items-center mb-2">
                <div class="small">ÁUDIO DE ÍNICIO <?php if ($muted): ?><span class="badge bg-secondary ms-2">Mutado</span><?php endif; ?></div>
            <!-- /* MUSIC PREVIEW v4 */ -->
            <?php if (!empty($ASSET_META['inicio']['path'])):
            $p=(string)($ASSET_META['inicio']['path'] ?? '');
            // Constrói URL absoluta da aplicação apontando para /public/uploads/...
            if(preg_match('~^(?:https?:)?//~i', $p)) {
                $url=$p; // já é URL absoluta
            } else {
                $path=ltrim($p, "/\\");                        // remove / inicial se houver
                if(stripos($path, 'uploads/') !==0) {          // garante prefixo uploads/
                $path='uploads/'.$path;
                }
                $appBase=rtrim(dirname(dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/\\'); // ex.: /roulette-admin-v5
                $url=$appBase.'/public/'.$path;
            }
            // MIME inline por extensão (sem dependências)
            $__mime=(function($u){
            $path=parse_url($u, PHP_URL_PATH);
            $ext =strtolower(pathinfo((string)$path, PATHINFO_EXTENSION));
            $map=[
                'mp3'=>'audio/mpeg',
                'wav'=>'audio/wav',
                'ogg'=>'audio/ogg',
                'm4a'=>'audio/mp4',
                'aac'=>'audio/aac',
            ];
            return $map[$ext] ?? 'audio/mpeg';
            })($url);
            $muted=(int)($ASSET_META['inicio']['is_muted'] ?? 0)===1;
            ?>
            <?php endif; ?>
            <!-- /* /MUSIC PREVIEW v4 */ -->

                <div class="d-flex gap-2">
                <button type="button" class="btn btn-sm btn-danger"
                        data-aid="<?= (int)$meta['id'] ?>"
                        data-action="delete">Excluir</button>
                </div>
            </div>
            <audio controls <?= $muted?'muted':'' ?> preload="none" style="width:100%">
                <source src="<?= htmlspecialchars($url, ENT_QUOTES) ?>" type="audio/mpeg">
                Seu navegador não suporta áudio.
            </audio>
            </div>
            <?php endif; ?>
        </div>

        <div class="mb-3">
          <label class="form-label fw-semibold">Áudio de Ganhar <?= asset_badge($assets['ganhou']) ?></label>
          <input type="file" name="ganhou" class="form-control form-control-sm">
            <?php if (!empty($ASSET_META['ganhou']['path'])):
                $meta=$ASSET_META['ganhou'];
                $muted=(int)($meta['is_muted'] ?? 0)===1;
                $url=asset_url((string)($meta['path'] ?? ''));
            ?>
            <div class="mt-2 border rounded p-2">
            <div class="d-flex justify-content-between align-items-center mb-2">
                <div class="small">ÁUDIO DE GANHAR <?php if ($muted): ?><span class="badge bg-secondary ms-2">Mutado</span><?php endif; ?></div>
            <!-- /* MUSIC PREVIEW v4 */ -->
            <?php if (!empty($ASSET_META['ganhou']['path'])):
            $p=(string)($ASSET_META['ganhou']['path'] ?? '');
            // Constrói URL absoluta da aplicação apontando para /public/uploads/...
            if(preg_match('~^(?:https?:)?//~i', $p)) {
                $url=$p; // já é URL absoluta
            } else {
                $path=ltrim($p, "/\\");                        // remove / inicial se houver
                if(stripos($path, 'uploads/') !==0) {          // garante prefixo uploads/
                $path='uploads/'.$path;
                }
                $appBase=rtrim(dirname(dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/\\'); // ex.: /roulette-admin-v5
                $url=$appBase.'/public/'.$path;
            }
            // MIME inline por extensão (sem dependências)
            $__mime=(function($u){
            $path=parse_url($u, PHP_URL_PATH);
            $ext =strtolower(pathinfo((string)$path, PATHINFO_EXTENSION));
            $map=[
                'mp3'=>'audio/mpeg',
                'wav'=>'audio/wav',
                'ogg'=>'audio/ogg',
                'm4a'=>'audio/mp4',
                'aac'=>'audio/aac',
            ];
            return $map[$ext] ?? 'audio/mpeg';
            })($url);
            $muted=(int)($ASSET_META['ganhou']['is_muted'] ?? 0)===1;
            ?>
            <?php endif; ?>
            <!-- /* /MUSIC PREVIEW v4 */ -->

                <div class="d-flex gap-2">
                <button type="button" class="btn btn-sm btn-danger"
                        data-aid="<?= (int)$meta['id'] ?>"
                        data-action="delete">Excluir</button>
                </div>
            </div>
            <audio controls <?= $muted?'muted':'' ?> preload="none" style="width:100%">
                <source src="<?= htmlspecialchars($url, ENT_QUOTES) ?>" type="audio/mpeg">
                Seu navegador não suporta áudio.
            </audio>
            </div>
            <?php endif; ?>
        </div>

        <div class="mb-3">
          <label class="form-label fw-semibold">Áudio de Perda <?= asset_badge($assets['perdeu']) ?></label>
          <input type="file" name="perdeu" class="form-control form-control-sm">
            <?php if (!empty($ASSET_META['perdeu']['path'])):
                $meta=$ASSET_META['perdeu'];
                $muted=(int)($meta['is_muted'] ?? 0)===1;
                $url=asset_url((string)($meta['path'] ?? ''));
            ?>
            <div class="mt-2 border rounded p-2">
            <div class="d-flex justify-content-between align-items-center mb-2">
                <div class="small">ÁUDIO DE PERDA <?php if ($muted): ?><span class="badge bg-secondary ms-2">Mutado</span><?php endif; ?></div>
            <!-- /* MUSIC PREVIEW v4 */ -->
            <?php if (!empty($ASSET_META['perdeu']['path'])):
            $p=(string)($ASSET_META['perdeu']['path'] ?? '');
            // Constrói URL absoluta da aplicação apontando para /public/uploads/...
            if(preg_match('~^(?:https?:)?//~i', $p)) {
                $url=$p; // já é URL absoluta
            } else {
                $path=ltrim($p, "/\\");                        // remove / inicial se houver
                if(stripos($path, 'uploads/') !==0) {          // garante prefixo uploads/
                $path='uploads/'.$path;
                }
                $appBase=rtrim(dirname(dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/\\'); // ex.: /roulette-admin-v5
                $url=$appBase.'/public/'.$path;
            }
            // MIME inline por extensão (sem dependências)
            $__mime=(function($u){
            $path=parse_url($u, PHP_URL_PATH);
            $ext =strtolower(pathinfo((string)$path, PATHINFO_EXTENSION));
            $map=[
                'mp3'=>'audio/mpeg',
                'wav'=>'audio/wav',
                'ogg'=>'audio/ogg',
                'm4a'=>'audio/mp4',
                'aac'=>'audio/aac',
            ];
            return $map[$ext] ?? 'audio/mpeg';
            })($url);
            $muted=(int)($ASSET_META['perdeu']['is_muted'] ?? 0)===1;
            ?>
            <?php endif; ?>
            <!-- /* /MUSIC PREVIEW v4 */ -->

                <div class="d-flex gap-2">
                <button type="button" class="btn btn-sm btn-danger"
                        data-aid="<?= (int)$meta['id'] ?>"
                        data-action="delete">Excluir</button>
                </div>
            </div>
            <audio controls <?= $muted?'muted':'' ?> preload="none" style="width:100%">
                <source src="<?= htmlspecialchars($url, ENT_QUOTES) ?>" type="audio/mpeg">
                Seu navegador não suporta áudio.
            </audio>
            </div>
            <?php endif; ?>
        </div>

      </div>
    </div>

    <div class="card shadow-sm mb-3">
      <div class="card-header asset-title"><i class="bi bi-image me-2"></i>Visual</div>
      <div class="card-body">
        <div class="mb-1">
          <label class="form-label fw-semibold">Background da Roleta <?= asset_badge($assets['background']) ?></label>
          <input type="file" name="background" class="form-control form-control-sm">
        </div>
        <div class="mb-1">
            <label class="form-label fw-semibold">Background Mobile (Opcional) <?= asset_badge($assets['background_mobile']) ?></label>
                <input type="file" name="background_mobile" class="form-control form-control-sm">
                <div class="form-text">Imagem de fundo específica para dispositivos móveis. Se não for definida, usará o background normal.</div>
        </div>
      </div>
    </div>
    
    <!-- SEGMENTOS -->
    <div class="card shadow-sm mb-3">
      <div class="card-header d-flex align-items-center justify-content-between">
        <span class="fw-bold">Segmentos</span>
        <button type="button" class="btn btn-primary btn-sm" onclick="addSegment()">
          <i class="bi bi-plus-lg"></i> Adicionar segmento
        </button>
      </div>
      <div class="card-body">
        <div id="segments">
          <?php
            if (!$segments) {
                // 8 segmentos padrão - alternando entre LOSE e WIN
                $defaultSegments = [
                    ['type'=>'LOSE','segment_order'=>1,'label_primary'=>'TENTE','label_unit'=>'NOVAMENTE','spin_count'=>0,'color'=>'#bbf7d0','weight'=>50,'game_name'=>'Perdeu','game_url'=>'','text_color'=>'#ffffff','text_size'=>24,'unit_text_size'=>13,'hide_text_all'=>0],
                    ['type'=>'WIN','segment_order'=>2,'label_primary'=>'10','label_unit'=>'GIROS','spin_count'=>10,'color'=>'#fecdd3','weight'=>50,'game_name'=>'Seu Jogo','game_url'=>'','text_color'=>'#ffffff','text_size'=>24,'unit_text_size'=>13,'hide_text_all'=>0],
                    ['type'=>'LOSE','segment_order'=>3,'label_primary'=>'TENTE','label_unit'=>'NOVAMENTE','spin_count'=>0,'color'=>'#bbf7d0','weight'=>50,'game_name'=>'Perdeu','game_url'=>'','text_color'=>'#ffffff','text_size'=>24,'unit_text_size'=>13,'hide_text_all'=>0],
                    ['type'=>'WIN','segment_order'=>4,'label_primary'=>'20','label_unit'=>'GIROS','spin_count'=>20,'color'=>'#fecdd3','weight'=>50,'game_name'=>'Seu Jogo','game_url'=>'','text_color'=>'#ffffff','text_size'=>24,'unit_text_size'=>13,'hide_text_all'=>0],
                    ['type'=>'LOSE','segment_order'=>5,'label_primary'=>'TENTE','label_unit'=>'NOVAMENTE','spin_count'=>0,'color'=>'#bbf7d0','weight'=>50,'game_name'=>'Perdeu','game_url'=>'','text_color'=>'#ffffff','text_size'=>24,'unit_text_size'=>13,'hide_text_all'=>0],
                    ['type'=>'WIN','segment_order'=>6,'label_primary'=>'30','label_unit'=>'GIROS','spin_count'=>30,'color'=>'#fecdd3','weight'=>50,'game_name'=>'Seu Jogo','game_url'=>'','text_color'=>'#ffffff','text_size'=>24,'unit_text_size'=>13,'hide_text_all'=>0],
                    ['type'=>'LOSE','segment_order'=>7,'label_primary'=>'TENTE','label_unit'=>'NOVAMENTE','spin_count'=>0,'color'=>'#bbf7d0','weight'=>50,'game_name'=>'Perdeu','game_url'=>'','text_color'=>'#ffffff','text_size'=>24,'unit_text_size'=>13,'hide_text_all'=>0],
                    ['type'=>'WIN','segment_order'=>8,'label_primary'=>'50','label_unit'=>'GIROS','spin_count'=>50,'color'=>'#fecdd3','weight'=>50,'game_name'=>'Seu Jogo','game_url'=>'','text_color'=>'#ffffff','text_size'=>24,'unit_text_size'=>13,'hide_text_all'=>0]
                ];
                
                foreach ($defaultSegments as $i => $seg) {
                    echo segment_row_html($i, $seg);
                }
            } else {
                foreach ($segments as $i=>$s) echo segment_row_html($i,$s);
            }
          ?>
        </div>
      </div>
    </div>

    <div class="text-end">
      <button class="btn btn-success btn-lg" type="submit" id="btnSalvarRoleta">
        <i class="bi bi-check-lg"></i> Salvar Roleta
      </button>
      <?php if (!empty($roulette['id'])): ?>
      <button type="button" class="btn btn-warning btn-lg ms-2" id="btnLimparCache"
              onclick="clearCache(<?= (int)$roulette['id'] ?>, 'all')">
        <i class="bi bi-arrow-clockwise"></i> Limpar Cache
      </button>
      
      <!-- BOTÃO DE SEGURANÇA NO RODAPÉ - APENAS PARA ROLETAS CADASTRADAS -->
      <button type="button" class="btn btn-info btn-lg ms-2" data-bs-toggle="modal" data-bs-target="#securityModal">
        <i class="bi bi-shield-lock"></i> Segurança
      </button>
      <?php endif; ?>
      <a href="index.php" class="btn btn-secondary btn-lg ms-2">
        <i class="bi bi-arrow-left"></i> Voltar
      </a>
    </div>
  </form>
</div>

<!-- Modal de Configurações de Segurança -->
<div class="modal fade" id="securityModal" tabindex="-1" aria-labelledby="securityModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="securityModalLabel">
                    <i class="bi bi-shield-lock me-2"></i>Configurações de Segurança - <?= h($roulette['name']) ?>
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="securityForm">
                    <input type="hidden" name="roulette_id" value="<?= $id ?>">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Máximo por Hora</label>
                            <input type="number" class="form-control" name="max_spins_per_hour" 
                                   value="<?= h($roulette_limits['max_spins_per_hour'] ?? 100) ?>">
                            <div class="form-text">Número máximo de giros por hora por IP</div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Máximo por Dia</label>
                            <input type="number" class="form-control" name="max_spins_per_day" 
                                   value="<?= h($roulette_limits['max_spins_per_day'] ?? 500) ?>">
                            <div class="form-text">Número máximo de giros por dia por IP</div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Máximo por Sessão</label>
                            <input type="number" class="form-control" name="max_spins_per_session" 
                                   value="<?= h($roulette_limits['max_spins_per_session'] ?? 50) ?>">
                            <div class="form-text">Número máximo de giros por sessão (1 hora)</div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Cooldown (minutos)</label>
                            <input type="number" class="form-control" name="cooldown_minutes" 
                                   value="<?= h($roulette_limits['cooldown_minutes'] ?? 5) ?>">
                            <div class="form-text">Tempo de espera após exceder limite de sessão</div>
                        </div>
                        
                        <!-- ===== NOVA SEÇÃO: LIMITE TOTAL DE GIROS ===== -->
                        <div class="col-12 mt-4">
                            <h6 class="fw-bold border-bottom pb-2">🎯 Limite Total de Giros por Usuário</h6>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Máximo Total de Giros</label>
                            <input type="number" class="form-control" name="max_total_spins" 
                                   value="<?= h($roulette_limits['max_total_spins'] ?? '') ?>" 
                                   placeholder="Ex: 1000 (deixe vazio para não limitar)">
                            <div class="form-text">Número total de giros permitidos por IP</div>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Período do Limite Total</label>
                            <select name="total_spins_period" class="form-select">
                                <option value="">Sem período (contagem infinita)</option>
                                <option value="day" <?= ($roulette_limits['total_spins_period'] ?? '') == 'day' ? 'selected' : '' ?>>Dia</option>
                                <option value="week" <?= ($roulette_limits['total_spins_period'] ?? '') == 'week' ? 'selected' : '' ?>>Semana</option>
                                <option value="month" <?= ($roulette_limits['total_spins_period'] ?? '') == 'month' ? 'selected' : '' ?>>Mês</option>
                                <option value="forever" <?= ($roulette_limits['total_spins_period'] ?? '') == 'forever' ? 'selected' : '' ?>>Para sempre (contagem infinita)</option>
                            </select>
                            <div class="form-text">Período para reinício da contagem</div>
                        </div>
                        
                        <div class="col-12">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="permanent_block_on_total" 
                                       value="1" <?= ($roulette_limits['permanent_block_on_total'] ?? true) ? 'checked' : '' ?>>
                                <label class="form-check-label fw-bold">Bloqueio permanente ao atingir o limite total</label>
                                <div class="form-text">Se desmarcado, o bloqueio será apenas até o final do período.</div>
                            </div>
                        </div>
                        <!-- ===== FIM DA NOVA SEÇÃO ===== -->
                        
                        <div class="col-12">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="enabled" 
                                       value="1" <?= ($roulette_limits['enabled'] ?? true) ? 'checked' : '' ?>>
                                <label class="form-check-label fw-bold">Habilitar sistema de segurança</label>
                            </div>
                        </div>
                    </div>
                </form>
                
                <!-- Estatísticas de Uso -->
                <?php if ($id > 0): ?>
                <div class="mt-4 p-3 border rounded">
                    <h6 class="fw-bold mb-3">📊 Estatísticas de Uso (Últimas 24h)</h6>
                    <div class="row text-center">
                        <div class="col-md-4">
                            <div class="fw-bold text-primary fs-5"><?= getSpinCountLast24h($pdo, $id) ?></div>
                            <small class="text-muted">Total de Giros</small>
                        </div>
                        <div class="col-md-4">
                            <div class="fw-bold text-warning fs-5"><?= getUniqueUsersLast24h($pdo, $id) ?></div>
                            <small class="text-muted">Usuários Únicos</small>
                        </div>
                        <div class="col-md-4">
                            <div class="fw-bold text-info fs-5"><?= getBlockedCountLast24h($pdo, $id) ?></div>
                            <small class="text-muted">Bloqueios</small>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fechar</button>
                <button type="button" class="btn btn-primary" onclick="saveSecurityConfig()">
                    <i class="bi bi-check-lg"></i> Salvar Configurações
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Template para novo segmento -->
<template id="seg-template">
  <?php
    echo segment_row_html('__INDEX__', [
      'type'=>'WIN',
      'segment_order'=>'__INDEX__',
      'label_primary'=>'10',
      'label_unit'=>'GIROS',
      'spin_count'=>10,
      'color'=>'#bbf7d0',
      'weight'=>50,
      'game_name'=>'',
      'game_url'=>'',
      'image_path'=>'',
      'image_fit'=>'cover',
      'image_opacity'=>95,
      'text_color'=>'#ffffff',
      'text_size'=>24,
      'unit_text_size'=>13,
      'hide_text_all'=>0
    ]);
  ?>
</template>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function qs(s,el=document){ return el.querySelector(s) }
function qsa(s,el=document){ return [...el.querySelectorAll(s)] }

function onTypeChange(sel){
  const card=sel.closest('.seg-card');
  const isWin=sel.value.toUpperCase()==='WIN';
  card.querySelector('.giros-wrap')?.classList.toggle('d-none', !isWin);

  const badge=card.querySelector('.type-badge');
  if(isWin){ badge.textContent='WIN'; badge.className='badge text-bg-success type-badge'; }
  else      { badge.textContent='LOSE'; badge.className='badge text-bg-danger type-badge'; }
}

function removeSegment(btn){
  btn.closest('.seg-card').remove();
  reindexSegments();
}

function addSegment(){
  const tmpl=qs('#seg-template').innerHTML;
  const cont=qs('#segments');
  const i=qsa('.seg-card', cont).length;

  let html=tmpl.replaceAll('segments[__INDEX__]', 'segments['+i+']')
                 .replaceAll('data-index="__INDEX__"', 'data-index="'+i+'"')
                 .replaceAll('value="__INDEX__"', 'value="'+(i+1)+'"'); // 1-based

  cont.insertAdjacentHTML('beforeend', html);
  reindexSegments();

  const card=cont.lastElementChild;
  const sel =card.querySelector('.sel-type'); onTypeChange(sel);
  const fitSel=card.querySelector('.seg-fit'); if(fitSel) applyFit(fitSel);
  const rng   =card.querySelector('.seg-op-range'); if(rng) applyOpacity(rng);
}

function reindexSegments(){
  qsa('#segments .seg-card').forEach((card, idx)=>{
    card.dataset.index=idx;
    qsa('input,select,textarea', card).forEach(el=>{
      if(!el.name) return;
      el.name=el.name.replace(/segments\[\d+\]/g, 'segments['+idx+']');
    });
  });
}

// Preview ao escolher arquivo
document.addEventListener('change', (ev)=>{
  const input=ev.target;
  if(input.matches('input[type=file][name^="segments"][name$="[image_file]"]')) {
    const card=input.closest('.seg-card');
    const img =card.querySelector('.seg-preview');
    const empty=card.querySelector('.seg-preview-wrap .text-muted');
    if(input.files && input.files[0]) {
      img.src=URL.createObjectURL(input.files[0]);
      img.classList.remove('d-none');
      if(empty) empty.classList.add('d-none');
    } else {
      img.src='';
      img.classList.add('d-none');
      if(empty) empty.classList.remove('d-none');
    }
  }
});

// Ajusta object-fit conforme select
function applyFit(sel){
  const card=sel.closest('.seg-card');
  const img =card.querySelector('.seg-preview');
  if(img) img.style.objectFit=sel.value || 'cover';
}

// Slider de opacidade sincronizado
function applyOpacity(range){
  const card=range.closest('.seg-card');
  const img =card.querySelector('.seg-preview');
  const val =Math.max(0, Math.min(100, parseInt(range.value||'0',10)));
  const out =card.querySelector('.seg-op-val');
  const hid =card.querySelector('.seg-op-hidden');
  if(img) img.style.opacity=val/100;
  if(out) out.textContent=val;
  if(hid) hid.value=val;
}

// inicializa existentes
qsa('#segments .seg-card').forEach(card=>{
  const sel=card.querySelector('.sel-type'); onTypeChange(sel);
  const fitSel=card.querySelector('.seg-fit'); if(fitSel) applyFit(fitSel);
  const rng=card.querySelector('.seg-op-range'); if(rng) applyOpacity(rng);
});

// título da aba
document.title=<?= json_encode(($roulette['name'] ?: 'Roleta')) ?>+' - Admin';

/* ===== Google Fonts – dinâmica ===== */
(function(){
  const select =document.getElementById('font_family');
  const linkEl =document.getElementById('gfLink');
  const preview=document.getElementById('fontPreview');

  function toParamFamily(name){ return String(name).trim().replace(/\s+/g, '+'); }
  function buildHref(name, weights){
    const fam=toParamFamily(name);
    const w  =(weights && weights.trim()) ? ':'+weights.trim() : '';
    return `https://fonts.googleapis.com/css2?family=${fam}${w}&display=swap`;
  }
  function applyFont(name, weights){
    linkEl.href=buildHref(name, weights);
    preview.style.fontFamily=`'${name}', system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif`;
  }

  select?.addEventListener('change', function(){
    const name   =this.value;
    const weights=this.options[this.selectedIndex].dataset.weights || '';
    applyFont(name, weights);
  });

  // init com valor vindo do PHP
  if(select) {
    const opt=select.options[select.selectedIndex];
    applyFont(opt.value, opt.dataset.weights || '');
  }
})();

// ===== Inicializar sliders de margem =====
document.addEventListener('DOMContentLoaded', function() {
    // Inicializar displays dos sliders
    const sliders=[
        'wheel_margin_top_desktop', 'wheel_margin_bottom_desktop',
        'wheel_margin_top_mobile', 'wheel_margin_bottom_mobile'
    ];
    
    sliders.forEach(sliderId=>{
        const slider=document.getElementById(sliderId);
        const output=document.getElementById(sliderId+'_out');
        if(slider && output) {
            output.value=slider.value+'px';
        }
    });
});
</script>

<script>
function saveSecurityConfig() {
    const form = document.getElementById('securityForm');
    if (!form) {
        console.error('Formulário de segurança não encontrado');
        showAlert('❌ Erro: Formulário não encontrado', 'danger');
        return;
    }

    const formData = new FormData(form);
    const submitBtn = document.querySelector('#securityModal .btn-primary');
    
    if (!submitBtn) {
        console.error('Botão de submit não encontrado');
        showAlert('❌ Erro: Botão não encontrado', 'danger');
        return;
    }

    // Validações básicas
    const rouletteId = formData.get('roulette_id');
    if (!rouletteId || rouletteId <= 0) {
        showAlert('❌ ID da roleta inválido', 'danger');
        return;
    }

    // Feedback visual
    const originalText = submitBtn.innerHTML;
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> Salvando...';

    // Log para debugging
    console.log('🔒 Enviando configurações de segurança...', {
        roulette_id: rouletteId,
        max_hour: formData.get('max_spins_per_hour'),
        max_day: formData.get('max_spins_per_day'),
        max_session: formData.get('max_spins_per_session'),
        cooldown: formData.get('cooldown_minutes'),
        max_total: formData.get('max_total_spins'),
        total_period: formData.get('total_spins_period'),
        permanent_block: formData.get('permanent_block_on_total'),
        enabled: formData.get('enabled')
    });

    fetch('roleta_security_save.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('🔒 Resposta do servidor:', data);
        
        if (data.ok) {
            const action = data.action || 'salvas';
            const message = data.message || `Configurações de segurança ${action} com sucesso!`;
            showAlert(`${message}`, 'success');
            
            // Fecha o modal - método compatível com Bootstrap 5
            const modalElement = document.getElementById('securityModal');
            if (modalElement) {
                const modal = bootstrap.Modal.getInstance(modalElement);
                if (modal) {
                    modal.hide();
                } else {
                    // Fallback se não encontrar a instância
                    modalElement.classList.remove('show');
                    modalElement.style.display = 'none';
                    document.body.classList.remove('modal-open');
                    const backdrop = document.querySelector('.modal-backdrop');
                    if (backdrop) backdrop.remove();
                }
            }
            
        } else {
            const errorMsg = data.message || 'Erro desconhecido ao salvar configurações';
            showAlert(`❌ ${errorMsg}`, 'danger');
        }
    })
    .catch(error => {
        console.error('❌ Erro completo:', error);
        showAlert('Erro de conexão ao salvar configurações. Verifique o console.', 'danger');
    })
    .finally(() => {
        // Restaura o botão
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    });
}
</script>

    <script>
      function _postAdminAction(url, params) {
        var form=document.createElement('form');
        form.method='POST';
        form.action=url;
        for(var k in params) {
          if(!params.hasOwnProperty(k)) continue;
          var input=document.createElement('input');
          input.type='hidden'; input.name=k; input.value=params[k];
          form.appendChild(input);
        }
        document.body.appendChild(form);
        form.submit();
      }
      document.addEventListener('click', function(ev){
        var btn=ev.target.closest('button[data-action]');
        if(!btn) return;
        var aid=btn.getAttribute('data-aid');
        var ridInput=document.querySelector('input[name="id"]');
        var rid=ridInput ? ridInput.value : '';
        var action=btn.getAttribute('data-action');
        if(action==='toggle-mute'){
          var muted=btn.getAttribute('data-muted')==='1' ? 0 : 1;
          if(!confirm(muted? 'Mutar este áudio?' : 'Desmutar este áudio?')) return;
          _postAdminAction('roulette_asset_toggle_mute.php', {asset_id: aid, roulette_id: rid, muted: muted});
        } else if(action==='delete'){
          if(!confirm('Excluir este áudio? Esta ação não pode ser desfeita.')) return;
          _postAdminAction('roulette_asset_delete.php', {asset_id: aid, roulette_id: rid});
        }
      });
    </script>
    
<script>
document.addEventListener('play', function (e) {
  if(e.target.tagName !== 'AUDIO') return;
  document.querySelectorAll('audio').forEach(function(a){
    if(a !== e.target) a.pause();
  });
}, true);
</script>
<script>
function toggleRimStyle() {
    const style=document.getElementById('rimStyleSelect').value;
    document.getElementById('solidRimColor').style.display=style==='solid' ? 'block' : 'none';
    document.getElementById('gradientRimColors').style.display=style==='gradient' ? 'block' : 'none';
}

// Inicializar on load
document.addEventListener('DOMContentLoaded', toggleRimStyle);
</script>
<script>
document.addEventListener('click', async (ev)=>{
  const btn=ev.target.closest('[data-action="segimg-delete"]');
  if(!btn) return;
  const segId=btn.getAttribute('data-segid');
  if(!segId) return;
  if(!confirm('Excluir a imagem deste segmento?')) return;
btn.disabled=true;
try {
  const res=await fetch('roulette_segment_image_delete.php', {
    method:'POST',
    credentials:'same-origin',
    headers: {
      'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
      'Accept':'application/json',
      'X-Requested-With':'XMLHttpRequest'
    },
    body: new URLSearchParams({ segment_id: segId })
  });

  const text=await res.text();
  let json;
  try { json=JSON.parse(text); }
  catch (e) {
    throw new Error('Resposta não-JSON do servidor: '+text.slice(0, 180));
  }

  if(!res.ok || !json.ok) {
    throw new Error(json?.error || ('HTTP '+res.status));
  }

  // Atualiza UI: zera hidden, limpa preview e remove o botão
  const card=btn.closest('.seg-card');
  if(card) {
    const hid=card.querySelector('input[name^="segments"][name$="[image_path_existing]"]');
    if(hid) hid.value='';
    const img=card.querySelector('.seg-preview');
    const empty=card.querySelector('.seg-preview-wrap .text-muted');
    if(img) { img.src=''; img.classList.add('d-none'); }
    if(empty) empty.classList.remove('d-none');
  }
  btn.remove();
  alert('Imagem excluída com sucesso!');
} catch(err) {
  console.error(err);
  alert('Erro ao excluir: '+(err && err.message ? err.message : err));
} finally {
  btn.disabled=false;
}
});
</script>

<script>
(function(){
  const btnSaveBottom =document.querySelector('#btnSalvarRoleta, .js-salvar-roleta, button[name="salvar_roleta"]');
  const btnCacheBottom=document.querySelector('#btnLimparCache, .js-limpar-cache, button[name="limpar_cache"]');
  const formRoleta    =document.getElementById('formRoleta');
  const btnSaveTop    =document.getElementById('btnSaveTop');
  const btnClearTop   =document.getElementById('btnClearCacheTop');

  btnSaveTop?.addEventListener('click', function(){
    if(btnSaveBottom) { btnSaveBottom.click(); return; }
    if(formRoleta && typeof formRoleta.requestSubmit==='function') formRoleta.requestSubmit();
    else if(formRoleta) formRoleta.submit();
    else { console.warn('[nova_roleta] Formulário não encontrado.'); alert('Formulário da roleta não encontrado.'); }
  });

  btnClearTop?.addEventListener('click', async function(){
    if(btnCacheBottom) { btnCacheBottom.click(); return; }
    try{
      const roletaId=(document.getElementById('roleta_id')?.value) || (new URLSearchParams(location.search).get('id'));
      const url=(window.CLEAR_CACHE_ENDPOINT) ? window.CLEAR_CACHE_ENDPOINT
                : ('../api/clear_cache.php'+(roletaId ? ('?roleta='+encodeURIComponent(roletaId)) : ''));
      const resp=await fetch(url, { method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'} });
      if(!resp.ok) throw new Error('HTTP '+resp.status);
      alert('Cache limpo com sucesso!');
    }catch(e){
      alert('Não foi possível limpar o cache. Verifique a rota/servidor.');
    }
  });
})();
</script>
</body>
</html>