<?php
/**
 * admin/editar.php
 * Crear nuevo aviso  →  GET  (sin ?id)
 * Editar aviso       →  GET  ?id=X
 * Guardar cabecera   →  POST action=guardar
 * Crear nuevo        →  POST action=crear
 */
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/../config/conn.php';
av_require_login();

$aviso  = null;
$bloques = [];
$msg    = '';
$is_new = false;

// ── Crear nuevo aviso ────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'crear') {
    av_csrf_verify();

    $titulo     = trim($_POST['titulo'] ?? '');
    $resumen    = trim($_POST['resumen'] ?? '');
    $fecha      = $_POST['fecha_publicacion'] ?? date('Y-m-d');
    $estado     = in_array($_POST['estado'] ?? '', ['borrador','publicado','archivado'], true)
                  ? $_POST['estado'] : 'borrador';
    $banner_alt = trim($_POST['banner_alt'] ?? '');
    if (!$titulo) $titulo = 'Sin título';
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $fecha)) $fecha = date('Y-m-d');

    $banner_path = null;
    // Banner upload deshabilitado — siempre se guarda como null
    /*
    if (!empty($_FILES['banner']['tmp_name']) && $_FILES['banner']['error'] === UPLOAD_ERR_OK) {
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime  = $finfo->file($_FILES['banner']['tmp_name']);
        if (in_array($mime, ['image/jpeg','image/png','image/gif','image/webp'], true)) {
            $ext    = preg_replace('/[^a-z0-9]/', '', strtolower(pathinfo($_FILES['banner']['name'], PATHINFO_EXTENSION)));
            $newnam = bin2hex(random_bytes(16)) . '.' . $ext;
            $dir    = __DIR__ . '/../uploads/avisos/banners/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            if (move_uploaded_file($_FILES['banner']['tmp_name'], $dir . $newnam)) {
                $banner_path = 'uploads/avisos/banners/' . $newnam;
            }
        }
    }
    */
    $banner_alt = null; // Texto alternativo deshabilitado

    $ins = $conn->prepare(
        "INSERT INTO av_avisos (titulo, resumen, fecha_publicacion, estado, banner_path, banner_alt, creado_por) VALUES (?,?,?,?,?,?,?)"
    );
    $ins->bind_param('ssssssi', $titulo, $resumen, $fecha, $estado, $banner_path, $banner_alt, $_SESSION['av_uid']);
    $ins->execute();
    $new_id = (int)$conn->insert_id;
    $ins->close();

    header('Location: editar.php?id=' . $new_id . '&nuevo=1');
    exit;
}

// ── Guardar cabecera del aviso ───────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'guardar') {
    av_csrf_verify();

    $id     = (int)($_POST['aviso_id'] ?? 0);
    $titulo = trim($_POST['titulo'] ?? '');
    $resumen = trim($_POST['resumen'] ?? '');
    $fecha  = $_POST['fecha_publicacion'] ?? date('Y-m-d');
    $estado = in_array($_POST['estado'] ?? '', ['borrador','publicado','archivado'], true)
              ? $_POST['estado'] : 'borrador';
    $banner_alt = trim($_POST['banner_alt'] ?? '');

    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $fecha)) $fecha = date('Y-m-d');

    // Verificar aviso existe
    $chk = $conn->prepare("SELECT banner_path FROM av_avisos WHERE id=? LIMIT 1");
    $chk->bind_param('i', $id);
    $chk->execute();
    $cur = $chk->get_result()->fetch_assoc();
    $chk->close();

    if (!$cur) {
        header('Location: index.php');
        exit;
    }

    $banner_path = null; // Banner deshabilitado — siempre se guarda como null
    // Subir banner deshabilitado
    /*
    $banner_path = $cur['banner_path'];
    if (!empty($_FILES['banner']['tmp_name']) && $_FILES['banner']['error'] === UPLOAD_ERR_OK) {
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime  = $finfo->file($_FILES['banner']['tmp_name']);
        if (in_array($mime, ['image/jpeg','image/png','image/gif','image/webp'], true)) {
            $ext     = preg_replace('/[^a-z0-9]/', '', strtolower(pathinfo($_FILES['banner']['name'], PATHINFO_EXTENSION)));
            $newnam  = bin2hex(random_bytes(16)) . '.' . $ext;
            $dir     = __DIR__ . '/../uploads/avisos/banners/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            if (move_uploaded_file($_FILES['banner']['tmp_name'], $dir . $newnam)) {
                $banner_path = 'uploads/avisos/banners/' . $newnam;
            }
        }
    }
    */
    $banner_alt = null; // Texto alternativo deshabilitado

    $upd = $conn->prepare(
        "UPDATE av_avisos SET titulo=?, resumen=?, fecha_publicacion=?, estado=?, banner_path=?, banner_alt=? WHERE id=?"
    );
    $upd->bind_param('ssssssi', $titulo, $resumen, $fecha, $estado, $banner_path, $banner_alt, $id);
    $upd->execute();
    $upd->close();

    header('Location: editar.php?id=' . $id . '&ok=1');
    exit;
}

// ── Cargar aviso para edición ────────────────────────────────
$id = (int)($_GET['id'] ?? 0);

if ($id) {
    $s = $conn->prepare("SELECT * FROM av_avisos WHERE id=? LIMIT 1");
    $s->bind_param('i', $id);
    $s->execute();
    $aviso = $s->get_result()->fetch_assoc();
    $s->close();

    if (!$aviso) {
        header('Location: index.php');
        exit;
    }

    $sb = $conn->prepare("SELECT * FROM av_aviso_bloques WHERE aviso_id=? ORDER BY orden ASC, id ASC");
    $sb->bind_param('i', $id);
    $sb->execute();
    $bloques = $sb->get_result()->fetch_all(MYSQLI_ASSOC);
    $sb->close();
} else {
    $is_new = true;
}

$edit_bloque = (int)($_GET['edit'] ?? 0); // bloque actualmente en modo edición
$ok_msg = isset($_GET['ok']) ? 'Cambios guardados correctamente.' : '';
$ok_msg = isset($_GET['nuevo']) ? 'Aviso creado. Ahora agrega el contenido.' : $ok_msg;

// ── Helper: icono por tipo ───────────────────────────────────
function tipo_icon(string $t): string {
    $icons = [
        'texto'   => '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>',
        'imagen'  => '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>',
        'video'   => '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2"/></svg>',
        'archivo' => '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><polyline points="13 2 13 9 20 9"/></svg>',
    ];
    return $icons[$t] ?? $icons['archivo'];
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= $is_new ? 'Nuevo aviso' : 'Editar aviso' ?> · Panel DEMO</title>
  <link rel="stylesheet" href="admin.css">
</head>
<body>
<div class="av-layout">

  <!-- Sidebar -->
  <aside class="av-sidebar">
    <div class="av-sidebar-brand">
      <img src="../img/demoLogo_SinFondo.png" alt="DEMO" style="max-height:36px;margin-bottom:.4rem"
           onerror="this.style.display='none'">
      <div class="av-sidebar-logo">Panel de Avisos</div>
      <div class="av-sidebar-sub">Servicios DEMO</div>
    </div>
    <nav class="av-sidebar-nav">
      <a href="index.php">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>
        Todos los avisos
      </a>
      <a href="editar.php" class="active">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
        Nuevo aviso
      </a>
      <a href="../index.php" target="_blank">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
        Ver sitio
      </a>
    </nav>
    <div class="av-sidebar-footer">
      Sesión: <strong><?= h(av_nombre()) ?></strong><br>
      <a href="logout.php">Cerrar sesión</a>
    </div>
  </aside>

  <!-- Main -->
  <div class="av-main">
    <div class="av-topbar">
      <span class="av-topbar-title">
        <?php if ($is_new): ?>
          <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-3px;margin-right:6px"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>Nuevo aviso
        <?php else: ?>
          <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-3px;margin-right:6px"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>Editar: <?= h(mb_substr($aviso['titulo'] ?? '', 0, 50)) ?>
        <?php endif; ?>
      </span>
      <div class="av-topbar-actions">
        <?php if (!$is_new): ?>
          <a href="preview.php?id=<?= $aviso['id'] ?>" target="_blank" class="av-btn av-btn--outline">
            <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>Vista previa
          </a>
          <?php if ($aviso['estado'] !== 'publicado'): ?>
          <form method="post" action="index.php" style="display:inline">
            <?= av_csrf_field() ?>
            <input type="hidden" name="aviso_id" value="<?= $aviso['id'] ?>">
            <input type="hidden" name="action" value="publicar">
            <button class="av-btn av-btn--success">Publicar</button>
          </form>
          <?php else: ?>
          <form method="post" action="index.php" style="display:inline">
            <?= av_csrf_field() ?>
            <input type="hidden" name="aviso_id" value="<?= $aviso['id'] ?>">
            <input type="hidden" name="action" value="borrador">
            <button class="av-btn av-btn--warning">Despublicar</button>
          </form>
          <?php endif; ?>
        <?php endif; ?>
        <a href="index.php" class="av-btn av-btn--outline">← Volver</a>
      </div>
    </div>

    <div class="av-content">

      <?php if ($ok_msg): ?>
        <div class="av-alert av-alert--success"><?= h($ok_msg) ?></div>
      <?php endif; ?>

      <?php if ($is_new): ?>
      <!-- ══════════════════════════════════════════════
           FORMULARIO CREAR NUEVO AVISO
           ══════════════════════════════════════════════ -->
      <div class="av-card">
        <div class="av-card-header"><h2>Datos del nuevo aviso</h2></div>
        <div class="av-card-body">
          <form method="post" enctype="multipart/form-data">
            <?= av_csrf_field() ?>
            <input type="hidden" name="action" value="crear">

            <div class="av-form-row">
              <div class="av-form-group" style="grid-column:1/-1">
                <label class="av-label" for="titulo">Título del aviso <span>*</span></label>
                <input class="av-input" type="text" id="titulo" name="titulo"
                       value="<?= h($_POST['titulo'] ?? '') ?>" required autofocus>
              </div>
              <div class="av-form-group">
                <label class="av-label" for="fecha">Fecha de publicación</label>
                <input class="av-input" type="date" id="fecha" name="fecha_publicacion"
                       value="<?= h($_POST['fecha_publicacion'] ?? date('Y-m-d')) ?>">
              </div>
              <div class="av-form-group">
                <label class="av-label" for="estado_crear">Estado inicial</label>
                <select class="av-select" id="estado_crear" name="estado">
                  <option value="borrador" selected>Borrador</option>
                  <option value="publicado">Publicado</option>
                  <option value="archivado">Archivado</option>
                </select>
              </div>
            </div>

            <div class="av-form-group">
              <label class="av-label" for="resumen">
                Resumen <span>(texto breve que aparece en las tarjetas del inicio)</span>
              </label>
              <textarea class="av-input" id="resumen" name="resumen" rows="2"
                        maxlength="130"
                        style="min-height:60px;resize:vertical"><?= h($_POST['resumen'] ?? '') ?></textarea>
            </div>

            <div class="av-form-row">
              <div class="av-form-group">
                <!-- Imagen de banner deshabilitada
                <label class="av-label" for="banner_crear">Imagen de banner <span>(opcional — JPG, PNG, WEBP)</span></label>
                <input class="av-input" type="file" id="banner_crear" name="banner"
                       accept="image/jpeg,image/png,image/gif,image/webp"
                       onchange="prevBanner(this)">
                <img id="banner-prev" class="av-banner-preview" style="display:none" alt="">
                -->
              </div>
              <div class="av-form-group">
                <!-- Texto alternativo del banner deshabilitado
                <label class="av-label" for="banner_alt_crear">Texto alternativo del banner</label>
                <input class="av-input" type="text" id="banner_alt_crear" name="banner_alt"
                       value="<?= h($_POST['banner_alt'] ?? '') ?>"
                       placeholder="Descripción de la imagen para accesibilidad">
                -->
              </div>
            </div>

            <button type="submit" class="av-btn av-btn--primary av-btn--lg">Crear aviso &rarr;</button>
          </form>
        </div>
      </div>

      <?php else: ?>
      <!-- ══════════════════════════════════════════════
           EDITAR CABECERA DEL AVISO
           ══════════════════════════════════════════════ -->
      <div class="av-card">
        <div class="av-card-header">
          <h2>Información del aviso</h2>
          <span class="av-badge av-badge--<?= h($aviso['estado']) ?>"><?= h($aviso['estado']) ?></span>
        </div>
        <div class="av-card-body">
          <form method="post" enctype="multipart/form-data">
            <?= av_csrf_field() ?>
            <input type="hidden" name="action" value="guardar">
            <input type="hidden" name="aviso_id" value="<?= $aviso['id'] ?>">

            <div class="av-form-group">
              <label class="av-label" for="titulo">Título</label>
              <input class="av-input" type="text" id="titulo" name="titulo"
                     value="<?= h($aviso['titulo']) ?>" required>
            </div>

            <div class="av-form-group">
              <label class="av-label" for="resumen">
                Resumen <span>(aparece en la tarjeta del inicio)</span>
              </label>
              <textarea class="av-input" id="resumen" name="resumen" rows="2"
                        maxlength="160"
                        style="min-height:60px;resize:vertical"><?= h($aviso['resumen'] ?? '') ?></textarea>
            </div>

            <div class="av-form-row">
              <div class="av-form-group">
                <label class="av-label" for="fecha">Fecha de publicación</label>
                <input class="av-input" type="date" id="fecha" name="fecha_publicacion"
                       value="<?= h($aviso['fecha_publicacion']) ?>">
              </div>
              <div class="av-form-group">
                <label class="av-label" for="estado">Estado</label>
                <select class="av-select" id="estado" name="estado">
                  <?php foreach (['borrador','publicado','archivado'] as $est): ?>
                    <option value="<?= $est ?>" <?= $aviso['estado'] === $est ? 'selected' : '' ?>>
                      <?= ucfirst($est) ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>

            <!-- Banner deshabilitado
            <div class="av-form-row">
              <div class="av-form-group">
                <label class="av-label" for="banner">
                  Imagen de banner <span>(JPG, PNG, WEBP — reemplaza el actual)</span>
                </label>
                <input class="av-input" type="file" id="banner" name="banner"
                       accept="image/jpeg,image/png,image/gif,image/webp"
                       onchange="prevBanner(this)">
                <?php if ($aviso['banner_path']): ?>
                  <img id="banner-prev" class="av-banner-preview"
                       src="../<?= h($aviso['banner_path']) ?>" alt="Banner actual">
                <?php else: ?>
                  <img id="banner-prev" class="av-banner-preview" style="display:none" alt="">
                <?php endif; ?>
              </div>
              <div class="av-form-group">
                <label class="av-label" for="banner_alt">Texto alternativo del banner</label>
                <input class="av-input" type="text" id="banner_alt" name="banner_alt"
                       value="<?= h($aviso['banner_alt'] ?? '') ?>"
                       placeholder="Descripción de la imagen para accesibilidad">
              </div>
            </div>
            -->

            <button type="submit" class="av-btn av-btn--primary">
            <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:5px"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>Guardar cambios
          </button>
          </form>
        </div>
      </div>

            <!-- ══════════════════════════════════════════════
           AGREGAR NUEVO BLOQUE
           ══════════════════════════════════════════════ -->
      <div class="av-card">
        <div class="av-card-header">
          <h2>
            <svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-3px;margin-right:6px"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>Agregar bloque de contenido
          </h2>
        </div>
        <div class="av-card-body">
          <form method="post" action="api/bloque.php" enctype="multipart/form-data" id="add-form">
            <?= av_csrf_field() ?>
            <input type="hidden" name="action" value="add">
            <input type="hidden" name="aviso_id" value="<?= $aviso['id'] ?>">

            <!-- Selector de tipo -->
            <div class="av-form-group">
              <label class="av-label">Tipo de bloque</label>
              <div class="av-type-grid">
                <button type="button" class="av-type-btn selected" onclick="selTipo('texto')" data-tipo="texto">
                  <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
                  <span>Texto</span>
                </button>
                <button type="button" class="av-type-btn" onclick="selTipo('imagen')" data-tipo="imagen">
                  <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                  <span>Imagen</span>
                </button>
                <button type="button" class="av-type-btn" onclick="selTipo('video')" data-tipo="video">
                  <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2"/></svg>
                  <span>Video</span>
                </button>
                <button type="button" class="av-type-btn" onclick="selTipo('archivo')" data-tipo="archivo">
                  <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><polyline points="13 2 13 9 20 9"/></svg>
                  <span>Archivo</span>
                </button>
              </div>
              <input type="hidden" name="tipo" id="tipo-val" value="texto">
            </div>

            <!-- Área de contenido (cambia con JS) -->
            <div id="add-texto">
              <label class="av-label">Contenido de texto</label>
              <div class="av-editor-toolbar">
                <span class="av-tb-group">
                  <select onchange="fmtAddBlock(this.value);this.value=''" title="Formato de párrafo">
                    <option value="">Formato</option>
                    <option value="p">Párrafo</option>
                    <option value="h2">Título H2</option>
                    <option value="h3">Subtítulo H3</option>
                    <option value="h4">H4</option>
                  </select>
                </span>
                <span class="av-tb-sep"></span>
                <span class="av-tb-group">
                  <button type="button" onclick="fmtAdd('bold')" title="Negrita"><b>B</b></button>
                  <button type="button" onclick="fmtAdd('italic')" title="Cursiva"><i>I</i></button>
                  <button type="button" onclick="fmtAdd('underline')" title="Subrayado"><u>U</u></button>
                  <button type="button" onclick="fmtAdd('strikeThrough')" title="Tachado"><s>S</s></button>
                </span>
                <span class="av-tb-sep"></span>
                <span class="av-tb-group">
                  <button type="button" onclick="fmtAdd('justifyLeft')" title="Alinear izquierda">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="15" y2="12"/><line x1="3" y1="18" x2="18" y2="18"/></svg>
                  </button>
                  <button type="button" onclick="fmtAdd('justifyCenter')" title="Centrar">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="6" y1="12" x2="18" y2="12"/><line x1="4" y1="18" x2="20" y2="18"/></svg>
                  </button>
                  <button type="button" onclick="fmtAdd('justifyRight')" title="Alinear derecha">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="9" y1="12" x2="21" y2="12"/><line x1="6" y1="18" x2="21" y2="18"/></svg>
                  </button>
                  <button type="button" onclick="fmtAdd('justifyFull')" title="Justificar">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
                  </button>
                </span>
                <span class="av-tb-sep"></span>
                <span class="av-tb-group">
                  <button type="button" onclick="fmtAdd('insertUnorderedList')" title="Lista con viñetas">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="9" y1="6" x2="20" y2="6"/><line x1="9" y1="12" x2="20" y2="12"/><line x1="9" y1="18" x2="20" y2="18"/><circle cx="4" cy="6" r="1.5" fill="currentColor" stroke="none"/><circle cx="4" cy="12" r="1.5" fill="currentColor" stroke="none"/><circle cx="4" cy="18" r="1.5" fill="currentColor" stroke="none"/></svg>
                  </button>
                  <button type="button" onclick="fmtAdd('insertOrderedList')" title="Lista numerada">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/><text x="2" y="9" font-size="8" font-family="sans-serif" fill="currentColor" stroke="none">1.</text><text x="2" y="15" font-size="8" font-family="sans-serif" fill="currentColor" stroke="none">2.</text><text x="2" y="21" font-size="8" font-family="sans-serif" fill="currentColor" stroke="none">3.</text></svg>
                  </button>
                </span>
                <span class="av-tb-sep"></span>
                <span class="av-tb-group">
                  <button type="button" onclick="fmtAddLink()" title="Insertar enlace">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
                  </button>
                  <button type="button" onclick="fmtAdd('unlink')" title="Quitar enlace">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/><line x1="2" y1="2" x2="22" y2="22"/></svg>
                  </button>
                  <button type="button" onclick="fmtAdd('removeFormat')" title="Limpiar formato" style="color:var(--av-danger)">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20.5 2l-15 15L2 21l4-3.5 15-15"/><path d="M6.5 17.5L2 22"/></svg>
                  </button>
                </span>
                <span class="av-tb-sep"></span>
                <span class="av-tb-group">
                  <label title="Color de texto" style="display:inline-flex;align-items:center;gap:2px;cursor:pointer;padding:0 4px">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2L2 19h20L12 2z"/></svg>
                    <input type="color" value="#000000" onchange="fmtAdd('foreColor',this.value)" style="width:20px;height:20px;border:none;padding:0;background:none;cursor:pointer">
                  </label>
                  <label title="Color de resaltado" style="display:inline-flex;align-items:center;gap:2px;cursor:pointer;padding:0 4px">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l-6 6v3h3l6-6"/><path d="M22 4l-9 9-3-3 9-9z"/></svg>
                    <input type="color" value="#ffff00" onchange="fmtHilite('add',this.value)" style="width:20px;height:20px;border:none;padding:0;background:none;cursor:pointer">
                  </label>
                </span>
                <span class="av-tb-sep"></span>
                <span class="av-tb-group">
                  <select onchange="fmtAdd('fontSize',this.value);this.value=''" title="Tamaño de fuente">
                    <option value="">Tamaño</option>
                    <option value="1">Muy pequeño</option>
                    <option value="2">Pequeño</option>
                    <option value="3">Normal</option>
                    <option value="4">Mediano</option>
                    <option value="5">Grande</option>
                    <option value="6">Muy grande</option>
                    <option value="7">Enorme</option>
                  </select>
                  <select onchange="fmtAdd('fontName',this.value);this.value=''" title="Tipo de letra">
                    <option value="">Fuente</option>
                    <option value="Arial">Arial</option>
                    <option value="Calibri">Calibri</option>
                    <option value="Georgia">Georgia</option>
                    <option value="Tahoma">Tahoma</option>
                    <option value="Times New Roman">Times New Roman</option>
                    <option value="Verdana">Verdana</option>
                    <option value="Courier New">Courier New</option>
                  </select>
                </span>
                <span class="av-tb-sep"></span>
                <span class="av-tb-group">
                  <button type="button" onclick="fmtAdd('subscript')" title="Subíndice">X<sub>2</sub></button>
                  <button type="button" onclick="fmtAdd('superscript')" title="Superíndice">X<sup>2</sup></button>
                </span>
                <span class="av-tb-sep"></span>
                <span class="av-tb-group">
                  <button type="button" onclick="fmtAdd('outdent')" title="Disminuir sangría">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="7 8 3 12 7 16"/><line x1="21" y1="6" x2="11" y2="6"/><line x1="21" y1="12" x2="11" y2="12"/><line x1="21" y1="18" x2="11" y2="18"/></svg>
                  </button>
                  <button type="button" onclick="fmtAdd('indent')" title="Aumentar sangría">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 8 7 12 3 16"/><line x1="21" y1="6" x2="11" y2="6"/><line x1="21" y1="12" x2="11" y2="12"/><line x1="21" y1="18" x2="11" y2="18"/></svg>
                  </button>
                  <button type="button" onclick="fmtAddBlock('blockquote')" title="Cita">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21c3 0 7-1 7-8V5c0-1.25-.756-2.017-2-2H4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2 1 0 1 0 1 1v1c0 1-1 2-2 2s-1 .008-1 1.031V20c0 1 0 1 1 1z"/><path d="M15 21c3 0 7-1 7-8V5c0-1.25-.757-2.017-2-2h-4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2h.75c0 2.25.25 4-2.75 4v3c0 1 0 1 1 1z"/></svg>
                  </button>
                  <button type="button" onclick="fmtAdd('formatBlock','pre')" title="Bloque de código">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
                  </button>
                  <button type="button" onclick="fmtAdd('insertHorizontalRule')" title="Línea horizontal">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="12" x2="21" y2="12"/></svg>
                  </button>
                </span>
                <span class="av-tb-sep"></span>
                <span class="av-tb-group">
                  <button type="button" onclick="fmtAdd('undo')" title="Deshacer">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 7 3 13 9 13"/><path d="M3 13a9 9 0 1 0 3-7"/></svg>
                  </button>
                  <button type="button" onclick="fmtAdd('redo')" title="Rehacer">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="21 7 21 13 15 13"/><path d="M21 13a9 9 0 1 1-3-7"/></svg>
                  </button>
                </span>
              </div>
              <div class="av-editor-area" contenteditable="true" id="add-editor"
                   oninput="document.getElementById('add-contenido').value=this.innerHTML">
              </div>
              <textarea name="contenido" hidden id="add-contenido"></textarea>
            </div>

            <div id="add-video" style="display:none">
              <div class="av-form-group">
                <label class="av-label">URL de YouTube / Vimeo</label>
                <input class="av-input" type="url" name="url_video" id="add-url-video"
                       placeholder="https://www.youtube.com/watch?v=...">
                <p class="av-hint">O sube un archivo de video:</p>
              </div>
              <div class="av-form-group">
                <label class="av-label">Archivo de video <span>(MP4, WEBM)</span></label>
                <input class="av-input" type="file" name="archivo" id="add-file-video"
                       accept="video/mp4,video/webm,video/ogg">
              </div>
            </div>

            <div id="add-archivo" style="display:none">
              <div class="av-form-group">
                <label class="av-label">Seleccionar archivo <span>(cualquier tipo, máx. 100 MB)</span></label>
                <input class="av-input" type="file" name="archivo" id="add-file-gen">
                <p class="av-hint">PDF, Word, Excel, imágenes, videos, ZIP, etc.</p>
              </div>
            </div>

            <div style="margin-top:.8rem">
              <button type="submit" class="av-btn av-btn--primary av-btn--lg"
                      onclick="syncAddEditor()">
                <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:5px"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>Agregar bloque
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- ══════════════════════════════════════════════
           BLOQUES DE CONTENIDO
           ══════════════════════════════════════════════ -->
      <div class="av-card">
        <div class="av-card-header">
          <h2>
            <svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-3px;margin-right:6px"><polyline points="21 8 21 21 3 21 3 8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>Contenido del aviso <span style="font-weight:400;opacity:.6;font-size:.85em">(<?= count($bloques) ?> bloques)</span>
          </h2>
          <a href="preview.php?id=<?= $aviso['id'] ?>" target="_blank" class="av-btn av-btn--outline av-btn--sm">
            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:3px"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>Vista previa
          </a>
        </div>
        <div class="av-card-body" style="padding:1rem">

          <?php if (empty($bloques)): ?>
            <p class="av-text-muted" style="text-align:center;padding:1.5rem 0">
              Sin bloques todavía. Usa el panel de abajo para agregar contenido.
            </p>
          <?php else: ?>
          <div class="av-blocks">
            <?php foreach ($bloques as $idx => $bloque):
                $is_edit = $edit_bloque === (int)$bloque['id'];
                $is_last = $idx === count($bloques) - 1;
                $prev_txt = strip_tags($bloque['contenido'] ?? $bloque['nombre_archivo'] ?? '—');
            ?>
            <div class="av-block">
              <div class="av-block-header <?= $is_edit ? 'is-editing' : '' ?>">
                <span class="av-block-num">#<?= $idx + 1 ?></span>
                <span class="av-badge av-badge--<?= h($bloque['tipo']) ?>">
                  <?= tipo_icon($bloque['tipo']) ?> <?= h($bloque['tipo']) ?>
                </span>
                <span class="av-block-preview"><?= h(mb_substr($prev_txt, 0, 90)) ?></span>
                <div class="av-block-actions">
                  <!-- Subir -->
                  <?php if ($idx > 0): ?>
                  <form method="post" action="api/bloque.php" style="display:inline">
                    <?= av_csrf_field() ?>
                    <input type="hidden" name="action" value="move">
                    <input type="hidden" name="dir" value="up">
                    <input type="hidden" name="bloque_id" value="<?= $bloque['id'] ?>">
                    <input type="hidden" name="aviso_id" value="<?= $aviso['id'] ?>">
                    <button type="submit" class="av-btn av-btn--outline av-btn--sm av-btn--icon" title="Mover arriba">
                      <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="18 15 12 9 6 15"/></svg>
                    </button>
                  </form>
                  <?php endif; ?>
                  <!-- Bajar -->
                  <?php if (!$is_last): ?>
                  <form method="post" action="api/bloque.php" style="display:inline">
                    <?= av_csrf_field() ?>
                    <input type="hidden" name="action" value="move">
                    <input type="hidden" name="dir" value="down">
                    <input type="hidden" name="bloque_id" value="<?= $bloque['id'] ?>">
                    <input type="hidden" name="aviso_id" value="<?= $aviso['id'] ?>">
                    <button type="submit" class="av-btn av-btn--outline av-btn--sm av-btn--icon" title="Mover abajo">
                      <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
                    </button>
                  </form>
                  <?php endif; ?>
                  <!-- Editar -->
                  <a href="editar.php?id=<?= $aviso['id'] ?>&edit=<?= $bloque['id'] ?><?= $is_edit ? '&cancel=1' : '' ?>"
                     class="av-btn av-btn--outline av-btn--sm">
                    <?php if ($is_edit): ?>
                      <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>Cerrar
                    <?php else: ?>
                      <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>Editar
                    <?php endif; ?>
                  </a>
                  <!-- Eliminar -->
                  <form method="post" action="api/bloque.php" style="display:inline"
                        onsubmit="return confirm('¿Eliminar este bloque?')">
                    <?= av_csrf_field() ?>
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="bloque_id" value="<?= $bloque['id'] ?>">
                    <input type="hidden" name="aviso_id" value="<?= $aviso['id'] ?>">
                    <button type="submit" class="av-btn av-btn--danger av-btn--sm av-btn--icon" title="Eliminar">
                      <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>
                    </button>
                  </form>
                </div>
              </div>

              <?php if ($is_edit): ?>
              <div class="av-block-form">
                <form method="post" action="api/bloque.php" enctype="multipart/form-data">
                  <?= av_csrf_field() ?>
                  <input type="hidden" name="action" value="update">
                  <input type="hidden" name="bloque_id" value="<?= $bloque['id'] ?>">
                  <input type="hidden" name="aviso_id" value="<?= $aviso['id'] ?>">

                  <?php if ($bloque['tipo'] === 'texto'): ?>
                    <div class="av-form-group">
                      <label class="av-label">Contenido</label>
                      <div class="av-editor-toolbar" id="tb-<?= $bloque['id'] ?>">
                        <span class="av-tb-group">
                          <select onchange="fmtBlock(this.value);this.value=''" title="Formato de párrafo">
                            <option value="">Formato</option>
                            <option value="p">Párrafo</option>
                            <option value="h2">Título H2</option>
                            <option value="h3">Subtítulo H3</option>
                            <option value="h4">H4</option>
                          </select>
                        </span>
                        <span class="av-tb-sep"></span>
                        <span class="av-tb-group">
                          <button type="button" onclick="fmt('bold')" title="Negrita"><b>B</b></button>
                          <button type="button" onclick="fmt('italic')" title="Cursiva"><i>I</i></button>
                          <button type="button" onclick="fmt('underline')" title="Subrayado"><u>U</u></button>
                          <button type="button" onclick="fmt('strikeThrough')" title="Tachado"><s>S</s></button>
                        </span>
                        <span class="av-tb-sep"></span>
                        <span class="av-tb-group">
                          <button type="button" onclick="fmt('justifyLeft')" title="Izquierda">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="15" y2="12"/><line x1="3" y1="18" x2="18" y2="18"/></svg>
                          </button>
                          <button type="button" onclick="fmt('justifyCenter')" title="Centrar">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="6" y1="12" x2="18" y2="12"/><line x1="4" y1="18" x2="20" y2="18"/></svg>
                          </button>
                          <button type="button" onclick="fmt('justifyRight')" title="Derecha">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="9" y1="12" x2="21" y2="12"/><line x1="6" y1="18" x2="21" y2="18"/></svg>
                          </button>
                          <button type="button" onclick="fmt('justifyFull')" title="Justificar">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
                          </button>
                        </span>
                        <span class="av-tb-sep"></span>
                        <span class="av-tb-group">
                          <button type="button" onclick="fmt('insertUnorderedList')" title="Lista con viñetas">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="9" y1="6" x2="20" y2="6"/><line x1="9" y1="12" x2="20" y2="12"/><line x1="9" y1="18" x2="20" y2="18"/><circle cx="4" cy="6" r="1.5" fill="currentColor" stroke="none"/><circle cx="4" cy="12" r="1.5" fill="currentColor" stroke="none"/><circle cx="4" cy="18" r="1.5" fill="currentColor" stroke="none"/></svg>
                          </button>
                          <button type="button" onclick="fmt('insertOrderedList')" title="Lista numerada">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/><text x="2" y="9" font-size="8" font-family="sans-serif" fill="currentColor" stroke="none">1.</text><text x="2" y="15" font-size="8" font-family="sans-serif" fill="currentColor" stroke="none">2.</text><text x="2" y="21" font-size="8" font-family="sans-serif" fill="currentColor" stroke="none">3.</text></svg>
                          </button>
                        </span>
                        <span class="av-tb-sep"></span>
                        <span class="av-tb-group">
                          <button type="button" onclick="fmtLink()" title="Insertar enlace">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
                          </button>
                          <button type="button" onclick="fmt('unlink')" title="Quitar enlace">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/><line x1="2" y1="2" x2="22" y2="22"/></svg>
                          </button>
                          <button type="button" onclick="fmt('removeFormat')" title="Limpiar formato" style="color:var(--av-danger)">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20.5 2l-15 15L2 21l4-3.5 15-15"/><path d="M6.5 17.5L2 22"/></svg>
                          </button>
                        </span>
                        <span class="av-tb-sep"></span>
                        <span class="av-tb-group">
                          <label title="Color de texto" style="display:inline-flex;align-items:center;gap:2px;cursor:pointer;padding:0 4px">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2L2 19h20L12 2z"/></svg>
                            <input type="color" value="#000000" onchange="fmt('foreColor',this.value)" style="width:20px;height:20px;border:none;padding:0;background:none;cursor:pointer">
                          </label>
                          <label title="Color de resaltado" style="display:inline-flex;align-items:center;gap:2px;cursor:pointer;padding:0 4px">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l-6 6v3h3l6-6"/><path d="M22 4l-9 9-3-3 9-9z"/></svg>
                            <input type="color" value="#ffff00" onchange="fmtHilite('edit',this.value)" style="width:20px;height:20px;border:none;padding:0;background:none;cursor:pointer">
                          </label>
                        </span>
                        <span class="av-tb-sep"></span>
                        <span class="av-tb-group">
                          <select onchange="fmt('fontSize',this.value);this.value=''" title="Tamaño de fuente">
                            <option value="">Tamaño</option>
                            <option value="1">Muy pequeño</option>
                            <option value="2">Pequeño</option>
                            <option value="3">Normal</option>
                            <option value="4">Mediano</option>
                            <option value="5">Grande</option>
                            <option value="6">Muy grande</option>
                            <option value="7">Enorme</option>
                          </select>
                          <select onchange="fmt('fontName',this.value);this.value=''" title="Tipo de letra">
                            <option value="">Fuente</option>
                            <option value="Arial">Arial</option>
                            <option value="Calibri">Calibri</option>
                            <option value="Georgia">Georgia</option>
                            <option value="Tahoma">Tahoma</option>
                            <option value="Times New Roman">Times New Roman</option>
                            <option value="Verdana">Verdana</option>
                            <option value="Courier New">Courier New</option>
                          </select>
                        </span>
                        <span class="av-tb-sep"></span>
                        <span class="av-tb-group">
                          <button type="button" onclick="fmt('subscript')" title="Subíndice">X<sub>2</sub></button>
                          <button type="button" onclick="fmt('superscript')" title="Superíndice">X<sup>2</sup></button>
                        </span>
                        <span class="av-tb-sep"></span>
                        <span class="av-tb-group">
                          <button type="button" onclick="fmt('outdent')" title="Disminuir sangría">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="7 8 3 12 7 16"/><line x1="21" y1="6" x2="11" y2="6"/><line x1="21" y1="12" x2="11" y2="12"/><line x1="21" y1="18" x2="11" y2="18"/></svg>
                          </button>
                          <button type="button" onclick="fmt('indent')" title="Aumentar sangría">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 8 7 12 3 16"/><line x1="21" y1="6" x2="11" y2="6"/><line x1="21" y1="12" x2="11" y2="12"/><line x1="21" y1="18" x2="11" y2="18"/></svg>
                          </button>
                          <button type="button" onclick="fmtBlock('blockquote')" title="Cita">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21c3 0 7-1 7-8V5c0-1.25-.756-2.017-2-2H4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2 1 0 1 0 1 1v1c0 1-1 2-2 2s-1 .008-1 1.031V20c0 1 0 1 1 1z"/><path d="M15 21c3 0 7-1 7-8V5c0-1.25-.757-2.017-2-2h-4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2h.75c0 2.25.25 4-2.75 4v3c0 1 0 1 1 1z"/></svg>
                          </button>
                          <button type="button" onclick="fmtBlock('pre')" title="Bloque de código">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
                          </button>
                          <button type="button" onclick="fmt('insertHorizontalRule')" title="Línea horizontal">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="12" x2="21" y2="12"/></svg>
                          </button>
                        </span>
                        <span class="av-tb-sep"></span>
                        <span class="av-tb-group">
                          <button type="button" onclick="fmt('undo')" title="Deshacer">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 7 3 13 9 13"/><path d="M3 13a9 9 0 1 0 3-7"/></svg>
                          </button>
                          <button type="button" onclick="fmt('redo')" title="Rehacer">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="21 7 21 13 15 13"/><path d="M21 13a9 9 0 1 1-3-7"/></svg>
                          </button>
                        </span>
                      </div>
                      <div class="av-editor-area" contenteditable="true"
                           id="editor-<?= $bloque['id'] ?>"
                           oninput="syncEditor(<?= $bloque['id'] ?>)"><?= $bloque['contenido'] ?></div>
                      <textarea name="contenido" hidden id="hidden-<?= $bloque['id'] ?>"><?= h($bloque['contenido'] ?? '') ?></textarea>
                    </div>

                  <?php elseif ($bloque['tipo'] === 'video'): ?>
                    <div class="av-form-group">
                      <label class="av-label">URL de YouTube o Vimeo</label>
                      <input class="av-input" type="url" name="url_video"
                             value="<?= h($bloque['contenido'] ?? '') ?>"
                             placeholder="https://www.youtube.com/watch?v=...">
                      <p class="av-hint">Si pegas URL se incrusta automáticamente. Déjalo vacío si subes archivo.</p>
                    </div>
                    <div class="av-form-group">
                      <label class="av-label">O sube un archivo de video <span>(MP4, WEBM)</span></label>
                      <?php if ($bloque['nombre_archivo']): ?>
                        <p class="av-hint" style="margin-bottom:.4rem">Actual: <?= h($bloque['nombre_archivo']) ?></p>
                      <?php endif; ?>
                      <input class="av-input" type="file" name="archivo" accept="video/mp4,video/webm,video/ogg">
                    </div>

                  <?php else: ?>
                    <div class="av-form-group">
                      <label class="av-label">
                        Subir nuevo archivo
                        <span>(deja vacío para conservar el actual)</span>
                      </label>
                      <?php if ($bloque['nombre_archivo']): ?>
                        <p class="av-hint" style="margin-bottom:.4rem">
                          Actual: <?= h($bloque['nombre_archivo']) ?>
                          (<?= $bloque['mime_type'] ?>
                          <?php if ($bloque['tamano_bytes']): ?>
                            · <?= number_format($bloque['tamano_bytes'] / 1024, 0) ?> KB
                          <?php endif; ?>)
                        </p>
                      <?php endif; ?>
                      <input class="av-input" type="file" name="archivo">
                    </div>
                  <?php endif; ?>

                  <div style="display:flex;gap:.5rem;margin-top:.3rem">
                    <button type="submit" class="av-btn av-btn--primary"
                            onclick="if(document.getElementById('editor-<?= $bloque['id'] ?>'))syncEditor(<?= $bloque['id'] ?>)">
                      <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>Guardar bloque
                    </button>
                    <a href="editar.php?id=<?= $aviso['id'] ?>" class="av-btn av-btn--outline">Cancelar</a>
                  </div>
                </form>
              </div>
              <?php endif; ?>

            </div><!-- /.av-block -->
            <?php endforeach; ?>
          </div><!-- /.av-blocks -->
          <?php endif; ?>

        </div>
      </div><!-- /bloques card -->



      <?php endif; /* end !is_new */ ?>

    </div><!-- /av-content -->
  </div><!-- /av-main -->
</div><!-- /av-layout -->

<script>
// ── Editor de texto: aplicar formato ──────────────────────────
function fmt(cmd, val) {
  document.execCommand(cmd, false, val || null);
}
function fmtBlock(tag) {
  document.execCommand('formatBlock', false, tag);
}
function fmtLink() {
  var url = prompt('URL del enlace:');
  if (url) document.execCommand('createLink', false, url);
}
function syncEditor(id) {
  var ed = document.getElementById('editor-' + id);
  var hid = document.getElementById('hidden-' + id);
  if (ed && hid) hid.value = ed.innerHTML;
}

// ── Add block editor ──────────────────────────────────────────
function fmtAdd(cmd, val) {
  document.getElementById('add-editor').focus();
  document.execCommand(cmd, false, val || null);
}
function fmtAddBlock(tag) {
  document.getElementById('add-editor').focus();
  document.execCommand('formatBlock', false, tag);
}
function fmtAddLink() {
  var url = prompt('URL del enlace:');
  if (url) { document.getElementById('add-editor').focus(); document.execCommand('createLink', false, url); }
}
function syncAddEditor() {
  var ed = document.getElementById('add-editor');
  if (ed) document.getElementById('add-contenido').value = ed.innerHTML;
}

// ── Resaltado (highlight) compatible con varios navegadores ───
function fmtHilite(scope, color) {
  if (scope === 'add') {
    document.getElementById('add-editor').focus();
  }
  // Chrome/Edge usan 'hiliteColor'; otros 'backColor'.
  if (!document.execCommand('hiliteColor', false, color)) {
    document.execCommand('backColor', false, color);
  }
}

// ── Tipo de bloque ─────────────────────────────────────────────
function selTipo(tipo) {
  document.querySelectorAll('.av-type-btn').forEach(function(b){ b.classList.remove('selected'); });
  document.querySelector('[data-tipo="' + tipo + '"]').classList.add('selected');
  document.getElementById('tipo-val').value = tipo;

  document.getElementById('add-texto').style.display   = tipo === 'texto'   ? '' : 'none';
  document.getElementById('add-video').style.display   = tipo === 'video'   ? '' : 'none';
  document.getElementById('add-archivo').style.display = (tipo === 'imagen' || tipo === 'archivo') ? '' : 'none';

  var fileInput = document.getElementById('add-file-gen');
  if (tipo === 'imagen') {
    fileInput.accept = 'image/jpeg,image/png,image/gif,image/webp';
  } else {
    fileInput.accept = '';
  }
}

// ── Preview del banner ─────────────────────────────────────────
function prevBanner(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      var img = document.getElementById('banner-prev');
      if (img) { img.src = e.target.result; img.style.display = ''; }
    };
    reader.readAsDataURL(input.files[0]);
  }
}
</script>
</body>
</html>
