import { getWooStoreApiUrl } from "@/lib/config";
import { formatWooMoney, type WooMoney } from "@/lib/woo-store-client";
import { starterRouteFetch } from "@/lib/wordpress-client";
import type {
  StorefrontArchivePage,
  StorefrontCategoryCard,
  StorefrontFeatureGridBanner,
  StorefrontFeaturedBanner,
  StorefrontHeaderCategory,
  StorefrontImage,
  StorefrontMenuItem,
  StorefrontOrderSummary,
  StorefrontProductCard,
  StorefrontProductDetail,
  StorefrontProductVariation,
  StorefrontSearchSuggestion,
  StorefrontTerm,
} from "@/types/storefront";
import type { StorefrontBrandItem } from "@/types/brand";

interface StarterRouteImage {
  src?: string;
  alt?: string;
}

interface StarterRouteTerm {
  id?: number;
  name?: string;
  slug?: string;
}

interface StarterRouteProductCard {
  id?: number;
  slug?: string;
  href?: string;
  name?: string;
  type?: string;
  shortDescription?: string;
  featuredImage?: StarterRouteImage | null;
  category?: StarterRouteTerm | null;
  brand?: StarterRouteTerm | null;
  price?: string;
  regularPrice?: string;
  salePrice?: string;
  lowestPrice30d?: string;
  isOnSale?: boolean;
  isInStock?: boolean;
}

interface StarterRouteProductVariation {
  id?: number;
  price?: string;
  regularPrice?: string;
  salePrice?: string;
  lowestPrice30d?: string;
  isOnSale?: boolean;
  isInStock?: boolean;
  attributes?: Array<{
    key?: string;
    label?: string;
    value?: string;
    slug?: string;
  }>;
}

interface StarterRouteProductResponse extends StarterRouteProductCard {
  description?: string;
  descriptionHtml?: string;
  tabs?: {
    descriptionHtml?: string;
    technicalDetailsHtml?: string;
    downloadsHtml?: string;
    sizeChartHtml?: string;
  };
  gallery?: StarterRouteImage[];
  attributes?: Array<{
    label?: string;
    value?: string;
  }>;
  variations?: StarterRouteProductVariation[];
}

interface StarterRouteArchiveResponse {
  title?: string;
  description?: string;
  totalResults?: number;
  currentPage?: number;
  totalPages?: number;
  priceRange?: {
    min?: number;
    max?: number;
  } | null;
  filters?: Array<{
    id?: string;
    label?: string;
    options?: Array<{
      id?: string;
      label?: string;
      count?: number;
    }>;
  }>;
  products?: StarterRouteProductCard[];
}

interface StarterRouteCategoryResponse {
  items?: Array<{
    id?: number;
    name?: string;
    slug?: string;
    parent?: number;
    href?: string;
    count?: number;
    image?: StarterRouteImage | null;
  }>;
}

interface StarterRouteFeaturedBannerResponse {
  id?: number;
  title?: string;
  href?: string;
  image?: StarterRouteImage | null;
}

interface StarterRouteFeatureGridResponse {
  items?: Array<{
    id?: string;
    title?: string;
    href?: string;
    image?: StarterRouteImage | null;
  }>;
}

interface StarterRouteMenuResponse {
  items?: Array<{
    id?: string;
    label?: string;
    href?: string;
  }>;
}

interface StarterRouteBrandsResponse {
  items?: Array<{
    id?: number;
    name?: string;
    slug?: string;
    href?: string;
    image?: StarterRouteImage | null;
  }>;
}

interface StarterRouteHeaderNavigationResponse {
  items?: Array<{
    id?: number;
    name?: string;
    slug?: string;
    href?: string;
    children?: Array<{
      id?: number;
      name?: string;
      slug?: string;
      href?: string;
      image?: StarterRouteImage | null;
    }>;
  }>;
}

interface StarterRouteOrderSummary {
  id?: number;
  orderKey?: string;
  number?: string;
  status?: string;
  paymentMethod?: string;
  shippingMethod?: string;
  billingAddress?: {
    firstName?: string;
    lastName?: string;
    company?: string;
    address1?: string;
    city?: string;
    postcode?: string;
    email?: string;
    phone?: string;
    oib?: string;
  };
  shippingAddress?: {
    firstName?: string;
    lastName?: string;
    address1?: string;
    city?: string;
    postcode?: string;
  };
  items?: Array<{
    id?: number;
    name?: string;
    quantity?: number;
    unitPrice?: string;
    taxTotal?: string;
    total?: string;
    meta?: Array<{
      label?: string;
      value?: string;
    }>;
  }>;
  subtotal?: string;
  taxTotal?: string;
  shippingTotal?: string;
  total?: string;
}

interface WooStoreImage {
  src?: string;
  alt?: string;
}

interface WooStoreTerm {
  id?: number;
  name?: string;
  slug?: string;
}

interface WooStoreProduct {
  id?: number;
  slug?: string;
  name?: string;
  type?: string;
  short_description?: string;
  description?: string;
  images?: WooStoreImage[];
  categories?: WooStoreTerm[];
  brands?: WooStoreTerm[];
  prices?: WooMoney & {
    price?: string;
    regular_price?: string;
    sale_price?: string;
  };
  is_on_sale?: boolean;
  is_in_stock?: boolean;
  attributes?: Array<{
    name?: string;
    terms?: WooStoreTerm[];
  }>;
}

interface WooStoreCategory {
  id?: number;
  name?: string;
  slug?: string;
  parent?: number;
  count?: number;
  image?: WooStoreImage | null;
}

const EMPTY_ARCHIVE: StorefrontArchivePage = {
  title: "Shop archive",
  description:
    "Dodaj proizvode u WooCommerce da bi se archive sadržaj prikazao u starteru.",
  totalResults: 0,
  products: [],
  filters: [],
  currentPage: 1,
  totalPages: 1,
  priceRange: null,
};

async function wooStoreFetchWithMeta<T>(
  path: string,
  init?: RequestInit,
): Promise<{ payload: T; response: Response }> {
  const response = await fetch(getWooStoreApiUrl(path), {
    ...init,
    headers: {
      Accept: "application/json",
      ...(init?.headers ?? {}),
    },
    cache: init?.cache ?? "no-store",
  });

  if (!response.ok) {
    let message = `Woo Store request failed for ${path}: ${response.status}`;

    try {
      const payload = (await response.json()) as { message?: string; code?: string };
      message = payload.message || payload.code || message;
    } catch {}

    throw new Error(message);
  }

  return {
    payload: (await response.json()) as T,
    response,
  };
}

export async function getStorefrontMenu(): Promise<StorefrontMenuItem[]> {
  try {
    const response = await starterRouteFetch<StarterRouteMenuResponse>("/menu");

    return (response.items ?? [])
      .map((item) => {
        const id = item.id?.trim();
        const label = item.label?.trim();
        const href = item.href?.trim();

        if (!id || !label || !href) {
          return null;
        }

        return { id, label, href };
      })
      .filter((item): item is StorefrontMenuItem => item !== null);
  } catch {
    return [
      { id: "shop", label: "Shop", href: "/shop" },
      { id: "blog", label: "Blog", href: "/blog" },
      { id: "wishlist", label: "Lista želja", href: "/wishlist" },
      { id: "cart", label: "Košarica", href: "/cart" },
      { id: "checkout", label: "Checkout", href: "/checkout" },
    ];
  }
}

export async function getHeaderNavigation(): Promise<StorefrontHeaderCategory[]> {
  try {
    const response = await starterRouteFetch<StarterRouteHeaderNavigationResponse>(
      "/header-navigation",
    );

    return (response.items ?? [])
      .map((item) => {
        if (
          typeof item.id !== "number" ||
          !item.name?.trim() ||
          !item.slug?.trim()
        ) {
          return null;
        }

        return {
          id: item.id,
          name: item.name.trim(),
          slug: item.slug.trim(),
          href: item.href?.trim() || `/shop?category=${item.slug.trim()}`,
          children: (item.children ?? [])
            .map((child) => {
              if (
                typeof child.id !== "number" ||
                !child.name?.trim() ||
                !child.slug?.trim()
              ) {
                return null;
              }

              return {
                id: child.id,
                name: child.name.trim(),
                slug: child.slug.trim(),
                href: child.href?.trim() || `/shop?category=${child.slug.trim()}`,
                image: mapImage(child.image),
              };
            })
            .filter(
              (child): child is StorefrontHeaderCategory["children"][number] =>
                child !== null,
            ),
        };
      })
      .filter((item): item is StorefrontHeaderCategory => item !== null);
  } catch {
    try {
      const { payload } = await wooStoreFetchWithMeta<WooStoreCategory[]>(
        "/products/categories?orderby=name&order=asc&per_page=100",
        { cache: "force-cache" },
      );
      const mappedCategories = payload
        .map((category) => {
          if (
            typeof category.id !== "number" ||
            !category.name?.trim() ||
            !category.slug?.trim()
          ) {
            return null;
          }

          return {
            id: category.id,
            name: category.name.trim(),
            slug: category.slug.trim(),
            href: `/shop?category=${category.slug.trim()}`,
            parent: typeof category.parent === "number" ? category.parent : 0,
            image: mapWooImage(category.image),
          };
        })
        .filter(
          (
            category,
          ): category is {
            id: number;
            name: string;
            slug: string;
            href: string;
            parent: number;
            image: StorefrontImage | null;
          } => category !== null,
        )
        .filter((category) => category.slug !== "uncategorized");

      const roots = mappedCategories.filter((category) => category.parent === 0);

      return roots.map((root) => ({
        id: root.id,
        name: root.name,
        slug: root.slug,
        href: root.href,
        children: mappedCategories
          .filter((category) => category.parent === root.id)
          .slice(0, 5)
          .map((child) => ({
            id: child.id,
            name: child.name,
            slug: child.slug,
            href: child.href,
            image: child.image,
          })),
      }));
    } catch {
      const categories = await getFeaturedCategories();

      return categories.map((category) => ({
        id: category.id,
        name: category.name,
        slug: category.slug,
        href: category.href,
        children: [],
      }));
    }
  }
}

export async function getSearchSuggestions(
  query: string,
): Promise<StorefrontSearchSuggestion[]> {
  const normalizedQuery = query.trim();

  if (normalizedQuery.length < 2) {
    return [];
  }

  try {
    const response = await starterRouteFetch<{ items?: StarterRouteProductCard[] }>(
      `/search-suggestions?q=${encodeURIComponent(normalizedQuery)}`,
      { cache: "no-store" },
    );

    return (response.items ?? [])
      .map((product) => {
        const card = mapProductCard(product);

        if (!card) {
          return null;
        }

        return {
          id: card.id,
          name: card.name,
          slug: card.slug,
          href: card.href,
          price: card.price,
          image: card.featuredImage,
          brand: card.brand,
        };
      })
      .filter((item): item is StorefrontSearchSuggestion => item !== null);
  } catch {
    const products = await getWooProductCards(
      `/products?search=${encodeURIComponent(normalizedQuery)}&per_page=6`,
    );

    return products.map((product) => ({
      id: product.id,
      name: product.name,
      slug: product.slug,
      href: product.href,
      price: product.price,
      image: product.featuredImage,
      brand: product.brand,
    }));
  }
}

export async function getFeaturedProducts(): Promise<StorefrontProductCard[]> {
  try {
    const response = await starterRouteFetch<{ items?: StarterRouteProductCard[] }>(
      "/featured-products",
    );

    return (response.items ?? [])
      .map(mapProductCard)
      .filter((product): product is StorefrontProductCard => product !== null);
  } catch {
    const featured = await getWooProductCards(
      "/products?on_sale=true&orderby=date&order=desc&per_page=100",
    );

    if (featured.length > 0) {
      return featured;
    }

    return [];
  }
}

export async function getFeaturedBanner(): Promise<StorefrontFeaturedBanner | null> {
  try {
    const response = await starterRouteFetch<StarterRouteFeaturedBannerResponse>(
      "/featured-banner",
    );

    if (typeof response.id !== "number" || !response.title?.trim()) {
      return null;
    }

    return {
      id: response.id,
      title: response.title.trim(),
      href: response.href?.trim() || undefined,
      image: mapImage(response.image),
    };
  } catch {
    return null;
  }
}

export async function getFeatureGridBanners(): Promise<StorefrontFeatureGridBanner[]> {
  try {
    const response = await starterRouteFetch<StarterRouteFeatureGridResponse>(
      "/feature-grid-banners",
    );

    return (response.items ?? [])
      .map((item) => {
        const id = item.id?.trim();
        const title = item.title?.trim();

        if (!id || !title) {
          return null;
        }

        const banner: StorefrontFeatureGridBanner = {
          id,
          title,
          image: mapImage(item.image),
        };

        const href = item.href?.trim();

        if (href) {
          banner.href = href;
        }

        return banner;
      })
      .filter((item): item is StorefrontFeatureGridBanner => item !== null);
  } catch {
    return [];
  }
}

export async function getStorefrontBrands(): Promise<StorefrontBrandItem[]> {
  try {
    const response = await starterRouteFetch<StarterRouteBrandsResponse>("/brands");

    return (response.items ?? [])
      .map((item) => {
        if (
          typeof item.id !== "number" ||
          !item.name?.trim() ||
          !item.slug?.trim()
        ) {
          return null;
        }

        const brand: StorefrontBrandItem = {
          id: item.id,
          name: item.name.trim(),
          slug: item.slug.trim(),
          image: mapImage(item.image) ?? undefined,
        };

        const href = item.href?.trim();

        if (href) {
          brand.href = href;
        }

        return brand;
      })
      .filter((item): item is StorefrontBrandItem => item !== null)
      .filter((item) => Boolean(item.image?.src));
  } catch {
    return [];
  }
}

export async function getFeaturedCategories(): Promise<StorefrontCategoryCard[]> {
  try {
    const { payload } = await wooStoreFetchWithMeta<WooStoreCategory[]>(
      "/products/categories?orderby=name&order=asc&per_page=100",
      { cache: "force-cache" },
    );

    return payload
      .map((category) => {
        if (
          typeof category.id !== "number" ||
          !category.name?.trim() ||
          !category.slug?.trim()
        ) {
          return null;
        }

        return {
          id: category.id,
          name: category.name.trim(),
          slug: category.slug.trim(),
          href: `/shop?category=${category.slug.trim()}`,
          parent: typeof category.parent === "number" ? category.parent : 0,
          count: typeof category.count === "number" ? category.count : 0,
          image: mapWooImage(category.image),
        };
      })
      .filter(
        (
          category,
        ): category is StorefrontCategoryCard & { parent: number } => category !== null,
      )
      .filter((category) => category.parent === 0)
      .filter(
        (category) =>
          category.slug !== "uncategorized" && category.slug !== "akcija",
      )
      .slice(0, 5)
      .map((category) => ({
        id: category.id,
        name: category.name,
        slug: category.slug,
        href: category.href,
        count: category.count,
        image: category.image,
      }));
  } catch {
    try {
      const response =
        await starterRouteFetch<StarterRouteCategoryResponse>("/featured-categories");

      return (response.items ?? [])
        .map((category) => {
          if (
            typeof category.id !== "number" ||
            !category.name?.trim() ||
            !category.slug?.trim()
          ) {
            return null;
          }

          return {
            id: category.id,
            name: category.name.trim(),
            slug: category.slug.trim(),
            href: category.href?.trim() || `/shop?category=${category.slug.trim()}`,
            parent: typeof category.parent === "number" ? category.parent : 0,
            count: typeof category.count === "number" ? category.count : 0,
            image: mapImage(category.image),
          };
        })
        .filter(
          (
            category,
          ): category is StorefrontCategoryCard & { parent: number } => category !== null,
        )
        .filter((category) => category.parent === 0)
        .filter(
          (category) =>
            category.slug !== "uncategorized" && category.slug !== "akcija",
        )
        .slice(0, 5)
        .map((category) => ({
          id: category.id,
          name: category.name,
          slug: category.slug,
          href: category.href,
          count: category.count,
          image: category.image,
        }));
    } catch {
      return [];
    }
  }
}

export async function getArchivePage(input?: {
  page?: number;
  perPage?: number;
  query?: string;
  categories?: string[];
  brands?: string[];
  sort?: "price-asc" | "price-desc";
  minPrice?: number;
  maxPrice?: number;
  onSale?: boolean;
}): Promise<StorefrontArchivePage> {
  try {
    const query = new URLSearchParams();
    const sort = input?.sort === "price-desc" ? "price-desc" : "price-asc";

    if (input?.page && input.page > 1) {
      query.set("page", String(input.page));
    }

    if (input?.perPage && input.perPage > 0) {
      query.set("per_page", String(input.perPage));
    }

    if (input?.query?.trim()) {
      query.set("q", input.query.trim());
    }

    if (input?.categories?.length) {
      query.set("category", input.categories.join(","));
    }

    if (input?.brands?.length) {
      query.set("brand", input.brands.join(","));
    }

    if (typeof input?.minPrice === "number" && Number.isFinite(input.minPrice)) {
      query.set("min_price", String(Math.max(0, Math.floor(input.minPrice))));
    }

    if (typeof input?.maxPrice === "number" && Number.isFinite(input.maxPrice)) {
      query.set("max_price", String(Math.max(0, Math.ceil(input.maxPrice))));
    }

    if (input?.onSale) {
      query.set("on_sale", "1");
    }

    query.set("sort", sort);

    const response = await starterRouteFetch<StarterRouteArchiveResponse>(
      `/archive${query.size > 0 ? `?${query.toString()}` : ""}`,
      { cache: "no-store" },
    );
    const filters: StorefrontArchivePage["filters"] = [];

    for (const filter of response.filters ?? []) {
      const id = filter.id?.trim();
      const label = filter.label?.trim();

      if (!id || !label) {
        continue;
      }

      const options: StorefrontArchivePage["filters"][number]["options"] = [];

      for (const option of filter.options ?? []) {
        const optionId = option.id?.trim();
        const optionLabel = option.label?.trim();

        if (!optionId || !optionLabel) {
          continue;
        }

        options.push({
          id: optionId,
          label: optionLabel,
          count: typeof option.count === "number" ? option.count : undefined,
        });
      }

      filters.push({
        id,
        label,
        type: "checkbox",
        options,
      });
    }

    const mappedProducts = (response.products ?? [])
      .map(mapProductCard)
      .filter((product): product is StorefrontProductCard => product !== null);
    const visibleProducts = input?.onSale
      ? mappedProducts.filter((product) => product.isOnSale)
      : mappedProducts;

    return {
      title: response.title?.trim() || EMPTY_ARCHIVE.title,
      description: response.description?.trim() || EMPTY_ARCHIVE.description,
      totalResults:
        typeof response.totalResults === "number"
          ? (input?.onSale ? visibleProducts.length : response.totalResults)
          : visibleProducts.length,
      currentPage:
        typeof response.currentPage === "number" ? response.currentPage : 1,
      totalPages: typeof response.totalPages === "number" ? response.totalPages : 1,
      priceRange:
        typeof response.priceRange?.min === "number" &&
        typeof response.priceRange?.max === "number"
          ? {
              min: response.priceRange.min,
              max: response.priceRange.max,
            }
          : null,
      products: visibleProducts,
      filters,
    };
  } catch {
    return getArchivePageFromWoo(input);
  }
}

export async function getProductBySlug(
  slug: string,
): Promise<StorefrontProductDetail | null> {
  try {
    const response = await starterRouteFetch<StarterRouteProductResponse>(
      `/product?slug=${encodeURIComponent(slug)}`,
      { cache: "no-store" },
    );
    const card = mapProductCard(response);

    if (!card) {
      return null;
    }

    const tabs = {
      descriptionHtml:
        response.tabs?.descriptionHtml?.trim() ||
        response.descriptionHtml?.trim() ||
        "",
      technicalDetailsHtml:
        response.tabs?.technicalDetailsHtml?.trim() || "",
      downloadsHtml: response.tabs?.downloadsHtml?.trim() || "",
      sizeChartHtml: response.tabs?.sizeChartHtml?.trim() || "",
    };
    const relatedProducts = card.category?.slug
      ? await getArchivePage({
          categories: [card.category.slug],
          page: 1,
          perPage: 8,
        }).then((archive) =>
          archive.products.filter((product) => product.id !== card.id).slice(0, 4),
        )
      : [];

    return {
      ...card,
      description:
        card.shortDescription?.trim() ||
        stripHtml(tabs.descriptionHtml) ||
        response.description?.trim() ||
        "",
      gallery: (response.gallery ?? [])
        .map(mapImage)
        .filter((image): image is StorefrontImage => image !== null),
      breadcrumbs: [
        { label: "Trgovina", href: "/shop" },
        ...(card.category
          ? [
              {
                label: card.category.name,
                href: `/shop?category=${encodeURIComponent(card.category.slug)}`,
              },
            ]
          : []),
        { label: card.name },
      ],
      attributes: (response.attributes ?? [])
        .map((attribute) => {
          const label = attribute.label?.trim();
          const value = attribute.value?.trim();

          if (!label || !value) {
            return null;
          }

          return { label, value };
        })
        .filter(
          (
            attribute,
          ): attribute is StorefrontProductDetail["attributes"][number] =>
            attribute !== null,
        ),
      variations: (response.variations ?? [])
        .map(mapProductVariation)
        .filter(
          (
            variation,
          ): variation is StorefrontProductVariation => variation !== null,
        ),
      relatedProducts,
      tabs,
    };
  } catch {
    return getProductBySlugFromWoo(slug);
  }
}

export async function getOrderSummary(
  orderId: number,
  orderKey: string,
): Promise<StorefrontOrderSummary | null> {
  if (!Number.isInteger(orderId) || orderId < 1 || !orderKey.trim()) {
    return null;
  }

  try {
    const response = await starterRouteFetch<StarterRouteOrderSummary>(
      `/order-summary?order_id=${orderId}&key=${encodeURIComponent(orderKey)}`,
      { cache: "no-store" },
    );

    if (
      typeof response.id !== "number" ||
      !response.number?.trim() ||
      !response.orderKey?.trim()
    ) {
      return null;
    }

    return {
      id: response.id,
      orderKey: response.orderKey.trim(),
      number: response.number.trim(),
      status: response.status?.trim() || "",
      paymentMethod: response.paymentMethod?.trim() || "",
      shippingMethod: response.shippingMethod?.trim() || "",
      billingAddress: {
        firstName: response.billingAddress?.firstName?.trim() || "",
        lastName: response.billingAddress?.lastName?.trim() || "",
        company: response.billingAddress?.company?.trim() || undefined,
        address1: response.billingAddress?.address1?.trim() || "",
        city: response.billingAddress?.city?.trim() || "",
        postcode: response.billingAddress?.postcode?.trim() || "",
        email: response.billingAddress?.email?.trim() || "",
        phone: response.billingAddress?.phone?.trim() || "",
        oib: response.billingAddress?.oib?.trim() || undefined,
      },
      shippingAddress: {
        firstName: response.shippingAddress?.firstName?.trim() || "",
        lastName: response.shippingAddress?.lastName?.trim() || "",
        address1: response.shippingAddress?.address1?.trim() || "",
        city: response.shippingAddress?.city?.trim() || "",
        postcode: response.shippingAddress?.postcode?.trim() || "",
      },
      items: (response.items ?? [])
        .map((item) => {
          if (
            typeof item.id !== "number" ||
            !item.name?.trim() ||
            typeof item.quantity !== "number"
          ) {
            return null;
          }

          const mappedItem: StorefrontOrderSummary["items"][number] = {
            id: item.id,
            name: item.name.trim(),
            quantity: item.quantity,
            unitPrice: item.unitPrice?.trim() || undefined,
            taxTotal: item.taxTotal?.trim() || undefined,
            total: item.total?.trim() || "0,00 €",
            meta: (item.meta ?? [])
              .map((entry) => {
                const label = entry.label?.trim();
                const value = entry.value?.trim();

                if (!label || !value) {
                  return null;
                }

                return { label, value };
              })
              .filter(
                (
                  entry,
                ): entry is StorefrontOrderSummary["items"][number]["meta"][number] =>
                  entry !== null,
              ),
          };

          return mappedItem;
        })
        .filter(
          (item): item is StorefrontOrderSummary["items"][number] => item !== null,
        ),
      subtotal: response.subtotal?.trim() || "0,00 €",
      taxTotal: response.taxTotal?.trim() || undefined,
      shippingTotal: response.shippingTotal?.trim() || "0,00 €",
      total: response.total?.trim() || "0,00 €",
    };
  } catch {
    return null;
  }
}

function mapProductCard(product: StarterRouteProductCard): StorefrontProductCard | null {
  if (
    typeof product.id !== "number" ||
    !product.slug?.trim() ||
    !product.name?.trim()
  ) {
    return null;
  }

  return {
    id: product.id,
    slug: product.slug.trim(),
    href: product.href?.trim() || `/product/${product.slug.trim()}`,
    name: product.name.trim(),
    type: product.type?.trim() || "simple",
    shortDescription: product.shortDescription?.trim() || "",
    featuredImage: mapImage(product.featuredImage),
    category: mapTerm(product.category),
    brand: mapTerm(product.brand),
    price: normalizePrice(product.price),
    regularPrice: product.regularPrice?.trim() || undefined,
    salePrice: product.salePrice?.trim() || undefined,
    lowestPrice30d: product.lowestPrice30d?.trim() || undefined,
    isOnSale: Boolean(product.isOnSale),
    isInStock: product.isInStock !== false,
  };
}

function mapProductVariation(
  variation: StarterRouteProductVariation,
): StorefrontProductVariation | null {
  if (typeof variation.id !== "number") {
    return null;
  }

  const attributes: StorefrontProductVariation["attributes"] = [];

  for (const attribute of variation.attributes ?? []) {
    const key = attribute.key?.trim();
    const label = attribute.label?.trim();
    const value = attribute.value?.trim();

    if (!key || !label || !value) {
      continue;
    }

    attributes.push({
      key,
      label,
      value,
      slug: attribute.slug?.trim() || undefined,
    });
  }

  return {
    id: variation.id,
    price: normalizePrice(variation.price),
    regularPrice: variation.regularPrice?.trim() || undefined,
    salePrice: variation.salePrice?.trim() || undefined,
    lowestPrice30d: variation.lowestPrice30d?.trim() || undefined,
    isOnSale: Boolean(variation.isOnSale),
    isInStock: variation.isInStock !== false,
    attributes,
  };
}

function mapTerm(term?: StarterRouteTerm | null): StorefrontTerm | null {
  if (!term || typeof term.id !== "number" || !term.name?.trim() || !term.slug?.trim()) {
    return null;
  }

  return {
    id: term.id,
    name: term.name.trim(),
    slug: term.slug.trim(),
  };
}

function mapWooTerm(term?: WooStoreTerm | null): StorefrontTerm | null {
  if (!term || typeof term.id !== "number" || !term.name?.trim() || !term.slug?.trim()) {
    return null;
  }

  return {
    id: term.id,
    name: term.name.trim(),
    slug: term.slug.trim(),
  };
}

function mapImage(image?: StarterRouteImage | null): StorefrontImage | null {
  if (!image?.src?.trim()) {
    return null;
  }

  return {
    src: image.src.trim(),
    alt: image.alt?.trim() || "",
  };
}

function mapWooImage(image?: WooStoreImage | null): StorefrontImage | null {
  if (!image?.src?.trim()) {
    return null;
  }

  return {
    src: image.src.trim(),
    alt: image.alt?.trim() || "",
  };
}

function normalizePrice(value?: string) {
  return value?.trim() || "0,00 €";
}

function mapWooMoney(
  value: string | undefined,
  money: WooMoney | undefined,
): string {
  if (!money || !value) {
    return "0,00 €";
  }

  return formatWooMoney(value, money);
}

function mapWooCategoryCard(
  category: WooStoreCategory,
): StorefrontCategoryCard | null {
  if (
    typeof category.id !== "number" ||
    !category.name?.trim() ||
    !category.slug?.trim()
  ) {
    return null;
  }

  return {
    id: category.id,
    name: category.name.trim(),
    slug: category.slug.trim(),
    href: `/shop?category=${category.slug.trim()}`,
    count: typeof category.count === "number" ? category.count : 0,
    image: mapWooImage(category.image),
  };
}

function mapWooProductCard(product: WooStoreProduct): StorefrontProductCard | null {
  if (
    typeof product.id !== "number" ||
    !product.slug?.trim() ||
    !product.name?.trim()
  ) {
    return null;
  }

  const prices = product.prices;
  const price = mapWooMoney(prices?.price, prices);
  const regularPrice =
    prices?.regular_price && Number(prices.regular_price) > 0
      ? formatWooMoney(prices.regular_price, prices)
      : undefined;
  const salePrice =
    prices?.sale_price && Number(prices.sale_price) > 0
      ? formatWooMoney(prices.sale_price, prices)
      : undefined;

  return {
    id: product.id,
    slug: product.slug.trim(),
    href: `/product/${product.slug.trim()}`,
    name: product.name.trim(),
    type: product.type?.trim() || "simple",
    shortDescription: stripHtml(product.short_description),
    featuredImage: mapWooImage(product.images?.[0]),
    category: mapWooTerm(product.categories?.[0]),
    brand: mapWooTerm(product.brands?.[0]),
    price,
    regularPrice,
    salePrice,
    isOnSale: Boolean(product.is_on_sale),
    isInStock: product.is_in_stock !== false,
  };
}

async function getWooProductCards(path: string) {
  const { payload } = await wooStoreFetchWithMeta<WooStoreProduct[]>(path, {
    cache: "no-store",
  });

  return payload
    .map(mapWooProductCard)
    .filter((product): product is StorefrontProductCard => product !== null);
}

async function getArchivePageFromWoo(input?: {
  page?: number;
  perPage?: number;
  query?: string;
  categories?: string[];
  brands?: string[];
  sort?: "price-asc" | "price-desc";
  minPrice?: number;
  maxPrice?: number;
  onSale?: boolean;
}): Promise<StorefrontArchivePage> {
  try {
    const perPage = input?.perPage && input.perPage > 0 ? input.perPage : 15;
    const sort = input?.sort === "price-desc" ? "price-desc" : "price-asc";
    const params = new URLSearchParams({
      page: String(input?.page && input.page > 0 ? input.page : 1),
      per_page: String(perPage),
      orderby: "price",
      order: sort === "price-desc" ? "desc" : "asc",
    });

    if (input?.categories?.length) {
      params.set("category", input.categories.join(","));
    }

    if (input?.brands?.length) {
      params.set("brand", input.brands.join(","));
    }

    if (input?.query?.trim()) {
      params.set("search", input.query.trim());
    }

    if (typeof input?.minPrice === "number" && Number.isFinite(input.minPrice)) {
      params.set("min_price", String(Math.max(0, Math.floor(input.minPrice))));
    }

    if (typeof input?.maxPrice === "number" && Number.isFinite(input.maxPrice)) {
      params.set("max_price", String(Math.max(0, Math.ceil(input.maxPrice))));
    }

    if (input?.onSale) {
      params.set("on_sale", "true");
    }

    const [{ payload: products, response }, { payload: categories }] =
      await Promise.all([
        wooStoreFetchWithMeta<WooStoreProduct[]>(`/products?${params.toString()}`, {
          cache: "no-store",
        }),
        wooStoreFetchWithMeta<WooStoreCategory[]>(
          "/products/categories?orderby=name&order=asc&per_page=100",
          { cache: "force-cache" },
        ),
      ]);

    const productCards = products
      .map(mapWooProductCard)
      .filter((product): product is StorefrontProductCard => product !== null);
    const visibleProductCards = input?.onSale
      ? productCards.filter((product) => product.isOnSale)
      : productCards;
    const categoryOptions = categories
      .map(mapWooCategoryCard)
      .filter((category): category is StorefrontCategoryCard => category !== null)
      .filter((category) => category.slug !== "uncategorized");
    const totalResults = Number(response.headers.get("X-WP-Total") ?? productCards.length);
    const totalPages = Number(response.headers.get("X-WP-TotalPages") ?? 1);
    const visiblePrices = productCards
      .map((product) => parsePriceNumber(product.price))
      .filter((price): price is number => price !== null);

    return {
      title: input?.onSale ? "Akcija" : "Shop",
      description: input?.query?.trim()
        ? `Rezultati pretrage za pojam "${input.query.trim()}".`
        : input?.onSale
          ? "Pregled proizvoda na akciji."
          : "Pregled svih proizvoda sinkroniziran iz WooCommerce Store API-ja.",
      totalResults: Number.isFinite(totalResults)
        ? (input?.onSale ? visibleProductCards.length : totalResults)
        : visibleProductCards.length,
      currentPage: input?.page && input.page > 0 ? input.page : 1,
      totalPages: Number.isFinite(totalPages) ? totalPages : 1,
      priceRange:
        visiblePrices.length > 0
          ? {
              min: Math.min(...visiblePrices),
              max: Math.max(...visiblePrices),
            }
          : null,
      products: visibleProductCards,
      filters:
        categoryOptions.length > 0
          ? [
              {
                id: "categories",
                label: "Kategorije",
                type: "checkbox",
                options: categoryOptions.map((category) => ({
                  id: category.slug,
                  label: category.name,
                  count: category.count,
                })),
              },
            ]
          : [],
    };
  } catch {
    return EMPTY_ARCHIVE;
  }
}

function parsePriceNumber(value: string) {
  const normalized = value.replace(/[^\d,.-]/g, "").replace(/\./g, "").replace(",", ".");
  const amount = Number.parseFloat(normalized);
  return Number.isFinite(amount) ? amount : null;
}

async function getProductBySlugFromWoo(
  slug: string,
): Promise<StorefrontProductDetail | null> {
  try {
    const { payload } = await wooStoreFetchWithMeta<WooStoreProduct[]>(
      `/products?slug=${encodeURIComponent(slug)}`,
      { cache: "no-store" },
    );
    const rawProduct = payload[0];
    const card = rawProduct ? mapWooProductCard(rawProduct) : null;

    if (!rawProduct || !card) {
      return null;
    }

    const relatedProducts = card.category?.slug
      ? await getWooProductCards(
          `/products?category=${encodeURIComponent(card.category.slug)}&per_page=8`,
        )
      : [];
    const tabs = {
      descriptionHtml: rawProduct.description || "",
      technicalDetailsHtml: "",
      downloadsHtml: "",
      sizeChartHtml: "",
    };

    return {
      ...card,
      description:
        card.shortDescription?.trim() ||
        stripHtml(tabs.descriptionHtml) ||
        "",
      gallery: (rawProduct.images ?? [])
        .map(mapWooImage)
        .filter((image): image is StorefrontImage => image !== null),
      breadcrumbs: [
        { label: "Trgovina", href: "/shop" },
        ...(card.category
          ? [
              {
                label: card.category.name,
                href: `/shop?category=${encodeURIComponent(card.category.slug)}`,
              },
            ]
          : []),
        { label: card.name },
      ],
      attributes: (rawProduct.attributes ?? [])
        .map((attribute) => {
          const label = attribute.name?.trim();
          const value = attribute.terms?.map((term) => term.name?.trim()).filter(Boolean).join(", ");

          if (!label || !value) {
            return null;
          }

          return { label, value };
        })
        .filter(
          (
            attribute,
          ): attribute is StorefrontProductDetail["attributes"][number] =>
            attribute !== null,
        ),
      variations: [],
      relatedProducts: relatedProducts.filter((product) => product.id !== card.id).slice(0, 4),
      tabs,
    };
  } catch {
    return null;
  }
}

function stripHtml(value?: string) {
  return (value ?? "").replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
}
