defmodule AprsmeWeb.Components.ErrorBoundaryTest do
  use ExUnit.Case, async: true

  import Phoenix.LiveViewTest

  alias AprsmeWeb.Components.ErrorBoundary

  test "renders inner content and default fallback" do
    html =
      render_component(&ErrorBoundary.error_boundary/1, %{
        id: "boundary-1",
        inner_block: text_slot("hello world"),
        fallback: []
      })

    assert html =~ ~s(id="boundary-1")
    assert html =~ "hello world"
    assert html =~ "phx-hook=\"ErrorBoundary\""
    assert html =~ "error-boundary-fallback hidden"
    # The default error message is rendered when no fallback slot is provided.
    assert html =~ "Something went wrong"
    assert html =~ "Refresh page"
  end

  test "honours custom class" do
    html =
      render_component(&ErrorBoundary.error_boundary/1, %{
        id: "boundary-2",
        class: "my-custom-class",
        inner_block: text_slot("content"),
        fallback: []
      })

    assert html =~ "my-custom-class"
  end

  test "uses the custom fallback slot when provided" do
    html =
      render_component(&ErrorBoundary.error_boundary/1, %{
        id: "boundary-3",
        inner_block: text_slot("content"),
        fallback: [
          %{__slot__: :fallback, inner_block: fn _changed, _ -> "custom error!" end}
        ]
      })

    assert html =~ "custom error!"
    # Default error message should not appear when a custom fallback is used.
    refute html =~ "Something went wrong"
  end

  defp text_slot(text) do
    [%{__slot__: :inner_block, inner_block: fn _changed, _ -> text end}]
  end
end
