defmodule SimpleshopThemeWeb.ShopLive.Home 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()

    preview_data = %{
      products: PreviewData.products(),
      categories: PreviewData.categories()
    }

    socket =
      socket
      |> assign(:page_title, "Home")
      |> assign(:theme_settings, theme_settings)
      |> assign(:generated_css, generated_css)
      |> assign(:logo_image, logo_image)
      |> assign(:header_image, header_image)
      |> assign(:preview_data, preview_data)
      |> assign(:mode, :shop)

    {:ok, socket}
  end

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