"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { Users } from "lucide-react";
import HeroBanner from "@/components/HeroBanner";
import Top12Bar from "@/components/Top12Bar";
import ArtistCard from "@/components/cards/ArtistCard";
import ArtistFilters, { type TagFilter } from "@/components/ArtistFilters";
import VoteModal from "@/components/VoteModal";
import { getActivityEndTime, sortArtists, type SortKey } from "@/lib/mock-data";
import { useVoteStore } from "@/lib/store";
import { useVoteAction } from "@/hooks/useVoteAction";
import { cn } from "@/lib/cn";

export default function Home() {
  const artists = useVoteStore((s) => s.artists);
  const { target, remaining, dailyQuota, openVote, closeVote, confirmVote } =
    useVoteAction();

  const [tagFilter, setTagFilter] = useState<TagFilter>("all");
  const [sortKey, setSortKey] = useState<SortKey>("votes");
  const [filterStuck, setFilterStuck] = useState(false);
  const filterSentinelRef = useRef<HTMLDivElement>(null);

  const endTime = useMemo(() => getActivityEndTime(), []);

  const visibleArtists = useMemo(() => {
    let list = [...artists];
    if (tagFilter !== "all") {
      list = list.filter((a) => a.tags.includes(tagFilter));
    }
    return sortArtists(list, sortKey);
  }, [artists, tagFilter, sortKey]);

  // 仅在首页启用 scroll-snap mandatory：用户下滑就立即切换到下一个 snap 点
  // (Hero → Top12 → 候选区)。卸载时还原。
  useEffect(() => {
    const root = document.documentElement;
    const prev = root.style.scrollSnapType;
    root.style.scrollSnapType = "y mandatory";
    return () => {
      root.style.scrollSnapType = prev;
    };
  }, []);

  // 检测筛选条是否吸顶：直接读哨兵相对视口的 top，越过 nav 下沿（80px）即 stuck。
  // 不用 IntersectionObserver — 它对零面积/scroll-snap 场景不稳定，scroll 监听更直接。
  useEffect(() => {
    const sentinel = filterSentinelRef.current;
    if (!sentinel) return;
    const update = () => {
      const top = sentinel.getBoundingClientRect().top;
      setFilterStuck(top <= 80);
    };
    update();
    window.addEventListener("scroll", update, { passive: true });
    window.addEventListener("resize", update);
    return () => {
      window.removeEventListener("scroll", update);
      window.removeEventListener("resize", update);
    };
  }, []);

  return (
    <>
      {/* Hero · 全屏沉浸式视频 · 作为第一个 snap 点 */}
      <div
        style={{
          scrollSnapAlign: "start",
          scrollMarginTop: "80px",
        }}
      >
        <HeroBanner endTime={endTime} videoSrc="/videos/hero-pv.mp4" />
      </div>

      {/* Top12 出道位 · 作为第二个 snap 点：滚动结束后自然落到这里，标题贴近顶部 */}
      <section
        style={{
          scrollSnapAlign: "start",
          scrollMarginTop: "80px",
        }}
        className="max-w-[1500px] mx-auto px-4 sm:px-6 lg:px-8 pt-8 sm:pt-10"
      >
        <Top12Bar artists={artists} />
      </section>

      {/* 候选人阵容 · 作为第三个 snap 点 */}
      <section
        id="artists"
        style={{
          scrollSnapAlign: "start",
          scrollMarginTop: "80px",
        }}
        className="pb-12"
      >
        {/* 大标题 · 版心内 */}
        <div className="max-w-[1500px] mx-auto px-4 sm:px-6 lg:px-8 pt-10">
          <div className="flex items-end justify-between mb-3 px-1">
            <h2 className="font-display text-base sm:text-lg tracking-[0.2em] text-white inline-flex items-center gap-2">
              <Users size={16} className="text-purple-300" />
              {artists.length} 位候选人
            </h2>
            <p className="font-label text-[11px] tracking-widest text-white/45 uppercase">
              当前显示{" "}
              <span className="text-purple-300 tabular-nums">
                {visibleArtists.length}
              </span>{" "}
              位
            </p>
          </div>
        </div>

        {/* 哨兵：用于检测筛选条是否吸顶 */}
        <div ref={filterSentinelRef} aria-hidden style={{ height: 0 }} />

        {/* 筛选条 · 外层铺满（与导航栏同宽），吸顶后启用毛玻璃；内层版心承载文案 */}
        <div
          className={cn(
            "sticky z-30 transition-colors duration-200",
            filterStuck &&
              "backdrop-blur-xl bg-[rgba(13,10,36,0.85)] border-b border-white/[0.08]",
          )}
          style={{ top: "80px" }}
        >
          <div className="max-w-[1500px] mx-auto px-4 sm:px-6 lg:px-8">
            <ArtistFilters
              tagFilter={tagFilter}
              onTagChange={setTagFilter}
              sort={sortKey}
              onSortChange={setSortKey}
            />
          </div>
        </div>

        {/* 候选人网格 · 版心内 */}
        <div className="max-w-[1500px] mx-auto px-4 sm:px-6 lg:px-8">
          {visibleArtists.length === 0 ? (
            <EmptyState />
          ) : (
            <div className="mt-6 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3 sm:gap-4">
              {visibleArtists.map((a) => (
                <ArtistCard key={a.id} artist={a} onVote={openVote} />
              ))}
            </div>
          )}
        </div>
      </section>

      <VoteModal
        artist={target}
        remaining={remaining}
        dailyQuota={dailyQuota}
        onClose={closeVote}
        onConfirm={confirmVote}
      />
    </>
  );
}

function EmptyState() {
  return (
    <div className="mt-8 py-16 text-center text-white/45 border border-dashed border-white/10 rounded-xl">
      <p className="font-label text-xs tracking-widest uppercase text-purple-300 mb-2">
        No Match
      </p>
      <p className="text-sm">该标签下暂无艺人</p>
    </div>
  );
}
