defmodule BerrypodWeb.Shop.NavigationTest do
  use BerrypodWeb.ConnCase, async: false

  import Phoenix.LiveViewTest
  import Berrypod.AccountsFixtures

  alias Berrypod.{Pages, Settings}
  alias Berrypod.Pages.PageCache

  setup do
    PageCache.invalidate_all()
    user_fixture()
    {:ok, _} = Settings.set_site_live(true)
    :ok
  end

  describe "header navigation" do
    test "renders default items", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/")

      assert html =~ "Home"
      assert html =~ "Shop"
      assert html =~ "About"
      assert html =~ "Contact"
    end

    test "renders from saved settings", %{conn: conn} do
      Settings.put_setting(
        "header_nav",
        [
          %{"label" => "Blog", "href" => "/blog", "slug" => "blog"},
          %{"label" => "FAQ", "href" => "/faq", "slug" => "faq"}
        ],
        "json"
      )

      {:ok, _view, html} = live(conn, ~p"/")

      assert html =~ "Blog"
      assert html =~ "FAQ"
      refute html =~ ~s(>Shop</a>)
    end
  end

  describe "footer navigation" do
    test "renders default items", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/")

      assert html =~ "Delivery &amp; returns"
      assert html =~ "Privacy policy"
      assert html =~ "Terms of service"
    end

    test "renders from saved settings", %{conn: conn} do
      Settings.put_setting(
        "footer_nav",
        [
          %{"label" => "Returns", "href" => "/returns", "slug" => "returns"},
          %{"label" => "Shipping", "href" => "/shipping", "slug" => "shipping"}
        ],
        "json"
      )

      {:ok, _view, html} = live(conn, ~p"/")

      assert html =~ "Returns"
      assert html =~ "Shipping"
      refute html =~ "Privacy policy"
    end
  end

  describe "custom page in navigation" do
    test "renders when added to header nav", %{conn: conn} do
      {:ok, _} = Pages.create_custom_page(%{slug: "faq", title: "FAQ"})

      Settings.put_setting(
        "header_nav",
        [
          %{"label" => "Home", "href" => "/", "slug" => "home"},
          %{"label" => "FAQ", "href" => "/faq", "slug" => "faq"}
        ],
        "json"
      )

      {:ok, _view, html} = live(conn, ~p"/")

      assert html =~ ~s(href="/faq")
      assert html =~ "FAQ"
    end
  end
end
