import { useState, useEffect } from 'react';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
import { usePublicAuthStore } from './store/publicAuthStore';
import { motion, AnimatePresence } from 'framer-motion';
import api from './services/api';

// Páginas e Interfaz
import HomePage from './pages/HomePage';
import ListingDetailPage from './pages/ListingDetailPage';
import LoginPage from './pages/LoginPage';
import ProfilePage from './pages/ProfilePage';
import PublishPage from './pages/PublishPage';
import PublishFeedback from './pages/PublishFeedback';

// Componentes de Seguridad y Navegación
import { ProtectedRoute } from './components/ProtectedRoute';
import {
  User as UserIcon,
  LogIn,
  ChevronDown,
  LogOut,
  PlusCircle,
  Mail,
  MapPin,
  Phone
} from 'lucide-react';

// ICONOS DE REDES SOCIALES (SVG PUROS)
const SocialIcons = {
  Facebook: () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M9.101 23.691v-7.98H6.627v-3.667h2.474v-1.58c0-4.085 1.848-5.978 5.858-5.978 1.62 0 3.341.252 3.341.252v3.389h-1.835c-1.906 0-2.456 1.159-2.456 2.439v1.478h3.82l-.611 3.667h-3.21v7.98H9.101z" /></svg>
  ),
  Instagram: () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="2" width="20" height="20" rx="5" ry="5"></rect><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"></path><line x1="17.5" y1="6.5" x2="17.51" y2="6.5"></line></svg>
  ),
  X: () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932 6.064-6.932zm-1.292 19.49h2.039L6.486 3.24H4.298L17.609 20.643z" /></svg>
  ),
  Youtube: () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z" /></svg>
  )
};

function App() {
  const { user, logout } = usePublicAuthStore();
  const [isUserMenuOpen, setIsUserMenuOpen] = useState(false);
  const [unreadCount, setUnreadCount] = useState(0);

  const handleLogout = () => {
    logout();
    setIsUserMenuOpen(false);
  };

  // Cargar conteo de mensajes no leídos
  useEffect(() => {
    if (user) {
      const loadUnread = async () => {
        try {
          const res = await api.get('/usernotes/unread-count');
          setUnreadCount(res.data);
        } catch (e) {
          console.error("Error cargando notificaciones", e);
        }
      };

      const handleUnreadChange = (e: any) => {
        if (e.detail !== undefined) {
          setUnreadCount(e.detail);
        } else {
          loadUnread();
        }
      };

      loadUnread();
      window.addEventListener('unread-count-changed', handleUnreadChange);

      // Polling cada 60 segundos por si acaso
      const interval = setInterval(loadUnread, 60000);

      return () => {
        window.removeEventListener('unread-count-changed', handleUnreadChange);
        clearInterval(interval);
      };
    }
  }, [user]);

  return (
    <BrowserRouter>
      <div className="flex flex-col min-h-screen font-sans bg-[#f8fafc]">
        {/* HEADER */}
        <header className="bg-white/80 backdrop-blur-md border-b border-slate-100 py-4 px-6 sticky top-0 z-50">
          <div className="max-w-7xl mx-auto flex items-center justify-between">
            <Link to="/" className="font-black text-3xl text-slate-900 tracking-tighter flex items-center gap-2">
              <span className="bg-blue-600 w-2 h-7 rounded-full"></span>
              SIG-CM
            </Link>

            <nav className="hidden md:flex gap-10 text-[10px] font-black uppercase tracking-[0.2em] text-slate-400">
              <Link to="/" className="hover:text-blue-600 transition-colors">Inicio</Link>
              <a href="/#categories" className="hover:text-blue-600 transition-colors">Categorías</a>
              <a href="#" className="hover:text-blue-600 transition-colors">Soporte</a>
            </nav>

            <div className="flex items-center gap-4">
              {user ? (
                <div className="flex items-center gap-3">
                  {/* CAMPANA DE NOTIFICACIONES */}
                  <Link
                    to="/profile?tab=mensajes"
                    className="relative p-3 bg-slate-50 rounded-2xl border border-slate-100 text-slate-400 hover:text-blue-600 hover:bg-white transition-all group"
                    title="Ver mensajes"
                  >
                    <Mail size={20} className="group-hover:scale-110 transition-transform" />
                    {unreadCount > 0 && (
                      <span className="absolute top-2 right-2 flex h-5 w-5 items-center justify-center rounded-full bg-rose-500 text-[10px] font-black text-white ring-4 ring-white shadow-lg shadow-rose-200 animate-bounce">
                        {unreadCount > 9 ? '9+' : unreadCount}
                      </span>
                    )}
                  </Link>

                  <div className="relative">
                    <button
                      onClick={() => setIsUserMenuOpen(!isUserMenuOpen)}
                      className="flex items-center gap-3 bg-slate-50 pl-4 pr-3 py-2 rounded-2xl hover:bg-slate-100 transition-all border border-slate-100 group"
                    >
                      <div className="w-8 h-8 bg-blue-600 rounded-xl flex items-center justify-center text-white shadow-lg shadow-blue-200">
                        <UserIcon size={16} />
                      </div>
                      <span className="hidden sm:block text-xs font-black text-slate-900 uppercase tracking-widest">
                        {user.username}
                      </span>
                      <ChevronDown size={14} className={`text-slate-400 transition-transform duration-300 ${isUserMenuOpen ? 'rotate-180' : ''}`} />
                    </button>

                    <AnimatePresence>
                      {isUserMenuOpen && (
                        <>
                          <div className="fixed inset-0 z-10" onClick={() => setIsUserMenuOpen(false)}></div>
                          <motion.div
                            initial={{ opacity: 0, y: 10, scale: 0.95 }}
                            animate={{ opacity: 1, y: 0, scale: 1 }}
                            exit={{ opacity: 0, y: 10, scale: 0.95 }}
                            className="absolute right-0 mt-3 w-64 bg-white rounded-[2rem] shadow-2xl border border-slate-100 py-4 z-20 overflow-hidden"
                          >
                            <div className="px-6 py-3 border-b border-slate-50 mb-2">
                              <p className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">Cuenta vinculada</p>
                              <p className="text-sm font-bold text-slate-900 truncate">{user.username}</p>
                            </div>
                            <Link
                              to="/profile"
                              onClick={() => setIsUserMenuOpen(false)}
                              className="flex items-center gap-3 px-6 py-4 hover:bg-blue-50 text-slate-600 hover:text-blue-600 transition-colors group"
                            >
                              <div className="p-2 bg-slate-50 group-hover:bg-blue-100 rounded-xl transition-colors">
                                <UserIcon size={18} className="group-hover:text-blue-600" />
                              </div>
                              <span className="text-xs font-black uppercase tracking-widest">Mi Perfil</span>
                            </Link>

                            {/* Acceso a mensajes desde el menú movil o dropdown */}
                            <Link
                              to="/profile?tab=mensajes"
                              onClick={() => setIsUserMenuOpen(false)}
                              className="flex md:hidden items-center gap-3 px-6 py-4 hover:bg-blue-50 text-slate-600 hover:text-blue-600 transition-colors group"
                            >
                              <div className="p-2 bg-slate-50 group-hover:bg-blue-100 rounded-xl transition-colors">
                                <Mail size={18} className="group-hover:text-blue-600" />
                              </div>
                              <span className="text-xs font-black uppercase tracking-widest">Mensajes</span>
                            </Link>

                            <button
                              onClick={handleLogout}
                              className="w-full flex items-center gap-3 px-6 py-4 mt-2 hover:bg-rose-50 text-rose-500 border-t border-slate-50 transition-colors group"
                            >
                              <div className="p-2 bg-slate-50 group-hover:bg-rose-100 rounded-xl transition-colors">
                                <LogOut size={18} />
                              </div>
                              <span className="text-xs font-black uppercase tracking-widest">Cerrar Sesión</span>
                            </button>
                          </motion.div>
                        </>
                      )}
                    </AnimatePresence>
                  </div>
                </div>
              ) : (
                <Link to="/login" className="flex items-center gap-2 text-xs font-black uppercase tracking-widest text-slate-900 hover:text-blue-600 transition-all px-4">
                  <LogIn size={18} /> Entrar
                </Link>
              )}

              <Link
                to="/publicar"
                className="bg-slate-900 text-white px-8 py-3 rounded-2xl font-black uppercase tracking-widest text-[10px] shadow-xl shadow-slate-200 hover:bg-black hover:-translate-y-0.5 transition-all flex items-center gap-2"
              >
                <PlusCircle size={14} className="text-blue-400" />
                Publicar
              </Link>
            </div>
          </div>
        </header>

        {/* CONTENIDO PRINCIPAL */}
        <main className="flex-1">
          <Routes>
            <Route path="/" element={<HomePage />} />
            <Route path="/listing/:id" element={<ListingDetailPage />} />
            <Route path="/login" element={<LoginPage />} />
            <Route element={<ProtectedRoute />}>
              <Route path="/profile" element={<ProfilePage />} />
              <Route path="/publicar" element={<PublishPage />} />
              <Route path="/publicar/exito" element={<PublishFeedback />} />
              <Route path="/publicar/error" element={<PublishFeedback />} />
            </Route>
          </Routes>
        </main>

        {/* FOOTER PREMIUM REFINADO */}
        <footer className="bg-[#0f172a] text-slate-400 pt-24 pb-12">
          <div className="max-w-7xl mx-auto px-8">
            <div className="grid grid-cols-1 md:grid-cols-12 gap-16 mb-20">

              {/* Columna 1: Branding y Propuesta */}
              <div className="md:col-span-5 space-y-8">
                <Link to="/" className="font-black text-3xl text-white tracking-tighter flex items-center gap-2">
                  <span className="bg-blue-600 w-2 h-7 rounded-full"></span>
                  SIG-CM
                </Link>
                <p className="text-sm leading-relaxed max-w-sm opacity-60 font-medium">
                  La plataforma de clasificados líder en la región. Seguridad, trayectoria y efectividad garantizada por el <strong>Diario El Día</strong> de La Plata.
                </p>
                <div className="space-y-4 pt-4">
                  <div className="flex items-center gap-4 text-xs font-bold uppercase tracking-widest text-slate-500">
                    <div className="w-10 h-10 rounded-2xl bg-white/5 flex items-center justify-center text-blue-500"><MapPin size={18} /></div>
                    Diagonal 80 No. 817, La Plata
                  </div>
                  <div className="flex items-center gap-4 text-xs font-bold uppercase tracking-widest text-slate-500">
                    <div className="w-10 h-10 rounded-2xl bg-white/5 flex items-center justify-center text-blue-500"><Phone size={18} /></div>
                    (0221) 412-0101
                  </div>
                </div>
              </div>

              {/* Columna 2: Navegación Rápida */}
              <div className="md:col-span-3 space-y-8">
                <h4 className="text-[10px] font-black uppercase tracking-[0.3em] text-white opacity-40">Plataforma</h4>
                <ul className="space-y-5">
                  <li><Link to="/" className="text-sm font-bold hover:text-white transition-colors">Centro de Ayuda</Link></li>
                  <li><Link to="/" className="text-sm font-bold hover:text-white transition-colors">Preguntas Frecuentes</Link></li>
                  <li><Link to="/" className="text-sm font-bold hover:text-white transition-colors">Términos del Servicio</Link></li>
                  <li><Link to="/" className="text-sm font-bold hover:text-white transition-colors">Política de Privacidad</Link></li>
                </ul>
              </div>

              {/* Columna 3: Comunidad y Redes */}
              <div className="md:col-span-4 space-y-8 text-left md:text-right">
                <h4 className="text-[10px] font-black uppercase tracking-[0.3em] text-white opacity-40">Síguenos en Redes</h4>
                <div className="flex justify-start md:justify-end gap-3">
                  <SocialButton href="https://facebook.com" color="hover:bg-[#1877F2]"><SocialIcons.Facebook /></SocialButton>
                  <SocialButton href="https://instagram.com" color="hover:bg-gradient-to-tr from-[#F58529] via-[#DD2A7B] to-[#8134AF]"><SocialIcons.Instagram /></SocialButton>
                  <SocialButton href="https://x.com" color="hover:bg-black"><SocialIcons.X /></SocialButton>
                  <SocialButton href="https://youtube.com" color="hover:bg-[#FF0000]"><SocialIcons.Youtube /></SocialButton>
                </div>
                <div className="pt-8">
                  <div className="inline-flex items-center gap-3 px-5 py-3 rounded-2xl bg-white/5 border border-white/10">
                    <Mail size={16} className="text-blue-500" />
                    <span className="text-[11px] font-black uppercase tracking-widest text-slate-300">soporte@eldia.com</span>
                  </div>
                </div>
              </div>
            </div>

            {/* Créditos Finales */}
            <div className="pt-12 border-t border-white/5 flex flex-col md:flex-row justify-between items-center gap-6">
              <p className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-600">
                &copy; 2026 SIG-CM Clasificados. Todos los derechos reservados.
              </p>
              <div className="flex items-center gap-6">
                <span className="text-[9px] font-black uppercase tracking-widest text-slate-700">Diseñado para Diario El Día</span>
                <div className="w-8 h-8 rounded-lg bg-white/5 flex items-center justify-center grayscale opacity-30 hover:grayscale-0 hover:opacity-100 transition-all cursor-pointer">
                  <div className="w-4 h-4 bg-white rounded-full"></div>
                </div>
              </div>
            </div>
          </div>
        </footer>
      </div>
    </BrowserRouter>
  );
}

// COMPONENTE AUXILIAR PARA BOTONES DE REDES
function SocialButton({ children, href, color }: { children: React.ReactNode, href: string, color: string }) {
  return (
    <a
      href={href}
      target="_blank"
      rel="noopener noreferrer"
      className={`w-12 h-12 rounded-2xl bg-white/5 border border-white/10 flex items-center justify-center text-white transition-all duration-300 hover:-translate-y-1 hover:shadow-xl hover:shadow-blue-500/10 ${color}`}
    >
      {children}
    </a>
  );
}

export default App;