import Link from "next/link";

import { CtkpEmptyPanel } from "@/components/CtkpPublicStates";
import {
  PostFeaturedImage,
  PostFeaturedPlaceholder,
  postFeaturedAspectClass,
} from "@/components/PostFeaturedMedia";
import { absoluteFromApiPath, getApiBaseUrl } from "@/lib/api";
import { isBetaPublicSurfaceEnabled } from "@/lib/betaVisibility";
import { fetchPublicPosts, type PublicPostListItem } from "@/lib/posts";

function formatDate(iso: string | null) {
  if (!iso) return "";
  try {
    return new Date(iso).toLocaleDateString("vi-VN", {
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  } catch {
    return "";
  }
}

const pillars = [
  {
    title: "Tử vi",
    body:
      "Bản đồ tinh tú và thời vận — đọc như soi gương, không như án tử hình. Là nơi tự hỏi, không phải nơi bị kết án.",
  },
  {
    title: "Kinh Dịch",
    body:
      "Quẻ như dòng nước chảy chậm: gợi hướng, không cầm tay bạn bước. Mỗi hào là một khoảnh khắc dừng lại và ngẫm.",
  },
  {
    title: "Chiêm nghiệm",
    body:
      "Chữ cổ mời ta chung bước — giữa ồn ào, tìm một nhịp thở và lời nhắc ôn hòa từ kinh nghiệm ngàn năm.",
  },
] as const;

export default async function HomePage() {
  const betaSurface = isBetaPublicSurfaceEnabled();
  let latest: PublicPostListItem[] = [];
  let postsFetchFailed = false;
  try {
    const data = await fetchPublicPosts({ page: 1, pageSize: 6 });
    latest = data.items.slice(0, 6);
  } catch {
    latest = [];
    postsFetchFailed = true;
  }
  const hasApi = Boolean(getApiBaseUrl());

  return (
    <main className="flex flex-1 flex-col">
      {/* 1. Hero — full bleed */}
      <section className="ctkp-hero relative left-1/2 right-1/2 -ml-[50vw] -mr-[50vw] w-screen">
        <div className="ctkp-hero-glow" aria-hidden />
        <div className="ctkp-hero-dust" aria-hidden />
        <div className="ctkp-hero-orbit hidden sm:block" aria-hidden />
        <div className="relative z-[1] mx-auto max-w-3xl px-4 pb-20 pt-16 text-center sm:px-8 sm:pb-28 sm:pt-28">
          <p className="ctkp-eyebrow tracking-[0.38em]">Cổ thư · tĩnh lặng</p>
          <h1 className="font-ctkp-display mt-8 text-[clamp(2rem,9vw,3.5rem)] font-semibold leading-[1.1] tracking-tight text-balance text-stone-100/95 sm:text-[3.35rem] sm:leading-[1.06]">
            Cổ Thư Kỳ Phổ
          </h1>
          <p className="mx-auto mt-9 max-w-lg text-pretty text-[15px] leading-[1.88] text-stone-500 sm:text-lg sm:leading-[1.82]">
            Nơi hội tụ tri thức xưa — tử vi, quẻ dịch và những lời soi chiếu nhẹ nhàng. Không hứa phép màu,
            chỉ mời bạn dừng lại, đọc chậm và lắng nghe trong mình.
          </p>
          <div className="mx-auto mt-12 flex w-full max-w-sm flex-col items-stretch gap-3 sm:max-w-none sm:flex-row sm:items-center sm:justify-center sm:gap-4">
            <Link href="/posts" className="ctkp-btn-primary w-full sm:w-auto sm:min-w-[11rem]">
              Lật sổ bài
            </Link>
            <Link href="/tu-vi" className="ctkp-btn-secondary w-full sm:w-auto sm:min-w-[11rem]">
              Mở lá số
            </Link>
          </div>
          <p className="mx-auto mt-5 max-w-md text-center text-sm text-stone-500">
            {betaSurface ?
              <>
                Hoặc{" "}
                <Link href="/gieo-que" className="ctkp-text-link">
                  gieo quẻ (X:Y)
                </Link>{" "}
                — một nhịp Kinh Dịch trên bàn cổ thư.
              </>
            : <>
                Hoặc{" "}
                <Link href="/fortune" className="ctkp-text-link">
                  gieo một quẻ
                </Link>{" "}
                — một nhịp Kinh Dịch trên bàn cổ thư.
              </>
            }
          </p>
        </div>
      </section>

      <div className="mx-auto w-full max-w-[1100px] flex-1 px-4 pb-8 sm:px-8">
        {/* 2. Spirit + pillars */}
        <section className="py-16 sm:py-20 lg:py-24" aria-labelledby="spirit-heading">
          <div className="mx-auto max-w-2xl text-center">
            <h2
              id="spirit-heading"
              className="font-ctkp-display text-2xl font-semibold tracking-tight text-stone-100 sm:text-3xl"
            >
              Tinh thần của quyển sách
            </h2>
            <p className="mt-5 text-[15px] leading-[1.82] text-stone-500 sm:text-base sm:leading-[1.8]">
              Cổ Thư Kỳ Phổ dành cho người tin vào độ sâu của lời cũ — trang trọng, khiêm nhường, và luôn chừa
              khoảng trống cho im lặng.
            </p>
            {!betaSurface ?
              <p className="mt-6">
                <Link href="/about" className="ctkp-text-link text-sm">
                  Đọc thêm về tinh thần cổ thư →
                </Link>
              </p>
            : null}
          </div>
          <ul className="mt-14 grid gap-5 sm:grid-cols-3 sm:gap-6">
            {pillars.map((p) => (
              <li key={p.title}>
                <div className="group h-full rounded-xl border border-stone-800/40 bg-[#0f0d0c]/55 p-6 transition-colors duration-200 ease-out hover:border-[#6b5a3a]/35 hover:bg-[#12100e]/65 sm:p-7">
                  <h3 className="font-ctkp-display text-xl font-semibold text-amber-100/90">{p.title}</h3>
                  <p className="mt-3 text-sm leading-[1.75] text-stone-500 group-hover:text-stone-400">
                    {p.body}
                  </p>
                </div>
              </li>
            ))}
          </ul>
        </section>

        {/* 3. Latest posts */}
        <section className="pb-16 sm:pb-20 lg:pb-24" aria-labelledby="latest-heading">
          <div className="mb-8 flex flex-col gap-3 sm:mb-10 sm:flex-row sm:items-end sm:justify-between">
            <div className="min-w-0">
              <h2
                id="latest-heading"
                className="font-ctkp-display text-pretty text-2xl font-semibold text-stone-100 sm:text-3xl"
              >
                Thiên mới ấn
              </h2>
              <p className="mt-1.5 text-sm text-stone-500">Những trang đã ấn định trên sổ — chọn lọc, không vội.</p>
            </div>
            <Link href="/posts" className="ctkp-text-link shrink-0 self-start text-sm sm:self-auto">
              Xem tất cả →
            </Link>
          </div>

          {latest.length === 0 ? (
            <CtkpEmptyPanel
              title={
                postsFetchFailed
                  ? "Chưa đọc được sổ bài"
                  : !hasApi
                    ? "Chưa kết nối kho bài"
                    : "Chưa có thiên mới"
              }
            >
              {postsFetchFailed ? (
                <>
                  Cổ thư không tải được danh sách từ máy chủ. Kiểm tra máy chủ dữ liệu và cấu hình triển khai, rồi tải lại
                  trang.
                </>
              ) : !hasApi ? (
                <>
                  Khi ứng dụng đã nối tới dịch vụ dữ liệu, các bài xuất bản sẽ hiện ở đây và trong{" "}
                  <Link href="/posts" className="ctkp-text-link text-amber-200/70 hover:text-amber-50">
                    sổ bài đầy đủ
                  </Link>
                  .
                </>
              ) : (
                <>
                  Hiện chưa có bài xuất bản — khi có thiên mới, chúng sẽ xuất hiện tại đây. Bạn vẫn có thể vào{" "}
                  <Link href="/posts" className="ctkp-text-link text-amber-200/70 hover:text-amber-50">
                    sổ bài
                  </Link>{" "}
                  để xem toàn bộ (nếu đã có bài ở trang khác).
                </>
              )}
            </CtkpEmptyPanel>
          ) : (
            <ul className="grid gap-7 lg:grid-cols-2">
              {latest.map((post) => {
                const img = absoluteFromApiPath(post.featuredImage);
                return (
                  <li key={post.id}>
                    <Link
                      href={`/posts/${post.slug}`}
                      className="group flex h-full flex-col overflow-hidden rounded-xl border border-stone-800/45 bg-[#0c0b0a]/90 transition-colors duration-200 ease-ctkp hover:border-[#7a6a4a]/32"
                    >
                      {img ? (
                        <PostFeaturedImage
                          src={img}
                          alt=""
                          variant="cover"
                          className={postFeaturedAspectClass}
                          imgClassName="transition-opacity duration-300 ease-ctkp group-hover:opacity-95"
                        />
                      ) : (
                        <PostFeaturedPlaceholder className={`${postFeaturedAspectClass} w-full`} />
                      )}
                      <div className="flex flex-1 flex-col p-6 sm:p-7">
                        <p className="ctkp-eyebrow tracking-[0.32em]">{post.category.name}</p>
                        <h3 className="font-ctkp-display mt-2 text-xl font-semibold leading-snug text-stone-100 transition-colors duration-200 ease-out group-hover:text-amber-50/95 sm:text-[1.35rem]">
                          {post.title}
                        </h3>
                        {post.excerpt ? (
                          <p className="mt-3 line-clamp-2 flex-1 text-sm leading-relaxed text-stone-500">
                            {post.excerpt}
                          </p>
                        ) : (
                          <div className="flex-1" />
                        )}
                        {post.publishedAt ? (
                          <time
                            className="mt-4 text-xs text-amber-200/35"
                            dateTime={post.publishedAt}
                          >
                            {formatDate(post.publishedAt)}
                          </time>
                        ) : null}
                      </div>
                    </Link>
                  </li>
                );
              })}
            </ul>
          )}
        </section>

        {/* 4. Future — quiet promise */}
        <section
          className="rounded-xl border border-stone-800/45 bg-[#0f0e0d]/65 px-6 py-11 sm:px-10 sm:py-14"
          aria-labelledby="future-heading"
        >
          <h2
            id="future-heading"
            className="font-ctkp-display text-center text-xl font-semibold text-stone-200 sm:text-2xl"
          >
            Điều đang được ấn
          </h2>
          <p className="mx-auto mt-3 max-w-lg text-center text-sm leading-relaxed text-stone-500">
            Không vội lật hết sổ — chúng tôi đang thêu thêm vài lối vào nhỏ, để bạn tự soi, tự nghe và tự hiểu.
          </p>
          <ul className="mx-auto mt-10 grid max-w-2xl gap-4 sm:grid-cols-3 sm:gap-5">
            <li className="rounded-xl border border-stone-800/55 bg-black/20 px-4 py-5 text-center transition-all duration-200 ease-ctkp hover:border-amber-900/35 hover:bg-black/32">
              <Link href="/tu-vi" className="block rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-amber-800/25">
                <p className="font-ctkp-display text-base text-stone-300 transition-colors duration-200 ease-ctkp hover:text-amber-100/90">
                  Mở lá số
                </p>
                <p className="mt-1.5 text-xs text-amber-200/40">Ghi canh khắc sinh — khung v1</p>
              </Link>
            </li>
            {betaSurface ?
              <>
                <li className="rounded-xl border border-stone-800/55 bg-black/20 px-4 py-5 text-center transition-all duration-200 ease-ctkp hover:border-amber-900/35 hover:bg-black/32">
                  <Link
                    href="/gieo-que"
                    className="block rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-amber-800/25"
                  >
                    <p className="font-ctkp-display text-base text-stone-300 transition-colors duration-200 ease-ctkp hover:text-amber-100/90">
                      Gieo quẻ (X:Y)
                    </p>
                    <p className="mt-1.5 text-xs text-amber-200/40">Một cặp số mở quẻ</p>
                  </Link>
                </li>
                <li className="rounded-xl border border-stone-800/55 bg-black/20 px-4 py-5 text-center transition-all duration-200 ease-ctkp hover:border-amber-900/35 hover:bg-black/32">
                  <Link href="/posts" className="block rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-amber-800/25">
                    <p className="font-ctkp-display text-base text-stone-300 transition-colors duration-200 ease-ctkp hover:text-amber-100/90">
                      Sổ bài
                    </p>
                    <p className="mt-1.5 text-xs text-amber-200/40">Đọc chậm những dòng đã ấn</p>
                  </Link>
                </li>
              </>
            : <>
                <li className="rounded-xl border border-stone-800/55 bg-black/20 px-4 py-5 text-center transition-all duration-200 ease-ctkp hover:border-amber-900/35 hover:bg-black/32">
                  <Link href="/fortune" className="block rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-amber-800/25">
                    <p className="font-ctkp-display text-base text-stone-300 transition-colors duration-200 ease-ctkp hover:text-amber-100/90">
                      Gieo quẻ
                    </p>
                    <p className="mt-1.5 text-xs text-amber-200/40">Mở ngay trên cổ thư</p>
                  </Link>
                </li>
                <li className="rounded-xl border border-stone-800/55 bg-black/20 px-4 py-5 text-center transition-all duration-200 ease-ctkp hover:border-amber-900/35 hover:bg-black/32">
                  <Link
                    href="/fortune/history"
                    className="block rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-amber-800/25"
                  >
                    <p className="font-ctkp-display text-base text-stone-300 transition-colors duration-200 ease-ctkp hover:text-amber-100/90">
                      Nhật ký
                    </p>
                    <p className="mt-1.5 text-xs text-amber-200/40">
                      Mở lại quẻ hoặc lá số đã lưu — luận AI là bước tùy chọn trên trang kết quả
                    </p>
                  </Link>
                </li>
              </>
            }
          </ul>
        </section>
      </div>
    </main>
  );
}
