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 }}
		/>
	);
}

/** Reads hiddenRosterAgents from context and exposes it via a data attribute. */
function HiddenAgentsProbe() {
	const { hiddenRosterAgents } = useLozengeFly();
	return (
		<div
			data-testid="hidden-agents-probe"
			data-hidden={[...hiddenRosterAgents].join(",")}
		/>
	);
}

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

// ─── Fly-out animation ────────────────────────────────────────────────────────

describe("LozengeFlyProvider fly-out", () => {
	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("creates a fly-out clone in document.body when agent is removed", async () => {
		const withAgent = makePipeline({
			current: [
				{
					story_id: "74_fly_out_test",
					name: "Fly Out Test",
					error: null,
					merge_failure: null,
					agent: { agent_name: "coder-1", model: "haiku", status: "completed" },
					review_hold: null,
					qa: null,
					depends_on: null,
				},
			],
		});

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

		// Advance past initial fly-in animation to get a clean state
		await act(async () => {
			vi.advanceTimersByTime(600);
		});

		// Remove the agent from the pipeline
		const noAgent = makePipeline({
			current: [
				{
					story_id: "74_fly_out_test",
					name: "Fly Out Test",
					error: null,
					merge_failure: null,
					agent: null,
					review_hold: null,
					qa: null,
					depends_on: null,
				},
			],
		});

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

		// A fly-out clone should now be in document.body
		const clone = document.body.querySelector(
			'[data-testid^="flying-lozenge-fly-out"]',
		);
		expect(clone).not.toBeNull();
	});
});

// ─── Agent swap (name change) triggers both fly-out and fly-in ────────────

describe("LozengeFlyProvider agent swap (name change)", () => {
	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("detects agent name change as both fly-out (old) and fly-in (new)", async () => {
		const withCoder1 = makePipeline({
			current: [
				{
					story_id: "109_swap_test",
					name: "Swap Test",
					error: null,
					merge_failure: null,
					agent: { agent_name: "coder-1", model: "sonnet", status: "running" },
					review_hold: null,
					qa: null,
					depends_on: null,
				},
			],
		});
		const withCoder2 = makePipeline({
			current: [
				{
					story_id: "109_swap_test",
					name: "Swap Test",
					error: null,
					merge_failure: null,
					agent: { agent_name: "coder-2", model: "haiku", status: "running" },
					review_hold: null,
					qa: null,
					depends_on: null,
				},
			],
		});

		const { rerender } = render(
			<LozengeFlyProvider pipeline={withCoder1}>
				<RosterFixture agentName="coder-1" />
				<RosterFixture agentName="coder-2" />
				<HiddenAgentsProbe />
				<StagePanel title="Current" items={withCoder1.current} />
			</LozengeFlyProvider>,
		);

		// Advance past initial fly-in
		await act(async () => {
			vi.advanceTimersByTime(600);
		});

		// Swap agent: coder-1 → coder-2
		await act(async () => {
			rerender(
				<LozengeFlyProvider pipeline={withCoder2}>
					<RosterFixture agentName="coder-1" />
					<RosterFixture agentName="coder-2" />
					<HiddenAgentsProbe />
					<StagePanel title="Current" items={withCoder2.current} />
				</LozengeFlyProvider>,
			);
		});

		// A fly-out clone for coder-1 should appear (old agent leaves)
		const flyOut = document.body.querySelector(
			'[data-testid^="flying-lozenge-fly-out"]',
		);
		expect(flyOut).not.toBeNull();

		// A fly-in clone for coder-2 should appear (new agent arrives)
		const flyIn = document.body.querySelector(
			'[data-testid^="flying-lozenge-fly-in"]',
		);
		expect(flyIn).not.toBeNull();
	});
});

// ─── Fly-out without a roster element (null rosterRect fallback) ──────────

describe("LozengeFlyProvider fly-out without roster element", () => {
	beforeEach(() => {
		vi.useFakeTimers();
		Element.prototype.getBoundingClientRect = vi.fn().mockReturnValue({
			left: 200,
			top: 100,
			right: 280,
			bottom: 120,
			width: 80,
			height: 20,
			x: 200,
			y: 100,
			toJSON: () => ({}),
		});
		vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => {
			cb(0);
			return 0;
		});
	});

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

	it("fly-out still works when no roster element is registered (uses fallback coords)", async () => {
		const withAgent = makePipeline({
			current: [
				{
					story_id: "109_no_roster_flyout",
					name: "No Roster Flyout",
					error: null,
					merge_failure: null,
					agent: {
						agent_name: "orphan-agent",
						model: null,
						status: "completed",
					},
					review_hold: null,
					qa: null,
					depends_on: null,
				},
			],
		});
		const noAgent = makePipeline({
			current: [
				{
					story_id: "109_no_roster_flyout",
					name: "No Roster Flyout",
					error: null,
					merge_failure: null,
					agent: null,
					review_hold: null,
					qa: null,
					depends_on: null,
				},
			],
		});

		const { rerender } = render(
			<LozengeFlyProvider pipeline={withAgent}>
				{/* No RosterFixture for orphan-agent */}
				<StagePanel title="Current" items={withAgent.current} />
			</LozengeFlyProvider>,
		);

		await act(async () => {
			vi.advanceTimersByTime(600);
		});

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

		// Fly-out clone should still appear even without roster element
		const clone = document.body.querySelector(
			'[data-testid^="flying-lozenge-fly-out"]',
		);
		expect(clone).not.toBeNull();
	});
});

// ─── hiddenRosterAgents: fly-out keeps agent hidden until clone lands ─────

describe("hiddenRosterAgents: fly-out keeps agent hidden until clone lands", () => {
	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("agent stays hidden in roster during fly-out (0–499 ms)", async () => {
		const withAgent = makePipeline({
			current: [
				{
					story_id: "85_flyout_hidden",
					name: "Fly-out Hidden",
					error: null,
					merge_failure: null,
					agent: { agent_name: "coder-1", model: null, status: "completed" },
					review_hold: null,
					qa: null,
					depends_on: null,
				},
			],
		});
		const noAgent = makePipeline({
			current: [
				{
					story_id: "85_flyout_hidden",
					name: "Fly-out Hidden",
					error: null,
					merge_failure: null,
					agent: null,
					review_hold: null,
					qa: null,
					depends_on: null,
				},
			],
		});

		const { rerender } = render(
			<LozengeFlyProvider pipeline={withAgent}>
				<RosterFixture agentName="coder-1" />
				<HiddenAgentsProbe />
				<StagePanel title="Current" items={withAgent.current} />
			</LozengeFlyProvider>,
		);

		// Advance past the initial fly-in
		await act(async () => {
			vi.advanceTimersByTime(600);
		});

		// Remove agent — fly-out starts
		await act(async () => {
			rerender(
				<LozengeFlyProvider pipeline={noAgent}>
					<RosterFixture agentName="coder-1" />
					<HiddenAgentsProbe />
					<StagePanel title="Current" items={noAgent.current} />
				</LozengeFlyProvider>,
			);
		});

		// Agent should still be hidden (fly-out clone is in flight)
		const probe = screen.getByTestId("hidden-agents-probe");
		expect(probe.dataset.hidden).toContain("coder-1");
	});

	it("agent reappears in roster after fly-out clone lands (500 ms)", async () => {
		const withAgent = makePipeline({
			current: [
				{
					story_id: "85_flyout_reveal",
					name: "Fly-out Reveal",
					error: null,
					merge_failure: null,
					agent: { agent_name: "coder-1", model: null, status: "completed" },
					review_hold: null,
					qa: null,
					depends_on: null,
				},
			],
		});
		const noAgent = makePipeline({
			current: [
				{
					story_id: "85_flyout_reveal",
					name: "Fly-out Reveal",
					error: null,
					merge_failure: null,
					agent: null,
					review_hold: null,
					qa: null,
					depends_on: null,
				},
			],
		});

		const { rerender } = render(
			<LozengeFlyProvider pipeline={withAgent}>
				<RosterFixture agentName="coder-1" />
				<HiddenAgentsProbe />
				<StagePanel title="Current" items={withAgent.current} />
			</LozengeFlyProvider>,
		);

		await act(async () => {
			vi.advanceTimersByTime(600);
		});

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

		// Advance past fly-out animation
		await act(async () => {
			vi.advanceTimersByTime(600);
		});

		// Agent should now be visible in roster
		const probe = screen.getByTestId("hidden-agents-probe");
		expect(probe.dataset.hidden).toBe("");
	});
});
