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

  import Phoenix.LiveViewTest
  import Berrypod.AccountsFixtures

  alias Berrypod.{Pages, Settings, Site}
  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
      # Seed defaults if not already present
      Site.seed_defaults()

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

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

    test "renders from database nav items", %{conn: conn} do
      # Clear existing and add custom items
      for item <- Site.list_nav_items("header"), do: Site.delete_nav_item(item)

      {:ok, _} =
        Site.create_nav_item(%{location: "header", label: "Blog", url: "/blog", position: 0})

      {:ok, _} =
        Site.create_nav_item(%{location: "header", label: "FAQ", url: "/faq", position: 1})

      {: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
      Site.seed_defaults()

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

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

    test "renders from database nav items", %{conn: conn} do
      # Clear existing and add custom items
      for item <- Site.list_nav_items("footer"), do: Site.delete_nav_item(item)

      {:ok, _} =
        Site.create_nav_item(%{
          location: "footer",
          label: "Returns",
          url: "/returns",
          position: 0
        })

      {:ok, _} =
        Site.create_nav_item(%{
          location: "footer",
          label: "Shipping",
          url: "/shipping",
          position: 1
        })

      {: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, page} = Pages.create_custom_page(%{slug: "faq", title: "FAQ"})

      # Clear existing header nav and add custom items
      for item <- Site.list_nav_items("header"), do: Site.delete_nav_item(item)

      {:ok, _} = Site.create_nav_item(%{location: "header", label: "Home", url: "/", position: 0})

      {:ok, _} =
        Site.create_nav_item(%{
          location: "header",
          label: "FAQ",
          url: "/faq",
          page_id: page.id,
          position: 1
        })

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

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