/**
 * @jest-environment jsdom
 */
import React from "react";
import { renderHook } from "@testing-library/react";
import { CspNonceProvider, useCspNonce } from "@/hooks/useCspNonce";

describe("useCspNonce", () => {
  afterEach(() => {
    // Clean up any meta tags added during tests
    document
      .querySelectorAll('meta[name="csp-nonce"]')
      .forEach((el) => el.remove());
  });

  it("returns nonce from provider context", () => {
    const wrapper = ({ children }: { children: React.ReactNode }) => (
      <CspNonceProvider nonce="test-nonce-123">{children}</CspNonceProvider>
    );
    const { result } = renderHook(() => useCspNonce(), { wrapper });
    expect(result.current).toBe("test-nonce-123");
  });

  it("returns empty string when no provider and no meta tag", () => {
    const { result } = renderHook(() => useCspNonce());
    expect(result.current).toBe("");
  });

  it("does NOT read nonce from DOM meta tag (meta tag fallback is removed)", () => {
    // Inject a meta tag — the hook must NOT read it
    const meta = document.createElement("meta");
    meta.setAttribute("name", "csp-nonce");
    meta.setAttribute("content", "injected-nonce-should-not-be-read");
    document.head.appendChild(meta);

    const { result } = renderHook(() => useCspNonce());
    // Must return '' — not the meta tag value
    expect(result.current).toBe("");
    expect(result.current).not.toBe("injected-nonce-should-not-be-read");
  });

  it("CspNonceProvider does NOT read meta tag when nonce prop is empty", () => {
    const meta = document.createElement("meta");
    meta.setAttribute("name", "csp-nonce");
    meta.setAttribute("content", "should-not-leak");
    document.head.appendChild(meta);

    const wrapper = ({ children }: { children: React.ReactNode }) => (
      <CspNonceProvider nonce="">{children}</CspNonceProvider>
    );
    const { result } = renderHook(() => useCspNonce(), { wrapper });
    expect(result.current).toBe("");
    expect(result.current).not.toBe("should-not-leak");
  });
});
