"use client";

import { useEffect, useState } from "react";
import { collection, onSnapshot } from "firebase/firestore";
import Link from "next/link";
import Image from "next/image";
import { getDb, firebaseConfigured } from "@/lib/firebase";
import { COLLECTIONS } from "@/lib/firestore-paths";
import type { BlogPost } from "@/types/models";
import { SectionTitle } from "@/components/ui/SectionTitle";
import { FadeIn } from "@/components/motion/FadeIn";
import { GlassPanel } from "@/components/ui/GlassPanel";
import { publicImageSrc } from "@/lib/public-image";

export default function BlogListPage() {
  const [posts, setPosts] = useState<BlogPost[]>([]);
  const [loading, setLoading] = useState(firebaseConfigured);

  useEffect(() => {
    if (!firebaseConfigured) {
      setPosts([]);
      setLoading(false);
      return;
    }
    const db = getDb();
    if (!db) {
      setLoading(false);
      return;
    }
    let cancelled = false;
    setLoading(true);
    const unsub = onSnapshot(
      collection(db, COLLECTIONS.posts),
      (snap) => {
        if (cancelled) return;
        const rows: BlogPost[] = snap.docs.map((d) => ({ id: d.id, ...d.data() } as BlogPost));
        const pub = rows.filter((p) => p.published !== false);
        pub.sort((a, b) => {
          const ta = a.createdAt?.toMillis?.() ?? 0;
          const tb = b.createdAt?.toMillis?.() ?? 0;
          return tb - ta;
        });
        setPosts(pub);
        setLoading(false);
      },
      () => {
        if (!cancelled) {
          setPosts([]);
          setLoading(false);
        }
      }
    );
    return () => {
      cancelled = true;
      unsub();
    };
  }, []);

  return (
    <div className="mx-auto max-w-6xl px-4 py-14 sm:px-6 lg:px-8">
      <FadeIn>
        <SectionTitle
          eyebrow="Yayınlar"
          title="Hukuki yazılar"
          subtitle="Güncel hukuk konularında sade ve okunabilir içerikler."
        />
      </FadeIn>

      {loading ? (
        <p className="mt-10 text-sm text-[var(--muted)]">Yükleniyor…</p>
      ) : posts.length === 0 ? (
        <GlassPanel className="mt-10 border border-black/5 bg-white/90 p-8 text-sm text-[var(--muted)]">
          Henüz yayınlanmış yazı yok. Admin panelden blog ekleyebilirsiniz.
        </GlassPanel>
      ) : (
        <div className="mt-12 grid gap-6 md:grid-cols-2">
          {posts.map((p, i) => (
            <FadeIn key={p.id} delay={i * 0.05}>
              <Link href={`/blog/${p.slug}`} className="group block h-full">
                <article className="flex h-full flex-col overflow-hidden rounded-2xl border border-black/5 bg-white shadow-[0_14px_40px_-22px_rgba(15,31,68,0.45)] transition duration-300 hover:-translate-y-0.5">
                  <div className="relative h-44 w-full bg-[#f0f2f7]">
                    {p.coverImageUrl ? (
                      <Image
                        src={publicImageSrc(p.coverImageUrl)}
                        alt=""
                        fill
                        className="object-cover transition duration-500 group-hover:scale-[1.02]"
                        unoptimized
                      />
                    ) : (
                      <div className="flex h-full items-center justify-center bg-gradient-to-br from-[#0f1f44] to-[#152a45] text-sm text-white/70">
                        Kapak görseli yok
                      </div>
                    )}
                  </div>
                  <div className="flex flex-1 flex-col p-6">
                    <h2 className="font-[family-name:var(--font-display)] text-xl text-[var(--navy)] group-hover:underline">
                      {p.title}
                    </h2>
                    <p className="mt-2 line-clamp-3 text-sm leading-relaxed text-[var(--muted)]">
                      {p.excerpt}
                    </p>
                    <span className="mt-4 inline-flex items-center gap-1 text-xs font-semibold text-[var(--gold-dark)]">
                      Devamını oku
                    </span>
                  </div>
                </article>
              </Link>
            </FadeIn>
          ))}
        </div>
      )}
    </div>
  );
}
