import { fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";

import { Lab1ConfidenceChat } from "~/components/labs/Lab1ConfidenceChat";

describe("Lab1ConfidenceChat", () => {
  beforeEach(() => {
    vi.restoreAllMocks();
  });

  it("renders colorized tokens and tooltip data from the Lab 1 chat route", async () => {
    vi.stubGlobal(
      "fetch",
      vi.fn(async () => {
        return {
          json: async () => ({
            content: "often works",
            model: "batiai/gemma4-e2b:q4",
            role: "assistant",
            tokens: [
              {
                logprob: Math.log(0.4),
                probability: 40,
                token: "often",
                topAlternatives: [
                  { probability: 14, token: "commonly" },
                  { probability: 10, token: "also" },
                ],
              },
              {
                logprob: Math.log(0.8),
                probability: 80,
                token: " works",
                topAlternatives: [],
              },
            ],
          }),
          ok: true,
        };
      }),
    );

    render(<Lab1ConfidenceChat />);

    fireEvent.change(screen.getByLabelText("Prompt"), {
      target: { value: "Explain how often phishing succeeds." },
    });
    fireEvent.submit(
      screen.getByRole("button", { name: "Generate Output" }).closest("form")!,
    );

    expect(await screen.findByLabelText("often 40.0%")).toBeInTheDocument();
    expect(screen.getByText("14.0%:")).toBeInTheDocument();
    expect(screen.getByText("commonly")).toBeInTheDocument();
    expect(screen.getByText("batiai/gemma4-e2b:q4")).toBeInTheDocument();
  });

  it("shows an inline error when the local route fails", async () => {
    vi.stubGlobal(
      "fetch",
      vi.fn(async () => {
        return {
          json: async () => ({
            error: "The local Ollama request failed.",
          }),
          ok: false,
        };
      }),
    );

    render(<Lab1ConfidenceChat />);

    fireEvent.change(screen.getByLabelText("Prompt"), {
      target: { value: "Trigger an error." },
    });
    fireEvent.submit(
      screen.getByRole("button", { name: "Generate Output" }).closest("form")!,
    );

    expect(
      await screen.findByText("The local Ollama request failed."),
    ).toBeInTheDocument();
  });
});
