defmodule ToweropsWeb.CoreComponentsTest do
  use ExUnit.Case, async: true

  import Phoenix.Component
  import Phoenix.LiveViewTest

  alias ToweropsWeb.CoreComponents

  describe "table/1" do
    test "renders basic table without row_link" do
      assigns = %{}

      html =
        rendered_to_string(~H"""
        <CoreComponents.table
          id="test-table"
          rows={[%{id: "1", name: "Alice"}, %{id: "2", name: "Bob"}]}
        >
          <:col :let={row} label="Name">{row.name}</:col>
        </CoreComponents.table>
        """)

      assert html =~ "Alice"
      assert html =~ "Bob"
      refute html =~ "<a "
    end

    test "renders row_link as real anchor tags with navigate" do
      assigns = %{}

      html =
        rendered_to_string(~H"""
        <CoreComponents.table
          id="test-table"
          rows={[%{id: "1", name: "Alice"}, %{id: "2", name: "Bob"}]}
          row_link={fn row -> "/users/#{row.id}" end}
        >
          <:col :let={row} label="Name">{row.name}</:col>
        </CoreComponents.table>
        """)

      assert html =~ ~s|href="/users/1"|
      assert html =~ ~s|href="/users/2"|
      assert html =~ "Alice"
      assert html =~ "Bob"
    end

    test "row_link renders a link in each column cell" do
      assigns = %{}

      html =
        rendered_to_string(~H"""
        <CoreComponents.table
          id="test-table"
          rows={[%{id: "1", name: "Alice", email: "alice@example.com"}]}
          row_link={fn row -> "/users/#{row.id}" end}
        >
          <:col :let={row} label="Name">{row.name}</:col>
          <:col :let={row} label="Email">{row.email}</:col>
        </CoreComponents.table>
        """)

      # Each column cell should have a link (2 columns = 2 links)
      link_count = length(Regex.scan(~r/href="\/users\/1"/, html))
      assert link_count == 2
    end

    test "row_click still works without row_link" do
      assigns = %{}

      html =
        rendered_to_string(~H"""
        <CoreComponents.table
          id="test-table"
          rows={[%{id: "1", name: "Alice"}]}
          row_click={fn row -> Phoenix.LiveView.JS.navigate("/users/#{row.id}") end}
        >
          <:col :let={row} label="Name">{row.name}</:col>
        </CoreComponents.table>
        """)

      assert html =~ "phx-click"
      assert html =~ "cursor-pointer"
      refute html =~ ~s|<a |
    end

    test "row_link zeros td padding and moves it to the link" do
      assigns = %{}

      html =
        rendered_to_string(~H"""
        <CoreComponents.table
          id="test-table"
          rows={[%{id: "1", name: "Alice"}]}
          row_link={fn row -> "/users/#{row.id}" end}
        >
          <:col :let={row} label="Name">{row.name}</:col>
        </CoreComponents.table>
        """)

      # td should have p-0 when row_link is used
      assert html =~ "p-0"
      # link should have the padding
      assert html =~ "py-4"
    end
  end
end
