/**
 * Regional context + component integration tests.
 *
 * Demonstrates how to test components that use the useRegional() hook.
 * Key pattern: wrap in <RegionalProvider registry={mockRegistry}> —
 * no build alias, no DAAS_REGION env var, no rsbuild config needed.
 *
 * Run with: daas test
 */
import { describe, test, expect, vi } from "vitest"
import { useState } from "react"
import type { ReactNode } from "react"
import { render, screen, fireEvent } from "@chrisluyi/daas-cli/test"
// Direct sub-module imports are intentional here — this test file lives inside
// src/regional/ itself, so it cannot import from the barrel ("../../regional")
// without a circular reference. In component files outside src/regional/, use
// the barrel: import { useRegional, FeatureGate } from "../../regional"
import { RegionalProvider, useRegional } from "./context"
import { useRegionalFeature } from "./useRegionalFeature"
import { withRegionalConfig } from "./withRegionalConfig"
import { FeatureGate } from "./FeatureGate"
import { ErrorBoundary } from "../components/ErrorBoundary"
import { ExplicitPricingWidget } from "../components/ui/PricingWidget"
import type { RegionalRegistry, RegionConfig } from "./types"

// ── Mock registry helpers ────────────────────────────────────────────────────

function makeMockConfig(overrides?: Partial<RegionConfig>): RegionConfig {
  return {
    id: "test",
    locale: "en-US",
    currency: "USD",
    dateFormat: "MM/DD/YYYY",
    numberFormat: { decimal: ".", thousands: "," },
    features: {
      showDetailsTab: true,
      showAnalyticsTab: true,
      enableExport: true,
    },
    ...overrides,
  }
}

function makeMockRegistry(overrides?: Partial<RegionalRegistry>): RegionalRegistry {
  return {
    config: makeMockConfig(),
    components: {
      PricingWidget: ({ amount }) => <span data-testid="pricing">${amount}</span>,
    },
    logic: {
      formatAmount: (n) => `$${n}`,
      validateAmount: (n) => n > 0,
    },
    addons: {
      wrappers: [],
    },
    ...overrides,
  }
}

// ── Provider + hook tests ────────────────────────────────────────────────────

describe("RegionalProvider + useRegional", () => {
  test("provides registry to child components via hook", () => {
    const registry = makeMockRegistry()

    function TestConsumer() {
      const { config } = useRegional()
      return <div data-testid="locale">{config.locale}</div>
    }

    render(
      <RegionalProvider registry={registry}>
        <TestConsumer />
      </RegionalProvider>
    )

    expect(screen.getByTestId("locale")).toHaveTextContent("en-US")
  })

  test("throws when useRegional is called outside provider", () => {
    function BadConsumer() {
      useRegional()
      return null
    }

    // Suppress React error boundary console output in tests
    const spy = vi.spyOn(console, "error").mockImplementation(() => {})
    expect(() => render(<BadConsumer />)).toThrow("useRegional must be used within <RegionalProvider>")
    spy.mockRestore()
  })

  test("logic.formatAmount from registry is called correctly", () => {
    const formatAmount = vi.fn((n: number) => `SGD ${n}`)
    const registry = makeMockRegistry({
      logic: { formatAmount, validateAmount: (n) => n > 0 },
    })

    function PriceDisplay() {
      const { logic } = useRegional()
      return <span>{logic.formatAmount(99.99)}</span>
    }

    render(
      <RegionalProvider registry={registry}>
        <PriceDisplay />
      </RegionalProvider>
    )

    expect(formatAmount).toHaveBeenCalledWith(99.99)
    expect(screen.getByText("SGD 99.99")).toBeInTheDocument()
  })
})

// ── PricingWidget slot pattern test ─────────────────────────────────────────

describe("PricingWidget slot via registry", () => {
  test("renders the registry's PricingWidget component", () => {
    const registry = makeMockRegistry()

    function TabContent() {
      const { components } = useRegional()
      const { PricingWidget } = components
      return <PricingWidget amount={49.95} />
    }

    render(
      <RegionalProvider registry={registry}>
        <TabContent />
      </RegionalProvider>
    )

    expect(screen.getByTestId("pricing")).toHaveTextContent("$49.95")
  })

  test("UK registry renders UK-specific PricingWidget", () => {
    const ukRegistry = makeMockRegistry({
      components: {
        PricingWidget: ({ amount }) => (
          <span data-testid="pricing">
            £{amount} <em>inc. VAT</em>
          </span>
        ),
      },
    })

    function TabContent() {
      const { components } = useRegional()
      const { PricingWidget } = components
      return <PricingWidget amount={49.95} />
    }

    render(
      <RegionalProvider registry={ukRegistry}>
        <TabContent />
      </RegionalProvider>
    )

    expect(screen.getByTestId("pricing")).toHaveTextContent("£49.95")
    expect(screen.getByText("inc. VAT")).toBeInTheDocument()
  })
})

// ── Feature flag tests ────────────────────────────────────────────────────────

describe("feature flags via registry config", () => {
  test("showDetailsTab false hides a conditional section", () => {
    const ukRegistry = makeMockRegistry({
      config: makeMockConfig({ features: { showDetailsTab: false, showAnalyticsTab: false, enableExport: false } }),
    })

    function FeatureGatedSection() {
      const { config } = useRegional()
      return config.features.showDetailsTab ? (
        <div data-testid="details">Details section</div>
      ) : null
    }

    render(
      <RegionalProvider registry={ukRegistry}>
        <FeatureGatedSection />
      </RegionalProvider>
    )

    expect(screen.queryByTestId("details")).not.toBeInTheDocument()
  })
})

// ── withRegionalConfig HOC tests (Pattern 2) ────────────────────────────────

describe("withRegionalConfig HOC", () => {
  test("sets displayName for React DevTools", () => {
    function PriceLabel({ registry }: { registry: RegionalRegistry }) {
      return <span>{registry.config.currency}</span>
    }
    const Wrapped = withRegionalConfig(PriceLabel)
    // DevTools will show "withRegionalConfig(PriceLabel)" in the component tree
    expect(Wrapped.displayName).toBe("withRegionalConfig(PriceLabel)")
  })

  test("injects registry as a prop into the wrapped component", () => {
    // Base component expects registry as a prop (Pattern 2)
    function PriceLabel({
      amount,
      registry,
    }: {
      amount: number
      registry: RegionalRegistry
    }) {
      return <span data-testid="price">{registry.logic.formatAmount(amount)}</span>
    }

    // HOC strips registry from the external interface — callers don't pass it
    const WrappedPriceLabel = withRegionalConfig(PriceLabel)
    const registry = makeMockRegistry()

    render(
      <RegionalProvider registry={registry}>
        <WrappedPriceLabel amount={42} />
      </RegionalProvider>
    )

    expect(screen.getByTestId("price")).toHaveTextContent("$42")
  })

  test("wrapped component re-renders when registry changes", () => {
    function CurrencyDisplay({ registry }: { registry: RegionalRegistry }) {
      return <span data-testid="currency">{registry.config.currency}</span>
    }
    const WrappedCurrencyDisplay = withRegionalConfig(CurrencyDisplay)

    const usdRegistry = makeMockRegistry()
    const gbpRegistry = makeMockRegistry({
      config: makeMockConfig({ currency: "GBP" }),
    })

    function Switcher() {
      const [useGbp, setUseGbp] = useState(false)
      const reg = useGbp ? gbpRegistry : usdRegistry
      return (
        <RegionalProvider registry={reg}>
          <WrappedCurrencyDisplay />
          <button type="button" onClick={() => setUseGbp(true)}>Switch</button>
        </RegionalProvider>
      )
    }

    render(<Switcher />)
    expect(screen.getByTestId("currency")).toHaveTextContent("USD")
    fireEvent.click(screen.getByText("Switch"))
    expect(screen.getByTestId("currency")).toHaveTextContent("GBP")
  })
})

// ── Add-on wrapper tests ──────────────────────────────────────────────────────

describe("add-on wrappers", () => {
  test("wrappers are applied outermost-first via reduceRight", () => {
    const OuterBanner = ({ children }: { children: ReactNode }) => (
      <div>
        <div data-testid="outer-banner">Outer</div>
        {children}
      </div>
    )

    const InnerBanner = ({ children }: { children: ReactNode }) => (
      <div>
        <div data-testid="inner-banner">Inner</div>
        {children}
      </div>
    )

    // reduceRight: wrappers[0] (Outer) is the outermost wrapper
    // DOM order: outer-banner → inner-banner → content
    const ukRegistry = makeMockRegistry({
      addons: { wrappers: [OuterBanner, InnerBanner] },
    })

    function AppWithWrappers() {
      const { addons } = useRegional()
      const content = <div data-testid="content">App Content</div>
      return addons.wrappers.reduceRight(
        (children, Wrapper) => <Wrapper>{children}</Wrapper>,
        content
      )
    }

    render(
      <RegionalProvider registry={ukRegistry}>
        <AppWithWrappers />
      </RegionalProvider>
    )

    expect(screen.getByTestId("outer-banner")).toBeInTheDocument()
    expect(screen.getByTestId("inner-banner")).toBeInTheDocument()
    expect(screen.getByTestId("content")).toBeInTheDocument()

    // Verify DOM order: outer appears before inner (outermost rendered first)
    const outer = screen.getByTestId("outer-banner")
    const inner = screen.getByTestId("inner-banner")
    expect(outer.compareDocumentPosition(inner)).toBe(Node.DOCUMENT_POSITION_FOLLOWING)
  })

  test("empty wrappers array renders content directly", () => {
    const registry = makeMockRegistry({ addons: { wrappers: [] } })

    function AppWithWrappers() {
      const { addons } = useRegional()
      const content = <div data-testid="content">App Content</div>
      return addons.wrappers.reduceRight(
        (children, Wrapper) => <Wrapper>{children}</Wrapper>,
        content
      )
    }

    render(
      <RegionalProvider registry={registry}>
        <AppWithWrappers />
      </RegionalProvider>
    )

    expect(screen.getByTestId("content")).toBeInTheDocument()
  })
})

// ── FeatureGate tests ─────────────────────────────────────────────────────────

describe("FeatureGate", () => {
  test("renders children when feature is enabled", () => {
    const registry = makeMockRegistry({
      config: makeMockConfig({ features: { showDetailsTab: true, showAnalyticsTab: true, enableExport: true } }),
    })

    render(
      <RegionalProvider registry={registry}>
        <FeatureGate feature="enableExport">
          <span data-testid="export-btn">Export</span>
        </FeatureGate>
      </RegionalProvider>
    )

    expect(screen.getByTestId("export-btn")).toBeInTheDocument()
  })

  test("renders nothing when feature is disabled (no fallback)", () => {
    const registry = makeMockRegistry({
      config: makeMockConfig({ features: { showDetailsTab: false, showAnalyticsTab: false, enableExport: false } }),
    })

    render(
      <RegionalProvider registry={registry}>
        <FeatureGate feature="enableExport">
          <span data-testid="export-btn">Export</span>
        </FeatureGate>
      </RegionalProvider>
    )

    expect(screen.queryByTestId("export-btn")).not.toBeInTheDocument()
  })

  test("renders fallback when feature is disabled", () => {
    const registry = makeMockRegistry({
      config: makeMockConfig({ features: { showDetailsTab: false, showAnalyticsTab: false, enableExport: false } }),
    })

    render(
      <RegionalProvider registry={registry}>
        <FeatureGate feature="enableExport" fallback={<span data-testid="unavailable">Not available</span>}>
          <span data-testid="export-btn">Export</span>
        </FeatureGate>
      </RegionalProvider>
    )

    expect(screen.queryByTestId("export-btn")).not.toBeInTheDocument()
    expect(screen.getByTestId("unavailable")).toBeInTheDocument()
  })
})

// ── ErrorBoundary tests ───────────────────────────────────────────────────────

describe("ErrorBoundary", () => {
  test("renders children when no error is thrown", () => {
    render(
      <ErrorBoundary>
        <span data-testid="child">Hello</span>
      </ErrorBoundary>
    )
    expect(screen.getByTestId("child")).toBeInTheDocument()
  })

  test("renders default fallback when a child throws", () => {
    function Bomb() {
      throw new Error("test error")
    }

    // Suppress React's error boundary console output
    const spy = vi.spyOn(console, "error").mockImplementation(() => {})
    render(
      <ErrorBoundary>
        <Bomb />
      </ErrorBoundary>
    )
    spy.mockRestore()

    expect(screen.getByText("Something went wrong loading this view.")).toBeInTheDocument()
  })

  test("renders custom fallback when provided and a child throws", () => {
    function Bomb() {
      throw new Error("boom")
    }

    const spy = vi.spyOn(console, "error").mockImplementation(() => {})
    render(
      <ErrorBoundary fallback={(err) => <div data-testid="custom-fallback">{err.message}</div>}>
        <Bomb />
      </ErrorBoundary>
    )
    spy.mockRestore()

    expect(screen.getByTestId("custom-fallback")).toHaveTextContent("boom")
  })

  test("renders children normally when a RegionalProvider is present — ErrorBoundary is region-agnostic", () => {
    // ErrorBoundary is in src/components/, not src/regional/ — it has no
    // regional context dependency. This test confirms that having a RegionalProvider
    // present does NOT interfere with ErrorBoundary rendering its children normally.
    const registry = makeMockRegistry()
    render(
      <RegionalProvider registry={registry}>
        <ErrorBoundary>
          <span data-testid="inside-provider">works inside provider</span>
        </ErrorBoundary>
      </RegionalProvider>
    )
    expect(screen.getByTestId("inside-provider")).toBeInTheDocument()
  })
})

// ── useRegionalFeature hook tests ─────────────────────────────────────────────

describe("useRegionalFeature", () => {
  test("returns true for an enabled feature", () => {
    const registry = makeMockRegistry({
      config: makeMockConfig({ features: { showDetailsTab: true, showAnalyticsTab: true, enableExport: true } }),
    })

    function ExportFlag() {
      const isExportEnabled = useRegionalFeature("enableExport")
      return <span data-testid="flag">{String(isExportEnabled)}</span>
    }

    render(
      <RegionalProvider registry={registry}>
        <ExportFlag />
      </RegionalProvider>
    )

    expect(screen.getByTestId("flag")).toHaveTextContent("true")
  })

  test("returns false for a disabled feature", () => {
    const registry = makeMockRegistry({
      config: makeMockConfig({ features: { showDetailsTab: false, showAnalyticsTab: false, enableExport: false } }),
    })

    function ExportFlag() {
      const isExportEnabled = useRegionalFeature("enableExport")
      return <span data-testid="flag">{String(isExportEnabled)}</span>
    }

    render(
      <RegionalProvider registry={registry}>
        <ExportFlag />
      </RegionalProvider>
    )

    expect(screen.getByTestId("flag")).toHaveTextContent("false")
  })

  test("returns the correct value after registry changes (re-render with a different provider)", () => {
    const enabledRegistry = makeMockRegistry({
      config: makeMockConfig({ features: { showDetailsTab: true, showAnalyticsTab: true, enableExport: true } }),
    })
    const disabledRegistry = makeMockRegistry({
      config: makeMockConfig({ features: { showDetailsTab: false, showAnalyticsTab: false, enableExport: false } }),
    })

    function ExportFlag() {
      const isExportEnabled = useRegionalFeature("enableExport")
      return <span data-testid="flag">{String(isExportEnabled)}</span>
    }

    function Switcher() {
      const [useDisabled, setUseDisabled] = useState(false)
      const reg = useDisabled ? disabledRegistry : enabledRegistry
      return (
        <RegionalProvider registry={reg}>
          <ExportFlag />
          <button type="button" onClick={() => setUseDisabled(true)}>Switch</button>
        </RegionalProvider>
      )
    }

    render(<Switcher />)
    expect(screen.getByTestId("flag")).toHaveTextContent("true")
    fireEvent.click(screen.getByText("Switch"))
    expect(screen.getByTestId("flag")).toHaveTextContent("false")
  })
})

// ── Pattern 3 — ExplicitPricingWidget (no provider required) ──────────────────

describe("ExplicitPricingWidget (Pattern 3)", () => {
  test("renders formatted amount using injected logic — no RegionalProvider needed", () => {
    // Pattern 3 key property: the component is pure — it receives logic as a prop.
    // No <RegionalProvider> ancestor is required. This is the main value of Pattern 3:
    // the component is independently testable with any logic implementation.
    const mockLogic = {
      formatAmount: (n: number) => `£${n} inc. VAT`,
      validateAmount: (n: number) => n > 0,
    }

    render(<ExplicitPricingWidget amount={99.99} logic={mockLogic} />)

    expect(screen.getByText("£99.99 inc. VAT")).toBeInTheDocument()
  })

  test("renders different output when a different logic implementation is injected", () => {
    // Same component, different logic — this is the core of Pattern 3's value proposition.
    const usdLogic = { formatAmount: (n: number) => `$${n}`, validateAmount: () => true }
    const sgdLogic = { formatAmount: (n: number) => `SGD ${n}`, validateAmount: () => true }

    const { rerender } = render(<ExplicitPricingWidget amount={50} logic={usdLogic} />)
    expect(screen.getByText("$50")).toBeInTheDocument()

    rerender(<ExplicitPricingWidget amount={50} logic={sgdLogic} />)
    expect(screen.getByText("SGD 50")).toBeInTheDocument()
  })
})
