import { describe, it, expect, vi } from "vitest";
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { renderWithMantine } from "../../test/utils";
import Composer from "../../components/Composer";

function makeProps(over?: Partial<React.ComponentProps<typeof Composer>>) {
  return {
    onSendText: vi.fn(async () => {}),
    onSendMarkdown: vi.fn(async () => {}),
    ...over,
  };
}

describe("Composer", () => {
  it("sends on plain Enter with the typed body", async () => {
    const user = userEvent.setup();
    const props = makeProps();
    renderWithMantine(<Composer {...props} />);

    const textarea = screen.getByPlaceholderText(/enter to send/i);
    await user.type(textarea, "hello world{Enter}");

    expect(props.onSendText).toHaveBeenCalledTimes(1);
    expect(props.onSendText).toHaveBeenCalledWith("hello world");
    expect(props.onSendMarkdown).not.toHaveBeenCalled();
  });

  it("Shift+Enter inserts a newline and does NOT send", async () => {
    const user = userEvent.setup();
    const props = makeProps();
    renderWithMantine(<Composer {...props} />);

    const textarea = screen.getByPlaceholderText(/enter to send/i) as HTMLTextAreaElement;
    await user.type(textarea, "line1{Shift>}{Enter}{/Shift}line2");

    expect(props.onSendText).not.toHaveBeenCalled();
    expect(textarea.value).toBe("line1\nline2");
  });

  it("clicking the Send action icon sends the body", async () => {
    const user = userEvent.setup();
    const props = makeProps();
    const { container } = renderWithMantine(<Composer {...props} />);

    const textarea = screen.getByPlaceholderText(/enter to send/i);
    await user.type(textarea, "via button");

    // Send is the last ActionIcon (button) in the Composer row.
    const buttons = container.querySelectorAll("button");
    const sendBtn = buttons[buttons.length - 1];
    await user.click(sendBtn);

    expect(props.onSendText).toHaveBeenCalledWith("via button");
  });

  it("empty body does not invoke onSendText", async () => {
    const user = userEvent.setup();
    const props = makeProps();
    renderWithMantine(<Composer {...props} />);

    const textarea = screen.getByPlaceholderText(/enter to send/i);
    // press Enter on empty textarea
    textarea.focus();
    await user.keyboard("{Enter}");
    await user.type(textarea, "   {Enter}");

    expect(props.onSendText).not.toHaveBeenCalled();
  });
});
