import React, { useEffect, act } from "react";
import { describe, expect, test, vi } from "vitest";
import { createRoot } from "react-dom/client";
import type { MediaSelection } from "@/types/media";
import { ImagePickerProvider, useImagePicker } from "./image-picker-context";

// React 18+：需要显式开启 act 环境标记，避免警告。
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

let lastDialogProps: null | { open: boolean; onSelect: (selection: MediaSelection) => void } = null;

vi.mock("@/components/media/image-picker-dialog", () => ({
  ImagePickerDialog: (props: { open: boolean; onSelect: (selection: MediaSelection) => void }) => {
    lastDialogProps = props;
    return null;
  },
}));

function Harness(props: { multiple: boolean; onSelect: (selection: MediaSelection) => void }) {
  const { openPicker } = useImagePicker();
  useEffect(() => {
    openPicker({
      mediaType: "file",
      multiple: props.multiple,
      onSelect: props.onSelect,
    });
  }, [openPicker, props.multiple, props.onSelect]);
  return null;
}

describe("ImagePickerProvider", () => {
  test("single 模式：选择后自动关闭", () => {
    lastDialogProps = null;
    const container = document.createElement("div");
    document.body.appendChild(container);
    const root = createRoot(container);
    const onSelect = vi.fn();

    act(() => {
      root.render(
        <ImagePickerProvider documentId="doc" workspaceId="ws">
          <Harness multiple={false} onSelect={onSelect} />
        </ImagePickerProvider>,
      );
    });

    expect(lastDialogProps?.open).toBe(true);

    act(() => {
      lastDialogProps?.onSelect({ assetId: "a", fileUrl: "https://example.com/a" });
    });

    expect(onSelect).toHaveBeenCalledTimes(1);
    expect(lastDialogProps?.open).toBe(false);

    act(() => root.unmount());
    container.remove();
  });

  test("multiple 模式：可连续选择，不会因第一次选择而关闭", () => {
    lastDialogProps = null;
    const container = document.createElement("div");
    document.body.appendChild(container);
    const root = createRoot(container);
    const onSelect = vi.fn();

    act(() => {
      root.render(
        <ImagePickerProvider documentId="doc" workspaceId="ws">
          <Harness multiple onSelect={onSelect} />
        </ImagePickerProvider>,
      );
    });

    expect(lastDialogProps?.open).toBe(true);

    act(() => {
      lastDialogProps?.onSelect({ assetId: "a", fileUrl: "https://example.com/a" });
    });
    act(() => {
      lastDialogProps?.onSelect({ assetId: "b", fileUrl: "https://example.com/b" });
    });

    expect(onSelect).toHaveBeenCalledTimes(2);
    expect(lastDialogProps?.open).toBe(true);

    act(() => root.unmount());
    container.remove();
  });
});
