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

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

  @impl true
  def mount(%{"id" => id}, _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()

    products = PreviewData.products()

    # Find product by ID (preview data uses integer IDs)
    product_id = String.to_integer(id)
    product = Enum.find(products, List.first(products), fn p -> p.id == product_id end)

    # Get related products (exclude current product, take 4)
    related_products =
      products
      |> Enum.reject(fn p -> p.id == product_id end)
      |> Enum.take(4)

    # Build gallery images
    gallery_images = [
      product.image_url,
      product.hover_image_url,
      product.image_url,
      product.hover_image_url
    ]

    socket =
      socket
      |> assign(:page_title, product.name)
      |> assign(:theme_settings, theme_settings)
      |> assign(:generated_css, generated_css)
      |> assign(:logo_image, logo_image)
      |> assign(:header_image, header_image)
      |> assign(:product, product)
      |> assign(:gallery_images, gallery_images)
      |> assign(:related_products, related_products)
      |> assign(:quantity, 1)
      |> assign(:mode, :shop)
      |> assign(:cart_items, [])
      |> assign(:cart_count, 0)
      |> assign(:cart_subtotal, "£0.00")

    {:ok, socket}
  end

  @impl true
  def render(assigns) do
    ~H"""
    <SimpleshopThemeWeb.PageTemplates.pdp
      theme_settings={@theme_settings}
      logo_image={@logo_image}
      header_image={@header_image}
      product={@product}
      gallery_images={@gallery_images}
      related_products={@related_products}
      quantity={@quantity}
      mode={@mode}
      cart_items={@cart_items}
      cart_count={@cart_count}
      cart_subtotal={@cart_subtotal}
    />
    """
  end
end
