import { useState, useEffect } from 'react'; import { useRouter } from 'next/router'; import Navbar from '../Navbar'; export default function Admin() { const [token, setToken] = useState(''); const [authorized, setAuthorized] = useState(false); const [tab, setTab] = useState('crear'); const [stats, setStats] = useState({ total: 0, top: [] }); const [form, setForm] = useState({ title: '', tags: '', content: '' }); const [posts, setPosts] = useState([]); const router = useRouter(); useEffect(() => { const t = localStorage.getItem('blog_token'); if (!t) { router.push('/login'); } else { setToken(t); setAuthorized(true); loadPosts(); loadStats(t); } }, []); const loadPosts = () => { fetch('http://localhost:9002/posts') .then(r => r.json()) .then(setPosts) .catch(e => console.error("Error cargando posts")); }; const loadStats = (t) => { fetch('http://localhost:9002/posts/stats', { headers: { 'Authorization': `Bearer ${t || token}` } }) .then(r => r.json()) .then(setStats) .catch(e => console.error("Error en stats")); }; const handleLogout = () => { localStorage.removeItem('blog_token'); router.push('/login'); }; const handleSave = async (e) => { e.preventDefault(); const res = await fetch('http://localhost:9002/posts', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify(form) }); if (res.ok) { alert('Publicado con éxito'); setForm({ title: '', tags: '', content: '' }); loadPosts(); } }; const handleDelete = async (id) => { if(!confirm('¿Estás seguro de eliminar este post?')) return; await fetch(`http://localhost:9002/posts/${id}`, { method: 'DELETE', headers: { 'Authorization': `Bearer ${token}` } }); loadPosts(); }; // Protección de renderizado if (!authorized) { return

Verificando credenciales...

; } return (

Panel Administrativo

{/* NAVEGACIÓN */}
{/* CONTENIDO */} {tab === 'crear' && (
setForm({...form, title: e.target.value})} style={{ width: '100%', padding: '15px', marginBottom: '20px', borderRadius: '8px', border: '1px solid #e2e8f0', fontSize: '1rem', boxSizing: 'border-box' }} required /> setForm({...form, tags: e.target.value})} style={{ width: '100%', padding: '15px', marginBottom: '20px', borderRadius: '8px', border: '1px solid #e2e8f0', fontSize: '1rem', boxSizing: 'border-box' }} />