import { useMemo } from 'react';
import { Link, useParams } from 'react-router-dom';
import { buildTree, collectRefs } from '@tts/extract';
import { useModStore } from '../stores/modStore';
import { useSearchStore } from '../stores/searchStore';
import { modFileUrl } from '../api';

/**
 * Replaces the global site header on the mod page: thumbnail, game name, and
 * a subheader with the mod id and stats, plus download/setup links styled like
 * the Search/BGM nav.
 */
export default function ModHeader() {
  const { id } = useParams<{ id: string }>();
  const { mod } = useModStore();
  const item = useSearchStore((s) => s.items.find((i) => i.id === id));
  const tree = useMemo(() => (mod ? buildTree(mod.mod) : []), [mod]);
  const refs = useMemo(() => (mod ? collectRefs(mod.mod) : []), [mod]);
  // Prefer the metadata fetched with the save (survives a refresh); fall back
  // to the search result for the brief moment before the save loads.
  const title = mod?.title ?? item?.title;
  const previewImageUrl = mod?.previewImageUrl ?? item?.previewImageUrl;

  return (
    <div className="mx-auto flex max-w-5xl items-center justify-between gap-4 px-4 py-4">
      <div className="flex min-w-0 items-center gap-3">
        {previewImageUrl && (
          <img
            src={previewImageUrl}
            alt={title}
            className="h-12 w-12 shrink-0 rounded-lg border border-zinc-800 object-cover"
          />
        )}
        <div className="min-w-0">
          <h1 className="truncate text-lg font-semibold tracking-tight">
            {title ?? `Mod ${id}`}
          </h1>
          {mod && (
            <p className="truncate text-sm text-zinc-400">
              <span className="font-mono">{id}</span> · {mod.mod.GameMode} ·{' '}
              {mod.mod.Date} · {tree.length} objects · {refs.length} asset refs
            </p>
          )}
        </div>
      </div>
      <nav className="flex shrink-0 gap-4 text-sm text-zinc-400">
        <Link to="/" className="hover:text-zinc-100">
          Search
        </Link>
        <a
          href={modFileUrl(id!, item?.fileUrl)}
          className="hover:text-zinc-100"
        >
          Download
        </a>
        <Link to={`/mod/${id}/setup`} className="hover:text-zinc-100">
          Setup
        </Link>
      </nav>
    </div>
  );
}