defmodule Berrypod.Pages.Defaults do
  @moduledoc """
  Default block definitions for all pages.

  These match the current static templates exactly. When a page has never
  been customised, `Pages.get_page/1` returns these defaults. First edit
  saves to the DB and overrides them.
  """

  @doc "Returns the default page definition for the given slug."
  def for_slug(slug) do
    %{
      slug: slug,
      title: title(slug),
      blocks: blocks(slug),
      type: "system",
      published: true,
      meta_description: nil,
      show_in_nav: false,
      nav_label: nil,
      nav_position: nil,
      url_slug: nil
    }
  end

  @doc "Returns default definitions for all pages."
  def all do
    Berrypod.Pages.Page.system_slugs()
    |> Enum.map(&for_slug/1)
  end

  @doc "Returns true if the given blocks match the defaults for the slug."
  def matches_defaults?(slug, current_blocks) when is_list(current_blocks) do
    default_blocks = blocks(slug)

    length(current_blocks) == length(default_blocks) and
      Enum.zip(current_blocks, default_blocks)
      |> Enum.all?(fn {current, default} ->
        current["type"] == default["type"] and
          current["settings"] == default["settings"]
      end)
  end

  def matches_defaults?(_slug, _blocks), do: false

  # ── Page titles ─────────────────────────────────────────────────

  defp title("home"), do: "Home page"
  defp title("about"), do: "About"
  defp title("delivery"), do: "Delivery"
  defp title("privacy"), do: "Privacy policy"
  defp title("terms"), do: "Terms & conditions"
  defp title("contact"), do: "Contact"
  defp title("collection"), do: "Collection"
  defp title("pdp"), do: "Product page"
  defp title("cart"), do: "Cart"
  defp title("search"), do: "Search"
  defp title("checkout_success"), do: "Checkout success"
  defp title("orders"), do: "Orders"
  defp title("order_detail"), do: "Order detail"
  defp title("error"), do: "Error"

  defp title(slug) do
    slug |> String.replace(~r/[-_]/, " ") |> String.capitalize()
  end

  # ── Block lists ─────────────────────────────────────────────────

  defp blocks("home") do
    [
      block("hero", %{
        "title" => "Your headline goes here",
        "description" =>
          "Write something short and punchy about your shop \u2013 what you sell and why it's worth a look.",
        "cta_text" => "Shop the collection",
        "cta_href" => "/collections/all",
        "variant" => "default"
      }),
      block("category_nav"),
      block("featured_products", %{
        "title" => "Featured products",
        "product_count" => 8
      }),
      block("image_text", %{
        "title" => "Your story in a nutshell",
        "description" =>
          "Use this section to share what makes your products special, your creative process, or a bit about you. Pick an image from your media library to go alongside it.",
        "link_text" => "Read more about us \u2192",
        "link_href" => "/about"
      })
    ]
  end

  defp blocks("about") do
    [
      block("hero", %{
        "title" => "About us",
        "description" => "Share a bit about who you are and what you do",
        "variant" => "sunken"
      }),
      block("content_body", %{
        "content" =>
          "Tell your customers who you are and what inspired your shop. What's the story behind your designs?\n\n" <>
            "This is placeholder text \u2013 edit it to make it your own. You can also add an image from your media library using the block settings."
      })
    ]
  end

  defp blocks("delivery") do
    [
      block("hero", %{
        "title" => "Delivery & returns",
        "description" => "Everything you need to know about shipping and returns",
        "variant" => "page"
      }),
      block("content_body")
    ]
  end

  defp blocks("privacy") do
    [
      block("hero", %{
        "title" => "Privacy policy",
        "description" => "How we handle your personal information",
        "variant" => "page"
      }),
      block("content_body")
    ]
  end

  defp blocks("terms") do
    [
      block("hero", %{
        "title" => "Terms of service",
        "description" => "The legal bits",
        "variant" => "page"
      }),
      block("content_body")
    ]
  end

  defp blocks("contact") do
    [
      block("hero", %{
        "title" => "Get in touch",
        "description" => "Add a friendly message about how customers can reach you",
        "variant" => "page"
      }),
      block("contact_form", %{"email" => "hello@example.com"}),
      block("order_tracking_card"),
      block("info_card", %{
        "title" => "Handy to know",
        "items" => [
          %{"label" => "Printing", "value" => "Update with your printing times"},
          %{"label" => "Delivery", "value" => "Update with your delivery times"},
          %{"label" => "Issues", "value" => "Update with your returns policy"}
        ]
      }),
      block("newsletter_card"),
      block("social_links_card")
    ]
  end

  defp blocks("collection") do
    [
      block("collection_header"),
      block("filter_bar"),
      block("product_grid")
    ]
  end

  defp blocks("pdp") do
    [
      block("breadcrumb"),
      block("product_hero"),
      block("trust_badges"),
      block("product_details"),
      block("reviews_section"),
      block("related_products")
    ]
  end

  defp blocks("cart") do
    [
      block("cart_items"),
      block("order_summary")
    ]
  end

  defp blocks("search") do
    [
      block("search_results")
    ]
  end

  defp blocks("checkout_success") do
    [
      block("checkout_result")
    ]
  end

  defp blocks("orders") do
    [
      block("order_card")
    ]
  end

  defp blocks("order_detail") do
    [
      block("order_detail_card")
    ]
  end

  defp blocks("error") do
    [
      block("hero", %{
        "variant" => "error",
        "cta_text" => "Go to Homepage",
        "cta_href" => "/",
        "secondary_cta_text" => "Browse Products",
        "secondary_cta_href" => "/collections/all"
      }),
      block("featured_products", %{
        "title" => "Featured products",
        "product_count" => 4,
        "layout" => "grid",
        "card_variant" => "minimal",
        "columns" => "fixed-4"
      })
    ]
  end

  defp blocks(_slug), do: []

  # ── Page templates ─────────────────────────────────────────────

  @doc "Returns available templates for new custom pages."
  def templates do
    [
      %{key: "blank", label: "Blank", description: "Start from scratch"},
      %{key: "content", label: "Content page", description: "Hero banner + text content"},
      %{key: "landing", label: "Landing page", description: "Hero, image + text, products, CTA"}
    ]
  end

  @doc "Returns the starter blocks for a template key."
  def template_blocks("content") do
    [
      block("hero", %{
        "title" => "Page title",
        "description" => "A short summary of this page",
        "variant" => "page"
      }),
      block("content_body", %{
        "content" => "Start writing your content here."
      })
    ]
  end

  def template_blocks("landing") do
    [
      block("hero", %{
        "title" => "Your headline here",
        "description" => "A compelling description that makes visitors want to keep reading.",
        "cta_text" => "Shop now",
        "cta_href" => "/collections/all"
      }),
      block("image_text", %{
        "title" => "Tell your story",
        "description" =>
          "Use this section to share what makes your products special, your process, or your inspiration."
      }),
      block("featured_products", %{
        "title" => "Featured products",
        "product_count" => 4,
        "layout" => "grid",
        "card_variant" => "default"
      }),
      block("button", %{
        "text" => "View all products",
        "href" => "/collections/all",
        "style" => "outline",
        "alignment" => "centre"
      }),
      block("newsletter_card")
    ]
  end

  def template_blocks(_), do: []

  # ── Helpers ─────────────────────────────────────────────────────

  defp block(type, settings \\ %{}) do
    %{
      "id" => generate_block_id(),
      "type" => type,
      "settings" => settings
    }
  end

  @doc "Generates a unique block ID."
  def generate_block_id do
    "blk_" <> (:crypto.strong_rand_bytes(8) |> Base.url_encode64(padding: false))
  end
end
