import { db } from "@/lib/db";
import { noticia, colegio } from "@/db/schema";
import { eq, desc, sql } from "drizzle-orm";
import Link from "next/link";
import Navbar from "@/components/front/Navbar";
import Footer from "@/components/front/Footer";
import { Newspaper, Calendar, Building2 } from "lucide-react";

export const dynamic = "force-dynamic";


export default async function NoticiasPublicaPage() {
  const noticiasResult = await db
    .select({
      id: noticia.id,
      titulo: noticia.titulo,
      contenido: noticia.contenido,
      resumen: noticia.resumen,
      publicado: noticia.publicado,
      createdAt: noticia.createdAt,
      nombreColegio: colegio.nombre
    })
    .from(noticia)
    .innerJoin(colegio, eq(noticia.colegioId, colegio.id))
    .where(eq(noticia.publicado, true))
    .orderBy(desc(noticia.createdAt));

  // También obtener noticias globales (sin colegio)
  const noticiasGlobales = await db
    .select({
      id: noticia.id,
      titulo: noticia.titulo,
      contenido: noticia.contenido,
      resumen: noticia.resumen,
      publicado: noticia.publicado,
      createdAt: noticia.createdAt,
      nombreColegio: sql<string | null>`NULL`.as("nombreColegio"),
    })
    .from(noticia)
    .where(eq(noticia.publicado, true))
    .orderBy(desc(noticia.createdAt));

  // Combinar resultados
  const noticiasConColegio = noticiasResult.map(n => ({
    ...n,
    nombreColegio: n.nombreColegio as string | null,
    colegio: n.nombreColegio ? { nombre: n.nombreColegio } : null
  }));

  const noticias = noticiasConColegio.concat(
    noticiasGlobales.filter(ng => !noticiasResult.find(nr => nr.id === ng.id)).map(ng => ({
      ...ng,
      colegio: null
    }))
  ).sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());

  return (
    <>
      <Navbar />
      <div className="min-h-screen bg-[#fafafa] flex flex-col">
        {/* Hero Minimalista Académico */}
        <div className="bg-[#1a1a1a] text-white py-24 px-8 text-center relative">
          <div className="absolute inset-0 opacity-10 bg-cover bg-center" style={{ backgroundImage: "url('https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/Pila_de_libros.svg/512px-Pila_de_libros.svg.png')" }} />
          <div className="absolute top-0 right-0 w-64 h-64 bg-[#f57c00] rounded-full blur-[120px] opacity-10"></div>
          
          <div className="relative z-10 max-w-3xl mx-auto">
            <h1 className="text-4xl md:text-5xl font-extrabold mb-4 tracking-tight">Noticias y Novedades</h1>
            <p className="text-gray-400 text-lg md:text-xl font-light">
              Entérate de las actividades, anuncios y eventos de nuestros centros de formación.
            </p>
          </div>
        </div>

        <div className="max-w-6xl mx-auto px-6 py-16 flex-grow w-full">
          {noticias.length === 0 ? (
            <div className="bg-white rounded-2xl p-16 text-center border border-gray-100 shadow-sm">
              <Newspaper className="w-16 h-16 mx-auto mb-6 text-gray-200" />
              <h2 className="text-2xl font-bold text-gray-800 mb-2">Sin publicaciones recientes</h2>
              <p className="text-gray-500">Aún no hemos publicado noticias. Vuelve pronto para enterarte de lo más nuevo.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
              {noticias.map((noticia, idx) => (
                <article key={noticia.id}
                  className={`group bg-white rounded-2xl border border-gray-100 shadow-[0_2px_10px_-3px_rgba(6,81,237,0.05)] hover:shadow-[0_8px_30px_rgb(0,0,0,0.04)] overflow-hidden transition-all duration-300 flex flex-col ${idx === 0 ? 'md:col-span-2 lg:col-span-2' : ''}`}>
                  
                  {/* Borde superior decorativo sutil */}
                  <div className={`h-1.5 w-full ${noticia.colegio ? 'bg-[#43a047]' : 'bg-[#fbc02d]'}`} />
                  
                  {/* Cuerpo de la Tarjeta */}
                  <div className="p-8 flex flex-col flex-grow">
                    <div className="flex flex-wrap items-center justify-between gap-3 mb-5">
                      <div className="flex items-center gap-2 text-xs font-semibold text-gray-400 uppercase tracking-wider">
                        <Calendar className="w-3.5 h-3.5" />
                        {new Date(noticia.createdAt).toLocaleDateString('es-VE', { day: '2-digit', month: 'long', year: 'numeric' })}
                      </div>

                      {/* Etiqueta Minimalista */}
                      <div>
                        {noticia.colegio ? (
                          <span className="flex items-center gap-1.5 bg-green-50 text-green-700 font-medium text-xs px-2.5 py-1 rounded-md">
                            <Building2 className="w-3.5 h-3.5" /> {noticia.colegio.nombre}
                          </span>
                        ) : (
                          <span className="bg-yellow-50 text-yellow-700 font-medium text-xs px-2.5 py-1 rounded-md">
                            🌐 Global
                          </span>
                        )}
                      </div>
                    </div>

                    <h2 className={`font-bold text-gray-900 mb-4 leading-snug group-hover:text-[#f57c00] transition-colors
                      ${idx === 0 ? 'text-2xl md:text-3xl' : 'text-xl'}`}>
                      {noticia.titulo}
                    </h2>
                    
                    {noticia.resumen && (
                      <p className={`text-gray-600 mb-5 leading-relaxed
                        ${idx === 0 ? 'text-lg' : 'text-sm'}`}>
                        {noticia.resumen}
                      </p>
                    )}
                    
                    <div className="text-gray-500 text-sm leading-relaxed line-clamp-3 flex-grow">
                      {noticia.contenido}
                    </div>

                    <div className="mt-8 pt-5 border-t border-gray-50 flex items-center justify-end">
                       <span className="text-gray-900 font-semibold text-sm group-hover:text-[#f57c00] transition-colors flex items-center gap-1">
                         Leer más <span className="text-lg opacity-0 -translate-x-2 group-hover:opacity-100 group-hover:translate-x-0 transition-all">→</span>
                       </span>
                    </div>
                  </div>
                </article>
              ))}
            </div>
          )}

          <div className="mt-16 text-center">
            <Link href="/cursos" className="inline-flex items-center gap-2 bg-gray-900 hover:bg-gray-800 text-white px-8 py-3.5 rounded-xl font-semibold transition-colors">
              Explorar Oferta Académica →
            </Link>
          </div>
        </div>
      </div>
      <Footer />
    </>
  );
}
