import React from "react";
import { render, waitFor, act } from "@testing-library/react-native";

import { SoluCXWidgetHost } from "../SoluCXWidgetHost";
import { SoluCXWidget, _unregisterHost } from "../SoluCXWidget";

const mockUpdateTimestamp = jest.fn().mockResolvedValue(undefined);
const mockBuildStorageId = jest.fn((_instanceKey: string, _data: Record<string, unknown>) => "mock-storage-id");

jest.mock("../SoluCXWidgetView", () => ({
    SoluCXWidgetView: () => null,
}));

jest.mock("../services/storage/StorageIdBuilder", () => ({
    buildStorageId: (instanceKey: string, data: Record<string, unknown>) => mockBuildStorageId(instanceKey, data),
}));

jest.mock("../services/storage/AsyncStorageService", () => ({
    AsyncStorageService: jest.fn().mockImplementation(() => ({})),
}));

jest.mock("../services/WidgetStateManager", () => ({
    WidgetStateManager: jest.fn().mockImplementation(() => ({
        updateTimestamp: (...args: unknown[]) => mockUpdateTimestamp(...args),
    })),
}));

describe("SoluCXWidgetHost", () => {
    beforeEach(() => {
        jest.clearAllMocks();
        _unregisterHost();
    });

    afterEach(() => {
        _unregisterHost();
    });

    it("persists lastDismiss when dismiss is called programmatically", async () => {
        const onClosed = jest.fn();

        render(<SoluCXWidgetHost />);

        await act(async () => {
            SoluCXWidget.create("instance-key")
                .setType("modal")
                .setData({ customer_id: "customer-1", journey: "checkout" })
                .setCallbacks({ onClosed })
                .show();
        });

        await act(async () => {
            SoluCXWidget.dismiss();
        });

        await waitFor(() => {
            expect(mockBuildStorageId).toHaveBeenCalledWith("instance-key", {
                customer_id: "customer-1",
                journey: "checkout",
            });
            expect(mockUpdateTimestamp).toHaveBeenCalledWith("lastDismiss");
            expect(onClosed).toHaveBeenCalledTimes(1);
        });
    });
});
