import { describe, expect, it, vi } from "vitest";
import { handleCashOfferClick, isCashOfferTrigger, openCashOfferDialog } from "../client/src/lib/cashOfferTrigger";

describe("isCashOfferTrigger", () => {
  it("opens the shared dialog for every supported offer link and labelled call to action", () => {
    expect(isCashOfferTrigger({ href: "/#offer-form" })).toBe(true);
    expect(isCashOfferTrigger({ href: "/#cash-offer-form" })).toBe(true);
    expect(isCashOfferTrigger({ text: "Get My Cash Offer" })).toBe(true);
    expect(isCashOfferTrigger({ text: "Start My Cash Offer" })).toBe(true);
    expect(isCashOfferTrigger({ text: "Request Cash Offer" })).toBe(true);
  });

  it("does not hijack the dialog's own final submit action", () => {
    expect(isCashOfferTrigger({ text: "Get My Free Cash Offer", isDialogSubmit: true })).toBe(false);
  });

  it("opens an explicit county-page dialog trigger without navigating away from the location page", () => {
    const event = { preventDefault: vi.fn() };
    const openOffer = vi.fn();

    handleCashOfferClick(event, openOffer);

    expect(event.preventDefault).toHaveBeenCalledOnce();
    expect(openOffer).toHaveBeenCalledOnce();
  });

  it("dispatches the one shared offer event used by homepage controls", () => {
    const dispatchEvent = vi.fn();
    const originalWindow = globalThis.window;
    Object.defineProperty(globalThis, "window", {
      configurable: true,
      value: { dispatchEvent },
    });

    try {
      openCashOfferDialog();
      expect(dispatchEvent).toHaveBeenCalledOnce();
      expect(dispatchEvent.mock.calls[0][0].type).toBe("open-cash-offer");
    } finally {
      Object.defineProperty(globalThis, "window", {
        configurable: true,
        value: originalWindow,
      });
    }
  });
});
