defmodule MvWeb.SignInLive do
  @moduledoc """
  Custom sign-in page with language selector and conditional Single Sign-On button.

  - Renders a language selector (same pattern as LinkOidcAccountLive).
  - Wraps the default AshAuthentication SignIn component in a container with
    `data-oidc-configured` so that CSS can hide the SSO button when OIDC is not configured.
  """
  use Phoenix.LiveView
  use Gettext, backend: MvWeb.Gettext

  alias AshAuthentication.Phoenix.Components
  alias Mv.Config

  @impl true
  def mount(_params, session, socket) do
    overrides =
      session
      |> Map.get("overrides", [AshAuthentication.Phoenix.Overrides.Default])

    # Locale: same fallback as LiveUserAuth so config :default_locale (e.g. "en" in test) is respected
    locale =
      session["locale"] || Application.get_env(:mv, :default_locale, "de")

    Gettext.put_locale(MvWeb.Gettext, locale)

    socket =
      socket
      |> assign(overrides: overrides)
      |> assign_new(:otp_app, fn -> nil end)
      |> assign(:path, session["path"] || "/")
      |> assign(:reset_path, session["reset_path"])
      |> assign(:register_path, session["register_path"])
      |> assign(:current_tenant, session["tenant"])
      |> assign(:resources, session["resources"])
      |> assign(:context, session["context"] || %{})
      |> assign(:auth_routes_prefix, session["auth_routes_prefix"])
      |> assign(:gettext_fn, session["gettext_fn"])
      |> assign(:live_action, :sign_in)
      |> assign(:oidc_configured, Config.oidc_configured?())
      |> assign(:oidc_only, Config.oidc_only?())
      |> assign(:root_class, "grid h-screen place-items-center bg-base-100")
      |> assign(:sign_in_id, "sign-in")
      |> assign(:locale, locale)

    {:ok, socket}
  end

  @impl true
  def handle_params(_, _uri, socket) do
    {:noreply, socket}
  end

  @impl true
  def render(assigns) do
    ~H"""
    <div
      id="sign-in-page"
      class={@root_class}
      data-oidc-configured={to_string(@oidc_configured)}
      data-oidc-only={to_string(@oidc_only)}
      data-locale={@locale}
    >
      <%!-- Language selector --%>
      <nav
        aria-label={dgettext("auth", "Language selection")}
        class="absolute top-4 right-4 flex justify-end z-10"
      >
        <form method="post" action="/set_locale" class="text-sm">
          <input type="hidden" name="_csrf_token" value={Plug.CSRFProtection.get_csrf_token()} />
          <select
            name="locale"
            onchange="this.form.submit()"
            class="select select-sm select-bordered bg-base-100"
            aria-label={dgettext("auth", "Select language")}
          >
            <option value="de" selected={@locale == "de"}>Deutsch</option>
            <option value="en" selected={@locale == "en"}>English</option>
          </select>
        </form>
      </nav>

      <.live_component
        module={Components.SignIn}
        otp_app={@otp_app}
        live_action={@live_action}
        path={@path}
        auth_routes_prefix={@auth_routes_prefix}
        resources={@resources}
        reset_path={@reset_path}
        register_path={@register_path}
        id={@sign_in_id}
        overrides={@overrides}
        current_tenant={@current_tenant}
        context={@context}
        gettext_fn={@gettext_fn}
      />
    </div>
    """
  end
end
