defmodule WhoNeedHelpWeb.LeaderboardLive do
  use WhoNeedHelpWeb, :live_view

  alias WhoNeedHelp.Trust

  @impl true
  def mount(_params, _session, socket) do
    page = Trust.paginate_leaderboard()

    {:ok,
     socket
     |> assign(:page_title, gettext("Community helpers"))
     |> assign(:leaders, page.entries)
     |> assign(:leaders_cursor, page.next_cursor)}
  end

  @impl true
  def handle_event("load-more", _params, socket) do
    page = Trust.paginate_leaderboard(after: socket.assigns.leaders_cursor)
    existing_ids = MapSet.new(socket.assigns.leaders, & &1.user.id)

    leaders =
      socket.assigns.leaders ++
        Enum.reject(page.entries, &MapSet.member?(existing_ids, &1.user.id))

    {:noreply,
     socket
     |> assign(:leaders, leaders)
     |> assign(:leaders_cursor, page.next_cursor)}
  end

  @impl true
  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope}>
      <.link navigate={~p"/requests"} class="btn btn-ghost btn-sm">
        {gettext("← Requests")}
      </.link>
      <div class="mt-5 max-w-4xl">
        <div class="text-sm font-semibold text-success">{gettext("COMMUNITY TRUST")}</div>
        <h1 class="mt-1 text-4xl font-black tracking-tight">
          {gettext("Helpers leaderboard")}
        </h1>
        <p class="mt-3 text-base-content/65">
          {gettext(
            "Ranking prioritizes unique people helped with optional location-supported evidence, then unique verified handovers. Repeated help between the same pair does not inflate the primary score."
          )}
        </p>

        <div class="mt-7 overflow-x-auto rounded-3xl border border-base-300">
          <table class="table">
            <thead>
              <tr>
                <th>{gettext("Rank")}</th>
                <th>{gettext("Helper")}</th>
                <th>{gettext("Location-supported people")}</th>
                <th>{gettext("Verified people")}</th>
                <th>{gettext("Unique people")}</th>
                <th>{gettext("Total")}</th>
                <th>{gettext("Rating")}</th>
              </tr>
            </thead>
            <tbody>
              <tr :if={@leaders == []}>
                <td colspan="7" class="py-10 text-center text-base-content/55">
                  {gettext("No completed help yet.")}
                </td>
              </tr>
              <tr :for={{entry, index} <- Enum.with_index(@leaders, 1)}>
                <td class="font-black">#{index}</td>
                <td class="font-semibold">{entry.user.display_name}</td>
                <td>{entry.location_supported_people}</td>
                <td>{entry.verified_people}</td>
                <td>{entry.unique_people}</td>
                <td>{entry.completed}</td>
                <td>{entry.rating || "—"}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <button
          :if={@leaders_cursor}
          type="button"
          phx-click="load-more"
          class="btn btn-outline mt-4"
        >
          {gettext("Load more")}
        </button>
      </div>
    </Layouts.app>
    """
  end
end
