"use client";

import { useState, useMemo } from "react";
import Link from "next/link";
import { Card, Table, Badge } from "react-bootstrap";
import { BoxArrowUpRight, Download, Eye } from "react-bootstrap-icons";
import ZxdbBreadcrumbs from "@/app/zxdb/components/ZxdbBreadcrumbs";
import FileViewer from "@/components/FileViewer";

type Label = { id: number; name: string; labeltypeId: string | null };
export type EntryDetailData = {
  id: number;
  title: string;
  isXrated: number;
  machinetype: { id: number | null; name: string | null };
  language: { id: string | null; name: string | null };
  genre: { id: number | null; name: string | null };
  authors: Label[];
  publishers: Label[];
  licenses?: {
    id: number;
    name: string;
    type: { id: string; name: string | null };
    isOfficial: boolean;
    linkWikipedia?: string | null;
    linkSite?: string | null;
    comments?: string | null;
  }[];
  relations?: {
    direction: "from" | "to";
    type: { id: string; name: string | null };
    entry: { id: number; title: string | null };
  }[];
  tags?: {
    id: number;
    name: string;
    type: { id: string; name: string | null };
    category: { id: number | null; name: string | null };
    memberSeq: number | null;
    link: string | null;
    comments: string | null;
  }[];
  ports?: {
    id: number;
    title: string | null;
    platform: { id: number; name: string | null };
    isOfficial: boolean;
    linkSystem: string | null;
  }[];
  remakes?: {
    id: number;
    title: string;
    fileLink: string;
    fileDate: string | null;
    fileSize: number | null;
    authors: string | null;
    platforms: string | null;
    remakeYears: string | null;
    remakeStatus: string | null;
  }[];
  scores?: {
    website: { id: number; name: string | null };
    score: number;
    votes: number;
  }[];
  notes?: {
    id: number;
    type: { id: string; name: string | null };
    text: string;
  }[];
  origins?: {
    type: { id: string; name: string | null };
    libraryTitle: string;
    publication: string | null;
    containerId: number | null;
    issueId: number | null;
    issue: { id: number; magazineId: number | null; magazineTitle: string | null } | null;
    date: { year: number | null; month: number | null; day: number | null };
  }[];
  maxPlayers?: number;
  availabletypeId?: string | null;
  withoutLoadScreen?: number;
  withoutInlay?: number;
  issueId?: number | null;
  files?: {
    id: number;
    link: string;
    size: number | null;
    md5: string | null;
    comments: string | null;
    type: { id: number; name: string };
  }[];
  downloadsFlat?: {
    id: number;
    link: string;
    size: number | null;
    md5: string | null;
    comments: string | null;
    isDemo: boolean;
    type: { id: number; name: string };
    language: { id: string | null; name: string | null };
    machinetype: { id: number | null; name: string | null };
    scheme: { id: string | null; name: string | null };
    source: { id: string | null; name: string | null };
    case: { id: string | null; name: string | null };
    year: number | null;
    releaseSeq: number;
    localLink?: string | null;
  }[];
  releases?: {
    releaseSeq: number;
    type: { id: string | null; name: string | null };
    language: { id: string | null; name: string | null };
    machinetype: { id: number | null; name: string | null };
    year: number | null;
    comments: string | null;
    downloads: {
      id: number;
      link: string;
      size: number | null;
      md5: string | null;
      comments: string | null;
      isDemo: boolean;
      type: { id: number; name: string };
      language: { id: string | null; name: string | null };
      machinetype: { id: number | null; name: string | null };
      scheme: { id: string | null; name: string | null };
      source: { id: string | null; name: string | null };
      case: { id: string | null; name: string | null };
      year: number | null;
      localLink?: string | null;
    }[];
  }[];
  aliases?: { releaseSeq: number; languageId: string; title: string }[];
  webrefs?: { link: string; languageId: string; website: { id: number; name: string; link?: string | null } }[];
  magazineRefs?: {
    id: number;
    issueId: number;
    magazineId: number | null;
    magazineName: string | null;
    referencetypeId: number;
    referencetypeName: string | null;
    page: number;
    isOriginal: number;
    scoreGroup: string;
    issue: {
      dateYear: number | null;
      dateMonth: number | null;
      dateDay: number | null;
      volume: number | null;
      number: number | null;
      special: string | null;
      supplement: string | null;
    };
  }[];
};

function formatSize(bytes: number | null) {
  if (bytes == null) return null;
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

function FileName({ link }: { link: string }) {
  return <span className="text-break">{link.split("/").pop() || link}</span>;
}

export default function EntryDetailClient({ data }: { data: EntryDetailData | null }) {
  const [viewer, setViewer] = useState<{ url: string; title: string } | null>(null);

  const groupedDownloads = useMemo(() => {
    if (!data?.downloadsFlat) return [];
    const groups = new Map<string, EntryDetailData["downloadsFlat"]>();
    for (const d of data.downloadsFlat) {
      const type = d.type.name;
      const arr = groups.get(type) ?? [];
      arr.push(d);
      groups.set(type, arr);
    }
    return Array.from(groups.entries()).sort((a, b) => a[0].localeCompare(b[0]));
  }, [data?.downloadsFlat]);

  if (!data) return <div className="alert alert-warning">Not found</div>;

  const hasDownloads = groupedDownloads.length > 0;
  const hasReleases = data.releases && data.releases.length > 0;
  const hasOrigins = data.origins && data.origins.length > 0;
  const hasRelations = data.relations && data.relations.length > 0;
  const hasTags = data.tags && data.tags.length > 0;
  const hasPorts = data.ports && data.ports.length > 0;
  const hasRemakes = data.remakes && data.remakes.length > 0;
  const hasScores = data.scores && data.scores.length > 0;
  const hasNotes = data.notes && data.notes.length > 0;
  const hasAliases = data.aliases && data.aliases.length > 0;
  const hasLicenses = data.licenses && data.licenses.length > 0;
  const hasWebrefs = data.webrefs && data.webrefs.length > 0;
  const hasMagRefs = data.magazineRefs && data.magazineRefs.length > 0;
  const hasFiles = data.files && data.files.length > 0;

  return (
    <div>
      <ZxdbBreadcrumbs
        items={[
          { label: "ZXDB", href: "/zxdb" },
          { label: "Entries", href: "/zxdb/entries" },
          { label: data.title },
        ]}
      />

      <div className="d-flex align-items-center gap-2 flex-wrap mb-3">
        <h1 className="mb-0">{data.title}</h1>
        {data.genre.name && (
          <Link className="badge text-bg-secondary text-decoration-none" href={`/zxdb/genres/${data.genre.id}`}>
            {data.genre.name}
          </Link>
        )}
        {data.language.name && (
          <Link className="badge text-bg-info text-decoration-none" href={`/zxdb/languages/${data.language.id}`}>
            {data.language.name}
          </Link>
        )}
        {data.machinetype.name && (
          <Link className="badge text-bg-primary text-decoration-none" href={`/zxdb/machinetypes/${data.machinetype.id}`}>
            {data.machinetype.name}
          </Link>
        )}
        {data.isXrated ? <Badge bg="danger">18+</Badge> : null}
      </div>

      <div className="row g-3">
        {/* Left column: summary + metadata */}
        <div className="col-lg-4">
          <Card className="shadow-sm mb-3">
            <Card.Body>
              <Card.Title>Entry Summary</Card.Title>
              <Table size="sm" striped className="align-middle mb-0">
                <tbody>
                  <tr>
                    <th style={{ width: 160 }}>ID</th>
                    <td>{data.id}</td>
                  </tr>
                  <tr>
                    <th>Machine</th>
                    <td>
                      {data.machinetype.id != null ? (
                        data.machinetype.name ? (
                          <Link href={`/zxdb/machinetypes/${data.machinetype.id}`}>{data.machinetype.name}</Link>
                        ) : <span>#{data.machinetype.id}</span>
                      ) : <span className="text-secondary">-</span>}
                    </td>
                  </tr>
                  <tr>
                    <th>Language</th>
                    <td>
                      {data.language.id ? (
                        data.language.name ? (
                          <Link href={`/zxdb/languages/${data.language.id}`}>{data.language.name}</Link>
                        ) : <span>{data.language.id}</span>
                      ) : <span className="text-secondary">-</span>}
                    </td>
                  </tr>
                  <tr>
                    <th>Genre</th>
                    <td>
                      {data.genre.id ? (
                        data.genre.name ? (
                          <Link href={`/zxdb/genres/${data.genre.id}`}>{data.genre.name}</Link>
                        ) : <span>#{data.genre.id}</span>
                      ) : <span className="text-secondary">-</span>}
                    </td>
                  </tr>
                  {typeof data.maxPlayers !== "undefined" && data.maxPlayers !== null && (
                    <tr>
                      <th>Max Players</th>
                      <td>{data.maxPlayers}</td>
                    </tr>
                  )}
                  {typeof data.availabletypeId !== "undefined" && data.availabletypeId !== null && (
                    <tr>
                      <th>Available Type</th>
                      <td>{data.availabletypeId}</td>
                    </tr>
                  )}
                </tbody>
              </Table>
            </Card.Body>
          </Card>

          <Card className="shadow-sm mb-3">
            <Card.Body>
              <Card.Title>People</Card.Title>
              <div className="d-flex flex-column gap-3">
                <div>
                  <div className="text-secondary small mb-1">Authors</div>
                  {data.authors.length === 0 && <span className="text-secondary">Unknown</span>}
                  {data.authors.map((a) => (
                    <div key={a.id}>
                      <Link href={`/zxdb/labels/${a.id}`}>{a.name}</Link>
                    </div>
                  ))}
                </div>
                <div>
                  <div className="text-secondary small mb-1">Publishers</div>
                  {data.publishers.length === 0 && <span className="text-secondary">Unknown</span>}
                  {data.publishers.map((p) => (
                    <div key={p.id}>
                      <Link href={`/zxdb/labels/${p.id}`}>{p.name}</Link>
                    </div>
                  ))}
                </div>
              </div>
            </Card.Body>
          </Card>

          {hasMagRefs && (
            <Card className="shadow-sm mb-3">
              <Card.Body>
                <Card.Title>Magazine References</Card.Title>
                <Table size="sm" striped className="align-middle mb-0">
                  <thead>
                    <tr>
                      <th>Magazine</th>
                      <th>Issue</th>
                      <th>Type</th>
                      <th>Score</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.magazineRefs!.map((m) => (
                      <tr key={m.id}>
                        <td>
                          {m.magazineId ? (
                            <Link href={`/zxdb/magazines/${m.magazineId}`}>{m.magazineName}</Link>
                          ) : <span>{m.magazineName}</span>}
                        </td>
                        <td>
                          <Link href={`/zxdb/issues/${m.issueId}`}>
                            {m.issue.dateYear ? `${m.issue.dateYear} ` : ""}
                            {m.issue.number ? `#${m.issue.number}` : ""}
                            {m.issue.special ? ` (${m.issue.special})` : ""}
                          </Link>
                        </td>
                        <td>{m.referencetypeName}</td>
                        <td>{m.scoreGroup || "-"}</td>
                      </tr>
                    ))}
                  </tbody>
                </Table>
              </Card.Body>
            </Card>
          )}

          {hasScores && (
            <Card className="shadow-sm mb-3">
              <Card.Body>
                <Card.Title>Scores</Card.Title>
                <Table size="sm" striped className="align-middle mb-0">
                  <thead>
                    <tr>
                      <th>Website</th>
                      <th style={{ width: 80 }}>Score</th>
                      <th style={{ width: 80 }}>Votes</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.scores!.map((s, idx) => (
                      <tr key={`${s.website.id}-${idx}`}>
                        <td>{s.website.name ?? `#${s.website.id}`}</td>
                        <td>{s.score}</td>
                        <td>{s.votes}</td>
                      </tr>
                    ))}
                  </tbody>
                </Table>
              </Card.Body>
            </Card>
          )}

          {hasWebrefs && (
            <Card className="shadow-sm mb-3">
              <Card.Body>
                <Card.Title>Web Links</Card.Title>
                <div className="d-flex flex-column gap-1">
                  {data.webrefs!.map((w, idx) => (
                    <div key={`${w.website.id}-${idx}`} className="d-flex align-items-center gap-2">
                      <a href={w.link} target="_blank" rel="noopener noreferrer" className="d-flex align-items-center gap-1">
                        {w.website.name} <BoxArrowUpRight size={10} />
                      </a>
                      {w.languageId && <Badge bg="info" className="text-uppercase" style={{ fontSize: "0.65rem" }}>{w.languageId}</Badge>}
                    </div>
                  ))}
                </div>
              </Card.Body>
            </Card>
          )}

          <Card className="shadow-sm mb-3">
            <Card.Body className="d-flex flex-wrap gap-2">
              <Link className="btn btn-sm btn-outline-secondary" href={`/zxdb/entries/${data.id}`}>Permalink</Link>
              <Link className="btn btn-sm btn-outline-primary" href="/zxdb/entries">Back to Entries</Link>
            </Card.Body>
          </Card>
        </div>

        {/* Right column: downloads + detail sections */}
        <div className="col-lg-8">
          {hasDownloads && (
            <Card className="shadow-sm mb-3">
              <Card.Body>
                <Card.Title>Downloads</Card.Title>
                {groupedDownloads.map(([type, items]) => (
                  <div key={type} className="mb-4">
                    <h6 className="text-primary border-bottom pb-1 mb-2">{type}</h6>
                    <div className="table-responsive">
                      <Table size="sm" striped className="align-middle">
                        <thead>
                          <tr>
                            <th>File</th>
                            <th style={{ width: 80 }} className="text-end">Size</th>
                            <th>Tags</th>
                            <th>Comments</th>
                          </tr>
                        </thead>
                        <tbody>
                          {items?.map((d) => {
                            const isHttp = d.link.startsWith("http://") || d.link.startsWith("https://");
                            const fileName = d.link.split("/").pop() || "file";
                            const canPreview = d.localLink && fileName.toLowerCase().match(/\.(txt|nfo|png|jpg|jpeg|gif|pdf)$/);
                            return (
                              <tr key={d.id}>
                                <td>
                                  <div className="d-flex flex-column gap-1">
                                    {isHttp ? (
                                      <a href={d.link} target="_blank" rel="noopener noreferrer" className="small">
                                        <FileName link={d.link} />
                                      </a>
                                    ) : (
                                      <span className="small"><FileName link={d.link} /></span>
                                    )}
                                    <div className="d-flex gap-1 flex-wrap">
                                      {d.localLink && (
                                        <a href={d.localLink} className="badge text-bg-success text-decoration-none" style={{ fontSize: "0.65rem" }}>
                                          <Download size={10} /> Local
                                        </a>
                                      )}
                                      {canPreview && (
                                        <button
                                          className="badge text-bg-info border-0"
                                          style={{ fontSize: "0.65rem", cursor: "pointer" }}
                                          onClick={() => setViewer({ url: d.localLink!, title: fileName })}
                                        >
                                          <Eye size={10} /> Preview
                                        </button>
                                      )}
                                    </div>
                                  </div>
                                </td>
                                <td className="text-end small">{formatSize(d.size) ?? "-"}</td>
                                <td>
                                  <div className="d-flex gap-1 flex-wrap">
                                    {d.isDemo && <Badge bg="warning" text="dark">Demo</Badge>}
                                    {d.scheme.name && <Badge bg="info">{d.scheme.name}</Badge>}
                                    {d.source.name && <Badge bg="light" text="dark" className="border">{d.source.name}</Badge>}
                                    {d.case.name && <Badge bg="secondary">{d.case.name}</Badge>}
                                    {d.language.name && (
                                      <Link className="badge text-bg-info text-decoration-none" href={`/zxdb/languages/${d.language.id}`}>{d.language.name}</Link>
                                    )}
                                    {d.machinetype.name && (
                                      <Link className="badge text-bg-primary text-decoration-none" href={`/zxdb/machinetypes/${d.machinetype.id}`}>{d.machinetype.name}</Link>
                                    )}
                                    {typeof d.year === "number" && <Badge bg="dark">{d.year}</Badge>}
                                    <Link className="badge text-bg-light text-decoration-none border" href={`/zxdb/releases/${data.id}/${d.releaseSeq}`}>
                                      rel #{d.releaseSeq}
                                    </Link>
                                  </div>
                                </td>
                                <td className="small text-secondary">{d.comments ?? ""}</td>
                              </tr>
                            );
                          })}
                        </tbody>
                      </Table>
                    </div>
                  </div>
                ))}
              </Card.Body>
            </Card>
          )}

          {hasReleases && (
            <Card className="shadow-sm mb-3">
              <Card.Body>
                <Card.Title>Releases</Card.Title>
                <Table size="sm" striped className="align-middle mb-0">
                  <thead>
                    <tr>
                      <th style={{ width: 100 }}>Release #</th>
                      <th style={{ width: 100 }}>Year</th>
                      <th style={{ width: 100 }}>Downloads</th>
                      <th>Comments</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.releases!.map((r) => (
                      <tr key={r.releaseSeq}>
                        <td>
                          <Link href={`/zxdb/releases/${data.id}/${r.releaseSeq}`}>#{r.releaseSeq}</Link>
                        </td>
                        <td>{r.year ?? <span className="text-secondary">-</span>}</td>
                        <td>{r.downloads.length}</td>
                        <td className="small text-secondary">{r.comments ?? ""}</td>
                      </tr>
                    ))}
                  </tbody>
                </Table>
              </Card.Body>
            </Card>
          )}

          {hasOrigins && (
            <Card className="shadow-sm mb-3">
              <Card.Body>
                <Card.Title>Origins</Card.Title>
                <Table size="sm" striped className="align-middle mb-0">
                  <thead>
                    <tr>
                      <th>Type</th>
                      <th>Title</th>
                      <th>Publication</th>
                      <th>Issue</th>
                      <th style={{ width: 120 }}>Date</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.origins!.map((o, idx) => {
                      const dateParts = [o.date.year, o.date.month, o.date.day]
                        .filter((v) => typeof v === "number" && Number.isFinite(v))
                        .map((v, i) => (i === 0 ? String(v) : String(v).padStart(2, "0")));
                      const dateText = dateParts.length ? dateParts.join("/") : "-";
                      return (
                        <tr key={`${o.type.id}-${idx}`}>
                          <td>{o.type.name ?? o.type.id}</td>
                          <td>{o.libraryTitle}</td>
                          <td>{o.publication ?? <span className="text-secondary">-</span>}</td>
                          <td>
                            {o.issue ? (
                              <Link href={`/zxdb/issues/${o.issue.id}`}>
                                {o.issue.magazineTitle ?? `Issue #${o.issue.id}`}
                              </Link>
                            ) : o.containerId ? (
                              <span>Container #{o.containerId}</span>
                            ) : <span className="text-secondary">-</span>}
                          </td>
                          <td>{dateText}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </Table>
              </Card.Body>
            </Card>
          )}

          {hasRelations && (
            <Card className="shadow-sm mb-3">
              <Card.Body>
                <Card.Title>Relations</Card.Title>
                <Table size="sm" striped className="align-middle mb-0">
                  <thead>
                    <tr>
                      <th style={{ width: 80 }}>Dir</th>
                      <th style={{ width: 160 }}>Type</th>
                      <th>Entry</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.relations!.map((r, idx) => (
                      <tr key={`${r.entry.id}-${r.type.id}-${idx}`}>
                        <td>{r.direction === "from" ? "From" : "To"}</td>
                        <td>{r.type.name ?? r.type.id}</td>
                        <td>
                          <Link href={`/zxdb/entries/${r.entry.id}`}>
                            {r.entry.title ?? `Entry #${r.entry.id}`}
                          </Link>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </Table>
              </Card.Body>
            </Card>
          )}

          {hasTags && (
            <Card className="shadow-sm mb-3">
              <Card.Body>
                <Card.Title>Tags / Members</Card.Title>
                <Table size="sm" striped className="align-middle mb-0">
                  <thead>
                    <tr>
                      <th>Tag</th>
                      <th style={{ width: 140 }}>Type</th>
                      <th style={{ width: 140 }}>Category</th>
                      <th>Links</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.tags!.map((t) => (
                      <tr key={`${t.id}-${t.category.id ?? "none"}`}>
                        <td>{t.name}</td>
                        <td>{t.type.name ?? t.type.id}</td>
                        <td>{t.category.name ?? (t.category.id != null ? `#${t.category.id}` : "-")}</td>
                        <td>
                          {t.link ? (
                            <a href={t.link} target="_blank" rel="noreferrer" className="d-inline-flex align-items-center gap-1">
                              Link <BoxArrowUpRight size={10} />
                            </a>
                          ) : t.comments ? (
                            <span className="text-secondary small">{t.comments}</span>
                          ) : <span className="text-secondary">-</span>}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </Table>
              </Card.Body>
            </Card>
          )}

          {hasPorts && (
            <Card className="shadow-sm mb-3">
              <Card.Body>
                <Card.Title>Ports</Card.Title>
                <Table size="sm" striped className="align-middle mb-0">
                  <thead>
                    <tr>
                      <th>Title</th>
                      <th style={{ width: 160 }}>Platform</th>
                      <th style={{ width: 100 }}>Official</th>
                      <th>Link</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.ports!.map((p) => (
                      <tr key={p.id}>
                        <td>{p.title ?? <span className="text-secondary">-</span>}</td>
                        <td>{p.platform.name ?? `#${p.platform.id}`}</td>
                        <td>{p.isOfficial ? "Yes" : "No"}</td>
                        <td>
                          {p.linkSystem ? (
                            <a href={p.linkSystem} target="_blank" rel="noreferrer" className="d-inline-flex align-items-center gap-1">
                              Link <BoxArrowUpRight size={10} />
                            </a>
                          ) : <span className="text-secondary">-</span>}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </Table>
              </Card.Body>
            </Card>
          )}

          {hasRemakes && (
            <Card className="shadow-sm mb-3">
              <Card.Body>
                <Card.Title>Remakes</Card.Title>
                <Table size="sm" striped className="align-middle mb-0">
                  <thead>
                    <tr>
                      <th>Title</th>
                      <th style={{ width: 140 }}>Platforms</th>
                      <th style={{ width: 100 }}>Years</th>
                      <th>Notes</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.remakes!.map((r) => (
                      <tr key={r.id}>
                        <td>
                          {r.fileLink ? (
                            <a href={r.fileLink} target="_blank" rel="noreferrer" className="d-inline-flex align-items-center gap-1">
                              {r.title} <BoxArrowUpRight size={10} />
                            </a>
                          ) : r.title}
                        </td>
                        <td>{r.platforms ?? <span className="text-secondary">-</span>}</td>
                        <td>{r.remakeYears ?? <span className="text-secondary">-</span>}</td>
                        <td className="small">{r.remakeStatus ?? r.authors ?? <span className="text-secondary">-</span>}</td>
                      </tr>
                    ))}
                  </tbody>
                </Table>
              </Card.Body>
            </Card>
          )}

          {hasNotes && (
            <Card className="shadow-sm mb-3">
              <Card.Body>
                <Card.Title>Notes</Card.Title>
                {data.notes!.map((n) => (
                  <div key={n.id} className="mb-2">
                    <Badge bg="secondary" className="me-2">{n.type.name ?? n.type.id}</Badge>
                    <span>{n.text}</span>
                  </div>
                ))}
              </Card.Body>
            </Card>
          )}

          {hasAliases && (
            <Card className="shadow-sm mb-3">
              <Card.Body>
                <Card.Title>Aliases</Card.Title>
                <Table size="sm" striped className="align-middle mb-0">
                  <thead>
                    <tr>
                      <th style={{ width: 90 }}>Release #</th>
                      <th style={{ width: 100 }}>Language</th>
                      <th>Title</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.aliases!.map((a, idx) => (
                      <tr key={`${a.releaseSeq}-${a.languageId}-${idx}`}>
                        <td>
                          <Link href={`/zxdb/releases/${data.id}/${a.releaseSeq}`}>#{a.releaseSeq}</Link>
                        </td>
                        <td>{a.languageId}</td>
                        <td>{a.title}</td>
                      </tr>
                    ))}
                  </tbody>
                </Table>
              </Card.Body>
            </Card>
          )}

          {hasLicenses && (
            <Card className="shadow-sm mb-3">
              <Card.Body>
                <Card.Title>Licenses</Card.Title>
                <Table size="sm" striped className="align-middle mb-0">
                  <thead>
                    <tr>
                      <th>Name</th>
                      <th style={{ width: 140 }}>Type</th>
                      <th style={{ width: 100 }}>Official</th>
                      <th>Links</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.licenses!.map((l) => (
                      <tr key={l.id}>
                        <td>{l.name}</td>
                        <td>{l.type.name ?? l.type.id}</td>
                        <td>{l.isOfficial ? "Yes" : "No"}</td>
                        <td>
                          <div className="d-flex gap-2 flex-wrap">
                            {l.linkWikipedia && (
                              <a href={l.linkWikipedia} target="_blank" rel="noreferrer">Wikipedia</a>
                            )}
                            {l.linkSite && (
                              <a href={l.linkSite} target="_blank" rel="noreferrer">Site</a>
                            )}
                            {!l.linkWikipedia && !l.linkSite && <span className="text-secondary">-</span>}
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </Table>
              </Card.Body>
            </Card>
          )}

          {hasFiles && (
            <Card className="shadow-sm mb-3">
              <Card.Body>
                <Card.Title>Files</Card.Title>
                <Table size="sm" striped className="align-middle mb-0">
                  <thead>
                    <tr>
                      <th>Type</th>
                      <th>Link</th>
                      <th style={{ width: 80 }} className="text-end">Size</th>
                      <th>Comments</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.files!.map((f) => {
                      const isHttp = f.link.startsWith("http://") || f.link.startsWith("https://");
                      return (
                        <tr key={f.id}>
                          <td><Badge bg="secondary">{f.type.name}</Badge></td>
                          <td>
                            {isHttp ? (
                              <a href={f.link} target="_blank" rel="noopener noreferrer" className="small">
                                <FileName link={f.link} />
                              </a>
                            ) : <span className="small"><FileName link={f.link} /></span>}
                          </td>
                          <td className="text-end small">{formatSize(f.size) ?? "-"}</td>
                          <td className="small">{f.comments ?? ""}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </Table>
              </Card.Body>
            </Card>
          )}

          {/* Show a summary when there's very little data */}
          {!hasDownloads && !hasReleases && !hasOrigins && !hasRelations && (
            <Card className="shadow-sm mb-3">
              <Card.Body className="text-secondary">
                No downloads, releases, or related data found for this entry.
              </Card.Body>
            </Card>
          )}
        </div>
      </div>
      {viewer && (
        <FileViewer
          url={viewer.url}
          title={viewer.title}
          onClose={() => setViewer(null)}
        />
      )}
    </div>
  );
}
