import { useState, useEffect } from 'react'; import { useSearchParams, useNavigate } from 'react-router-dom'; // Importar useNavigate import { AvisosService } from '../services/avisos.service'; import { AdsV2Service } from '../services/ads.v2.service'; import { AuthService, type UserSession } from '../services/auth.service'; import type { DatosAvisoDto } from '../types/aviso.types'; import FormularioAviso from '../components/FormularioAviso'; import LoginModal from '../components/LoginModal'; const TAREAS_DISPONIBLES = [ { id: 'EAUTOS', label: 'Automóviles', icon: '🚗', description: 'Venta de Autos, Camionetas y Utilitarios' }, { id: 'EMOTOS', label: 'Motos', icon: '🏍️', description: 'Venta de Motos, Cuatriciclos y Náutica' }, ]; export default function PublicarAvisoPage() { const [searchParams] = useSearchParams(); const navigate = useNavigate(); // Hook de navegación const editId = searchParams.get('edit'); const [categorySelection, setCategorySelection] = useState(''); const [tarifas, setTarifas] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [planSeleccionado, setPlanSeleccionado] = useState(null); const [fixedCategory, setFixedCategory] = useState(null); const [user, setUser] = useState(AuthService.getCurrentUser()); useEffect(() => { if (editId) { cargarAvisoParaEdicion(parseInt(editId)); } }, [editId]); const cargarAvisoParaEdicion = async (id: number) => { setLoading(true); try { const ad = await AdsV2Service.getById(id); // Determinamos la categoría para cargar las tarifas correspondientes const categoryCode = ad.vehicleTypeID === 1 ? 'EAUTOS' : 'EMOTOS'; setCategorySelection(categoryCode); // 🟢 FIX: Bloquear el cambio de categoría setFixedCategory(categoryCode); // 🟢 FIX: NO seleccionamos plan automáticamente. // Dejamos que el usuario elija el plan en las tarjetas. // (Eliminamos todo el bloque de setPlanSeleccionado) /* BLOQUE ELIMINADO: const tarifasData = await AvisosService.obtenerConfiguracion('EMOTORES', ad.isFeatured ? 1 : 0); const tarifaReal = tarifasData[0]; if (!tarifaReal) throw new Error("Tarifa no encontrada"); setPlanSeleccionado({ ... }); */ } catch (err) { console.error(err); setError("Error al cargar el aviso."); } finally { setLoading(false); } }; useEffect(() => { if (!categorySelection) return; const cargarTarifas = async () => { setLoading(true); setError(null); try { const [simple, destacado] = await Promise.all([ AvisosService.obtenerConfiguracion('EMOTORES', 0), AvisosService.obtenerConfiguracion('EMOTORES', 1) ]); const planes = [...simple, ...destacado]; planes.sort((a, b) => a.importeTotsiniva - b.importeTotsiniva); setTarifas(planes); } catch (err) { setError("Error al cargar tarifas."); console.error(err); } finally { setLoading(false); } }; cargarTarifas(); }, [categorySelection]); const handleSelectPlan = (plan: DatosAvisoDto) => { const vehicleTypeId = categorySelection === 'EAUTOS' ? 1 : 2; const nombrePlanAmigable = plan.paquete === 1 ? 'PLAN DESTACADO' : 'PLAN ESTÁNDAR'; setPlanSeleccionado({ ...plan, idRubro: vehicleTypeId, nomavi: nombrePlanAmigable }); }; // Manejador centralizado de éxito const handleSuccess = (adId: number, isAdminAction: boolean = false) => { const status = isAdminAction ? 'admin_created' : 'approved'; navigate(`/pago-confirmado?status=${status}&adId=${adId}`); }; if (!user) { return (
setUser(u)} onClose={() => navigate('/')} />
); } // ELIMINADO: Bloque if (publicacionExitosa) { return ... } if (planSeleccionado) { return (
Publicando como: {user.username}
setPlanSeleccionado(null)} onSuccess={handleSuccess} // Usamos la redirección editId={editId ? parseInt(editId) : null} />
); } return (

Comienza a Vender

Selecciona una categoría para ver los planes de publicación.

{/* SECCIÓN DE CATEGORÍA */}
{TAREAS_DISPONIBLES.map(t => { // Lógica de bloqueo const isDisabled = fixedCategory && fixedCategory !== t.id; return ( ); })}
{/* LISTA DE PLANES */} {categorySelection && (

Planes Disponibles

Para {categorySelection === 'EAUTOS' ? 'Automóviles' : 'Motos'}

Precios finales (IVA Incluido)
{error && (

Error de Conexión

{error}

)} {loading ? (
) : (
{tarifas.map((tarifa, idx) => { const precioRaw = tarifa.importeTotsiniva > 0 ? tarifa.importeTotsiniva * 1.105 : tarifa.importeSiniva * 1.105; const precioFinal = Math.round(precioRaw); const esDestacado = tarifa.paquete === 1; const tituloPlan = esDestacado ? "DESTACADO" : "ESTÁNDAR"; const descripcionPlan = esDestacado ? "Máxima visibilidad. Tu aviso aparecerá en el carrusel de inicio y primeros lugares de búsqueda." : "Presencia esencial. Tu aviso aparecerá en el listado general de búsqueda."; return (
handleSelectPlan(tarifa)} className={`glass-card p-8 rounded-[2.5rem] flex flex-col group cursor-pointer relative overflow-hidden transition-all hover:-translate-y-2 hover:shadow-2xl ${esDestacado ? 'border-blue-500/30 hover:border-blue-500 hover:shadow-blue-900/20' : 'hover:border-white/30'}`}>
{esDestacado ? 'RECOMENDADO' : 'BÁSICO'}

{tituloPlan}

{descripcionPlan}

  • Plataforma SOLO WEB
  • Duración {tarifa.cantidadDias} Días
  • Fotos Hasta 5
  • Visibilidad {esDestacado ? 'ALTA ⭐' : 'NORMAL'}
Precio Final
${precioFinal.toLocaleString('es-AR', { minimumFractionDigits: 0, maximumFractionDigits: 0 })} ARS
); })}
)}
)}
); }