import { act, render, screen } from "@testing-library/react";
import * as React from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { PipelineState } from "../api/client";
import { LozengeFlyProvider, useLozengeFly } from "./LozengeFlyContext";
import { StagePanel } from "./StagePanel";

// ─── Helpers ──────────────────────────────────────────────────────────────────

function makePipeline(overrides: Partial<PipelineState> = {}): PipelineState {
	return {
		backlog: [],
		current: [],
		qa: [],
		merge: [],
		done: [],
		deterministic_merges_in_flight: [],
		...overrides,
	};
}

/** A minimal roster element fixture that registers itself with the context. */
function RosterFixture({ agentName }: { agentName: string }) {
	const { registerRosterEl } = useLozengeFly();
	const ref = React.useRef<HTMLSpanElement>(null);
	React.useEffect(() => {
		const el = ref.current;
		if (el) registerRosterEl(agentName, el);
		return () => registerRosterEl(agentName, null);
	}, [agentName, registerRosterEl]);
	return (
		<span
			ref={ref}
			data-testid={`roster-${agentName}`}
			style={{ position: "fixed", top: 10, left: 20, width: 80, height: 20 }}
		/>
	);
}

function Wrapper({
	pipeline,
	children,
}: {
	pipeline: PipelineState;
	children: React.ReactNode;
}) {
	return (
		<LozengeFlyProvider pipeline={pipeline}>{children}</LozengeFlyProvider>
	);
}

// ─── Fly-in: slot lozenge visibility ─────────────────────────────────────────

describe("LozengeFlyProvider fly-in visibility", () => {
	beforeEach(() => {
		Element.prototype.getBoundingClientRect = vi.fn().mockReturnValue({
			left: 100,
			top: 50,
			right: 180,
			bottom: 70,
			width: 80,
			height: 20,
			x: 100,
			y: 50,
			toJSON: () => ({}),
		});
		vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => {
			cb(0);
			return 0;
		});
	});

	afterEach(() => {
		vi.restoreAllMocks();
	});

	it("slot lozenge starts hidden when a matching roster element exists", async () => {
		const noPipeline = makePipeline();
		const withAgent = makePipeline({
			current: [
				{
					story_id: "74_hidden_test",
					name: "Hidden Test",
					error: null,
					merge_failure: null,
					agent: { agent_name: "coder-1", model: null, status: "running" },
					review_hold: null,
					qa: null,
					depends_on: null,
				},
			],
		});

		const { rerender } = render(
			<Wrapper pipeline={noPipeline}>
				<RosterFixture agentName="coder-1" />
				<StagePanel title="Current" items={[]} />
			</Wrapper>,
		);

		// Rerender with the agent assigned
		await act(async () => {
			rerender(
				<Wrapper pipeline={withAgent}>
					<RosterFixture agentName="coder-1" />
					<StagePanel title="Current" items={withAgent.current} />
				</Wrapper>,
			);
		});

		const lozenge = screen.getByTestId("slot-lozenge-74_hidden_test");
		// Hidden while fly-in is in progress
		expect(lozenge.style.opacity).toBe("0");
	});

	it("slot lozenge is visible when no roster element is registered", async () => {
		const noPipeline = makePipeline();
		const withAgent = makePipeline({
			current: [
				{
					story_id: "74_no_roster",
					name: "No Roster",
					error: null,
					merge_failure: null,
					agent: {
						agent_name: "unknown-agent",
						model: null,
						status: "running",
					},
					review_hold: null,
					qa: null,
					depends_on: null,
				},
			],
		});

		const { rerender } = render(
			<Wrapper pipeline={noPipeline}>
				{/* No RosterFixture for "unknown-agent" */}
				<StagePanel title="Current" items={[]} />
			</Wrapper>,
		);

		await act(async () => {
			rerender(
				<Wrapper pipeline={withAgent}>
					<StagePanel title="Current" items={withAgent.current} />
				</Wrapper>,
			);
		});

		const lozenge = screen.getByTestId("slot-lozenge-74_no_roster");
		// Immediately visible because no fly-in animation is possible
		expect(lozenge.style.opacity).toBe("1");
	});
});

// ─── Fly-in: flying clone in document.body portal ────────────────────────────

describe("LozengeFlyProvider fly-in clone", () => {
	beforeEach(() => {
		vi.useFakeTimers();
		Element.prototype.getBoundingClientRect = vi.fn().mockReturnValue({
			left: 100,
			top: 50,
			right: 180,
			bottom: 70,
			width: 80,
			height: 20,
			x: 100,
			y: 50,
			toJSON: () => ({}),
		});
		vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => {
			cb(0);
			return 0;
		});
	});

	afterEach(() => {
		vi.useRealTimers();
		vi.restoreAllMocks();
	});

	it("renders a fixed-position clone in document.body when fly-in triggers", async () => {
		const noPipeline = makePipeline();
		const withAgent = makePipeline({
			current: [
				{
					story_id: "74_portal_test",
					name: "Portal Test",
					error: null,
					merge_failure: null,
					agent: { agent_name: "coder-1", model: "sonnet", status: "running" },
					review_hold: null,
					qa: null,
					depends_on: null,
				},
			],
		});

		const { rerender } = render(
			<Wrapper pipeline={noPipeline}>
				<RosterFixture agentName="coder-1" />
				<StagePanel title="Current" items={[]} />
			</Wrapper>,
		);

		await act(async () => {
			rerender(
				<Wrapper pipeline={withAgent}>
					<RosterFixture agentName="coder-1" />
					<StagePanel title="Current" items={withAgent.current} />
				</Wrapper>,
			);
			vi.runAllTimers();
		});

		// Clone is in document.body (portal), not inside the component container
		const clone = document.body.querySelector(
			'[data-testid^="flying-lozenge-fly-in"]',
		) as HTMLElement | null;
		expect(clone).not.toBeNull();
		expect(clone?.style.position).toBe("fixed");
		expect(Number(clone?.style.zIndex)).toBeGreaterThanOrEqual(9999);
		expect(clone?.style.pointerEvents).toBe("none");
	});

	it("clone is removed from document.body after 500 ms", async () => {
		const noPipeline = makePipeline();
		const withAgent = makePipeline({
			current: [
				{
					story_id: "74_clone_remove",
					name: "Clone Remove",
					error: null,
					merge_failure: null,
					agent: { agent_name: "coder-1", model: null, status: "running" },
					review_hold: null,
					qa: null,
					depends_on: null,
				},
			],
		});

		const { rerender } = render(
			<Wrapper pipeline={noPipeline}>
				<RosterFixture agentName="coder-1" />
				<StagePanel title="Current" items={[]} />
			</Wrapper>,
		);

		await act(async () => {
			rerender(
				<Wrapper pipeline={withAgent}>
					<RosterFixture agentName="coder-1" />
					<StagePanel title="Current" items={withAgent.current} />
				</Wrapper>,
			);
		});

		// Clone should exist before timeout
		const cloneBefore = document.body.querySelector(
			'[data-testid^="flying-lozenge-fly-in"]',
		);
		expect(cloneBefore).not.toBeNull();

		// Advance past the 500ms cleanup timeout
		await act(async () => {
			vi.advanceTimersByTime(600);
		});

		const cloneAfter = document.body.querySelector(
			'[data-testid^="flying-lozenge-fly-in"]',
		);
		expect(cloneAfter).toBeNull();
	});

	it("slot lozenge becomes visible (opacity 1) after 500 ms timeout", async () => {
		const noPipeline = makePipeline();
		const withAgent = makePipeline({
			current: [
				{
					story_id: "74_reveal_test",
					name: "Reveal Test",
					error: null,
					merge_failure: null,
					agent: { agent_name: "coder-1", model: null, status: "running" },
					review_hold: null,
					qa: null,
					depends_on: null,
				},
			],
		});

		const { rerender } = render(
			<Wrapper pipeline={noPipeline}>
				<RosterFixture agentName="coder-1" />
				<StagePanel title="Current" items={[]} />
			</Wrapper>,
		);

		await act(async () => {
			rerender(
				<Wrapper pipeline={withAgent}>
					<RosterFixture agentName="coder-1" />
					<StagePanel title="Current" items={withAgent.current} />
				</Wrapper>,
			);
		});

		// Initially hidden
		const lozenge = screen.getByTestId("slot-lozenge-74_reveal_test");
		expect(lozenge.style.opacity).toBe("0");

		// After 500ms the slot becomes visible
		await act(async () => {
			vi.advanceTimersByTime(600);
		});

		expect(lozenge.style.opacity).toBe("1");
	});
});

// ─── Flying clone renders in initial (non-flying) state ───────────────────

describe("FlyingLozengeClone initial non-flying render", () => {
	beforeEach(() => {
		vi.useFakeTimers();
		Element.prototype.getBoundingClientRect = vi.fn().mockReturnValue({
			left: 100,
			top: 50,
			right: 180,
			bottom: 70,
			width: 80,
			height: 20,
			x: 100,
			y: 50,
			toJSON: () => ({}),
		});
	});

	afterEach(() => {
		vi.useRealTimers();
		vi.restoreAllMocks();
	});

	it("clone has transition: none before rAF fires", async () => {
		// Collect rAF callbacks instead of firing them immediately
		const rafCallbacks: FrameRequestCallback[] = [];
		vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => {
			rafCallbacks.push(cb);
			return rafCallbacks.length;
		});

		const noPipeline = makePipeline();
		const withAgent = makePipeline({
			current: [
				{
					story_id: "109_nontransition_test",
					name: "Non-transition Test",
					error: null,
					merge_failure: null,
					agent: { agent_name: "coder-1", model: null, status: "running" },
					review_hold: null,
					qa: null,
					depends_on: null,
				},
			],
		});

		const { rerender } = render(
			<LozengeFlyProvider pipeline={noPipeline}>
				<RosterFixture agentName="coder-1" />
				<StagePanel title="Current" items={[]} />
			</LozengeFlyProvider>,
		);

		// Trigger fly-in but don't flush rAF callbacks
		await act(async () => {
			rerender(
				<LozengeFlyProvider pipeline={withAgent}>
					<RosterFixture agentName="coder-1" />
					<StagePanel title="Current" items={withAgent.current} />
				</LozengeFlyProvider>,
			);
		});

		// Clone should exist in its initial (non-flying) state
		const clone = document.body.querySelector(
			'[data-testid^="flying-lozenge-fly-in"]',
		) as HTMLElement | null;
		expect(clone).not.toBeNull();
		expect(clone?.style.transition).toBe("none");

		// Now flush rAF callbacks to trigger the flying state
		await act(async () => {
			for (const cb of rafCallbacks) cb(0);
			rafCallbacks.length = 0;
			// Flush inner rAF callbacks too
			for (const cb of rafCallbacks) cb(0);
		});
	});
});
