defmodule TarakanWeb.NavActiveStateTest do
  use TarakanWeb.ConnCase, async: true

  import Phoenix.LiveViewTest

  # The highlight used to be applied by JavaScript after paint, so the server
  # rendered nothing active and dead routes never highlighted at all.
  test "a LiveView marks its own nav entry active on first paint", %{conn: conn} do
    {:ok, _view, html} = live(conn, ~p"/leaderboard")

    assert html =~ ~r/href="\/leaderboard"[^>]*aria-current="page"/
    refute html =~ ~r/href="\/pricing"[^>]*aria-current="page"/
  end

  test "a dead controller route marks its nav entry active too", %{conn: conn} do
    html = conn |> get(~p"/pricing") |> html_response(200)

    assert html =~ ~r/href="\/pricing"[^>]*aria-current="page"/
    refute html =~ ~r/href="\/leaderboard"[^>]*aria-current="page"/
  end

  test "a section stays active on its subtree" do
    alias TarakanWeb.CurrentPath

    assert CurrentPath.active?("/jobs/12", "/jobs")
    assert CurrentPath.active?("/jobs", "/jobs")
    refute CurrentPath.active?("/jobsomething", "/jobs")
    # Root must not own every page.
    refute CurrentPath.active?("/jobs", "/")
    assert CurrentPath.active?("/", "/")
    refute CurrentPath.active?(nil, "/jobs")
  end

  # Leaderboard, Models and Pricing used to be hidden below lg while the other
  # five were not. The desktop bar starts at md and the hamburger stops at md,
  # so between 768 and 1024 those three were unreachable from any navigation.
  test "every primary nav entry is reachable at every width", %{conn: conn} do
    {:ok, _view, html} = live(conn, ~p"/")

    nav =
      Regex.run(~r/<nav[^>]*aria-label="Primary".*?<\/nav>/s, html)
      |> List.first()

    for path <- ~w(/explore /infestations /jobs /bounties /agents /leaderboard /models /pricing) do
      assert nav =~ ~s(href="#{path}"), "#{path} missing from the primary nav"
    end

    refute nav =~ "hidden lg:", "no primary nav entry may be hidden at a breakpoint"
  end

  test "the mobile menu carries the same entries", %{conn: conn} do
    {:ok, _view, html} = live(conn, ~p"/")

    menu = Regex.run(~r/<nav[^>]*aria-label="Site".*?<\/nav>/s, html) |> List.first()

    for path <- ~w(/explore /infestations /jobs /bounties /agents /leaderboard /models /pricing) do
      assert menu =~ ~s(href="#{path}"), "#{path} missing from the mobile menu"
    end
  end
end
