defmodule SimpleshopThemeWeb.ShopLive.Cart do
  use SimpleshopThemeWeb, :live_view

  alias SimpleshopTheme.Settings
  alias SimpleshopTheme.Media
  alias SimpleshopTheme.Theme.{CSSCache, CSSGenerator, PreviewData}

  @impl true
  def mount(_params, _session, socket) do
    theme_settings = Settings.get_theme_settings()

    generated_css =
      case CSSCache.get() do
        {:ok, css} -> css
        :miss ->
          css = CSSGenerator.generate(theme_settings)
          CSSCache.put(css)
          css
      end

    logo_image = Media.get_logo()
    header_image = Media.get_header()

    # For now, use preview data for cart items
    # In a real implementation, this would come from session/database
    cart_page_items = PreviewData.cart_items()
    cart_page_subtotal = Enum.reduce(cart_page_items, 0, fn item, acc ->
      acc + item.product.price * item.quantity
    end)

    socket =
      socket
      |> assign(:page_title, "Cart")
      |> assign(:theme_settings, theme_settings)
      |> assign(:generated_css, generated_css)
      |> assign(:logo_image, logo_image)
      |> assign(:header_image, header_image)
      |> assign(:cart_page_items, cart_page_items)
      |> assign(:cart_page_subtotal, cart_page_subtotal)
      |> assign(:mode, :shop)
      |> assign(:cart_items, PreviewData.cart_drawer_items())
      |> assign(:cart_count, length(cart_page_items))
      |> assign(:cart_subtotal, format_subtotal(cart_page_subtotal))

    {:ok, socket}
  end

  @impl true
  def render(assigns) do
    ~H"""
    <SimpleshopThemeWeb.PageTemplates.cart
      theme_settings={@theme_settings}
      logo_image={@logo_image}
      header_image={@header_image}
      cart_page_items={@cart_page_items}
      cart_page_subtotal={@cart_page_subtotal}
      mode={@mode}
      cart_items={@cart_items}
      cart_count={@cart_count}
      cart_subtotal={@cart_subtotal}
    />
    """
  end

  defp format_subtotal(subtotal_pence) do
    "£#{Float.round(subtotal_pence / 100, 2)}"
  end
end
