import "@testing-library/jest-dom"

class ResizeObserverStub {
    observe(): void {}
    unobserve(): void {}
    disconnect(): void {}
}

globalThis.ResizeObserver = globalThis.ResizeObserver ?? ResizeObserverStub

// cmdk / Radix Command calls scrollIntoView (not implemented in jsdom)
globalThis.HTMLElement.prototype.scrollIntoView ??= function scrollIntoView() {}

// Mock Radix Portals to render inline for stable tests (forwardRef satisfies Radix Presence/ref)
jest.mock("@radix-ui/react-portal", () => {
    const React = require("react")
    const Portal = React.forwardRef(({ children }: { children?: React.ReactNode }, _ref: unknown) =>
        React.createElement(React.Fragment, null, children)
    )
    Portal.displayName = "Portal"
    return { Portal }
})

// Mock sonner to prevent hanging timers
jest.mock("sonner", () => ({
    toast: {
        success: jest.fn(),
        error: jest.fn(),
        info: jest.fn(),
        warning: jest.fn(),
    },
}))

// Mock import.meta for Jest
// @ts-ignore
global.importMeta = {
    env: {
        VITE_API_URL: "http://localhost:5000/api",
    },
}

// Increase global timeout for JSDOM performance
jest.setTimeout(60000)

// Global Feature Mocks
// Note: We use the root-level setup requested by the user to ensure 
// all feature modules have access to stable mocks by default.
jest.mock("@/services/onboarding.service", () => ({ 
  onboardingService: require("./testing/mocks").mockOnboardingService 
}))
jest.mock("@/services/collaboration.service", () => ({ 
  collaborationService: require("./testing/mocks").mockCollaborationService 
}))
jest.mock("@/services/worknote.service", () => ({ 
  worknoteService: require("./testing/mocks").mockCollaborationService 
}))
jest.mock("@/services/eor.service", () => ({ 
  eorService: require("./testing/mocks").mockEORService 
}))
jest.mock("@/services/admin.service", () => ({ 
  adminService: require("./testing/mocks").mockAdminService 
}))
jest.mock("@/services/audit.service", () => ({
    auditService: {
        getAuditLogs: jest.fn().mockResolvedValue([]),
        createAuditLog: jest.fn().mockResolvedValue(undefined),
    },
}))
jest.mock("@/api/API", () => {
    const mocks = require("./testing/mocks")
    /** Apisauce-like shape: body is JSON under `data` */
    const fddPayload = () =>
        mocks.createGlobalMockApplication({
            overallStatus: "FDD Verification",
            currentStage: "FDD_VERIFICATION",
            fddAssignments: [{ id: "fdd-asg-test" }],
        })
    return {
        API: {
            getApplicationById: jest.fn().mockResolvedValue({
                ok: true,
                data: { success: true, data: fddPayload() },
            }),
            getFddAssignment: jest.fn().mockResolvedValue({
                ok: true,
                data: {
                    success: true,
                    data: { id: "fdd-asg-test", status: "Assigned" },
                },
            }),
            uploadDocument: jest.fn().mockResolvedValue({
                ok: true,
                data: { success: true, data: { id: "mock-doc-id" } },
            }),
            submitFddReport: jest.fn().mockResolvedValue({
                ok: true,
                data: { success: true },
            }),
            flagNonResponsive: jest.fn().mockResolvedValue({
                ok: true,
                data: { success: true },
            }),
        },
    }
})

/**
 * Keeps Jest output readable: React dev warnings that are environmental (jsdom,
 * Router opt-in flags, imperfect component trees under test) are not actionable
 * as test failures. Opt out: JEST_VERBOSE_CONSOLE=1
 */
function formatConsoleArgs(args: unknown[]): string {
    return args
        .map((a) => {
            if (typeof a === "string") return a
            if (a instanceof Error) return a.message
            try {
                return String(a)
            } catch {
                return ""
            }
        })
        .join(" ")
}

function shouldSilenceKnownDevNoise(message: string): boolean {
    if (process.env.JEST_VERBOSE_CONSOLE === "1") return false
    return (
        message.includes("React Router Future Flag Warning") ||
        message.includes("validateDOMNesting") ||
        message.includes("cannot appear as a descendant of") ||
        message.includes("Function components cannot be given refs")
    )
}

const _origError = console.error.bind(console)
const _origWarn = console.warn.bind(console)

console.error = (...args: unknown[]) => {
    if (shouldSilenceKnownDevNoise(formatConsoleArgs(args))) return
    _origError(...args)
}

console.warn = (...args: unknown[]) => {
    if (shouldSilenceKnownDevNoise(formatConsoleArgs(args))) return
    _origWarn(...args)
}
