/**
 * Isolated test file for the error-re-throw path in useOptionalConsent.
 * Uses vi.mock to make useConsent throw a non-ConsentContextError so that
 * lines 52-53 (the `throw e` branch) are exercised.
 */
import { describe, it, expect, vi } from "vitest";
import { Component, type ReactNode } from "react";
import { render, screen } from "@testing-library/react";

vi.mock("@repo/core-consent/react", () => ({
  useConsent: vi.fn(() => {
    throw new Error("unexpected-non-consent-error");
  }),
  ConsentContextError: class ConsentContextError extends Error {
    constructor() {
      super("no provider");
      this.name = "ConsentContextError";
    }
  },
}));

import { CookieConsentBanner } from "./cookie-consent-banner";

class ErrorBoundary extends Component<
  { children: ReactNode },
  { caught: string | null }
> {
  constructor(props: { children: ReactNode }) {
    super(props);
    this.state = { caught: null };
  }

  static getDerivedStateFromError(error: Error) {
    return { caught: error.message };
  }

  render() {
    if (this.state.caught) {
      return <div data-testid="caught">{this.state.caught}</div>;
    }
    return this.props.children;
  }
}

describe("CookieConsentBanner — useOptionalConsent rethrows non-ConsentContextError", () => {
  it("surfaces unexpected render errors through an error boundary", () => {
    const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});

    render(
      <ErrorBoundary>
        <CookieConsentBanner variant="modal" />
      </ErrorBoundary>,
    );

    expect(screen.getByTestId("caught")).toHaveTextContent(
      "unexpected-non-consent-error",
    );

    consoleSpy.mockRestore();
  });
});
