import { describe, it, expect, beforeEach, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { setActivePinia, createPinia } from "pinia";
import { useDevicesStore } from "../../../../stores/devices.js";
import DevicesListPage from "../DevicesListPage.vue";

const routerLinkStub = { template: "<a><slot /></a>" };

describe("DevicesListPage", () => {
  beforeEach(() => {
    setActivePinia(createPinia());
  });

  it("renders loading state", () => {
    const store = useDevicesStore();
    store.isLoading = true;
    const wrapper = mount(DevicesListPage);
    expect(wrapper.text()).toContain("Loading devices");
  });

  it("renders device table after loading", async () => {
    const wrapper = mount(DevicesListPage, {
      global: { stubs: { "router-link": routerLinkStub } },
    });
    await new Promise((resolve) => setTimeout(resolve, 50));
    expect(wrapper.text()).toContain("Relay 1");
    expect(wrapper.text()).toContain("Total: 1");
  });

  it("shows stale badge for old data", async () => {
    const store = useDevicesStore();
    store.lastLoadedAt = new Date(Date.now() - 10 * 60 * 1000).toISOString();
    store.isLoading = false;
    store.devices = [
      { id: 1, name: "Relay 1", alias: "relay_1", device_type: "relay", device_ip: "192.168.1.10", connection_status: "active" },
    ];
    vi.spyOn(store, "loadDevices").mockResolvedValue({ ok: true });
    vi.spyOn(store, "loadDeviceStates").mockResolvedValue();

    const wrapper = mount(DevicesListPage, {
      global: { stubs: { "router-link": routerLinkStub } },
    });
    await flushPromises();
    expect(wrapper.text()).toContain("Stale data");
  });
});
