import type { HistoryWindowState } from "./viewerHudState";
import type { Selectable, WorldState } from "./viewerTypes";

export function createHistoryWindowState(
  target: Selectable,
  historyWindowsCount: number,
  historyWindowCounter: number,
): HistoryWindowState {
  return {
    id: `history-${historyWindowCounter}`,
    target,
    title: "History",
    bodyHtml: "No history selected.",
    text: "",
    copyLabel: "Copy",
    width: Math.min(520, window.innerWidth - 40),
    height: Math.min(360, Math.max(240, window.innerHeight * 0.42)),
    x: Math.max(20, 20 + ((historyWindowsCount * 28) % Math.max(40, window.innerWidth - 580))),
    y: Math.max(20, 20 + ((historyWindowsCount * 28) % Math.max(40, window.innerHeight - 420))),
    zIndex: 1,
  };
}

export function refreshHistoryWindow(
  world: WorldState,
  windowState: HistoryWindowState,
  renderRecentEvents: (entityKind: string, entityId: string) => string,
): boolean {
  if (windowState.target.kind === "ship") {
    const ship = world.ships.get(windowState.target.id);
    if (!ship) {
      return false;
    }

    windowState.title = `${ship.name} History`;
    windowState.text = ship.history.length > 0 ? ship.history.join("\n") : "No history yet.";
    windowState.bodyHtml = windowState.text.replaceAll("\n", "<br>");
    return true;
  }

  if (windowState.target.kind === "station") {
    const station = world.stations.get(windowState.target.id);
    if (!station) {
      return false;
    }

    windowState.title = `${station.label} History`;
    windowState.text = renderRecentEvents("station", station.id).replaceAll("<br>", "\n") || "No history yet.";
    windowState.bodyHtml = windowState.text.replaceAll("\n", "<br>");
    return true;
  }

  return false;
}
