import { useState } from "react";
import { expect, test } from "vitest";
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { renderApp } from "../test/render";
import { LabelEditor } from "./label-editor";
import type { components } from "../api/schema";

type LabelInput = components["schemas"]["LabelInput"];

function Harness({ onChange }: { onChange: (v: LabelInput[]) => void }) {
  const [value, setValue] = useState<LabelInput[]>([]);
  return (
    <LabelEditor
      value={value}
      onChange={(v) => {
        setValue(v);
        onChange(v);
      }}
    />
  );
}

test("typing EN and SV emits both labels; empty langs are omitted", async () => {
  const seen: LabelInput[][] = [];
  renderApp(<Harness onChange={(v) => seen.push(v)} />);
  await userEvent.type(screen.getByLabelText(/label \(en\)/i), "Bronze");
  await userEvent.type(screen.getByLabelText(/label \(sv\)/i), "Brons");
  const last = seen.at(-1)!;
  expect(last).toEqual(
    expect.arrayContaining([
      { lang: "en", label: "Bronze" },
      { lang: "sv", label: "Brons" },
    ]),
  );
  expect(seen.some((v) => v.length === 1 && v[0].lang === "en")).toBe(true);
});
