defmodule BerrypodWeb.Admin.LayoutTest do
  use BerrypodWeb.ConnCase, async: false

  import Phoenix.LiveViewTest
  import Berrypod.AccountsFixtures

  setup do
    user = user_fixture()
    %{user: user}
  end

  describe "admin sidebar" do
    setup %{conn: conn, user: user} do
      %{conn: log_in_user(conn, user)}
    end

    test "renders sidebar nav links on admin pages", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/admin/orders")

      assert has_element?(view, ~s(a[href="/admin"]), "Dashboard")
      assert has_element?(view, ~s(a[href="/admin/orders"]), "Orders")
      assert has_element?(view, ~s(a[href="/?edit=theme"]), "Theme")
      assert has_element?(view, ~s(a[href="/admin/settings"]), "Settings")
    end

    test "highlights active nav link for current page", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/admin/orders")

      assert has_element?(view, ~s(a.active[href="/admin/orders"]))
      refute has_element?(view, ~s(a.active[href="/admin/settings"]))
    end

    test "highlights correct link on different pages", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/admin/settings")

      assert has_element?(view, ~s(a.active[href="/admin/settings"]))
      refute has_element?(view, ~s(a.active[href="/admin/orders"]))
    end

    test "shows shop and log out links", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/admin/orders")

      assert has_element?(view, ~s(a[href="/"]), "Shop")
      assert has_element?(view, ~s(a[href="/users/log-out"]), "Log out")
    end
  end

  describe "admin bar on shop pages" do
    setup do
      {:ok, _} = Berrypod.Settings.set_site_live(true)
      :ok
    end

    test "shows admin link when logged in", %{conn: conn, user: user} do
      conn = log_in_user(conn, user)
      {:ok, _view, html} = live(conn, ~p"/")

      assert html =~ ~s(href="/admin")
    end

    test "does not show admin link when logged out", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/")

      refute html =~ ~s(href="/admin")
    end
  end
end
