<?php
// nuevo_producto_market.php
require __DIR__ . '/market_bootstrap.php';

if (!market_is_logged()) {
    header('Location: login_market.php');
    exit;
}
$pdo = market_pdo();
$U   = market_current_user();

$errores = [];
$ok      = '';

$titulo     = '';
$descripcion= '';
$precio     = '';
$modo_precio= 'consultar';
$ubicacion  = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $titulo      = trim($_POST['titulo'] ?? '');
    $descripcion = trim($_POST['descripcion'] ?? '');
    $precio      = trim($_POST['precio'] ?? '');
    $modo_precio = ($_POST['modo_precio'] ?? 'consultar') === 'precio' ? 'precio' : 'consultar';
    $ubicacion   = trim($_POST['ubicacion'] ?? '');

    if ($titulo === '') {
        $errores[] = 'Poné un título para el producto.';
    }

    if (!$errores) {
        $precioVal = null;
        if ($modo_precio === 'precio' && $precio !== '') {
            $precioVal = (float)str_replace(',','.', $precio);
        }

        $st = $pdo->prepare("
            INSERT INTO market_productos (usuario_id, titulo, descripcion, precio, modo_precio, ubicacion, estado, created_at)
            VALUES (?, ?, ?, ?, ?, ?, 'activo', NOW())
        ");
        $st->execute([$U['id'], $titulo, $descripcion, $precioVal, $modo_precio, $ubicacion]);
        $producto_id = (int)$pdo->lastInsertId();

        // Fotos múltiples
        if (!empty($_FILES['fotos']['name'][0])) {
            $total = count($_FILES['fotos']['name']);
            for ($i = 0; $i < $total; $i++) {
                if ($_FILES['fotos']['error'][$i] !== UPLOAD_ERR_OK || $_FILES['fotos']['name'][$i] === '') {
                    continue;
                }
                // Armar un archivo temporal para reutilizar market_upload_file
                $tmp = [
                    'name'     => $_FILES['fotos']['name'][$i],
                    'type'     => $_FILES['fotos']['type'][$i],
                    'tmp_name' => $_FILES['fotos']['tmp_name'][$i],
                    'error'    => $_FILES['fotos']['error'][$i],
                    'size'     => $_FILES['fotos']['size'][$i],
                ];
                $_FILES['_mkfoto'] = $tmp;
                $ruta = market_upload_file('_mkfoto', null);
                unset($_FILES['_mkfoto']);

                if ($ruta) {
                    $es_portada = ($i === 0) ? 1 : 0;
                    $stF = $pdo->prepare("
                        INSERT INTO market_productos_fotos (producto_id, archivo, es_portada)
                        VALUES (?, ?, ?)
                    ");
                    $stF->execute([$producto_id, $ruta, $es_portada]);
                }
            }
        }

        $ok = 'Producto publicado correctamente.';
        // reset para que quede limpio el formulario
        $titulo = $descripcion = $precio = $ubicacion = '';
        $modo_precio = 'consultar';
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <title>Nuevo producto - Marketplace</title>
    <?php require __DIR__ . '/_head_assets.php'; ?>
    <style>
        :root {
            --mk-primary: #198754;
            --mk-primary-light: #20c997;
            --mk-secondary: #6c757d;
            --mk-dark: #212529;
            --mk-light: #f8f9fc;
            --mk-border: #e0e4f0;
            --mk-shadow: 0 12px 30px rgba(0,0,0,0.08);
            --mk-shadow-hover: 0 18px 40px rgba(0,0,0,0.12);
            --mk-radius: 16px;
            --mk-radius-sm: 12px;
        }

        body {
            font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        }

        .mk-main {
            padding: 2rem 0 3rem;
            background: linear-gradient(135deg, #f4f6fb 0%, #f0f4ff 100%);
            min-height: 100vh;
        }

        .mk-card {
            background: #fff;
            border-radius: var(--mk-radius);
            box-shadow: var(--mk-shadow);
            overflow: hidden;
            max-width: 900px;
            margin: 0 auto;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            border: 1px solid rgba(255,255,255,0.2);
        }

        .mk-card:hover {
            transform: translateY(-3px);
            box-shadow: var(--mk-shadow-hover);
        }

        .mk-card-header {
            padding: 1.8rem 2rem;
            background: linear-gradient(135deg, var(--mk-primary), var(--mk-primary-light));
            color: #fff;
            position: relative;
            overflow: hidden;
        }

        .mk-card-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 100%;
            height: 200%;
            background: linear-gradient(45deg, transparent, rgba(255,255,255,0.1), transparent);
            transform: rotate(45deg);
            animation: shine 3s infinite;
        }

        @keyframes shine {
            0% { transform: translateX(-100%) rotate(45deg); }
            100% { transform: translateX(100%) rotate(45deg); }
        }

        .mk-card-header h1 {
            font-size: 1.6rem;
            margin: 0;
            font-weight: 700;
            line-height: 1.3;
            position: relative;
            z-index: 2;
        }

        .mk-card-header p {
            margin: 0.4rem 0 0;
            font-size: 0.95rem;
            opacity: 0.95;
            font-weight: 500;
            position: relative;
            z-index: 2;
        }

        .mk-card-body {
            padding: 2rem;
        }

        /* ===== FORM CONTROLS ===== */
        .mk-form-group {
            margin-bottom: 1.5rem;
        }

        .mk-label {
            font-weight: 600;
            font-size: 0.9rem;
            color: var(--mk-dark);
            margin-bottom: 0.5rem;
            display: block;
        }

        .mk-label-required::after {
            content: ' *';
            color: #dc3545;
        }

        .mk-form-control {
            border: 1.5px solid #e0e4f0;
            border-radius: var(--mk-radius-sm);
            padding: 0.75rem 1rem;
            font-size: 0.95rem;
            transition: all 0.3s ease;
            background: #fff;
            width: 100%;
        }

        .mk-form-control:focus {
            outline: none;
            border-color: var(--mk-primary);
            box-shadow: 0 0 0 3px rgba(25, 135, 84, 0.1);
            background: #fff;
        }

        .mk-form-control::placeholder {
            color: #9ca3af;
            font-size: 0.9rem;
        }

        textarea.mk-form-control {
            resize: vertical;
            min-height: 100px;
            line-height: 1.5;
        }

        .mk-help {
            font-size: 0.8rem;
            color: var(--mk-secondary);
            margin-top: 0.4rem;
            line-height: 1.4;
        }

        /* ===== RADIO CHIPS MEJORADOS ===== */
        .mk-radio-group {
            display: flex;
            gap: 0.8rem;
            margin-bottom: 1rem;
            flex-wrap: wrap;
        }

        .mk-radio-chip {
            position: relative;
        }

        .mk-radio-chip input {
            position: absolute;
            opacity: 0;
        }

        .mk-radio-chip label {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.7rem 1.2rem;
            border: 1.5px solid #e0e4f0;
            border-radius: 50px;
            font-size: 0.9rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            background: #fff;
            color: var(--mk-dark);
        }

        .mk-radio-chip label:hover {
            border-color: var(--mk-primary);
            transform: translateY(-1px);
        }

        .mk-radio-chip input:checked + label {
            background: linear-gradient(135deg, var(--mk-primary), var(--mk-primary-light));
            color: #fff;
            border-color: var(--mk-primary);
            box-shadow: 0 4px 12px rgba(25, 135, 84, 0.2);
        }

        .mk-radio-icon {
            width: 16px;
            height: 16px;
            opacity: 0.8;
        }

        .mk-radio-chip input:checked + label .mk-radio-icon {
            opacity: 1;
            filter: brightness(0) invert(1);
        }

        /* ===== DROPZONE MEJORADO ===== */
        .mk-dropzone {
            border: 2px dashed #d1d9e6;
            border-radius: var(--mk-radius-sm);
            padding: 1.5rem;
            background: var(--mk-light);
            transition: all 0.3s ease;
            text-align: center;
            cursor: pointer;
            position: relative;
        }

        .mk-dropzone:hover {
            border-color: var(--mk-primary);
            background: rgba(25, 135, 84, 0.02);
            transform: translateY(-1px);
        }

        .mk-dropzone.dragover {
            border-color: var(--mk-primary);
            background: rgba(25, 135, 84, 0.05);
            transform: scale(1.02);
        }

        .mk-dropzone-icon {
            font-size: 2rem;
            margin-bottom: 0.8rem;
            opacity: 0.7;
        }

        .mk-dropzone:hover .mk-dropzone-icon {
            opacity: 1;
            transform: scale(1.1);
        }

        .mk-dropzone-title {
            font-weight: 600;
            font-size: 1rem;
            color: var(--mk-dark);
            margin-bottom: 0.4rem;
        }

        .mk-dropzone-subtitle {
            font-size: 0.85rem;
            color: var(--mk-secondary);
            margin-bottom: 1rem;
        }

        .mk-file-input {
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            opacity: 0;
            cursor: pointer;
        }

        /* ===== PREVIEW DE IMÁGENES ===== */
        .mk-preview-container {
            margin-top: 1.5rem;
            display: none;
        }

        .mk-preview-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 1rem;
            margin-top: 1rem;
        }

        .mk-preview-item {
            position: relative;
            border-radius: var(--mk-radius-sm);
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            background: #f8f9fa;
            aspect-ratio: 1;
        }

        .mk-preview-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.15);
        }

        .mk-preview-item.portada::before {
            content: 'PORTADA';
            position: absolute;
            top: 8px;
            left: 8px;
            background: var(--mk-primary);
            color: white;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 0.7rem;
            font-weight: 600;
            z-index: 2;
        }

        .mk-preview-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s ease;
        }

        .mk-preview-item:hover .mk-preview-img {
            transform: scale(1.05);
        }

        .mk-preview-info {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: linear-gradient(transparent, rgba(0,0,0,0.7));
            color: white;
            padding: 0.5rem;
            font-size: 0.75rem;
        }

        .mk-preview-name {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-weight: 500;
        }

        .mk-preview-size {
            opacity: 0.8;
            font-size: 0.7rem;
        }

        .mk-preview-remove {
            position: absolute;
            top: 8px;
            right: 8px;
            width: 24px;
            height: 24px;
            background: rgba(220, 53, 69, 0.9);
            border: none;
            border-radius: 50%;
            color: white;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.8rem;
            transition: all 0.3s ease;
            opacity: 0;
        }

        .mk-preview-item:hover .mk-preview-remove {
            opacity: 1;
        }

        .mk-preview-remove:hover {
            background: #dc3545;
            transform: scale(1.1);
        }

        .mk-preview-empty {
            text-align: center;
            padding: 2rem;
            color: var(--mk-secondary);
            font-size: 0.9rem;
        }

        .mk-preview-empty-icon {
            font-size: 2rem;
            margin-bottom: 0.5rem;
            opacity: 0.5;
        }

        /* ===== LOADING STATE ===== */
        .mk-preview-loading {
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f8f9fa;
        }

        .mk-loading-spinner {
            width: 30px;
            height: 30px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid var(--mk-primary);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* ===== BOTONES MEJORADOS ===== */
        .mk-actions {
            display: flex;
            flex-wrap: wrap;
            gap: 0.8rem;
            margin-top: 2rem;
            padding-top: 1.5rem;
            border-top: 1px solid var(--mk-border);
        }

        .mk-btn {
            border: none;
            border-radius: var(--mk-radius-sm);
            font-weight: 600;
            padding: 0.8rem 1.8rem;
            font-size: 0.9rem;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .mk-btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            transition: left 0.5s;
        }

        .mk-btn:hover::before {
            left: 100%;
        }

        .mk-btn-primary {
            background: linear-gradient(135deg, var(--mk-primary), var(--mk-primary-light));
            color: #fff;
            box-shadow: 0 4px 15px rgba(25, 135, 84, 0.3);
        }

        .mk-btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(25, 135, 84, 0.4);
            color: #fff;
        }

        .mk-btn-outline {
            background: transparent;
            border: 1.5px solid var(--mk-secondary);
            color: var(--mk-secondary);
        }

        .mk-btn-outline:hover {
            background: var(--mk-secondary);
            color: #fff;
            transform: translateY(-2px);
        }

        .mk-btn-dark {
            background: transparent;
            border: 1.5px solid var(--mk-dark);
            color: var(--mk-dark);
        }

        .mk-btn-dark:hover {
            background: var(--mk-dark);
            color: #fff;
            transform: translateY(-2px);
        }

        .mk-btn-icon {
            width: 16px;
            height: 16px;
        }

        /* ===== ALERTS MEJORADOS ===== */
        .mk-alert {
            border-radius: var(--mk-radius-sm);
            padding: 1rem 1.2rem;
            margin-bottom: 1.5rem;
            border: 1px solid transparent;
            font-size: 0.9rem;
        }

        .mk-alert-danger {
            background: linear-gradient(135deg, #f8d7da, #f5c6cb);
            border-color: #f1aeb5;
            color: #721c24;
        }

        .mk-alert-success {
            background: linear-gradient(135deg, #d1edff, #b6e0ff);
            border-color: #66b3ff;
            color: #004085;
        }

        /* ===== ANIMACIONES ===== */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .mk-card {
            animation: fadeInUp 0.6s ease-out;
        }

        /* ===== RESPONSIVE ===== */
        @media (max-width: 767.98px) {
            .mk-main {
                padding: 1.5rem 0 2rem;
            }
            
            .mk-card-body {
                padding: 1.5rem;
            }
            
            .mk-card-header {
                padding: 1.5rem 1.5rem;
            }
            
            .mk-card-header h1 {
                font-size: 1.4rem;
            }
            
            .mk-radio-group {
                flex-direction: column;
                gap: 0.5rem;
            }
            
            .mk-radio-chip label {
                width: 100%;
                justify-content: center;
            }
            
            .mk-preview-grid {
                grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
                gap: 0.8rem;
            }
            
            .mk-actions {
                flex-direction: column;
            }
            
            .mk-actions .mk-btn {
                width: 100%;
                justify-content: center;
            }
        }

        @media (max-width: 575.98px) {
            .mk-card-body {
                padding: 1.2rem;
            }
            
            .mk-dropzone {
                padding: 1rem;
            }
            
            .mk-preview-grid {
                grid-template-columns: repeat(3, 1fr);
            }
        }
    </style>
</head>
<body>
<?php require __DIR__ . '/_navbar.php'; ?>

<main class="mk-main">
    <div class="container">
        <div class="mk-card">
            <div class="mk-card-header">
                <h1>Nuevo producto</h1>
                <p>Publicá un producto o servicio para otros camioneros.</p>
            </div>
            <div class="mk-card-body">
                <?php if ($errores): ?>
                    <div class="mk-alert mk-alert-danger">
                        <?php foreach ($errores as $e): ?>
                            <div><?= htmlspecialchars($e, ENT_QUOTES, 'UTF-8') ?></div>
                        <?php endforeach; ?>
                    </div>
                <?php elseif ($ok): ?>
                    <div class="mk-alert mk-alert-success"><?= htmlspecialchars($ok, ENT_QUOTES, 'UTF-8') ?></div>
                <?php endif; ?>

                <form method="post" enctype="multipart/form-data" id="mkForm">
                    <!-- TÍTULO -->
                    <div class="mk-form-group">
                        <label class="mk-label mk-label-required">Título del producto</label>
                        <input class="mk-form-control" type="text" name="titulo"
                               value="<?= htmlspecialchars($titulo, ENT_QUOTES, 'UTF-8') ?>" 
                               placeholder="Ej: Acoplado semi remolque excelente estado"
                               required>
                    </div>

                    <!-- DESCRIPCIÓN -->
                    <div class="mk-form-group">
                        <label class="mk-label">Descripción</label>
                        <textarea class="mk-form-control" name="descripcion" rows="4"
                                  placeholder="Detalles, estado, forma de entrega, características técnicas, etc."><?= htmlspecialchars($descripcion, ENT_QUOTES, 'UTF-8') ?></textarea>
                        <div class="mk-help">Incluí toda la información relevante para los compradores.</div>
                    </div>

                    <!-- PRECIO Y UBICACIÓN -->
                    <div class="row g-4">
                        <div class="col-md-6">
                            <div class="mk-form-group">
                                <label class="mk-label">Tipo de precio</label>
                                <div class="mk-radio-group">
                                    <div class="mk-radio-chip">
                                        <input type="radio" name="modo_precio" id="mp1" value="precio" <?= $modo_precio==='precio'?'checked':''; ?>>
                                        <label for="mp1">
                                            <span class="mk-radio-icon">💰</span>
                                            Mostrar precio
                                        </label>
                                    </div>
                                    <div class="mk-radio-chip">
                                        <input type="radio" name="modo_precio" id="mp2" value="consultar" <?= $modo_precio!=='precio'?'checked':''; ?>>
                                        <label for="mp2">
                                            <span class="mk-radio-icon">💬</span>
                                            Consultar precio
                                        </label>
                                    </div>
                                </div>
                                <input class="mk-form-control" type="text" name="precio"
                                       value="<?= htmlspecialchars($precio, ENT_QUOTES, 'UTF-8') ?>"
                                       placeholder="Ej: 150000"
                                       id="precioInput">
                                <div class="mk-help">Si elegís "Consultar precio", este valor no se mostrará públicamente.</div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mk-form-group">
                                <label class="mk-label">Ubicación</label>
                                <input class="mk-form-control" type="text" name="ubicacion"
                                       value="<?= htmlspecialchars($ubicacion, ENT_QUOTES, 'UTF-8') ?>"
                                       placeholder="Ej: Rosario, Santa Fe">
                                <div class="mk-help">Ciudad / provincia o zona donde se encuentra el producto.</div>
                            </div>
                        </div>
                    </div>

                    <!-- FOTOS -->
                    <div class="mk-form-group">
                        <label class="mk-label">Fotos del producto</label>
                        <div class="mk-dropzone" id="mkDropzone">
                            <div class="mk-dropzone-icon">📷</div>
                            <div class="mk-dropzone-title">Subí las fotos de tu producto</div>
                            <div class="mk-dropzone-subtitle">Arrastrá imágenes aquí o hacé click para seleccionar</div>
                            <input class="mk-file-input" type="file" name="fotos[]" multiple accept="image/*" id="fileInput">
                            <div class="text-muted" style="font-size: 0.8rem;">Formatos: JPG, PNG, GIF • Máx: 5MB por imagen</div>
                        </div>
                        
                        <!-- PREVIEW DE IMÁGENES -->
                        <div class="mk-preview-container" id="previewContainer">
                            <div class="mk-label">Vista previa de las fotos</div>
                            <div class="mk-preview-grid" id="previewGrid"></div>
                        </div>
                    </div>

                    <!-- ACCIONES -->
                    <div class="mk-actions">
                        <button type="submit" class="mk-btn mk-btn-primary">
                            <span class="mk-btn-icon">🚀</span>
                            Publicar en el Marketplace
                        </button>
                        <a href="perfil_market.php" class="mk-btn mk-btn-outline">
                            <span class="mk-btn-icon">👤</span>
                            Volver a mi perfil
                        </a>
                        <a href="market.php" class="mk-btn mk-btn-dark">
                            <span class="mk-btn-icon">←</span>
                            Volver al listado
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</main>

<?php require __DIR__ . '/_footer.php'; ?>
<?php require __DIR__ . '/_navbar_script.php'; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const dropzone = document.getElementById('mkDropzone');
    const fileInput = document.getElementById('fileInput');
    const previewContainer = document.getElementById('previewContainer');
    const previewGrid = document.getElementById('previewGrid');
    const precioInput = document.getElementById('precioInput');
    const modoPrecioRadios = document.querySelectorAll('input[name="modo_precio"]');
    const form = document.getElementById('mkForm');

    let uploadedFiles = [];

    // Manejar drag & drop
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropzone.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    ['dragenter', 'dragover'].forEach(eventName => {
        dropzone.addEventListener(eventName, highlight, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dropzone.addEventListener(eventName, unhighlight, false);
    });

    function highlight() {
        dropzone.classList.add('dragover');
    }

    function unhighlight() {
        dropzone.classList.remove('dragover');
    }

    dropzone.addEventListener('drop', handleDrop, false);

    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        handleFiles(files);
    }

    fileInput.addEventListener('change', function() {
        handleFiles(this.files);
    });

    function handleFiles(files) {
        if (files.length > 0) {
            Array.from(files).forEach((file, index) => {
                if (file.type.startsWith('image/')) {
                    addFileToPreview(file, uploadedFiles.length);
                    uploadedFiles.push(file);
                }
            });
            
            updateDropzoneText();
            updateFileInput();
            showPreviewContainer();
        }
    }

    function addFileToPreview(file, index) {
        const reader = new FileReader();
        
        const previewItem = document.createElement('div');
        previewItem.className = `mk-preview-item ${index === 0 ? 'portada' : ''}`;
        previewItem.setAttribute('data-index', index);
        
        // Loading state
        previewItem.innerHTML = `
            <div class="mk-preview-loading">
                <div class="mk-loading-spinner"></div>
            </div>
        `;
        
        previewGrid.appendChild(previewItem);

        reader.onload = function(e) {
            previewItem.innerHTML = `
                <img src="${e.target.result}" alt="${file.name}" class="mk-preview-img" loading="lazy">
                <div class="mk-preview-info">
                    <div class="mk-preview-name">${file.name}</div>
                    <div class="mk-preview-size">${(file.size / 1024 / 1024).toFixed(2)} MB</div>
                </div>
                <button type="button" class="mk-preview-remove" onclick="removeFile(${index})">×</button>
            `;
        };

        reader.readAsDataURL(file);
    }

    function removeFile(index) {
        uploadedFiles.splice(index, 1);
        renderPreview();
        updateDropzoneText();
        updateFileInput();
        
        if (uploadedFiles.length === 0) {
            hidePreviewContainer();
        }
    }

    function renderPreview() {
        previewGrid.innerHTML = '';
        uploadedFiles.forEach((file, index) => {
            addFileToPreview(file, index);
        });
    }

    function updateDropzoneText() {
        const subtitle = dropzone.querySelector('.mk-dropzone-subtitle');
        if (uploadedFiles.length === 0) {
            subtitle.textContent = 'Arrastrá imágenes aquí o hacé click para seleccionar';
        } else if (uploadedFiles.length === 1) {
            subtitle.textContent = '1 imagen seleccionada • Hacé click para agregar más';
        } else {
            subtitle.textContent = `${uploadedFiles.length} imágenes seleccionadas • Hacé click para agregar más`;
        }
    }

    function updateFileInput() {
        // Crear un nuevo DataTransfer para actualizar los archivos
        const dt = new DataTransfer();
        uploadedFiles.forEach(file => {
            dt.items.add(file);
        });
        fileInput.files = dt.files;
    }

    function showPreviewContainer() {
        previewContainer.style.display = 'block';
        previewContainer.style.animation = 'fadeInUp 0.5s ease-out';
    }

    function hidePreviewContainer() {
        previewContainer.style.display = 'none';
    }

    // Mostrar/ocultar campo de precio según selección
    function togglePrecioInput() {
        const mostrarPrecio = document.querySelector('input[name="modo_precio"]:checked').value === 'precio';
        precioInput.style.display = mostrarPrecio ? 'block' : 'none';
        if (!mostrarPrecio) {
            precioInput.value = '';
        }
    }

    modoPrecioRadios.forEach(radio => {
        radio.addEventListener('change', togglePrecioInput);
    });

    // Inicializar estado del campo precio
    togglePrecioInput();

    // Validación del formulario
    form.addEventListener('submit', function(e) {
        const titulo = form.querySelector('input[name="titulo"]').value.trim();
        if (!titulo) {
            e.preventDefault();
            form.querySelector('input[name="titulo"]').focus();
            return;
        }
    });

    // Hacer la función removeFile global para que funcione en los botones
    window.removeFile = removeFile;
});
</script>
</body>
</html>