import { render, screen, waitFor, fireEvent } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import GetStartedPage from "./page";

// ── Mocks ────────────────────────────────────────────────

const mockUseSearchParams = jest.fn();

jest.mock("next/navigation", () => ({
  useSearchParams: () => mockUseSearchParams(),
}));

jest.mock("next/link", () => {
  return function MockLink({ href, children, ...props }: { href: string; children: React.ReactNode; [key: string]: unknown }) {
    return <a href={href} {...props}>{children}</a>;
  };
});

const mockFetch = jest.fn();
global.fetch = mockFetch;

Object.assign(navigator, {
  clipboard: { writeText: jest.fn() },
});

function setSearchParams(params: Record<string, string | undefined> = {}) {
  mockUseSearchParams.mockReturnValue({
    get: (key: string) => params[key] ?? null,
  });
}

const verifiedDomain = {
  domain: "verified.example.com",
  verified: true,
  verification_token: "e2a-verify=abc123",
  dns_records: {
    mx: { host: "verified.example.com", value: "mx.e2a.dev", priority: 10 },
    txt: { host: "verified.example.com", value: "e2a-verify=abc123" },
  },
  created_at: "2026-01-01T00:00:00Z",
  verified_at: "2026-01-15T00:00:00Z",
};

/** Mock both listDomains and listAgents returning empty (fresh user). */
function mockFreshUser() {
  mockFetch.mockImplementation((url: string) => {
    if (url === "/api/v1/domains") {
      return Promise.resolve({ ok: true, json: () => Promise.resolve({ domains: [] }) });
    }
    if (url === "/api/dashboard/agents") {
      return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ agents: [] }) });
    }
    return Promise.resolve({ ok: false, text: () => Promise.resolve("not found") });
  });
}

beforeEach(() => {
  mockFetch.mockReset();
  setSearchParams();
});

function mockAgentCreation(email: string) {
  mockFetch.mockImplementation((url: string, init?: RequestInit) => {
    if (url === "/api/v1/domains") {
      return Promise.resolve({ ok: true, json: () => Promise.resolve({ domains: [] }) });
    }
    if (url === "/api/dashboard/agents" && !init?.method) {
      return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ agents: [] }) });
    }
    if (url === "/api/v1/agents" && init?.method === "POST") {
      return Promise.resolve({
        ok: true,
        status: 200,
        json: () => Promise.resolve({ id: "ag_test", domain: "agents.e2a.dev", email }),
      });
    }
    return Promise.resolve({ ok: false, text: () => Promise.resolve("not found") });
  });
}

function mockAgentCreationFailure(errorMessage: string) {
  mockFetch.mockImplementation((url: string, init?: RequestInit) => {
    if (url === "/api/v1/domains") {
      return Promise.resolve({ ok: true, json: () => Promise.resolve({ domains: [] }) });
    }
    if (url === "/api/dashboard/agents" && !init?.method) {
      return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ agents: [] }) });
    }
    if (url === "/api/v1/agents" && init?.method === "POST") {
      return Promise.resolve({
        ok: false,
        status: 400,
        text: () => Promise.resolve(errorMessage),
      });
    }
    return Promise.resolve({ ok: false, text: () => Promise.resolve("not found") });
  });
}

// ── Address type choice ──────────────────────────────────

describe("Address type choice", () => {
  it("renders Shared e2a domain and Custom domain options for fresh user", async () => {
    mockFreshUser();
    render(<GetStartedPage />);
    await waitFor(() => {
      expect(screen.getByText("Shared e2a domain")).toBeInTheDocument();
    });
    expect(screen.getByText("Custom domain")).toBeInTheDocument();
  });

  it("shows a neutral chooser on plain /get-started with no state", async () => {
    mockFreshUser();
    render(<GetStartedPage />);

    await waitFor(() => {
      expect(screen.getByRole("button", { name: /Shared e2a domain/i })).toHaveAttribute(
        "aria-pressed",
        "false",
      );
    });
    expect(screen.getByRole("button", { name: /Custom domain/i })).toHaveAttribute(
      "aria-pressed",
      "false",
    );
  });

  it("does NOT show Cloud Agents or Local Agents labels", async () => {
    mockFreshUser();
    render(<GetStartedPage />);
    await waitFor(() => {
      expect(screen.getByText("Shared e2a domain")).toBeInTheDocument();
    });
    expect(screen.queryByText("Cloud Agents")).not.toBeInTheDocument();
    expect(screen.queryByText("Local Agents")).not.toBeInTheDocument();
  });

  it("shows shared form when Shared e2a domain is clicked", async () => {
    mockFreshUser();
    render(<GetStartedPage />);

    await waitFor(() => {
      expect(screen.getByText("Shared e2a domain")).toBeInTheDocument();
    });
    fireEvent.click(screen.getByText("Shared e2a domain"));

    await waitFor(() => {
      expect(screen.getByText("Delivery mode")).toBeInTheDocument();
    });
    expect(screen.getByPlaceholderText("my-agent")).toBeInTheDocument();
  });

  it("shows custom domain checklist when Custom domain is clicked", async () => {
    mockFreshUser();
    render(<GetStartedPage />);

    await waitFor(() => {
      expect(screen.getByText("Custom domain")).toBeInTheDocument();
    });
    fireEvent.click(screen.getByText("Custom domain"));

    await waitFor(() => {
      expect(screen.getByText("Choose a domain")).toBeInTheDocument();
    });
  });
});

// ── Shared local flow ────────────────────────────────────

describe("Shared local flow", () => {
  it("creates a local agent and shows local success state", async () => {
    mockAgentCreation("my-bot@agents.e2a.dev");
    render(<GetStartedPage />);

    // Wait for bootstrap then choose shared
    await waitFor(() => { expect(screen.getByText("Shared e2a domain")).toBeInTheDocument(); });
    fireEvent.click(screen.getByText("Shared e2a domain"));
    await waitFor(() => {
      expect(screen.getByPlaceholderText("my-agent")).toBeInTheDocument();
    });

    // Local agent is selected by default
    expect(screen.getByText("Local agent")).toBeInTheDocument();

    // Enter slug
    await userEvent.type(screen.getByPlaceholderText("my-agent"), "my-bot");

    // Submit
    fireEvent.click(screen.getByText("Create agent"));

    // Verify API call
    await waitFor(() => {
      expect(mockFetch).toHaveBeenCalledWith(
        "/api/v1/agents",
        expect.objectContaining({
          method: "POST",
          body: JSON.stringify({ slug: "my-bot", agent_mode: "local" }),
        }),
      );
    });

    // Should show local success state
    await waitFor(() => {
      expect(screen.getByText("Agent registered!")).toBeInTheDocument();
    });
    expect(screen.getByText("Connect your agent")).toBeInTheDocument();
    expect(screen.getByText("Install the e2a skill")).toBeInTheDocument();
  });
});

// ── Shared cloud flow ────────────────────────────────────

describe("Shared cloud flow", () => {
  it("creates a cloud agent and shows cloud success state", async () => {
    mockAgentCreation("my-bot@agents.e2a.dev");
    render(<GetStartedPage />);

    // Wait for bootstrap then choose shared
    await waitFor(() => { expect(screen.getByText("Shared e2a domain")).toBeInTheDocument(); });
    fireEvent.click(screen.getByText("Shared e2a domain"));
    await waitFor(() => {
      expect(screen.getByText("Delivery mode")).toBeInTheDocument();
    });

    // Switch to cloud
    fireEvent.click(screen.getByText("Cloud agent"));

    // Webhook URL field should appear
    await waitFor(() => {
      expect(screen.getByPlaceholderText("https://your-agent.com/webhook")).toBeInTheDocument();
    });

    // Enter slug and webhook URL
    await userEvent.type(screen.getByPlaceholderText("my-agent"), "my-bot");
    await userEvent.type(
      screen.getByPlaceholderText("https://your-agent.com/webhook"),
      "https://example.com/hook",
    );

    // Submit
    fireEvent.click(screen.getByText("Create agent"));

    // Verify API call includes agent_mode: "cloud" and webhook_url
    await waitFor(() => {
      expect(mockFetch).toHaveBeenCalledWith(
        "/api/v1/agents",
        expect.objectContaining({
          method: "POST",
          body: JSON.stringify({
            slug: "my-bot",
            agent_mode: "cloud",
            webhook_url: "https://example.com/hook",
          }),
        }),
      );
    });

    // Should show cloud success state
    await waitFor(() => {
      expect(screen.getByText("Agent registered!")).toBeInTheDocument();
    });
    expect(screen.getByText("Connect your agent")).toBeInTheDocument();
    // Should show the configured webhook URL
    expect(screen.getByText("Webhook endpoint")).toBeInTheDocument();
    expect(screen.getByText("https://example.com/hook")).toBeInTheDocument();
    expect(screen.getByText("Install the e2a skill")).toBeInTheDocument();
  });
});

// ── Webhook validation ───────────────────────────────────

describe("Webhook validation for shared cloud", () => {
  it("shows inline error for invalid webhook URL", async () => {
    mockFreshUser();
    render(<GetStartedPage />);

    await waitFor(() => { expect(screen.getByText("Shared e2a domain")).toBeInTheDocument(); });
    fireEvent.click(screen.getByText("Shared e2a domain"));
    await waitFor(() => {
      expect(screen.getByText("Cloud agent")).toBeInTheDocument();
    });
    fireEvent.click(screen.getByText("Cloud agent"));

    await userEvent.type(screen.getByPlaceholderText("my-agent"), "my-bot");
    await userEvent.type(
      screen.getByPlaceholderText("https://your-agent.com/webhook"),
      "http://example.com/hook",
    );

    fireEvent.click(screen.getByText("Create agent"));

    await waitFor(() => {
      expect(screen.getByText("Webhook URL must be a valid HTTPS URL.")).toBeInTheDocument();
    });

    expect(mockFetch).not.toHaveBeenCalledWith("/api/v1/agents", expect.anything());
  });

  it("shows inline error for invalid slug", async () => {
    mockFreshUser();
    render(<GetStartedPage />);

    await waitFor(() => { expect(screen.getByText("Shared e2a domain")).toBeInTheDocument(); });
    fireEvent.click(screen.getByText("Shared e2a domain"));
    await waitFor(() => {
      expect(screen.getByPlaceholderText("my-agent")).toBeInTheDocument();
    });

    await userEvent.type(screen.getByPlaceholderText("my-agent"), "a");
    fireEvent.click(screen.getByText("Create agent"));

    await waitFor(() => {
      expect(screen.getByText(/Slug must be 2/)).toBeInTheDocument();
    });

    expect(mockFetch).not.toHaveBeenCalledWith("/api/v1/agents", expect.anything());
  });
});

// ── Slug/server error handling ───────────────────────────

describe("Slug/server error handling", () => {
  it("shows server error inline and keeps the slug field populated", async () => {
    mockAgentCreationFailure('slug "my-bot" is already taken');
    render(<GetStartedPage />);

    await waitFor(() => { expect(screen.getByText("Shared e2a domain")).toBeInTheDocument(); });
    fireEvent.click(screen.getByText("Shared e2a domain"));
    await waitFor(() => {
      expect(screen.getByPlaceholderText("my-agent")).toBeInTheDocument();
    });

    await userEvent.type(screen.getByPlaceholderText("my-agent"), "my-bot");
    fireEvent.click(screen.getByText("Create agent"));

    await waitFor(() => {
      expect(screen.getByText('slug "my-bot" is already taken')).toBeInTheDocument();
    });

    // Slug field should still have the value
    expect(screen.getByPlaceholderText("my-agent")).toHaveValue("my-bot");
    // Should still be on the form
    expect(screen.getByText("Create agent")).toBeInTheDocument();
  });
});

// ── Query param support ──────────────────────────────────

describe("Query param support", () => {
  it("?mode=shared renders the shared flow immediately", () => {
    setSearchParams({ mode: "shared" });
    render(<GetStartedPage />);

    // Should skip the address choice and show the shared form
    expect(screen.queryByText("Give your agent an email address")).not.toBeInTheDocument();
    expect(screen.getByText("Delivery mode")).toBeInTheDocument();
    expect(screen.getByPlaceholderText("my-agent")).toBeInTheDocument();
  });

  it("?domain= resumes at agent creation for a verified domain", async () => {
    setSearchParams({ domain: "verified.example.com" });
    mockFetch.mockImplementation((url: string) => {
      if (url === "/api/v1/domains") {
        return Promise.resolve({
          ok: true,
          json: () => Promise.resolve({ domains: [verifiedDomain] }),
        });
      }
      return Promise.resolve({ ok: false, text: () => Promise.resolve("not found") });
    });

    render(<GetStartedPage />);

    await waitFor(() => {
      expect(screen.getByText("Create your agent")).toBeInTheDocument();
    });
    expect(screen.getByText("@verified.example.com")).toBeInTheDocument();
    expect(screen.getByPlaceholderText("support")).toBeInTheDocument();
  });

  it("?domain= falls back to choose when domain is not owned", async () => {
    setSearchParams({ domain: "missing.example.com" });
    mockFetch.mockImplementation((url: string) => {
      if (url === "/api/v1/domains") {
        return Promise.resolve({
          ok: true,
          json: () => Promise.resolve({ domains: [] }),
        });
      }
      return Promise.resolve({ ok: false, text: () => Promise.resolve("not found") });
    });

    render(<GetStartedPage />);

    await waitFor(() => {
      expect(
        screen.getByText("Domain missing.example.com not found in your account"),
      ).toBeInTheDocument();
    });
    // Should show address choice, not register step
    expect(screen.getByText("Shared e2a domain")).toBeInTheDocument();
  });

  it("?domain= for unverified domain resumes at DNS+verify step", async () => {
    const unverifiedDomainFixture = {
      ...verifiedDomain,
      domain: "unverified.example.com",
      verified: false,
      verified_at: null,
    };
    setSearchParams({ domain: "unverified.example.com" });
    mockFetch.mockImplementation((url: string) => {
      if (url === "/api/v1/domains") {
        return Promise.resolve({
          ok: true,
          json: () => Promise.resolve({ domains: [unverifiedDomainFixture] }),
        });
      }
      return Promise.resolve({ ok: false, text: () => Promise.resolve("not found") });
    });

    render(<GetStartedPage />);

    // DNS and verify shown together for unverified domains
    await waitFor(() => {
      expect(screen.getByText("Configure DNS records")).toBeInTheDocument();
    });
    expect(screen.getByText("Route email to e2a")).toBeInTheDocument();
    expect(screen.getByText("Verify domain ownership")).toBeInTheDocument();
  });
});

// ── Custom-domain flow: new domain ───────────────────────

const unverifiedDomain = {
  domain: "mail.newco.com",
  verified: false,
  verification_token: "e2a-verify=new123",
  dns_records: {
    mx: { host: "mail.newco.com", value: "mx.e2a.dev", priority: 10 },
    txt: { host: "mail.newco.com", value: "e2a-verify=new123" },
  },
  created_at: "2026-03-01T00:00:00Z",
  verified_at: null,
};

function mockCustomDomainFlow() {
  let domainVerified = false;
  mockFetch.mockImplementation((url: string, init?: RequestInit) => {
    // listAgents — empty for bootstrap
    if (url === "/api/dashboard/agents" && !init?.method) {
      return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ agents: [] }) });
    }
    // listDomains — initially empty
    if (url === "/api/v1/domains" && (!init?.method || init.method === "GET")) {
      return Promise.resolve({
        ok: true,
        json: () => Promise.resolve({ domains: [] }),
      });
    }
    // registerDomain
    if (url === "/api/v1/domains" && init?.method === "POST") {
      return Promise.resolve({
        ok: true,
        json: () => Promise.resolve(unverifiedDomain),
      });
    }
    // verifyDomain
    if (url.includes("/verify") && init?.method === "POST") {
      domainVerified = true;
      return Promise.resolve({
        ok: true,
        json: () => Promise.resolve({ domain: "mail.newco.com", verified: true }),
      });
    }
    // createAgent
    if (url === "/api/v1/agents" && init?.method === "POST") {
      const body = JSON.parse(init.body as string);
      return Promise.resolve({
        ok: true,
        status: 200,
        json: () => Promise.resolve({
          id: "ag_custom",
          domain: "mail.newco.com",
          email: body.email,
        }),
      });
    }
    return Promise.resolve({ ok: false, text: () => Promise.resolve("not found") });
  });
  return { isDomainVerified: () => domainVerified };
}

describe("Custom-domain flow: new domain -> DNS -> verify -> local agent", () => {
  it("completes the full custom local flow", async () => {
    mockCustomDomainFlow();
    render(<GetStartedPage />);

    // Wait for bootstrap then choose custom domain
    await waitFor(() => { expect(screen.getByText("Custom domain")).toBeInTheDocument(); });
    fireEvent.click(screen.getByText("Custom domain"));

    // Wait for domain selector to load
    await waitFor(() => {
      expect(screen.getByText("Choose a domain")).toBeInTheDocument();
    });

    // Register new domain
    await userEvent.type(screen.getByPlaceholderText("mail.yourcompany.com"), "mail.newco.com");
    fireEvent.click(screen.getByText("Register domain"));

    // Should show DNS records and verify together
    await waitFor(() => {
      expect(screen.getByText("Configure DNS records")).toBeInTheDocument();
    });
    expect(screen.getByText("Route email to e2a")).toBeInTheDocument();
    expect(screen.getByText("Verify domain ownership")).toBeInTheDocument();

    // Verify domain
    fireEvent.click(screen.getByText("Verify domain"));

    // Should show agent creation with mode choice
    await waitFor(() => {
      expect(screen.getByText("Create your agent")).toBeInTheDocument();
    });
    expect(screen.getByText("Delivery mode")).toBeInTheDocument();
    expect(screen.getByText("Local agent")).toBeInTheDocument();
    expect(screen.getByText("Cloud agent")).toBeInTheDocument();

    // Local is default — enter local part and submit
    await userEvent.type(screen.getByPlaceholderText("support"), "hello");
    fireEvent.click(screen.getByText("Create agent"));

    // Should show local success
    await waitFor(() => {
      expect(screen.getByText("Agent registered!")).toBeInTheDocument();
    });
    expect(screen.getByText("Connect your agent")).toBeInTheDocument();
  });
});

describe("Custom-domain flow: new domain -> DNS -> verify -> cloud agent", () => {
  it("completes the full custom cloud flow", async () => {
    mockCustomDomainFlow();
    render(<GetStartedPage />);

    // Wait for bootstrap then choose custom domain
    await waitFor(() => { expect(screen.getByText("Custom domain")).toBeInTheDocument(); });
    fireEvent.click(screen.getByText("Custom domain"));
    await waitFor(() => {
      expect(screen.getByText("Choose a domain")).toBeInTheDocument();
    });

    // Register, DNS+verify shown together
    await userEvent.type(screen.getByPlaceholderText("mail.yourcompany.com"), "mail.newco.com");
    fireEvent.click(screen.getByText("Register domain"));
    await waitFor(() => {
      expect(screen.getByText("Configure DNS records")).toBeInTheDocument();
      expect(screen.getByText("Verify domain ownership")).toBeInTheDocument();
    });
    fireEvent.click(screen.getByText("Verify domain"));

    // Should show agent creation
    await waitFor(() => {
      expect(screen.getByText("Create your agent")).toBeInTheDocument();
    });

    // Switch to cloud
    fireEvent.click(screen.getByText("Cloud agent"));

    // Webhook field should appear
    await waitFor(() => {
      expect(screen.getByPlaceholderText("https://your-agent.com/webhook")).toBeInTheDocument();
    });

    // Enter local part and webhook
    await userEvent.type(screen.getByPlaceholderText("support"), "hello");
    await userEvent.type(
      screen.getByPlaceholderText("https://your-agent.com/webhook"),
      "https://hook.newco.com/inbox",
    );
    fireEvent.click(screen.getByText("Create agent"));

    // Should show cloud success
    await waitFor(() => {
      expect(screen.getByText("Agent registered!")).toBeInTheDocument();
    });
    expect(screen.getByText("Connect your agent")).toBeInTheDocument();
    expect(screen.getByText("https://hook.newco.com/inbox")).toBeInTheDocument();
  });
});

describe("Custom-domain flow: existing verified domain -> create agent directly", () => {
  it("skips DNS/verify for already-verified domains", async () => {
    setSearchParams({ domain: "verified.example.com" });
    mockFetch.mockImplementation((url: string, init?: RequestInit) => {
      if (url === "/api/v1/domains") {
        return Promise.resolve({
          ok: true,
          json: () => Promise.resolve({ domains: [verifiedDomain] }),
        });
      }
      if (url === "/api/v1/agents" && init?.method === "POST") {
        return Promise.resolve({
          ok: true,
          status: 200,
          json: () => Promise.resolve({
            id: "ag_v",
            domain: "verified.example.com",
            email: "bot@verified.example.com",
          }),
        });
      }
      return Promise.resolve({ ok: false, text: () => Promise.resolve("not found") });
    });

    render(<GetStartedPage />);

    // Should jump straight to agent creation
    await waitFor(() => {
      expect(screen.getByText("Create your agent")).toBeInTheDocument();
    });
    expect(screen.getByText("Delivery mode")).toBeInTheDocument();

    // Create agent
    await userEvent.type(screen.getByPlaceholderText("support"), "bot");
    fireEvent.click(screen.getByText("Create agent"));

    await waitFor(() => {
      expect(screen.getByText("Agent registered!")).toBeInTheDocument();
    });
  });
});

describe("Custom-domain flow: existing unverified domain -> resume verify", () => {
  it("resumes at DNS+verify for unverified domain via query param", async () => {
    const unverified = {
      ...verifiedDomain,
      domain: "pending.example.com",
      verified: false,
      verified_at: null,
    };
    setSearchParams({ domain: "pending.example.com" });
    mockFetch.mockImplementation((url: string, init?: RequestInit) => {
      if (url === "/api/v1/domains") {
        return Promise.resolve({
          ok: true,
          json: () => Promise.resolve({ domains: [unverified] }),
        });
      }
      if (url.includes("/verify") && init?.method === "POST") {
        return Promise.resolve({
          ok: true,
          json: () => Promise.resolve({ domain: "pending.example.com", verified: true }),
        });
      }
      return Promise.resolve({ ok: false, text: () => Promise.resolve("not found") });
    });

    render(<GetStartedPage />);

    // DNS and verify shown together
    await waitFor(() => {
      expect(screen.getByText("Configure DNS records")).toBeInTheDocument();
      expect(screen.getByText("Verify domain ownership")).toBeInTheDocument();
    });

    // Verify
    fireEvent.click(screen.getByText("Verify domain"));

    // Should advance to agent creation
    await waitFor(() => {
      expect(screen.getByText("Create your agent")).toBeInTheDocument();
    });
    expect(screen.getByText("Delivery mode")).toBeInTheDocument();
  });
});

describe("Custom-domain flow: verification retry", () => {
  it("shows error and allows retry on verification failure", async () => {
    mockFetch.mockImplementation((url: string, init?: RequestInit) => {
      if (url === "/api/dashboard/agents" && !init?.method) {
        return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ agents: [] }) });
      }
      if (url === "/api/v1/domains" && (!init?.method || init.method === "GET")) {
        return Promise.resolve({
          ok: true,
          json: () => Promise.resolve({ domains: [] }),
        });
      }
      if (url === "/api/v1/domains" && init?.method === "POST") {
        return Promise.resolve({
          ok: true,
          json: () => Promise.resolve(unverifiedDomain),
        });
      }
      if (url.includes("/verify") && init?.method === "POST") {
        return Promise.resolve({
          ok: false,
          status: 400,
          text: () => Promise.resolve("TXT record not found"),
        });
      }
      return Promise.resolve({ ok: false, text: () => Promise.resolve("not found") });
    });

    render(<GetStartedPage />);

    // Wait for bootstrap, then custom -> register -> DNS+verify shown together
    await waitFor(() => { expect(screen.getByText("Custom domain")).toBeInTheDocument(); });
    fireEvent.click(screen.getByText("Custom domain"));
    await waitFor(() => { expect(screen.getByText("Choose a domain")).toBeInTheDocument(); });
    await userEvent.type(screen.getByPlaceholderText("mail.yourcompany.com"), "mail.newco.com");
    fireEvent.click(screen.getByText("Register domain"));
    await waitFor(() => {
      expect(screen.getByText("Configure DNS records")).toBeInTheDocument();
      expect(screen.getByText("Verify domain ownership")).toBeInTheDocument();
    });

    // Attempt verify — should fail
    fireEvent.click(screen.getByText("Verify domain"));

    await waitFor(() => {
      expect(screen.getByText("TXT record not found")).toBeInTheDocument();
    });

    // Should still be on verify step with retry available
    expect(screen.getByText("Verify domain")).toBeInTheDocument();
    expect(screen.getAllByText(/DNS changes can take a few minutes/).length).toBeGreaterThan(0);
  });
});

// ── Smart re-entry / resume ─────────────────────────────

describe("Plain /get-started always shows address choice", () => {
  it("shows address choice even when user has existing agents", async () => {
    mockFetch.mockImplementation((url: string, init?: RequestInit) => {
      if (url === "/api/v1/domains") {
        return Promise.resolve({ ok: true, json: () => Promise.resolve({ domains: [] }) });
      }
      if (url === "/api/dashboard/agents" && !init?.method) {
        return Promise.resolve({
          ok: true,
          status: 200,
          json: () => Promise.resolve({
            agents: [{
              id: "ag_1", domain: "agents.e2a.dev", email: "bot@agents.e2a.dev",
              name: "bot", webhook_url: "", agent_mode: "local",
              domain_verified: true, public: false, created_at: "2026-01-01T00:00:00Z",
            }],
          }),
        });
      }
      return Promise.resolve({ ok: false, text: () => Promise.resolve("not found") });
    });

    render(<GetStartedPage />);

    await waitFor(() => {
      expect(screen.getByText("Shared e2a domain")).toBeInTheDocument();
      expect(screen.getByText("Custom domain")).toBeInTheDocument();
    });
  });

  it("shows address choice even with unverified domains", async () => {
    const unverified = {
      ...verifiedDomain,
      domain: "pending.co",
      verified: false,
      verified_at: null,
    };
    mockFetch.mockImplementation((url: string, init?: RequestInit) => {
      if (url === "/api/v1/domains") {
        return Promise.resolve({ ok: true, json: () => Promise.resolve({ domains: [unverified] }) });
      }
      if (url === "/api/dashboard/agents" && !init?.method) {
        return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ agents: [] }) });
      }
      return Promise.resolve({ ok: false, text: () => Promise.resolve("not found") });
    });

    render(<GetStartedPage />);

    await waitFor(() => {
      expect(screen.getByText("Shared e2a domain")).toBeInTheDocument();
      expect(screen.getByText("Custom domain")).toBeInTheDocument();
    });
  });

  it("shows address choice even with verified domain and no agents", async () => {
    mockFetch.mockImplementation((url: string, init?: RequestInit) => {
      if (url === "/api/v1/domains") {
        return Promise.resolve({ ok: true, json: () => Promise.resolve({ domains: [verifiedDomain] }) });
      }
      if (url === "/api/dashboard/agents" && !init?.method) {
        return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ agents: [] }) });
      }
      return Promise.resolve({ ok: false, text: () => Promise.resolve("not found") });
    });

    render(<GetStartedPage />);

    await waitFor(() => {
      expect(screen.getByText("Shared e2a domain")).toBeInTheDocument();
      expect(screen.getByText("Custom domain")).toBeInTheDocument();
    });
  });
});
