import Link from "next/link";
import { listPosts } from "@/lib/cms";
import { Header } from "@/components/header";
import { Footer } from "@/components/footer";
import { PostCard } from "@/components/post-card";
import { SectionHeader } from "@/components/section-header";
import { NewsletterSection } from "@/components/newsletter";
import { loadActiveSkin } from "@/lib/theme";
import HomePageV2 from "@/components/v2/home-page-v2";

const CAT_IDS = {
  tinNong: 148,
  phanTich: 36,
  crypto: 37,
  vang: 252,
  chungKhoan: 40,
  forex: 39,
};

export const dynamic = "force-dynamic";
export const revalidate = 60;

export default async function HomePage() {
  const skin = await loadActiveSkin();
  if (skin === "v2") {
    return <HomePageV2 />;
  }

  // Featured-first hero: editor đánh dấu bài quan trọng → hiển thị to. Fallback: bài mới nhất.
  const [
    { posts: featuredPosts },
    { posts: secondaryRaw },
    { posts: tinNong },
    { posts: phanTich },
    { posts: crypto },
    { posts: vang },
  ] = await Promise.all([
    listPosts({ perPage: 1, featured: true, orderBy: "date", order: "desc" }),
    listPosts({ perPage: 5, orderBy: "date", order: "desc" }),
    listPosts({ perPage: 6, categories: [CAT_IDS.tinNong] }),
    listPosts({ perPage: 5, categories: [CAT_IDS.phanTich] }),
    listPosts({ perPage: 3, categories: [CAT_IDS.crypto] }),
    listPosts({ perPage: 3, categories: [CAT_IDS.vang] }),
  ]);

  const heroPost =
    featuredPosts[0] ?? secondaryRaw[0] ?? null;
  const heroId = heroPost?.id;
  const secondary = secondaryRaw.filter((p) => p.id !== heroId).slice(0, 3);
  const { posts: latestRail } = await listPosts({ perPage: 5, orderBy: "date" });

  return (
    <>
      <Header />
      <main id="main">
        {/* HERO BAND */}
        {heroPost && (
          <section className="border-b hairline-strong" style={{ background: "var(--bg)" }}>
            <div className="mx-auto max-w-[var(--container-content)] px-6 lg:px-10 py-12 lg:py-16">
              <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">
                <div className="lg:col-span-8">
                  <PostCard post={heroPost} variant="feature" priority asPageHeading />
                </div>
                <aside className="lg:col-span-4 lg:border-l hairline-strong lg:pl-10">
                  <div className="border-b-2 hairline-strong pb-2.5 mb-4 flex items-center justify-between">
                    <h2 className="font-[family-name:var(--font-newsreader)] text-2xl font-medium">
                      Mới nhất
                    </h2>
                    <span
                      className="text-[10px] flex items-center gap-1.5 font-[family-name:var(--font-jetbrains-mono)] font-mono uppercase tracking-wider"
                      style={{ color: "var(--ink-3)" }}
                    >
                      <span
                        className="w-1.5 h-1.5 rounded-full animate-pulse"
                        style={{ background: "var(--up)" }}
                      />
                      Live
                    </span>
                  </div>
                  <ul className="space-y-0">
                    {latestRail.map((p) => (
                      <li key={p.id}>
                        <PostCard post={p} variant="rail" />
                      </li>
                    ))}
                  </ul>
                  <Link
                    href="/category/tin-nong"
                    className="mt-4 inline-flex items-center gap-1 text-[13px] font-semibold hover:gap-2 transition-all"
                    style={{ color: "var(--accent)" }}
                  >
                    Tất cả tin nóng <span aria-hidden>→</span>
                  </Link>
                </aside>
              </div>
            </div>
          </section>
        )}

        {/* 3 SECONDARIES — bordered cards w/ offset shadow on hover */}
        {secondary.length > 0 && (
          <section style={{ background: "var(--paper)" }}>
            <div className="mx-auto max-w-[var(--container-content)] px-6 lg:px-10 py-12">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
                {secondary.map((p) => (
                  <div key={p.id} className="card-modern p-6">
                    <PostCard post={p} variant="card" showImage={false} />
                  </div>
                ))}
              </div>
            </div>
          </section>
        )}

        {/* TIN NONG */}
        {tinNong.length > 0 && (
          <section className="border-t hairline-strong" style={{ background: "var(--bg)" }}>
            <div className="mx-auto max-w-[var(--container-content)] px-6 lg:px-10 py-14">
              <SectionHeader
                title="Tin nóng hôm nay"
                eyebrow="Phần II"
                href="/category/tin-nong"
              />
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-10">
                {tinNong.map((p) => (
                  <PostCard key={p.id} post={p} variant="card" />
                ))}
              </div>
            </div>
          </section>
        )}

        {/* PHAN TICH */}
        {phanTich.length > 0 && (
          <section className="border-t hairline-strong" style={{ background: "var(--paper)" }}>
            <div className="mx-auto max-w-[var(--container-content)] px-6 lg:px-10 py-14">
              <SectionHeader
                title="Phân tích chuyên sâu"
                eyebrow="Phần III"
                href="/category/phan-tich"
              />
              <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">
                <div className="lg:col-span-7 lg:border-r hairline lg:pr-10">
                  <PostCard post={phanTich[0]!} variant="feature" />
                </div>
                <ol className="lg:col-span-5 space-y-0 list-none">
                  {phanTich.slice(1, 5).map((p, i) => {
                    const numerals = ["i.", "ii.", "iii.", "iv."];
                    return (
                      <li
                        key={p.id}
                        className={`post-row py-4 ${i < 3 ? "border-b hairline" : ""} cursor-pointer`}
                      >
                        <Link href={`/${p.slug}`} className="flex gap-4 items-start group">
                          <span
                            className="font-[family-name:var(--font-fraunces)] italic text-3xl w-9 shrink-0 leading-none pt-1"
                            style={{
                              color: "var(--ink-3)",
                              fontVariationSettings: "'opsz' 72",
                            }}
                          >
                            {numerals[i]}
                          </span>
                          <div>
                            <h3 className="display-md mb-1 group-hover:text-[var(--accent)]">
                              {p.title}
                            </h3>
                            <span
                              className="text-[10px] font-[family-name:var(--font-jetbrains-mono)] font-mono uppercase tracking-wider"
                              style={{ color: "var(--ink-3)" }}
                            >
                              {p.readMinutes} PHÚT
                            </span>
                          </div>
                        </Link>
                      </li>
                    );
                  })}
                </ol>
              </div>
            </div>
          </section>
        )}

        {/* CRYPTO */}
        {crypto.length > 0 && (
          <section className="border-t hairline-strong" style={{ background: "var(--bg)" }}>
            <div className="mx-auto max-w-[var(--container-content)] px-6 lg:px-10 py-14">
              <SectionHeader title="Crypto" eyebrow="Phần IV" href="/category/crypto" />
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-10">
                {crypto.map((p) => (
                  <PostCard key={p.id} post={p} variant="card" />
                ))}
              </div>
            </div>
          </section>
        )}

        {/* VANG */}
        {vang.length > 0 && (
          <section className="border-t hairline-strong" style={{ background: "var(--paper)" }}>
            <div className="mx-auto max-w-[var(--container-content)] px-6 lg:px-10 py-14">
              <SectionHeader title="Vàng" eyebrow="Phần V" href="/category/vang" />
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-10">
                {vang.map((p) => (
                  <PostCard key={p.id} post={p} variant="card" />
                ))}
              </div>
            </div>
          </section>
        )}

        <NewsletterSection />
      </main>
      <Footer />
    </>
  );
}
