defmodule ToweropsWeb.NetworkMapLiveTest do
  use ToweropsWeb.ConnCase, async: true

  import Phoenix.LiveViewTest

  setup :register_and_log_in_user

  setup %{user: user} do
    {:ok, organization} = Towerops.Organizations.create_organization(%{name: "Test Org"}, user.id)

    %{organization: organization}
  end

  describe "mount and render" do
    test "mounts and renders the network map page", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/network-map")

      assert html =~ "Network Map"
      assert html =~ "Experimental"
      assert html =~ "Topology Visualization"
    end

    test "shows stats bar with default zeros", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/network-map")

      assert html =~ "Total Devices"
      assert html =~ "Added Devices"
      assert html =~ "Discovered"
      assert html =~ "Connections"
    end

    test "shows tab navigation with added and all tabs", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/network-map")

      assert html =~ "Added Devices"
      assert html =~ "All Devices"
    end

    test "shows empty state when no devices exist", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/network-map")

      assert html =~ "No network topology available"
      assert html =~ "Add devices"
    end

    test "shows refresh button", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/network-map")

      assert html =~ "Refresh"
    end

    test "shows legend with role and confidence indicators", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/network-map")

      assert html =~ "Roles:"
      assert html =~ "Router"
      assert html =~ "Switch"
      assert html =~ "Firewall"
      assert html =~ "Discovered"
      assert html =~ "Links:"
      assert html =~ "High confidence"
    end

    test "shows cytoscape container with network map hook", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/network-map")

      assert html =~ "cy-container"
      assert html =~ "NetworkMap"
    end
  end

  describe "tab navigation" do
    test "defaults to added tab", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/network-map")

      # The "Added Devices" tab should have active styling
      assert html =~ "Added Devices"
    end

    test "switches to all tab via params", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/network-map?tab=all")

      assert html =~ "All Devices"
    end
  end

  describe "events" do
    test "refresh_topology reloads data and shows flash", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/network-map")

      html = render_click(view, "refresh_topology")

      assert html =~ "Network map refreshed"
    end
  end

  describe "unauthenticated access" do
    test "requires authentication" do
      conn = build_conn()
      {:error, redirect} = live(conn, ~p"/network-map")

      assert {:redirect, %{to: path}} = redirect
      assert path == ~p"/users/log-in"
    end
  end
end
