"use client";
import * as React from 'react';
import { useMemo, Fragment as Fragment$1, useState, useCallback } from 'react';
import { useForm, Form, Field } from '@page-speed/forms';
import { TextInput as TextInput$1 } from '@page-speed/forms/inputs';
import { Img } from '@page-speed/img';
import { clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
import { Pressable } from '@page-speed/pressable';
import { Icon } from '@page-speed/icon';
import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
import { Slot } from '@radix-ui/react-slot';
import { cva } from 'class-variance-authority';
import * as AspectRatioPrimitive from '@radix-ui/react-aspect-ratio';
import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
import * as LabelPrimitive from '@radix-ui/react-label';
import { submitPageSpeedForm, PageSpeedFormSubmissionError, isValidEmail } from '@page-speed/forms/integration';

// components/blocks/resource-list/resource-list-hero-filter.tsx
var TextInput = TextInput$1;
function cn(...inputs) {
  return twMerge(clsx(inputs));
}
function getNestedCardBg(parentBg, variant = "muted", options) {
  {
    switch (variant) {
      case "muted":
        return "bg-muted";
      case "card":
        return "bg-card";
      case "accent":
        return "bg-accent";
      case "subtle":
        return "bg-muted/50";
    }
  }
}
function getNestedCardTextColor(parentBg, options) {
  const isDark = parentBg === "primary";
  return isDark ? "text-foreground" : "";
}
var DEFAULT_ICON_API_KEY = "au382bi7fsh96w9h9xlrnat2jglx";
var DynamicIcon = React.memo(function DynamicIcon2({
  apiKey,
  name,
  ...props
}) {
  if (name == null) return null;
  if (typeof name !== "string") {
    return /* @__PURE__ */ jsx(Fragment, { children: name });
  }
  return /* @__PURE__ */ jsx(Icon, { ...props, name, apiKey: apiKey ?? DEFAULT_ICON_API_KEY });
});
DynamicIcon.displayName = "DynamicIcon";
var badgeVariants = cva(
  "inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
  {
    variants: {
      variant: {
        default: "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
        secondary: "border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
        destructive: "border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
        outline: "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"
      }
    },
    defaultVariants: {
      variant: "default"
    }
  }
);
function Badge({
  className,
  variant,
  asChild = false,
  ...props
}) {
  const Comp = asChild ? Slot : "span";
  return /* @__PURE__ */ jsx(
    Comp,
    {
      "data-slot": "badge",
      className: cn(badgeVariants({ variant }), className),
      ...props
    }
  );
}
function Card({ className, ...props }) {
  return /* @__PURE__ */ jsx(
    "div",
    {
      "data-slot": "card",
      className: cn(
        "bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
        className
      ),
      ...props
    }
  );
}
function CardContent({ className, ...props }) {
  return /* @__PURE__ */ jsx(
    "div",
    {
      "data-slot": "card-content",
      className: cn("px-6", className),
      ...props
    }
  );
}
function AspectRatio({
  ...props
}) {
  return /* @__PURE__ */ jsx(AspectRatioPrimitive.Root, { "data-slot": "aspect-ratio", ...props });
}
function Checkbox({
  className,
  ...props
}) {
  return /* @__PURE__ */ jsx(
    CheckboxPrimitive.Root,
    {
      "data-slot": "checkbox",
      className: cn(
        "peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
        className
      ),
      ...props,
      children: /* @__PURE__ */ jsx(
        CheckboxPrimitive.Indicator,
        {
          "data-slot": "checkbox-indicator",
          className: "grid place-content-center text-current transition-none",
          children: /* @__PURE__ */ jsx(DynamicIcon, { name: "lucide/check", size: 14 })
        }
      )
    }
  );
}
function Label({
  className,
  ...props
}) {
  return /* @__PURE__ */ jsx(
    LabelPrimitive.Root,
    {
      "data-slot": "label",
      className: cn(
        "flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
        className
      ),
      ...props
    }
  );
}
function Breadcrumb({ ...props }) {
  return /* @__PURE__ */ jsx("nav", { "aria-label": "breadcrumb", "data-slot": "breadcrumb", ...props });
}
function BreadcrumbList({ className, ...props }) {
  return /* @__PURE__ */ jsx(
    "ol",
    {
      "data-slot": "breadcrumb-list",
      className: cn(
        "flex flex-wrap items-center gap-1.5 text-sm wrap-break-word sm:gap-2.5",
        className
      ),
      ...props
    }
  );
}
function BreadcrumbItem({ className, ...props }) {
  return /* @__PURE__ */ jsx(
    "li",
    {
      "data-slot": "breadcrumb-item",
      className: cn("inline-flex items-center gap-1.5", className),
      ...props
    }
  );
}
function BreadcrumbLink({
  asChild,
  className,
  ...props
}) {
  const Comp = asChild ? Slot : "a";
  return /* @__PURE__ */ jsx(
    Comp,
    {
      "data-slot": "breadcrumb-link",
      className: cn("hover:underline transition-colors", className),
      ...props
    }
  );
}
function BreadcrumbSeparator({
  children,
  className,
  ...props
}) {
  return /* @__PURE__ */ jsx(
    "li",
    {
      "data-slot": "breadcrumb-separator",
      role: "presentation",
      "aria-hidden": "true",
      className: cn("[&>svg]:size-3.5", className),
      ...props,
      children: children ?? /* @__PURE__ */ jsx(DynamicIcon, { name: "lucide/chevron-right", size: 14 })
    }
  );
}

// lib/patternSvgs.ts
var patternSvgs = {
  dotPattern2: "https://cdn.ing/assets/files/record/286189/arez6gd2s7isn9i1o6c7sexdq7bl"};
var FilterForm = ({ categories, onCategoryChange }) => {
  const [selectedItems, setSelectedItems] = useState(["all"]);
  const handleCheckboxChange = useCallback(
    (checked, categoryValue) => {
      let updatedValues = checked ? [...selectedItems, categoryValue] : selectedItems.filter((value) => value !== categoryValue);
      if (updatedValues.length === 0) {
        setSelectedItems(["all"]);
        onCategoryChange(["all"]);
        return;
      }
      if (updatedValues.includes("all") && categoryValue !== "all") {
        updatedValues = updatedValues.filter((v) => v !== "all");
      }
      if (categoryValue === "all" && checked) {
        updatedValues = ["all"];
      }
      setSelectedItems(updatedValues);
      onCategoryChange(updatedValues);
    },
    [selectedItems, onCategoryChange]
  );
  return /* @__PURE__ */ jsx("div", { className: "flex w-full flex-wrap items-center gap-2.5", children: categories.map((category) => {
    const isChecked = selectedItems.includes(category.value);
    return /* @__PURE__ */ jsxs(
      Label,
      {
        className: "flex cursor-pointer items-center gap-2.5 rounded-full bg-muted px-2.5 py-1.5",
        children: [
          /* @__PURE__ */ jsx("span", { children: category.label }),
          /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: isChecked,
              onCheckedChange: (checked) => handleCheckboxChange(!!checked, category.value)
            }
          )
        ]
      },
      category.value
    );
  }) });
};
var ResourcesResult = ({
  posts,
  categories,
  postsPerPage,
  loadMoreText,
  categoriesClassName,
  postsClassName,
  optixFlowConfig
}) => {
  const [visibleCount, setVisibleCount] = useState(postsPerPage);
  const [selectedCategories, setSelectedCategories] = useState([
    "all"
  ]);
  const handleCategoryChange = useCallback((selected) => {
    setSelectedCategories(selected);
    setVisibleCount(postsPerPage);
  }, [postsPerPage]);
  const handleLoadMore = useCallback(() => {
    setVisibleCount((prev) => prev + postsPerPage);
  }, [postsPerPage]);
  const filteredPosts = useMemo(() => {
    return posts.filter(
      (post) => selectedCategories.includes(post.category.toLowerCase()) || selectedCategories.includes("all")
    );
  }, [posts, selectedCategories]);
  const postsToDisplay = filteredPosts.length > 0 ? filteredPosts : posts;
  const hasMore = visibleCount < postsToDisplay.length;
  return /* @__PURE__ */ jsxs("div", { children: [
    /* @__PURE__ */ jsx("div", { className: categoriesClassName, children: /* @__PURE__ */ jsx(
      FilterForm,
      {
        categories,
        onCategoryChange: handleCategoryChange
      }
    ) }),
    /* @__PURE__ */ jsxs("div", { className: cn("flex w-full flex-col gap-4 py-8", postsClassName), children: [
      /* @__PURE__ */ jsx("div", { className: "grid gap-10 md:grid-cols-2 lg:grid-cols-3", children: postsToDisplay.slice(0, visibleCount).map((post, idx) => /* @__PURE__ */ jsx(ResourceCard, { ...post, optixFlowConfig }, idx)) }),
      hasMore && /* @__PURE__ */ jsx(
        Pressable,
        {
          className: "w-full",
          variant: "secondary",
          asButton: true,
          onClick: handleLoadMore,
          children: loadMoreText
        }
      )
    ] })
  ] });
};
var BreadcrumbBlog = ({ breadcrumb }) => {
  return /* @__PURE__ */ jsx(Breadcrumb, { children: /* @__PURE__ */ jsx(BreadcrumbList, { children: breadcrumb.map((item, i) => {
    return /* @__PURE__ */ jsxs(Fragment$1, { children: [
      /* @__PURE__ */ jsx(BreadcrumbItem, { children: /* @__PURE__ */ jsx(BreadcrumbLink, { href: item.link, children: item.label }) }),
      i < breadcrumb.length - 1 ? /* @__PURE__ */ jsx(BreadcrumbSeparator, { children: /* @__PURE__ */ jsx(DynamicIcon, { name: "lucide/slash", size: 16 }) }) : null
    ] }, `${item.label}`);
  }) }) });
};
var EmailForm = ({
  emailPlaceholder,
  buttonText,
  formConfig,
  onSubmit,
  onSuccess,
  onError
}) => {
  const form = useForm({
    initialValues: {
      email: ""
    },
    validationSchema: {
      email: (value) => {
        if (!value) return "Email is required";
        if (!isValidEmail(value)) return "Please enter a valid email address";
        return void 0;
      }
    },
    onSubmit: async (values, helpers) => {
      const shouldAutoSubmit = Boolean(formConfig?.endpoint);
      if (!shouldAutoSubmit && !onSubmit) {
        return;
      }
      try {
        let result;
        if (shouldAutoSubmit) {
          result = await submitPageSpeedForm(values, formConfig);
        }
        if (onSubmit) {
          await onSubmit(values.email);
        }
        if (shouldAutoSubmit || onSubmit) {
          if (formConfig?.resetOnSuccess !== false) {
            helpers.resetForm();
          }
          onSuccess?.(result);
        }
      } catch (error) {
        if (error instanceof PageSpeedFormSubmissionError && error.formErrors) {
          helpers.setErrors(error.formErrors);
        }
        onError?.(error);
        throw error;
      }
    }
  });
  const formMethod = formConfig?.method?.toLowerCase() === "get" ? "get" : "post";
  return /* @__PURE__ */ jsx(
    Form,
    {
      form,
      action: formConfig?.endpoint,
      method: formMethod,
      className: "w-full",
      children: /* @__PURE__ */ jsx(Field, { name: "email", children: ({ field, meta }) => /* @__PURE__ */ jsxs("div", { className: "w-full", children: [
        /* @__PURE__ */ jsxs("div", { className: "relative flex w-full flex-col gap-2 lg:block", children: [
          /* @__PURE__ */ jsx(
            TextInput,
            {
              ...field,
              type: "email",
              placeholder: emailPlaceholder,
              error: meta.touched && !!meta.error,
              className: "h-fit bg-background py-4 pr-5 pl-5 lg:pr-55",
              "aria-label": emailPlaceholder
            }
          ),
          /* @__PURE__ */ jsx("div", { className: "top-1/2 right-2.5 lg:absolute lg:-translate-y-1/2", children: /* @__PURE__ */ jsxs(
            Pressable,
            {
              componentType: "button",
              type: "submit",
              className: "w-full rounded-full lg:w-fit",
              variant: "default",
              asButton: true,
              disabled: form.isSubmitting,
              children: [
                buttonText,
                /* @__PURE__ */ jsx(DynamicIcon, { name: "lucide/arrow-right", size: 16, className: "ml-2" })
              ]
            }
          ) })
        ] }),
        meta.touched && meta.error && /* @__PURE__ */ jsx("p", { className: "py-1 text-sm text-destructive", children: meta.error })
      ] }) })
    }
  );
};
var ResourceCard = ({
  category,
  categoryLabel,
  title,
  thumbnail,
  summary,
  link,
  cta,
  className,
  optixFlowConfig
}) => {
  return /* @__PURE__ */ jsx(Pressable, { href: link, className: cn("block h-full w-full", className), children: /* @__PURE__ */ jsx(Card, { className: "size-full border py-0", children: /* @__PURE__ */ jsxs(CardContent, { className: "p-0", children: [
    /* @__PURE__ */ jsx("div", { className: "border-b p-2.5 text-sm leading-[1.2] font-medium text-muted-foreground", children: categoryLabel ?? category }),
    /* @__PURE__ */ jsx(AspectRatio, { ratio: 1.520833333, className: "overflow-hidden", children: /* @__PURE__ */ jsx(
      Img,
      {
        src: thumbnail,
        alt: typeof title === "string" ? title : "Resource",
        className: "block size-full object-cover object-center",
        optixFlowConfig
      }
    ) }),
    /* @__PURE__ */ jsxs("div", { className: "flex w-full flex-col gap-5 p-5", children: [
      typeof title === "string" ? /* @__PURE__ */ jsx("h2", { className: "text-lg leading-none font-bold md:text-2xl", children: title }) : /* @__PURE__ */ jsx("div", { className: "text-lg leading-none font-bold md:text-2xl", children: title }),
      /* @__PURE__ */ jsx("div", { className: "w-full max-w-[20rem]", children: typeof summary === "string" ? /* @__PURE__ */ jsx("p", { className: "text-sm leading-[1.4] font-medium", children: summary }) : /* @__PURE__ */ jsx("div", { className: "text-sm leading-[1.4] font-medium", children: summary }) }),
      /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs(Badge, { className: "rounded-full", children: [
        cta,
        /* @__PURE__ */ jsx(DynamicIcon, { name: "lucide/arrow-right", size: 14, className: "ml-1" })
      ] }) })
    ] })
  ] }) }) });
};
function ResourceListHeroFilter({
  className,
  title,
  titleClassName,
  description,
  descriptionClassName,
  breadcrumb,
  breadcrumbSlot,
  breadcrumbClassName,
  primaryPost,
  primaryPostSlot,
  primaryPostClassName,
  posts,
  postsSlot,
  postsClassName,
  categories,
  categoriesClassName,
  allPostsTitle,
  allPostsTitleClassName,
  emailPlaceholder,
  buttonText,
  postsPerPage = 6,
  loadMoreText,
  heroClassName,
  contentClassName,
  heroPatternUrl,
  heroPatternSize,
  formConfig,
  onSubmit,
  onSuccess,
  onError,
  optixFlowConfig
}) {
  const renderedBreadcrumb = useMemo(() => {
    if (breadcrumbSlot) return breadcrumbSlot;
    if (!breadcrumb || breadcrumb.length === 0) return null;
    return /* @__PURE__ */ jsx("div", { className: breadcrumbClassName, children: /* @__PURE__ */ jsx(BreadcrumbBlog, { breadcrumb }) });
  }, [breadcrumbSlot, breadcrumb, breadcrumbClassName]);
  const renderedPrimaryPost = useMemo(() => {
    if (primaryPostSlot) return primaryPostSlot;
    if (!primaryPost) return null;
    return /* @__PURE__ */ jsx("div", { className: cn("w-full max-w-110", primaryPostClassName), children: /* @__PURE__ */ jsx(ResourceCard, { ...primaryPost, optixFlowConfig }) });
  }, [primaryPostSlot, primaryPost, primaryPostClassName, optixFlowConfig]);
  const renderedPosts = useMemo(() => {
    if (postsSlot) return postsSlot;
    if (!posts || posts.length === 0) return null;
    return /* @__PURE__ */ jsx(
      ResourcesResult,
      {
        posts,
        categories: categories ?? [],
        postsPerPage,
        loadMoreText,
        categoriesClassName,
        postsClassName,
        optixFlowConfig
      }
    );
  }, [postsSlot, posts, categories, postsPerPage, loadMoreText, categoriesClassName, postsClassName, optixFlowConfig]);
  return /* @__PURE__ */ jsxs("section", { className: cn("pb-32", className), children: [
    /* @__PURE__ */ jsx(
      "div",
      {
        className: cn(
          "bg-repeat",
          getNestedCardBg(),
          getNestedCardTextColor(void 0),
          heroClassName
        ),
        style: {
          backgroundImage: `url('${heroPatternUrl ?? patternSvgs.dotPattern2}')`,
          backgroundSize: heroPatternSize
        },
        children: /* @__PURE__ */ jsxs("div", { className: "container flex flex-col items-start justify-start gap-16 py-20 lg:flex-row lg:items-center lg:justify-between", children: [
          /* @__PURE__ */ jsx("div", { className: "flex w-full flex-col justify-between gap-12", children: /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-xl flex-col gap-8", children: [
            renderedBreadcrumb,
            /* @__PURE__ */ jsxs("div", { className: "flex w-full flex-col gap-5", children: [
              title && (typeof title === "string" ? /* @__PURE__ */ jsx("h1", { className: cn("text-[2.5rem] leading-[1.2] font-semibold md:text-5xl lg:text-6xl", titleClassName), children: title }) : /* @__PURE__ */ jsx("div", { className: titleClassName, children: title })),
              description && (typeof description === "string" ? /* @__PURE__ */ jsx("p", { className: cn("text-xl leading-[1.4] font-semibold", descriptionClassName), children: description }) : /* @__PURE__ */ jsx("div", { className: descriptionClassName, children: description }))
            ] }),
            /* @__PURE__ */ jsx("div", { className: "max-w-120", children: /* @__PURE__ */ jsx(
              EmailForm,
              {
                emailPlaceholder,
                buttonText,
                formConfig,
                onSubmit,
                onSuccess,
                onError
              }
            ) })
          ] }) }),
          renderedPrimaryPost
        ] })
      }
    ),
    /* @__PURE__ */ jsx("div", { className: cn("py-20", contentClassName), children: /* @__PURE__ */ jsxs("div", { className: "container flex flex-col gap-8", children: [
      allPostsTitle && (typeof allPostsTitle === "string" ? /* @__PURE__ */ jsx("h2", { className: cn("text-[1.75rem] leading-none font-medium md:text-[2.25rem] lg:text-[2rem]", allPostsTitleClassName), children: allPostsTitle }) : /* @__PURE__ */ jsx("div", { className: allPostsTitleClassName, children: allPostsTitle })),
      /* @__PURE__ */ jsx("div", { children: renderedPosts })
    ] }) })
  ] });
}

export { ResourceListHeroFilter };
