"use client";

import { useEffect, useState } from "react";
import { useProfile } from "@/lib/profile/context";
import { getHistoryEntry } from "@/lib/profile/db";
import { getUnlocks } from "@/lib/profile/db";
import {
  getAchievementDef,
  getAchievementDefs,
} from "@/lib/profile/achievements";

function formatTime(seconds: number): string {
  if (seconds < 60) return `${seconds}s`;
  const m = Math.floor(seconds / 60);
  const h = Math.floor(m / 60);
  if (h > 0) return `${h}h ${m % 60}m`;
  return `${m}m`;
}

export function PlayTimeStat({ gameSlug }: { gameSlug: string }) {
  const { ready, profile } = useProfile();
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    if (!ready || !profile) return;
    void getHistoryEntry(profile.id, gameSlug).then((h) =>
      setSeconds(h?.totalSeconds ?? 0),
    );
  }, [ready, profile, gameSlug]);

  if (!ready || seconds <= 0) return null;

  return (
    <div>
      <dt className="font-display text-[0.5rem] tracking-wider text-muted uppercase">
        Time played
      </dt>
      <dd>{formatTime(seconds)}</dd>
    </div>
  );
}

export function GameAchievements({ gameSlug }: { gameSlug: string }) {
  const { ready, profile } = useProfile();
  const [unlocked, setUnlocked] = useState<Set<string>>(new Set());

  useEffect(() => {
    if (!ready || !profile) return;
    void getUnlocks(profile.id).then((rows) =>
      setUnlocked(new Set(rows.map((r) => r.achievementId))),
    );
  }, [ready, profile]);

  const relevant = getAchievementDefs().filter(
    (d) =>
      !d.gameSlug ||
      d.gameSlug === gameSlug ||
      d.rule.type === "first_play" ||
      d.rule.type === "play_minutes" ||
      d.rule.type === "sessions",
  );

  if (!ready || relevant.length === 0) return null;

  return (
    <div className="mt-10">
      <h2 className="font-display text-sm tracking-wider text-foreground uppercase">
        Achievements
      </h2>
      <ul className="mt-4 space-y-2">
        {relevant.slice(0, 6).map((d) => {
          const on = unlocked.has(d.id);
          return (
            <li
              key={d.id}
              className={`border border-line px-3 py-2 text-sm ${on ? "border-crt/40 text-foreground" : "text-muted"}`}
            >
              <span className="font-medium">{d.title}</span>
              <span className="ml-2 text-xs opacity-70">
                {on ? "Unlocked" : d.description}
              </span>
            </li>
          );
        })}
      </ul>
    </div>
  );
}

export function formatPlayTime(seconds: number) {
  return formatTime(seconds);
}

export function AchievementToast({
  ids,
  onDone,
}: {
  ids: string[];
  onDone: () => void;
}) {
  const [visible, setVisible] = useState(ids.length > 0);

  useEffect(() => {
    if (ids.length === 0) return;
    setVisible(true);
    const t = window.setTimeout(() => {
      setVisible(false);
      onDone();
    }, 4200);
    return () => window.clearTimeout(t);
  }, [ids, onDone]);

  if (!visible || ids.length === 0) return null;
  const titles = ids
    .map((id) => getAchievementDef(id)?.title ?? id)
    .join(", ");

  return (
    <div className="pointer-events-none fixed bottom-6 left-1/2 z-[60] max-w-sm -translate-x-1/2 border border-crt/50 bg-panel/95 px-4 py-3 text-center shadow-lg backdrop-blur">
      <p className="font-display text-[0.55rem] tracking-[0.2em] text-crt uppercase">
        Achievement unlocked
      </p>
      <p className="mt-1 text-sm text-foreground">{titles}</p>
    </div>
  );
}
