"use client";

import { useMemo } from "react";
import { signOut } from "next-auth/react";
import toast from "react-hot-toast";
import UserHeader from "@/components/me/UserHeader";
import QuotaCard from "@/components/me/QuotaCard";
import StatsGrid from "@/components/me/StatsGrid";
import MyFanSupport from "@/components/me/MyFanSupport";
import {
  useVoteStore,
  selectRemaining,
  DAILY_VOTE_QUOTA,
  type MySupport,
} from "@/lib/store";

interface MeContentProps {
  session: {
    id: string;
    nickname: string;
  };
}

export default function MeContent({ session }: MeContentProps) {
  // 订阅 store 原始引用（稳定，仅在 set() 时变更），组件内 useMemo 派生 supports，
  // 避免 Zustand v5 + useSyncExternalStore 对"selector 返回新引用"报 infinite-loop 错。
  const myTotalVotes = useVoteStore((s) => s.myTotalVotes);
  const myVotesByArtist = useVoteStore((s) => s.myVotesByArtist);
  const storeArtists = useVoteStore((s) => s.artists);
  const remaining = useVoteStore(selectRemaining);

  const supports = useMemo<MySupport[]>(() => {
    const list: MySupport[] = [];
    for (const [id, votedCount] of Object.entries(myVotesByArtist)) {
      if (votedCount <= 0) continue;
      const artist = storeArtists.find((a) => a.id === id);
      if (artist) list.push({ artist, votedCount });
    }
    list.sort((a, b) => b.votedCount - a.votedCount);
    return list;
  }, [myVotesByArtist, storeArtists]);

  const handleLogout = () => {
    toast("正在退出登录…");
    signOut({ callbackUrl: "/" });
  };

  return (
    <div className="max-w-[1500px] mx-auto px-4 sm:px-6 lg:px-8 py-8 sm:py-10 space-y-8">
      <UserHeader
        nickname={session.nickname}
        userId={session.id}
        onLogout={handleLogout}
      />

      <QuotaCard remaining={remaining} dailyQuota={DAILY_VOTE_QUOTA} />

      <StatsGrid totalVotes={myTotalVotes} supportingCount={supports.length} />

      <section>
        <SectionTitle label="我的应援" />
        <MyFanSupport supports={supports} />
      </section>
    </div>
  );
}

function SectionTitle({ label }: { label: string }) {
  return (
    <div className="mb-4 flex items-center gap-2.5">
      <span
        aria-hidden
        className="w-1 h-4 rounded-full bg-purple-400 shadow-[0_0_8px_rgba(167,139,250,0.7)]"
      />
      <h2 className="text-sm font-semibold text-white tracking-wider">
        {label}
      </h2>
    </div>
  );
}
