defmodule MicrowavepropWeb.ContactMapLiveTest do
  use MicrowavepropWeb.ConnCase, async: true

  import Phoenix.LiveViewTest

  alias Microwaveprop.Radio.Contact
  alias Microwaveprop.Repo

  defp create_contact(attrs) do
    default = %{
      station1: "W5XD",
      station2: "K5TR",
      qso_timestamp: ~U[2026-03-28 18:00:00Z],
      mode: "CW",
      band: Decimal.new("1296"),
      grid1: "EM12",
      grid2: "EM00",
      pos1: %{"lat" => 32.9, "lon" => -97.0},
      pos2: %{"lat" => 30.3, "lon" => -97.7},
      distance_km: Decimal.new("295")
    }

    {:ok, contact} =
      %Contact{}
      |> Contact.changeset(Map.merge(default, attrs))
      |> Repo.insert()

    contact
  end

  describe "GET /contacts/map" do
    test "renders the shell with the Contact Map heading + JS hook container", %{conn: conn} do
      {:ok, _lv, html} = live(conn, ~p"/contacts/map")

      assert html =~ "Contact Map"
      assert html =~ ~s(id="contacts-map")
      assert html =~ ~s(phx-hook="ContactsMap")
      # Client fetches the JSON blob from the controller endpoint.
      assert html =~ ~s(data-fetch-url="/api/contacts/map")
    end

    test "shows the contact count and the populated band list", %{conn: conn} do
      _c1 = create_contact(%{band: Decimal.new("1296")})
      _c2 = create_contact(%{band: Decimal.new("10000"), station1: "W5OTHR"})

      {:ok, _lv, html} = live(conn, ~p"/contacts/map")

      assert html =~ "2 contacts"
      # band_label/1 converts bands ≥ 1000 MHz into GHz — integer values
      # stay whole ("10 GHz"), non-integer ratios round to 1 decimal ("1.3 GHz").
      assert html =~ "1.3 GHz"
      assert html =~ "10 GHz"
    end

    test "empty DB renders '0 contacts' and no band checkboxes", %{conn: conn} do
      {:ok, _lv, html} = live(conn, ~p"/contacts/map")
      assert html =~ "0 contacts"
    end
  end

  describe "filter_callsign event" do
    test "stores the trimmed filter and pushes apply_filter to the hook", %{conn: conn} do
      {:ok, lv, _html} = live(conn, ~p"/contacts/map")

      html =
        lv
        # There's a mobile and a desktop filter form — submit via the
        # desktop one (input.input-sm lives only inside the desktop form).
        |> form(~s|form[phx-submit="filter_callsign"]:has(input.input-sm)|,
          callsign: "  W5ISP  "
        )
        |> render_submit()

      # Server stored the trimmed value in assigns, which round-trips
      # back through the `value=` attribute.
      assert html =~ ~s(value="W5ISP")
    end

    test "blank input round-trips as an empty value", %{conn: conn} do
      {:ok, lv, _html} = live(conn, ~p"/contacts/map")

      html =
        lv
        |> form(~s|form[phx-submit="filter_callsign"]:has(input.input-sm)|,
          callsign: "   "
        )
        |> render_submit()

      refute html =~ ~s(value="   ")
      assert html =~ ~s(value="")
    end

    test "renders a Filter button next to the callsign input", %{conn: conn} do
      {:ok, lv, _html} = live(conn, ~p"/contacts/map")

      assert has_element?(
               lv,
               ~s|form[phx-submit="filter_callsign"] button[type="submit"]|,
               "Filter"
             )
    end
  end

  describe "filter_dates event" do
    test "stores trimmed start/end dates and round-trips them in the inputs", %{conn: conn} do
      {:ok, lv, _html} = live(conn, ~p"/contacts/map")

      html =
        lv
        |> form(~s|form[phx-submit="filter_dates"]:has(input.input-sm)|,
          start_date: "2025-01-01",
          end_date: "2026-01-01"
        )
        |> render_submit()

      assert html =~ ~s(name="start_date" value="2025-01-01")
      assert html =~ ~s(name="end_date" value="2026-01-01")
      # Clear button shows up only once a filter is set.
      assert html =~ ~s(phx-click="clear_dates")
    end

    test "clear_dates wipes both inputs", %{conn: conn} do
      {:ok, lv, _html} = live(conn, ~p"/contacts/map")

      lv
      |> form(~s|form[phx-submit="filter_dates"]:has(input.input-sm)|,
        start_date: "2025-01-01",
        end_date: "2026-01-01"
      )
      |> render_submit()

      html =
        render_click(element(lv, ~s|form:has(input.input-sm) button[phx-click="clear_dates"]|))

      refute html =~ ~s(value="2025-01-01")
      refute html =~ ~s(value="2026-01-01")
    end
  end
end
