"use client";

import { useCallback, useEffect, useState } from "react";
import { useProfile } from "@/lib/profile/context";
import {
  addAnalyticsEvent,
  isFavorite,
  toggleFavorite,
} from "@/lib/profile/db";
import { evaluateAchievements } from "@/lib/profile/achievements";
import { getCompetitiveAdapter } from "@/lib/adapters/competitive";

export function FavoriteButton({ gameSlug }: { gameSlug: string }) {
  const { ready, profile, account } = useProfile();
  const [on, setOn] = useState(false);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (!ready || !profile) return;
    void isFavorite(profile.id, gameSlug).then(setOn);
  }, [ready, profile, gameSlug]);

  const onClick = useCallback(async () => {
    if (!profile || busy) return;
    setBusy(true);
    try {
      const next = await toggleFavorite(profile.id, gameSlug);
      setOn(next);
      await addAnalyticsEvent({
        type: next ? "favorite_add" : "favorite_remove",
        accountId: account?.id,
        profileId: profile.id,
        gameSlug,
        at: Date.now(),
      });
      const fresh = await evaluateAchievements(profile.id);
      const competitive = getCompetitiveAdapter();
      for (const u of fresh) {
        await competitive.unlockAchievement(u.achievementId);
      }
    } finally {
      setBusy(false);
    }
  }, [profile, gameSlug, busy, account?.id]);

  if (!ready) return null;

  return (
    <button
      type="button"
      className="btn-ghost"
      onClick={() => void onClick()}
      disabled={busy}
      aria-pressed={on}
    >
      {on ? "Favorited" : "Favorite"}
    </button>
  );
}
