import type { AppSnapshot, Recommendation } from "../../../types/domain";
import type { ReactNode } from "react";
import { verdictMeta } from "../../common/verdictMeta";

export interface OverlayPreviewModel {
  candidate: Recommendation | null;
  artifactName: string;
  scoreText: string;
  metaClassName: string;
  metaLabel: string;
  metaIcon: ReactNode;
  artifactSlotLine: string;
  artifactSubstatsText: string;
  artifactMainStat: string;
  characterNames: string[];
  reason: string;
  hasArtifact: boolean;
}

interface UseOverlayPreviewModelInput {
  snapshot: AppSnapshot;
}

export function useOverlayPreviewModel({ snapshot }: UseOverlayPreviewModelInput): OverlayPreviewModel {
  const candidate = snapshot.recommendations.find((entry) => entry.verdict === "keep")
    ?? snapshot.recommendations.find((entry) => entry.verdict === "character_specific")
    ?? snapshot.recommendations.find((entry) => entry.verdict === "maybe_level")
    ?? snapshot.recommendations[0]
    ?? null;

  const artifact = snapshot.artifacts.find((entry) => entry.id === candidate?.artifactId);
  const meta = verdictMeta[candidate?.verdict ?? "needs_review"];
  const characterNames =
    candidate?.bestCharacters.map((id) => snapshot.characters.find((character) => character.id === id)?.name ?? id).slice(0, 3) ?? [];
  const characterDisplayNames = characterNames.length > 0 ? characterNames : ["Review first"];

  return {
    candidate,
    artifactName: artifact?.setName ?? "Artifact detected",
    scoreText: candidate ? `${Math.round(candidate.score)}` : "--",
    metaClassName: meta.className,
    metaLabel: meta.label,
    metaIcon: meta.icon,
    artifactSlotLine: artifact ? `${artifact.slot} | +${artifact.level}` : "No artifact",
    artifactSubstatsText: artifact?.substats
      .slice(0, 3)
      .map((substat) => `${substat.key} ${substat.value}${substat.unit === "%" ? "%" : ""}`)
      .join(" | ") ?? "",
    artifactMainStat: artifact?.mainStat ?? "No main stat",
    characterNames: characterDisplayNames,
    reason: candidate?.reason ?? "Waiting for artifact detail view.",
    hasArtifact: Boolean(artifact),
  };
}
