<?php
$title='Elegir avatar';
require_once __DIR__ . '/../inc/header.php';

$styles = [
  'adventurer', 'adventurer-neutral', 'avataaars', 'avataaars-neutral',
  'bottts', 'bottts-neutral', 'big-smile', 'croodles', 'croodles-neutral',
  'fun-emoji', 'icons', 'identicon', 'lorelei', 'lorelei-neutral',
  'micah', 'miniavs', 'notionists', 'notionists-neutral',
  'open-peeps', 'personas', 'pixel-art', 'pixel-art-neutral',
  'rings', 'thumbs'
];

$me = current_user();
$pdo = db();

// Guardar selección
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $style = trim($_POST['style'] ?? 'adventurer');
  $seed  = trim($_POST['seed'] ?? '');
  if (!in_array($style, $styles, true)) $style = 'adventurer';
  if ($seed === '') $seed = bin2hex(random_bytes(4));

  // DiceBear v7
  $avatar_url = 'https://api.dicebear.com/7.x/' . rawurlencode($style) . '/svg?seed=' . rawurlencode($seed);

  // Asegura columna avatar_url (si no existe, fallará; en tu app ya existe)
  $st = $pdo->prepare("UPDATE users SET avatar_url=? WHERE id=?");
  $st->execute([$avatar_url, (int)$me['id']]);

  flash_set('success', 'Avatar actualizado.');
  redirect('users/avatar_picker.php');
}

$current_url = $me['avatar_url'] ?? '';
$default_style = 'adventurer';
$default_seed = 'Rob';
if ($current_url) {
  // Intentar extraer style/seed desde la URL actual
  $m=[];
  if (preg_match('#/7\.x/([^/]+)/svg\?seed=([^&]+)#', $current_url, $m)) {
    $default_style = urldecode($m[1]);
    $default_seed  = urldecode($m[2]);
  }
}
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="mb-0">Elegir avatar (DiceBear)</h4>
    <div class="text-muted">Elige un estilo y un “seed”. Vista previa inmediata.</div>
  </div>
  <a class="btn btn-outline-secondary" href="<?= url('users/profile.php') ?>">Volver</a>
</div>

<div class="row g-3">
  <div class="col-lg-5">
    <div class="card shadow-sm">
      <div class="card-body">
        <form method="post" id="frm">
          <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
          <div class="mb-3">
            <label class="form-label">Estilo</label>
            <select class="form-select" name="style" id="style">
              <?php foreach($styles as $s): ?>
                <option value="<?= h($s) ?>" <?= $s===$default_style?'selected':'' ?>><?= h($s) ?></option>
              <?php endforeach; ?>
            </select>
            <div class="form-text">Consejo: prueba <b>notionists</b>, <b>avataaars</b> o <b>pixel-art</b>.</div>
          </div>

          <div class="mb-3">
            <label class="form-label">Seed (texto)</label>
            <div class="input-group">
              <input class="form-control" name="seed" id="seed" value="<?= h($default_seed) ?>" placeholder="Ej: Ruben, empresa, etc.">
              <button type="button" class="btn btn-outline-secondary" id="btnRandom">Aleatorio</button>
            </div>
            <div class="form-text">El seed controla la cara. Cambia el seed para variar.</div>
          </div>

          <button class="btn btn-primary w-100">Guardar avatar</button>
        </form>

        <hr>
        <div class="d-flex align-items-center gap-3">
          <img id="preview" class="avatar-lg" src="<?= h($current_url ?: ('https://api.dicebear.com/7.x/'.$default_style.'/svg?seed='.$default_seed)) ?>" alt="preview">
          <div>
            <div class="fw-semibold">Vista previa</div>
            <div class="text-muted small">Cuadrado, perfecto para tu sidebar.</div>
          </div>
        </div>

      </div>
    </div>
  </div>

  <div class="col-lg-7">
    <div class="card shadow-sm">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-center mb-2">
          <div>
            <h6 class="mb-0">Elige rápido</h6>
            <div class="text-muted small">Pulsa una miniatura para usar ese seed.</div>
          </div>
          <button class="btn btn-sm btn-outline-secondary" type="button" id="btnShuffle">Barajar</button>
        </div>

        <div id="grid" class="d-grid" style="grid-template-columns: repeat(6, 1fr); gap: 10px;"></div>
      </div>
    </div>
  </div>
</div>

<script>
const styleEl = document.getElementById('style');
const seedEl  = document.getElementById('seed');
const preview = document.getElementById('preview');
const grid    = document.getElementById('grid');

function dicebearUrl(style, seed){
  return `https://api.dicebear.com/7.x/${encodeURIComponent(style)}/svg?seed=${encodeURIComponent(seed)}`;
}

function updatePreview(){
  preview.src = dicebearUrl(styleEl.value, seedEl.value || 'Rob');
}

function randomSeed(){
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789';
  let s='';
  for(let i=0;i<8;i++) s+=chars[Math.floor(Math.random()*chars.length)];
  return s;
}

function buildGrid(){
  grid.innerHTML='';
  const style = styleEl.value;
  for(let i=0;i<24;i++){
    const seed = randomSeed();
    const img = document.createElement('img');
    img.src = dicebearUrl(style, seed);
    img.alt = seed;
    img.title = `Usar seed: ${seed}`;
    img.style.width = '100%';
    img.style.aspectRatio = '1 / 1';
    img.style.objectFit = 'cover';
    img.style.borderRadius = '12px';
    img.style.border = '1px solid #e5e7eb';
    img.style.cursor = 'pointer';
    img.addEventListener('click', () => {
      seedEl.value = seed;
      updatePreview();
      window.scrollTo({top:0, behavior:'smooth'});
    });
    grid.appendChild(img);
  }
}

document.getElementById('btnRandom').addEventListener('click', () => {
  seedEl.value = randomSeed();
  updatePreview();
});

document.getElementById('btnShuffle').addEventListener('click', () => buildGrid());

styleEl.addEventListener('change', () => { updatePreview(); buildGrid(); });
seedEl.addEventListener('input', updatePreview);

updatePreview();
buildGrid();
</script>

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