<?php 
include ('../includes/header3.php');

/* =========================
   CONFIG
   ========================= */
$table_name = "ads";
$base_file = basename($_SERVER["SCRIPT_NAME"]);

/* Garantir a coluna owner (usada no WHERE e INSERT) */
$adb->exec("
CREATE TABLE IF NOT EXISTS {$table_name}(
  id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
  title VARCHAR(100), 
  url TEXT,
  owner TEXT
)");

/* Listagem filtrada pelo seller atual */
$res = $adb->query("SELECT * FROM {$table_name} WHERE owner = '$seller_name'");

/* Busca registro para update (se houver) */
@$resU = $adb->query("SELECT * FROM {$table_name} WHERE id='{$_GET['update']}'");
@$rowU = $resU ? $resU->fetchArray() : null;

/* Validação simples de imagem */
function isImageUrl($url) {
    $image_extensions = ['jpg','jpeg','png','gif','webp','svg'];
    $path = parse_url($url, PHP_URL_PATH);
    $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    return in_array($ext, $image_extensions);
}

/* Atualizar */
if (isset($_POST['submitU'])) {
    if (isImageUrl($_POST['url'])) {
        $id = intval($_POST['id']);
        $title = SQLite3::escapeString($_POST['title']);
        $url = SQLite3::escapeString($_POST['url']);
        $adb->exec("UPDATE {$table_name} SET title='{$title}', url='{$url}' WHERE id='{$id}' AND owner = '$seller_name'");
        echo "<script>window.location.href='ads.php';</script>";
        exit;
    } else {
        echo "<script>window.customToast && window.customToast('Por favor, insira um link válido de imagem!', 'error');</script>";
    }
}

/* Inserir */
if (isset($_POST['submit'])) {
    if (isImageUrl($_POST['url'])) {
        $title = SQLite3::escapeString($_POST['title']);
        $url = SQLite3::escapeString($_POST['url']);
        $owner = SQLite3::escapeString($seller_name);
        $adb->exec("INSERT INTO {$table_name}(title, url, owner) VALUES('{$title}', '{$url}', '{$owner}')");
        echo "<script>window.location.href='ads.php';</script>";
        exit;
    } else {
        echo "<script>window.customToast && window.customToast('Por favor, insira um link válido de imagem!', 'error');</script>";
    }
}

/* Deletar */
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $adb->exec("DELETE FROM {$table_name} WHERE id={$id} AND owner = '$seller_name'");
    echo "<script>window.location.href='ads.php';</script>";
    exit;
}
?>

<style>
/* === DESIGN FUTURISTA PARA ANÚNCIOS - TEMA REVENDA === */
:root {
    --primary: #FF6B9D;
    --primary-dark: #D94A7E;
    --secondary: #00D4FF;
    --accent: #FFD166;
    --surface: #0A0F1C;
    --surface-light: #1A1F2C;
    --surface-lighter: #2A2F3C;
    --text-primary: #FFFFFF;
    --text-secondary: #B0B7C3;
    --text-muted: #6B7280;
    --border: rgba(255,255,255,0.1);
    --glow: 0 0 20px rgba(255, 107, 157, 0.3);
    --glow-accent: 0 0 20px rgba(255, 209, 102, 0.3);
    --glow-secondary: 0 0 20px rgba(0, 212, 255, 0.3);
}

/* Fundo com partículas */
body {
    background: radial-gradient(1200px 600px at 30% -10%, rgba(255, 107, 157, 0.15), transparent),
                radial-gradient(1000px 500px at 80% 120%, rgba(0, 212, 255, 0.12), transparent),
                var(--surface);
    color: var(--text-primary);
    font-family: 'Inter', sans-serif;
}

.main-wrap {
    padding: 24px;
}

/* === CARDS FUTURISTAS === */
.card-fx {
    background: var(--surface-light);
    border: 1px solid var(--border);
    border-radius: 20px;
    box-shadow: var(--glow), 0 8px 32px rgba(0,0,0,0.35);
    overflow: hidden;
    position: relative;
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;
}

.card-fx:hover {
    transform: translateY(-2px);
    box-shadow: 0 12px 40px rgba(255, 107, 157, 0.4);
}

.card-fx::before {
    content: '';
    position: absolute;
    top: 0; 
    left: 0; 
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, var(--primary), var(--accent), var(--secondary));
    animation: barFlow 3s ease-in-out infinite;
}

@keyframes barFlow { 
    0%, 100% { opacity: 0.7; }
    50% { opacity: 1; }
}

.card-fx .card-header {
    background: linear-gradient(135deg, var(--surface-lighter), var(--surface-light));
    border-bottom: 1px solid var(--border);
    padding: 20px 24px;
}

.card-title {
    margin: 0;
    font-weight: 700;
    letter-spacing: 0.5px;
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    display: flex;
    align-items: center;
    gap: 12px;
}

/* === BOTÕES FUTURISTAS === */
.btn-fx {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    border: none;
    border-radius: 12px;
    color: var(--text-primary) !important;
    padding: 12px 20px;
    font-weight: 600;
    letter-spacing: 0.3px;
    box-shadow: var(--glow);
    transition: all 0.3s ease;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.btn-fx:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(255, 107, 157, 0.5);
    color: var(--text-primary) !important;
    text-decoration: none;
}

.btn-accent {
    background: linear-gradient(135deg, var(--accent), #FFB347);
    box-shadow: var(--glow-accent);
}

.btn-secondary-fx {
    background: linear-gradient(135deg, var(--secondary), #0099CC);
    box-shadow: var(--glow-secondary);
}

.btn-danger-fx {
    background: linear-gradient(135deg, #FF4757, #FF3742);
    box-shadow: 0 0 20px rgba(255, 71, 87, 0.4);
}

.btn-sm {
    padding: 8px 16px;
    font-size: 0.9rem;
}

/* === FORMULÁRIOS FUTURISTAS === */
.form-control.fx {
    background: var(--surface-lighter) !important;
    border: 1px solid var(--border) !important;
    color: var(--text-primary) !important;
    border-radius: 12px !important;
    padding: 14px 16px !important;
    transition: all 0.3s ease;
    font-size: 1rem;
}

.form-control.fx:focus {
    background: var(--surface-lighter) !important;
    border-color: var(--primary) !important;
    box-shadow: 0 0 0 0.2rem rgba(255, 107, 157, 0.25) !important;
    color: var(--text-primary) !important;
    outline: none;
}

.form-control.fx::placeholder {
    color: var(--text-muted) !important;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    color: var(--text-primary);
    font-weight: 600;
    margin-bottom: 8px;
    display: block;
}

/* === TABELA FUTURISTA === */
.table.fx {
    background: var(--surface-light);
    border: 1px solid var(--border);
    border-radius: 16px;
    overflow: hidden;
    margin-bottom: 0;
}

.table.fx thead {
    background: linear-gradient(135deg, var(--surface-lighter), var(--surface-light));
}

.table.fx th {
    color: var(--text-primary);
    border-bottom: 2px solid var(--primary);
    text-transform: uppercase;
    font-size: 0.85rem;
    letter-spacing: 0.5px;
    font-weight: 700;
    padding: 16px 12px;
}

.table.fx td {
    color: var(--text-secondary);
    vertical-align: middle;
    padding: 14px 12px;
    border-color: var(--border) !important;
}

.table.fx tbody tr {
    background: var(--surface-light);
    transition: all 0.3s ease;
    border-bottom: 1px solid var(--border);
}

.table.fx tbody tr:hover {
    background: rgba(255, 107, 157, 0.1);
    transform: translateX(4px);
}

/* === PREVIEW DE MÍDIA === */
.media-preview {
    border: 1px dashed var(--border);
    border-radius: 12px;
    padding: 16px;
    background: rgba(0, 0, 0, 0.2);
    text-align: center;
    transition: all 0.3s ease;
}

.media-preview:hover {
    border-color: var(--primary);
    background: rgba(255, 107, 157, 0.05);
}

.media-preview img,
.media-preview video {
    border-radius: 8px;
    max-width: 100%;
    height: auto;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

/* === MODAL FUTURISTA === */
.modal .modal-content {
    background: var(--surface-light);
    border: 1px solid var(--border);
    border-radius: 18px;
    color: var(--text-primary);
    box-shadow: var(--glow);
    backdrop-filter: blur(20px);
}

.modal .modal-header {
    border-bottom: 1px solid var(--border);
    background: linear-gradient(135deg, var(--surface-lighter), var(--surface-light));
    border-radius: 18px 18px 0 0;
    padding: 20px 24px;
}

.modal .modal-body {
    color: var(--text-secondary);
    padding: 24px;
}

.modal .modal-footer {
    border-top: 1px solid var(--border);
    padding: 20px 24px;
    border-radius: 0 0 18px 18px;
}

.modal .close {
    color: var(--text-primary);
    opacity: 0.8;
}

.modal .close:hover {
    opacity: 1;
    color: var(--primary);
}

/* === ALERTAS E NOTIFICAÇÕES === */
.alert-info {
    background: rgba(0, 212, 255, 0.1);
    border: 1px solid var(--secondary);
    color: var(--text-secondary);
    border-radius: 12px;
    padding: 16px 20px;
    margin-bottom: 20px;
}

.alert-info i {
    color: var(--secondary);
    margin-right: 8px;
}

/* === TOAST NOTIFICATIONS === */
.toast-fx {
    position: fixed;
    left: 50%;
    bottom: 24px;
    transform: translateX(-50%) translateY(100px);
    background: var(--surface-lighter);
    color: var(--text-primary);
    border: 1px solid var(--border);
    box-shadow: var(--glow);
    border-radius: 12px;
    padding: 16px 20px;
    font-weight: 600;
    z-index: 9999;
    opacity: 0;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 300px;
    text-align: center;
}

.toast-fx.show {
    transform: translateX(-50%) translateY(0);
    opacity: 1;
}

.toast-fx.error {
    border-color: rgba(255, 71, 87, 0.5);
    background: rgba(255, 71, 87, 0.1);
}

.toast-fx.success {
    border-color: rgba(0, 212, 255, 0.5);
    background: rgba(0, 212, 255, 0.1);
}

/* === PARTÍCULAS DECORATIVAS === */
.particle {
    position: fixed;
    bottom: 0;
    width: 2px;
    height: 2px;
    background: var(--primary);
    opacity: 0.4;
    animation: rise linear infinite;
    z-index: -1;
}

.particle:nth-child(odd) {
    background: var(--accent);
    opacity: 0.3;
}

@keyframes rise {
    from {
        transform: translateY(0) rotate(0deg);
        opacity: 0.6;
    }
    to {
        transform: translateY(-100vh) rotate(360deg);
        opacity: 0;
    }
}

/* === RESPONSIVIDADE === */
@media (max-width: 768px) {
    .main-wrap {
        padding: 16px;
    }
    
    .card-fx .card-header {
        padding: 16px 20px;
    }
    
    .btn-fx {
        padding: 10px 16px;
        font-size: 0.9rem;
    }
    
    .table.fx th,
    .table.fx td {
        padding: 12px 8px;
        font-size: 0.8rem;
    }
    
    .media-preview {
        padding: 12px;
    }
    
    .toast-fx {
        min-width: 280px;
        font-size: 0.9rem;
    }
}

/* === ANIMAÇÕES DE ENTRADA === */
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(30px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.card-fx {
    animation: fadeInUp 0.6s ease-out;
}
</style>

<div class="main-wrap container-fluid">
    <!-- Sistema de Partículas -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const n = 30;
            const body = document.body;
            
            for(let i = 0; i < n; i++) {
                const particle = document.createElement('div');
                particle.className = 'particle';
                particle.style.left = (Math.random() * 100) + 'vw';
                particle.style.animationDuration = (3 + Math.random() * 8) + 's';
                particle.style.animationDelay = (Math.random() * 5) + 's';
                particle.style.width = particle.style.height = (1 + Math.random() * 3) + 'px';
                body.appendChild(particle);
            }
            
            // Sistema de Toast
            window.customToast = function(message, type = 'success') {
                let toast = document.getElementById('toastFX');
                if (!toast) {
                    toast = document.createElement('div');
                    toast.id = 'toastFX';
                    toast.className = 'toast-fx';
                    document.body.appendChild(toast);
                }
                
                const icon = type === 'error' ? '❌' : '✅';
                toast.innerHTML = `${icon} ${message}`;
                toast.className = `toast-fx ${type}`;
                toast.classList.add('show');
                
                setTimeout(() => {
                    toast.classList.remove('show');
                }, 3000);
            };
        });
    </script>

    <?php if (isset($_GET['create'])) { ?>
        <!-- FORMULÁRIO DE CRIAÇÃO -->
        <div class="row justify-content-center">
            <div class="col-lg-8 col-xl-6">
                <div class="card-fx mb-4">
                    <div class="card-header">
                        <h4 class="card-title">
                            <i class="fas fa-plus-circle"></i>
                            Novo Anúncio
                        </h4>
                    </div>
                    <div class="card-body">
                        <div class="alert-info">
                            <i class="fas fa-info-circle"></i>
                            <strong>Dimensões recomendadas:</strong> 3295 x 2337 pixels (imagens claras, formatos: PNG, JPG, GIF, SVG, WEBP).
                        </div>
                        
                        <form method="post" onsubmit="return validateImageUrl(this.url.value)">
                            <div class="form-group">
                                <label>Título do Anúncio</label>
                                <input class="form-control fx" type="text" name="title" 
                                       placeholder="Ex: Promoção Especial - Black Friday" required>
                            </div>
                            
                            <div class="form-group">
                                <label>URL da Imagem</label>
                                <input class="form-control fx" type="text" name="url" id="createUrl" 
                                       placeholder="https://exemplo.com/banner.jpg" required 
                                       oninput="livePreview(this.value, 'createPreview')">
                                <small style="color: var(--text-muted); margin-top: 8px; display: block;">
                                    <i class="fas fa-link"></i> Insira um link direto para a imagem
                                </small>
                            </div>
                            
                            <div class="media-preview mb-4" id="createPreview" style="display: none;">
                                <!-- Preview será inserido aqui -->
                            </div>
                            
                            <div class="d-flex gap-3 flex-wrap">
                                <button type="submit" name="submit" class="btn-fx btn-accent">
                                    <i class="fas fa-save"></i>
                                    Salvar Anúncio
                                </button>
                                <a href="./<?php echo $base_file; ?>" class="btn-fx btn-secondary-fx">
                                    <i class="fas fa-arrow-left"></i>
                                    Voltar
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

    <?php } else if (isset($_GET['update'])) { ?>
        <!-- FORMULÁRIO DE EDIÇÃO -->
        <div class="row justify-content-center">
            <div class="col-lg-8 col-xl-6">
                <div class="card-fx mb-4">
                    <div class="card-header">
                        <h4 class="card-title">
                            <i class="fas fa-edit"></i>
                            Editar Anúncio
                        </h4>
                    </div>
                    <div class="card-body">
                        <form method="post" onsubmit="return validateImageUrl(this.url.value)">
                            <input type="hidden" name="id" value="<?= $_GET['update'] ?>">
                            
                            <div class="form-group">
                                <label>Título do Anúncio</label>
                                <input type="text" name="title" class="form-control fx" 
                                       value="<?= htmlspecialchars($rowU['title'] ?? '', ENT_QUOTES) ?>" required>
                            </div>
                            
                            <div class="form-group">
                                <label>URL da Imagem</label>
                                <input type="text" class="form-control fx" id="updateUrl" name="url" 
                                       value="<?= htmlspecialchars($rowU['url'] ?? '', ENT_QUOTES) ?>" required 
                                       oninput="livePreview(this.value, 'updatePreview')">
                            </div>
                            
                            <div class="media-preview mb-4" id="updatePreview" 
                                 style="display: <?= (!empty($rowU['url']) ? 'block' : 'none') ?>">
                                <?php if (!empty($rowU['url'])): ?>
                                    <img src="<?= $rowU['url'] ?>" width="280" style="border-radius: 8px" 
                                         onerror="this.style.display='none'" />
                                <?php endif; ?>
                            </div>
                            
                            <div class="d-flex gap-3 flex-wrap">
                                <button type="submit" name="submitU" class="btn-fx btn-accent">
                                    <i class="fas fa-sync-alt"></i>
                                    Atualizar Anúncio
                                </button>
                                <a href="./<?php echo $base_file; ?>" class="btn-fx btn-secondary-fx">
                                    <i class="fas fa-arrow-left"></i>
                                    Voltar
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

    <?php } else { ?>
        <!-- LISTA DE ANÚNCIOS -->
        <div class="row">
            <div class="col-12">
                <div class="card-fx mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-3">
                        <h4 class="card-title m-0">
                            <i class="fas fa-bullhorn"></i>
                            Meus Anúncios
                        </h4>
                        <a href="./<?php echo $base_file ?>?create" class="btn-fx btn-accent">
                            <i class="fas fa-plus"></i>
                            Novo Anúncio
                        </a>
                    </div>
                    
                    <div class="card-body">
                        <?php if ($res->fetchArray() === false): ?>
                            <div class="text-center py-5">
                                <i class="fas fa-inbox" style="font-size: 3rem; color: var(--text-muted); margin-bottom: 16px;"></i>
                                <h5 style="color: var(--text-secondary); margin-bottom: 8px;">Nenhum anúncio encontrado</h5>
                                <p style="color: var(--text-muted);">Comece criando seu primeiro anúncio!</p>
                                <a href="./<?php echo $base_file ?>?create" class="btn-fx btn-accent mt-3">
                                    <i class="fas fa-plus"></i>
                                    Criar Primeiro Anúncio
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-sm fx">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Título</th>
                                            <th>URL</th>
                                            <th>Proprietário</th>
                                            <th>Pré-visualização</th>
                                            <th>Ações</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $res->reset();
                                        while ($row = $res->fetchArray()): 
                                        ?>
                                            <tr>
                                                <td>
                                                    <span style="font-family: 'Courier New', monospace; color: var(--accent); font-weight: 600;">
                                                        #<?= $row['id'] ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <strong style="color: var(--text-primary);">
                                                        <?= htmlspecialchars($row['title']) ?>
                                                    </strong>
                                                </td>
                                                <td class="text-truncate" style="max-width: 300px;">
                                                    <span style="font-family: monospace; color: var(--text-secondary); font-size: 0.9rem;">
                                                        <?= htmlspecialchars($row['url']) ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <span style="font-family: monospace; color: var(--secondary);">
                                                        <?= htmlspecialchars($row['owner']) ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <div class="media-preview">
                                                        <?php if (isImageUrl($row['url'])): ?>
                                                            <img src="<?= $row['url'] ?>" width="120" 
                                                                 style="border-radius: 8px; max-height: 80px; object-fit: cover;"
                                                                 onerror="this.style.display='none'">
                                                        <?php else: ?>
                                                            <span style="color: var(--text-muted); font-size: 0.8rem;">
                                                                <i class="fas fa-eye-slash"></i> Sem preview
                                                            </span>
                                                        <?php endif; ?>
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="d-flex gap-2 flex-wrap">
                                                        <a href="<?php echo $base_file ?>?update=<?= $row['id'] ?>" 
                                                           class="btn-fx btn-secondary-fx btn-sm"
                                                           title="Editar">
                                                            <i class="fas fa-edit"></i>
                                                        </a>
                                                        <a href="#" 
                                                           class="btn-fx btn-danger-fx btn-sm"
                                                           data-href="<?php echo $base_file ?>?delete=<?= $row['id'] ?>" 
                                                           data-toggle="modal" data-target="#confirm-delete"
                                                           title="Excluir">
                                                            <i class="fas fa-trash"></i>
                                                        </a>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    <?php } ?>
</div>

<!-- Modal de Confirmação de Exclusão -->
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="modalDeleteLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 id="modalDeleteLabel" class="modal-title">
                    <i class="fas fa-exclamation-triangle" style="color: var(--accent);"></i>
                    Confirmar Exclusão
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
                    <span aria-hidden="true" style="color: var(--text-primary);">&times;</span>
                </button>
            </div>
            <div class="modal-body" style="color: var(--text-secondary);">
                <p>Tem certeza que deseja excluir este anúncio?</p>
                <p style="font-size: 0.9rem; color: var(--text-muted);">
                    <i class="fas fa-info-circle"></i> Esta ação não pode ser desfeita.
                </p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-fx btn-secondary-fx" data-dismiss="modal">
                    <i class="fas fa-times"></i>
                    Cancelar
                </button>
                <a class="btn-fx btn-danger-fx btn-ok">
                    <i class="fas fa-trash"></i>
                    Deletar
                </a>
            </div>
        </div>
    </div>
</div>

<?php include ('../includes/footer2.php'); ?>

<script>
// Configuração do Modal de Confirmação
$('#confirm-delete').on('show.bs.modal', function(e) {
    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});

// Validação de URL de Imagem
function validateImageUrl(url) {
    const validExtensions = /\.(jpg|jpeg|png|gif|webp|svg)(\?.*)?$/i;
    const isValid = validExtensions.test(url.trim());
    
    if (!isValid) {
        window.customToast('Por favor, insira um link válido de imagem! (JPG, PNG, GIF, WEBP, SVG)', 'error');
    }
    
    return isValid;
}

// Preview em Tempo Real
function livePreview(url, targetId) {
    const previewBox = document.getElementById(targetId);
    if (!previewBox) return;
    
    if (!url.trim()) {
        previewBox.style.display = 'none';
        previewBox.innerHTML = '';
        return;
    }
    
    previewBox.style.display = 'block';
    
    if (/\.(jpg|jpeg|png|gif|webp|svg)$/i.test(url)) {
        previewBox.innerHTML = `
            <img src="${url}" width="280" style="border-radius: 8px; max-height: 200px; object-fit: cover;" 
                 onerror="this.style.display='none'" />
            <div style="margin-top: 8px; color: var(--text-muted); font-size: 0.8rem;">
                <i class="fas fa-image"></i> Preview da imagem
            </div>
        `;
    } else {
        previewBox.innerHTML = `
            <div style="color: var(--text-muted); text-align: center; padding: 20px;">
                <i class="fas fa-eye-slash" style="font-size: 2rem; margin-bottom: 8px;"></i>
                <div>Formato não suportado para preview</div>
            </div>
        `;
    }
}

// Inicializar previews existentes
document.addEventListener('DOMContentLoaded', function() {
    // Preview no formulário de edição
    const updateUrl = document.getElementById('updateUrl');
    if (updateUrl && updateUrl.value) {
        livePreview(updateUrl.value, 'updatePreview');
    }
});
</script>