import { describe, expect, it } from "vitest";
import {
  generateDashboardLayout,
  generateLegacyDashboardLayout,
  normalizeSavedDashboardLayout,
  shouldUpgradeLegacyDashboardLayout,
  type LayoutItem,
} from "./layoutUtils";

const DEFAULT_CARDS = [
  "stat_pending_arc",
  "stat_open_violations",
  "stat_collections",
  "stat_active_owners",
  "stat_open_requests",
  "chart_community_health",
  "chart_recent_activity",
  "table_tasks",
  "table_projects",
  "table_reminders",
  "table_stripe",
  "table_form_inbox",
  "quick_actions",
];

function getRowWidths(layout: LayoutItem[]) {
  const widthsByRow = new Map<number, number>();

  layout.forEach((item) => {
    widthsByRow.set(item.y, (widthsByRow.get(item.y) ?? 0) + item.w);
  });

  return [...widthsByRow.values()];
}

describe("dashboard layout utils", () => {
  it("stretches generated rows to use the full 12-column desktop grid", () => {
    const layout = generateDashboardLayout(DEFAULT_CARDS);

    expect(getRowWidths(layout)).toEqual([12, 12, 12, 12, 12]);
    expect(layout.find((item) => item.i === "quick_actions")?.w).toBe(12);
  });

  it("recognizes legacy auto-layouts even when the grid has compacted their row offsets", () => {
    const legacyLayout = generateLegacyDashboardLayout(DEFAULT_CARDS);
    const compactedRowMap = new Map([
      [0, 0],
      [3, 3],
      [6, 7],
      [9, 12],
      [12, 17],
    ]);

    const compactedLegacyLayout = legacyLayout.map((item) => ({
      ...item,
      y: compactedRowMap.get(item.y) ?? item.y,
    }));

    expect(shouldUpgradeLegacyDashboardLayout(DEFAULT_CARDS, legacyLayout)).toBe(true);
    expect(shouldUpgradeLegacyDashboardLayout(DEFAULT_CARDS, compactedLegacyLayout)).toBe(true);

    const normalized = normalizeSavedDashboardLayout(DEFAULT_CARDS, compactedLegacyLayout);
    expect(normalized.didUpgradeLegacyLayout).toBe(true);
    expect(getRowWidths(normalized.layout)).toEqual([12, 12, 12, 12, 12]);
  });
});