import { describe, expect, it } from "vitest";
import {
  DASHBOARD_LAYOUT_VERSION,
  createDefaultDashboardLayout,
  createDashboardWidget,
  getNextDashboardWidgetY,
  normalizeDashboardLayout,
} from "../index.js";

describe("dashboard layout normalization", () => {
  it("returns the default layout for non-object input", () => {
    expect(normalizeDashboardLayout(null)).toEqual(createDefaultDashboardLayout());
  });

  it("repairs invalid persisted widget coordinates and normalizes config", () => {
    const layout = normalizeDashboardLayout({
      version: 1,
      gridCols: 12,
      widgets: [
        {
          id: "alpha",
          type: "stat-cards",
          x: 0,
          y: 0,
          w: 12,
          h: 3,
          minW: 6,
          minH: 2,
          config: { ignored: true },
        },
        {
          id: "beta",
          type: "peak-times-chart",
          x: 0,
          y: null,
          w: 8,
          h: 5,
          minW: 4,
          minH: 4,
          config: { granularity: "week", groupBy: "chapter", extra: "drop-me" },
        },
      ],
    });

    expect(layout.version).toBe(DASHBOARD_LAYOUT_VERSION);
    expect(layout.widgets).toHaveLength(2);
    expect(layout.widgets[0]?.config).toEqual({ showDetails: false });
    expect(layout.widgets[1]?.y).toBe(3);
    expect(layout.widgets[1]?.config).toEqual({
      showDetails: false,
      granularity: "week",
      groupBy: "chapter",
    });
  });

  it("drops unknown widgets and deduplicates ids", () => {
    const layout = normalizeDashboardLayout({
      gridCols: 12,
      widgets: [
        createDashboardWidget("resource-table", { id: "duplicate", y: 0 }),
        createDashboardWidget("project-table", { id: "duplicate", y: 6 }),
        { id: "bad", type: "not-real", x: 0, y: 0, w: 1, h: 1, config: {} },
      ],
    });

    expect(layout.widgets).toHaveLength(2);
    expect(layout.widgets[0]?.id).toBe("duplicate");
    expect(layout.widgets[1]?.id).toBe("duplicate-2");
  });

  it("computes the next widget row from current widget bottoms", () => {
    const widgets = [
      createDashboardWidget("stat-cards", { id: "one", y: 0, h: 3 }),
      createDashboardWidget("demand-view", { id: "two", y: 4, h: 5 }),
    ];

    expect(getNextDashboardWidgetY(widgets)).toBe(9);
  });
});
