import { fireEvent, render, screen } from "@testing-library/react";
import { expect, test } from "vitest";
import { AppIdentity } from "./AppIdentity.jsx";

test("renders the server-provided app logo beside the app name", () => {
    const { container } = render(
        <AppIdentity app={{ appCode: "lalu", appName: "Lalu", logoUrl: "https://media.example.com/lalu.png" }} />,
    );

    expect(screen.getByText("Lalu")).toBeInTheDocument();
    expect(container.querySelector("img")).toHaveAttribute("src", "https://media.example.com/lalu.png");
});

test("falls back to a stable initial when the logo cannot load", () => {
    const { container } = render(
        <AppIdentity app={{ appCode: "lalu", appName: "Lalu", logoUrl: "https://media.example.com/missing.png" }} />,
    );

    fireEvent.error(container.querySelector("img"));
    expect(container.querySelector("img")).toBeNull();
    expect(screen.getByText("L", { selector: "span" })).toBeInTheDocument();
});

test("supports the snake case Social BI app contract", () => {
    const { container } = render(
        <AppIdentity app={{ app_code: "aslan", app_name: "Aslan", logo_url: "https://media.example.com/aslan.png" }} />,
    );

    expect(screen.getByText("Aslan")).toBeInTheDocument();
    expect(container.querySelector("img")).toHaveAttribute("src", "https://media.example.com/aslan.png");
});

test("can hide the fallback when a surface must only show a database logo", () => {
    const { container } = render(
        <AppIdentity app={{ appCode: "fami", appName: "Fami", logoUrl: "" }} showLogoFallback={false} />,
    );

    expect(container.querySelector("img")).toBeNull();
    expect(screen.getByText("Fami")).toBeInTheDocument();
    expect(screen.queryByText("F", { selector: "span" })).not.toBeInTheDocument();
});

test("does not invent a fallback when an external portal database logo fails to load", () => {
    const { container } = render(
        <AppIdentity
            app={{ appCode: "fami", appName: "Fami", logoUrl: "https://media.example.com/apps/missing-fami.png" }}
            showLogoFallback={false}
        />,
    );

    fireEvent.error(container.querySelector("img"));
    expect(container.querySelector("img")).toBeNull();
    expect(screen.getByText("Fami")).toBeInTheDocument();
    expect(screen.queryByText("F", { selector: "span" })).not.toBeInTheDocument();
});
