import { createContext, useMemo, useState, useCallback, useEffect, useContext, useRef } from 'react';
import { Box, Progress, Text, Group, Button, Kbd, Modal, Stack, Transition, Title, UnstyledButton, TextInput, Textarea, Center, Alert, Card, ActionIcon, Paper } from '@mantine/core';
import { IconArrowLeft, IconCheck, IconArrowRight, IconPlus, IconPencil, IconTrash, IconX } from '@tabler/icons-react';
import { createPortal } from 'react-dom';
import { jsxs, jsx, Fragment } from 'react/jsx-runtime';

// src/components/typeform/TypeformSurvey.tsx
function normalizeToPages(config) {
  if (config.pages && config.pages.length > 0) {
    return config.pages;
  }
  if (config.questions && config.questions.length > 0) {
    return config.questions.map((q) => ({
      id: `page-${q.id}`,
      questions: [q]
    }));
  }
  return [];
}
function validateArrayQuestion(question, value, fieldErrors) {
  const items = value || [];
  const completedItems = items.filter((item) => item._status === "completed");
  const editingItems = items.filter((item) => item._status === "editing");
  if (editingItems.length > 0) {
    return "Complete or remove all pending items before continuing";
  }
  if (question.minItems && completedItems.length < question.minItems) {
    return `At least ${question.minItems} item(s) required`;
  }
  if (question.maxItems && items.length > question.maxItems) {
    return `Maximum ${question.maxItems} item(s) allowed`;
  }
  let hasNestedError = false;
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    if (item._status !== "completed") continue;
    for (const field of question.itemTemplate.fields) {
      if (field.type === "content") continue;
      if (field.required) {
        const fieldValue = item[field.id];
        const isEmpty = !fieldValue || typeof fieldValue === "string" && !fieldValue.trim() || Array.isArray(fieldValue) && fieldValue.length === 0;
        if (isEmpty) {
          const errorKey = `${question.id}[${i}].${field.id}`;
          fieldErrors[errorKey] = `${field.question || field.id} is required`;
          hasNestedError = true;
        }
      }
    }
  }
  if (hasNestedError) {
    return "Please complete all required fields in each item";
  }
  return null;
}
function evaluateCondition(condition, answers) {
  if (!condition) return true;
  if (typeof condition === "function") return condition(answers);
  const rawValue = answers[condition.field];
  let value;
  if (rawValue && typeof rawValue === "object" && "type" in rawValue) {
    value = rawValue.value;
  } else if (Array.isArray(rawValue) && rawValue.length > 0 && typeof rawValue[0] === "object" && "type" in rawValue[0]) {
    value = rawValue.map((v) => v.value);
  } else {
    value = rawValue;
  }
  switch (condition.operator) {
    case "equals":
      return value === condition.value;
    case "notEquals":
      return value !== condition.value;
    case "includes":
      return Array.isArray(value) ? value.includes(condition.value) : String(value ?? "").includes(condition.value);
    case "notIncludes":
      return Array.isArray(value) ? !value.includes(condition.value) : !String(value ?? "").includes(condition.value);
    case "isEmpty":
      return !value || Array.isArray(value) && value.length === 0 || value === "";
    case "isNotEmpty":
      return !!value && (!Array.isArray(value) || value.length > 0) && value !== "";
    default:
      return true;
  }
}
function useTypeform(config) {
  const { schema, onSubmit, onStepChange, onPageChange, initialValues } = config;
  const pages = useMemo(() => normalizeToPages(config), [config]);
  const [currentPageIndex, setCurrentPageIndex] = useState(0);
  const [answers, setAnswers] = useState(() => {
    if (initialValues) {
      return initialValues;
    }
    return {};
  });
  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isComplete, setIsComplete] = useState(false);
  const [direction, setDirection] = useState("forward");
  const visiblePages = useMemo(
    () => pages.filter((page) => evaluateCondition(page.condition, answers)),
    [pages, answers]
  );
  const currentVisiblePageIndex = useMemo(() => {
    if (currentPageIndex >= visiblePages.length) {
      return Math.max(0, visiblePages.length - 1);
    }
    return currentPageIndex;
  }, [currentPageIndex, visiblePages.length]);
  const currentPage = visiblePages[currentVisiblePageIndex] ?? null;
  const currentPageQuestions = currentPage?.questions ?? [];
  const currentQuestion = currentPageQuestions[0] ?? null;
  const allQuestions = useMemo(
    () => visiblePages.flatMap((p) => p.questions).filter((q) => q.type !== "content"),
    [visiblePages]
  );
  const progress = visiblePages.length > 0 ? (currentVisiblePageIndex + 1) / visiblePages.length * 100 : 0;
  const isFirstPage = currentVisiblePageIndex === 0;
  const isLastPage = currentVisiblePageIndex === visiblePages.length - 1;
  const isFirstQuestion = isFirstPage;
  const isLastQuestion = isLastPage;
  const validateQuestion = useCallback(
    (question, fieldErrors) => {
      if (question.type === "content") {
        return null;
      }
      const answer = answers[question.id];
      if (question.type === "array") {
        const arrayQ = question;
        const arrayValue = answer;
        const errorsCollector = fieldErrors || {};
        return validateArrayQuestion(arrayQ, arrayValue, errorsCollector);
      }
      if (question.required) {
        if (answer === void 0 || answer === "" || Array.isArray(answer) && answer.length === 0) {
          return "This field is required";
        }
      }
      if (question.type === "email" || question.type === "text" && question.inputType === "email") {
        if (answer && typeof answer === "string") {
          const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
          if (!emailRegex.test(answer)) {
            return "Please enter a valid email address";
          }
        }
      }
      if (question.type === "checkbox") {
        const checkboxQ = question;
        const selectedCount = Array.isArray(answer) ? answer.length : 0;
        if (checkboxQ.minSelect && selectedCount < checkboxQ.minSelect) {
          return `Please select at least ${checkboxQ.minSelect} option(s)`;
        }
        if (checkboxQ.maxSelect && selectedCount > checkboxQ.maxSelect) {
          return `Please select at most ${checkboxQ.maxSelect} option(s)`;
        }
      }
      return null;
    },
    [answers]
  );
  const validateCurrentPage = useCallback(() => {
    const pageErrors = {};
    for (const question of currentPageQuestions) {
      if (question.type === "content") continue;
      const error = validateQuestion(question, pageErrors);
      if (error) {
        pageErrors[question.id] = error;
      }
    }
    return pageErrors;
  }, [currentPageQuestions, validateQuestion]);
  const canProceed = useMemo(() => {
    if (!currentPage) return false;
    for (const question of currentPageQuestions) {
      if (question.type === "content") continue;
      if (validateQuestion(question) !== null) {
        return false;
      }
    }
    return true;
  }, [currentPage, currentPageQuestions, validateQuestion]);
  const setAnswer = useCallback(
    (questionId, value) => {
      setAnswers((prev) => ({ ...prev, [questionId]: value }));
      setErrors((prev) => {
        const next2 = { ...prev };
        delete next2[questionId];
        return next2;
      });
    },
    []
  );
  const setArrayItemAnswer = useCallback(
    (questionId, itemIndex, fieldId, value) => {
      setAnswers((prev) => {
        const currentArray = prev[questionId] || [];
        const newArray = [...currentArray];
        if (!newArray[itemIndex]) {
          newArray[itemIndex] = { _status: "editing" };
        }
        newArray[itemIndex] = { ...newArray[itemIndex], [fieldId]: value };
        return { ...prev, [questionId]: newArray };
      });
      setErrors((prev) => {
        const next2 = { ...prev };
        const errorKey = `${questionId}[${itemIndex}].${fieldId}`;
        delete next2[errorKey];
        return next2;
      });
    },
    []
  );
  const next = useCallback(() => {
    if (!currentPage) return;
    const pageErrors = validateCurrentPage();
    if (Object.keys(pageErrors).length > 0) {
      setErrors((prev) => ({ ...prev, ...pageErrors }));
      return;
    }
    if (currentVisiblePageIndex < visiblePages.length - 1) {
      const nextIndex = currentVisiblePageIndex + 1;
      setDirection("forward");
      setCurrentPageIndex(nextIndex);
      const nextPage = visiblePages[nextIndex];
      onPageChange?.(nextIndex, nextPage);
      if (nextPage.questions[0]) {
        onStepChange?.(nextIndex, nextPage.questions[0]);
      }
    }
  }, [currentVisiblePageIndex, currentPage, visiblePages, validateCurrentPage, onPageChange, onStepChange]);
  const back = useCallback(() => {
    if (currentVisiblePageIndex > 0) {
      const prevIndex = currentVisiblePageIndex - 1;
      setDirection("backward");
      setCurrentPageIndex(prevIndex);
      const prevPage = visiblePages[prevIndex];
      onPageChange?.(prevIndex, prevPage);
      if (prevPage.questions[0]) {
        onStepChange?.(prevIndex, prevPage.questions[0]);
      }
    }
  }, [currentVisiblePageIndex, visiblePages, onPageChange, onStepChange]);
  const goTo = useCallback(
    (index) => {
      if (index >= 0 && index < visiblePages.length) {
        setCurrentPageIndex(index);
        const page = visiblePages[index];
        onPageChange?.(index, page);
        if (page.questions[0]) {
          onStepChange?.(index, page.questions[0]);
        }
      }
    },
    [visiblePages, onPageChange, onStepChange]
  );
  const submit = useCallback(async () => {
    const allErrors = {};
    for (const question of allQuestions) {
      const error = validateQuestion(question);
      if (error) {
        allErrors[question.id] = error;
      }
    }
    if (Object.keys(allErrors).length > 0) {
      setErrors(allErrors);
      for (let i = 0; i < visiblePages.length; i++) {
        const page = visiblePages[i];
        if (page.questions.some((q) => allErrors[q.id])) {
          setCurrentPageIndex(i);
          break;
        }
      }
      return;
    }
    if (schema) {
      const result = schema.safeParse(answers);
      if (!result.success) {
        const zodErrors = {};
        for (const issue of result.error.issues) {
          const pathStr = issue.path.join(".");
          const topLevelField = issue.path[0];
          if (typeof topLevelField === "string") {
            if (zodErrors[topLevelField]) {
              zodErrors[topLevelField] += `; ${issue.message}`;
            } else {
              zodErrors[topLevelField] = issue.message;
            }
          }
          if (pathStr && pathStr !== String(topLevelField)) {
            zodErrors[pathStr] = issue.message;
          }
        }
        setErrors(zodErrors);
        for (let i = 0; i < visiblePages.length; i++) {
          const page = visiblePages[i];
          const pageQuestionIds = page.questions.map((q) => q.id);
          if (pageQuestionIds.some((qId) => zodErrors[qId])) {
            setCurrentPageIndex(i);
            break;
          }
        }
        return;
      }
    }
    setIsSubmitting(true);
    try {
      await onSubmit(answers);
      setIsComplete(true);
    } catch (error) {
      console.error("[Typeform] Form submission error:", error);
      setErrors({ _form: error instanceof Error ? error.message : "Submission failed. Please try again." });
    } finally {
      setIsSubmitting(false);
    }
  }, [answers, allQuestions, visiblePages, schema, onSubmit, validateQuestion]);
  const reset = useCallback(() => {
    setCurrentPageIndex(0);
    setAnswers(initialValues ? initialValues : {});
    setErrors({});
    setIsSubmitting(false);
    setIsComplete(false);
  }, [initialValues]);
  const terminateAndSubmit = useCallback(
    async (reason) => {
      if (!config.terminationAction?.onTerminate) {
        console.warn("terminateAndSubmit called but no terminationAction.onTerminate configured");
        return;
      }
      try {
        setIsSubmitting(true);
        const partialData = answers;
        const currentPage2 = visiblePages[currentVisiblePageIndex];
        const lastPageIndex = pages.findIndex((p) => p.id === currentPage2?.id);
        await config.terminationAction.onTerminate({
          partialData,
          lastPageIndex: lastPageIndex >= 0 ? lastPageIndex : currentVisiblePageIndex,
          reason
        });
        setIsComplete(true);
      } catch (error) {
        console.error("Termination failed:", error);
        throw error;
      } finally {
        setIsSubmitting(false);
      }
    },
    [answers, config, currentVisiblePageIndex, visiblePages, pages]
  );
  return {
    // State
    currentIndex: currentVisiblePageIndex,
    // backwards compatibility
    answers,
    errors,
    isSubmitting,
    isComplete,
    direction,
    // Computed
    currentQuestion,
    currentPage,
    currentPageIndex: currentVisiblePageIndex,
    pages: visiblePages,
    // Return visible pages for progress bar
    progress,
    isFirstQuestion,
    isLastQuestion,
    isFirstPage,
    isLastPage,
    canProceed,
    // Actions
    next,
    back,
    goTo,
    setAnswer,
    setArrayItemAnswer,
    submit,
    reset,
    terminateAndSubmit
  };
}

// src/components/typeform/theme.ts
var defaultTheme = {
  colors: {
    primary: "var(--mantine-color-blue-6)",
    background: "var(--color-background)",
    card: "var(--mantine-color-blue-9)",
    cardBorder: "var(--mantine-color-dark-5)",
    text: "var(--color-text)",
    textMuted: "var(--color-text-dimmed)"
  },
  spacing: {
    questionGap: 12,
    contentMaxWidth: 800,
    // Wider default for better multi-question support
    pageGap: 32
    // Gap between questions on same page
  },
  animation: {
    duration: 300,
    easing: "ease"
  },
  options: {
    autoAdvance: false,
    compact: false
    // Compact mode for multi-question pages
  }
};
function mergeTheme(theme) {
  return {
    colors: { ...defaultTheme.colors, ...theme?.colors },
    spacing: { ...defaultTheme.spacing, ...theme?.spacing },
    animation: { ...defaultTheme.animation, ...theme?.animation },
    options: { ...defaultTheme.options, ...theme?.options }
  };
}
function TypeformProgress({
  current,
  total,
  showPercentage = false,
  usePortal = false
}) {
  const { styles } = useTypeformContext();
  const percentage = total > 0 ? Math.round(current / total * 100) : 0;
  const [mounted, setMounted] = useState(false);
  useEffect(() => {
    setMounted(true);
  }, []);
  const content = /* @__PURE__ */ jsxs(
    Box,
    {
      style: {
        position: "fixed",
        top: 0,
        left: 0,
        right: 0,
        zIndex: 1e3,
        ...styles?.progress
      },
      children: [
        /* @__PURE__ */ jsx(
          Progress,
          {
            value: percentage,
            size: 4,
            radius: 0,
            transitionDuration: 300,
            style: styles?.progressBar,
            styles: {
              root: {
                background: "var(--mantine-color-dark-6)"
              }
            }
          }
        ),
        showPercentage && /* @__PURE__ */ jsxs(Text, { size: "xs", c: "dimmed", ta: "right", pr: "md", pt: 4, style: styles?.progressText, children: [
          percentage,
          "%"
        ] })
      ]
    }
  );
  if (usePortal && mounted && typeof document !== "undefined") {
    return createPortal(content, document.body);
  }
  return content;
}
function TypeformNavigation({
  onBack,
  onNext,
  onSubmit,
  canGoBack,
  canGoNext,
  isLastQuestion,
  isSubmitting,
  terminationAction,
  onTerminate
}) {
  const { styles } = useTypeformContext();
  const [showTerminationModal, setShowTerminationModal] = useState(false);
  return /* @__PURE__ */ jsxs(
    Box,
    {
      style: {
        position: "sticky",
        bottom: 0,
        padding: "var(--mantine-spacing-md)",
        background: "var(--color-background)",
        borderTop: "1px solid var(--color-border)",
        borderRadius: "var(--mantine-radius-default)",
        ...styles?.navigation
      },
      children: [
        /* @__PURE__ */ jsxs(Group, { justify: "space-between", maw: 600, mx: "auto", children: [
          /* @__PURE__ */ jsxs(Group, { gap: "xs", children: [
            terminationAction && onTerminate && !canGoBack && /* @__PURE__ */ jsx(
              Button,
              {
                variant: terminationAction.variant || "subtle",
                color: terminationAction.color || "red",
                onClick: () => {
                  if (terminationAction.confirmText) {
                    setShowTerminationModal(true);
                  } else {
                    onTerminate();
                  }
                },
                style: styles?.buttonTerminate,
                children: terminationAction.label
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                variant: "subtle",
                color: "gray",
                leftSection: /* @__PURE__ */ jsx(IconArrowLeft, { size: 16 }),
                onClick: onBack,
                disabled: !canGoBack,
                style: styles?.buttonBack,
                styles: {
                  root: {
                    visibility: canGoBack ? "visible" : "hidden"
                  }
                },
                children: "Back"
              }
            )
          ] }),
          /* @__PURE__ */ jsxs(Group, { gap: "xs", children: [
            /* @__PURE__ */ jsxs(Text, { size: "sm", c: "dimmed", children: [
              "Press ",
              /* @__PURE__ */ jsx(Kbd, { size: "xs", children: "Enter" })
            ] }),
            isLastQuestion ? /* @__PURE__ */ jsx(
              Button,
              {
                rightSection: /* @__PURE__ */ jsx(IconCheck, { size: 16 }),
                onClick: onSubmit,
                loading: isSubmitting,
                disabled: !canGoNext,
                style: {
                  background: "var(--color-primary)",
                  color: "white",
                  transition: "all 150ms ease",
                  ...styles?.buttonSubmit
                },
                children: "Submit"
              }
            ) : /* @__PURE__ */ jsx(
              Button,
              {
                rightSection: /* @__PURE__ */ jsx(IconArrowRight, { size: 16 }),
                onClick: onNext,
                disabled: !canGoNext,
                style: {
                  background: "var(--color-primary)",
                  color: "white",
                  transition: "all 150ms ease",
                  ...styles?.buttonNext
                },
                children: "Continue"
              }
            )
          ] })
        ] }),
        terminationAction && onTerminate && /* @__PURE__ */ jsx(
          Modal,
          {
            opened: showTerminationModal,
            onClose: () => setShowTerminationModal(false),
            title: terminationAction.label,
            centered: true,
            children: /* @__PURE__ */ jsxs(Stack, { children: [
              /* @__PURE__ */ jsx(Text, { children: terminationAction.confirmText }),
              /* @__PURE__ */ jsxs(Group, { justify: "flex-end", children: [
                /* @__PURE__ */ jsx(Button, { variant: "subtle", onClick: () => setShowTerminationModal(false), children: "Cancel" }),
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    color: terminationAction.color || "red",
                    onClick: async () => {
                      await onTerminate();
                      setShowTerminationModal(false);
                    },
                    children: "Confirm"
                  }
                )
              ] })
            ] })
          }
        )
      ]
    }
  );
}
var slideForward = {
  in: { opacity: 1, transform: "translateY(0)" },
  out: { opacity: 0, transform: "translateY(-40px)" },
  transitionProperty: "opacity, transform"
};
var slideBackward = {
  in: { opacity: 1, transform: "translateY(0)" },
  out: { opacity: 0, transform: "translateY(40px)" },
  transitionProperty: "opacity, transform"
};
function TypeformQuestionWrapper({
  question,
  description,
  questionNumber,
  isActive,
  children,
  error,
  direction = "forward",
  theme,
  compact = false,
  styles: customStyles
}) {
  const maxWidth = theme?.spacing?.contentMaxWidth ?? 800;
  return /* @__PURE__ */ jsx(
    Transition,
    {
      mounted: isActive,
      transition: direction === "backward" ? slideBackward : slideForward,
      duration: theme?.animation?.duration ?? 300,
      timingFunction: theme?.animation?.easing ?? "ease",
      children: (transitionStyles) => /* @__PURE__ */ jsx(
        Box,
        {
          style: {
            ...transitionStyles,
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            justifyContent: "flex-start",
            minHeight: "100vh",
            padding: "var(--mantine-spacing-xl)",
            paddingTop: "min(15vh, 80px)",
            paddingBottom: 100,
            // Space for navigation
            overflow: "auto",
            ...customStyles?.question
          },
          children: /* @__PURE__ */ jsxs(Box, { maw: maxWidth, w: "100%", children: [
            /* @__PURE__ */ jsxs(Text, { size: "sm", c: "dimmed", mb: "xs", style: customStyles?.questionNumber, children: [
              questionNumber,
              " \u2192"
            ] }),
            /* @__PURE__ */ jsx(
              Title,
              {
                order: 2,
                mb: "sm",
                style: {
                  fontSize: compact ? "clamp(1.25rem, 3vw, 1.5rem)" : "clamp(1.5rem, 4vw, 2rem)",
                  fontWeight: 500,
                  lineHeight: 1.3,
                  ...customStyles?.questionTitle
                },
                children: question
              }
            ),
            description && /* @__PURE__ */ jsx(Text, { size: compact ? "md" : "lg", c: "dimmed", mb: "xl", style: customStyles?.questionDescription, children: description }),
            /* @__PURE__ */ jsx(Box, { mt: "xl", children }),
            error && /* @__PURE__ */ jsx(Text, { size: "sm", c: "red", mt: "md", style: customStyles?.error, children: error })
          ] })
        }
      )
    }
  );
}
function TypeformPageWrapper({
  page,
  pageNumber,
  isActive,
  direction = "forward",
  theme,
  compact = false,
  styles: customStyles,
  errors,
  renderField
}) {
  const maxWidth = theme?.spacing?.contentMaxWidth ?? 800;
  const pageGap = theme?.spacing?.pageGap ?? 32;
  const isMultiQuestion = page.questions.length > 1;
  return /* @__PURE__ */ jsx(
    Transition,
    {
      mounted: isActive,
      transition: direction === "backward" ? slideBackward : slideForward,
      duration: theme?.animation?.duration ?? 300,
      timingFunction: theme?.animation?.easing ?? "ease",
      children: (transitionStyles) => /* @__PURE__ */ jsx(
        Box,
        {
          style: {
            ...transitionStyles,
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            justifyContent: "flex-start",
            minHeight: "100vh",
            padding: "var(--mantine-spacing-xl)",
            paddingTop: "min(15vh, 80px)",
            paddingBottom: 100,
            // Space for navigation
            overflow: "auto",
            ...customStyles?.question
          },
          children: /* @__PURE__ */ jsxs(Box, { maw: maxWidth, w: "100%", children: [
            page.title && /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsxs(Text, { size: "sm", c: "dimmed", mb: "xs", style: customStyles?.questionNumber, children: [
                pageNumber,
                " \u2192"
              ] }),
              /* @__PURE__ */ jsx(
                Title,
                {
                  order: 2,
                  mb: "sm",
                  style: {
                    fontSize: "clamp(1.5rem, 4vw, 2rem)",
                    fontWeight: 600,
                    lineHeight: 1.3,
                    ...customStyles?.questionTitle
                  },
                  children: page.title
                }
              ),
              page.description && /* @__PURE__ */ jsx(Text, { size: "md", c: "dimmed", mb: "lg", style: customStyles?.questionDescription, children: page.description })
            ] }),
            /* @__PURE__ */ jsx(Stack, { gap: pageGap, children: page.questions.map((question) => {
              const error = errors[question.id];
              const showQuestionNumber = !page.title;
              if (question.type === "content") {
                return /* @__PURE__ */ jsx(Box, { mt: isMultiQuestion ? "sm" : "md", children: renderField(question) }, question.id);
              }
              return /* @__PURE__ */ jsxs(Box, { children: [
                showQuestionNumber && !isMultiQuestion && /* @__PURE__ */ jsxs(Text, { size: "sm", c: "dimmed", mb: "xs", style: customStyles?.questionNumber, children: [
                  pageNumber,
                  " \u2192"
                ] }),
                /* @__PURE__ */ jsxs(
                  Title,
                  {
                    order: isMultiQuestion ? 3 : 2,
                    mb: "xs",
                    style: {
                      fontSize: isMultiQuestion ? "clamp(1.125rem, 2.5vw, 1.25rem)" : compact ? "clamp(1.25rem, 3vw, 1.5rem)" : "clamp(1.5rem, 4vw, 2rem)",
                      fontWeight: 500,
                      lineHeight: 1.4
                    },
                    children: [
                      question.question,
                      question.required && /* @__PURE__ */ jsx(Text, { component: "span", c: "red", ml: 6, children: "*" })
                    ]
                  }
                ),
                question.description && /* @__PURE__ */ jsx(
                  Text,
                  {
                    size: isMultiQuestion ? "sm" : compact ? "md" : "lg",
                    c: "dimmed",
                    mb: "md",
                    style: customStyles?.questionDescription,
                    children: question.description
                  }
                ),
                /* @__PURE__ */ jsx(Box, { mt: isMultiQuestion ? "sm" : "xl", children: renderField(question) }),
                error && /* @__PURE__ */ jsx(Text, { size: "sm", c: "red", mt: "md", style: customStyles?.error, children: error })
              ] }, question.id);
            }) })
          ] })
        }
      )
    }
  );
}

// src/components/typeform/hooks.ts
function useCardStyle() {
  const { config, styles } = useTypeformContext();
  const theme = config.theme;
  const getCardStyle = (isSelected, isHovered) => {
    const base = {
      display: "block",
      width: "100%",
      padding: "var(--mantine-spacing-sm) var(--mantine-spacing-md)",
      borderRadius: "var(--mantine-radius-md)",
      border: "1px solid var(--color-border)",
      backgroundColor: "transparent",
      ...styles?.card,
      // Force-disable any preset transition (instant state changes)
      transition: "none"
    };
    const fallbackSelected = {
      border: "var(--active-border)",
      backgroundColor: "var(--active-background)"
    };
    const fallbackHovered = {
      backgroundColor: "var(--color-surface)"
    };
    if (isSelected) {
      return {
        ...base,
        ...fallbackSelected,
        ...styles?.cardSelected
      };
    }
    if (isHovered) {
      return {
        ...base,
        ...fallbackHovered,
        ...styles?.cardHovered
      };
    }
    return base;
  };
  const getKeyStyle = (isSelected, isHovered) => ({
    minWidth: 24,
    height: 24,
    display: "inline-flex",
    alignItems: "center",
    justifyContent: "center",
    fontSize: "var(--mantine-font-size-xs)",
    backgroundColor: isSelected || isHovered ? "var(--color-primary)" : "var(--mantine-color-dark-5)",
    color: isSelected || isHovered ? "#ffffff" : void 0,
    border: "none",
    flexShrink: 0,
    ...styles?.cardKey,
    transition: "none",
    ...isSelected || isHovered ? { backgroundColor: "var(--color-primary)", color: "#ffffff" } : null
  });
  return { getCardStyle, getKeyStyle, theme, styles };
}

// src/components/typeform/types.ts
function createPresetValue(value) {
  return { type: "preset", value };
}
function createCustomValue(value) {
  return { type: "custom", value };
}
function isCustomValue(answer) {
  return answer.type === "custom";
}
function isPresetValue(answer) {
  return answer.type === "preset";
}
function getAnswerString(answer) {
  return answer?.value ?? "";
}
function getMultiAnswerStrings(answers) {
  return answers.map((a) => a.value);
}
function hasCustomValue(answers) {
  return answers.some((a) => a.type === "custom");
}
function getCustomValueText(answers) {
  const custom = answers.find((a) => a.type === "custom");
  return custom?.value;
}
function hasPresetValue(answers, value) {
  return answers.some((a) => a.type === "preset" && a.value === value);
}
function extractAnswerValue(answer) {
  return answer.value;
}
function extractMultiAnswerValues(answers) {
  return answers.map((a) => a.value);
}
function createSurveyConfig(config) {
  return config;
}
function TypeformRadioGroup({ question, value, onChange, error }) {
  const { getCardStyle, getKeyStyle, styles } = useCardStyle();
  const { options } = question;
  const [hoveredIndex, setHoveredIndex] = useState(null);
  const [otherText, setOtherText] = useState(() => {
    if (value && isCustomValue(value)) {
      return value.value;
    }
    return "";
  });
  useEffect(() => {
    if (value && isCustomValue(value)) {
      setOtherText(value.value);
    } else if (!value || !isCustomValue(value)) {
      setOtherText("");
    }
  }, [value]);
  const isOtherSelected = value && isCustomValue(value);
  const selectedPresetValue = value && !isCustomValue(value) ? value.value : null;
  const handleOptionClick = (optionValue) => {
    const isOther = optionValue.toLowerCase() === "other";
    if (isOther) {
      onChange(createCustomValue(otherText));
    } else {
      onChange(createPresetValue(optionValue));
      setOtherText("");
    }
  };
  const handleOtherTextChange = (text) => {
    setOtherText(text);
    onChange(createCustomValue(text));
  };
  return /* @__PURE__ */ jsxs(Stack, { gap: "xs", children: [
    options.map((option, index) => {
      const isOther = option.value.toLowerCase() === "other";
      const isSelected = isOther ? isOtherSelected : selectedPresetValue === option.value;
      const letterKey = String.fromCharCode(65 + index);
      return /* @__PURE__ */ jsx(
        UnstyledButton,
        {
          onClick: () => handleOptionClick(option.value),
          onMouseEnter: () => setHoveredIndex(index),
          onMouseLeave: () => setHoveredIndex(null),
          style: getCardStyle(!!isSelected, hoveredIndex === index),
          children: /* @__PURE__ */ jsxs(Group, { gap: "sm", wrap: "nowrap", children: [
            /* @__PURE__ */ jsx(Kbd, { size: "xs", style: getKeyStyle(!!isSelected, hoveredIndex === index), children: letterKey }),
            /* @__PURE__ */ jsxs(Box, { style: { flex: 1 }, children: [
              /* @__PURE__ */ jsx(Text, { size: "sm", fw: 500, style: styles?.cardLabel, children: option.label }),
              option.description && /* @__PURE__ */ jsx(Text, { size: "xs", c: "dimmed", mt: 2, style: styles?.cardDescription, children: option.description })
            ] }),
            isSelected && /* @__PURE__ */ jsx(IconCheck, { size: 16, style: { color: "var(--color-primary)", ...styles?.cardCheckmark } })
          ] })
        },
        option.value
      );
    }),
    isOtherSelected && /* @__PURE__ */ jsx(Box, { mt: "md", children: /* @__PURE__ */ jsx(
      TextInput,
      {
        placeholder: "Please specify...",
        value: otherText,
        onChange: (e) => handleOtherTextChange(e.target.value),
        styles: {
          input: {
            ...styles?.input,
            fontSize: 16
          }
        }
      }
    ) }),
    error && /* @__PURE__ */ jsx(Text, { size: "sm", c: "red", mt: "sm", style: styles?.error, children: error })
  ] });
}
function TypeformCheckboxGroup({ question, value, onChange, error }) {
  const { getCardStyle, getKeyStyle, styles } = useCardStyle();
  const { options } = question;
  const [hoveredIndex, setHoveredIndex] = useState(null);
  const [otherText, setOtherText] = useState(() => getCustomValueText(value) ?? "");
  useEffect(() => {
    const customText = getCustomValueText(value);
    if (customText !== void 0) {
      setOtherText(customText);
    } else if (!hasCustomValue(value)) {
      setOtherText("");
    }
  }, [value]);
  const isOtherSelected = hasCustomValue(value);
  const handleToggle = (optionValue) => {
    const isOther = optionValue.toLowerCase() === "other";
    if (isOther) {
      if (isOtherSelected) {
        onChange(value.filter((v) => v.type !== "custom"));
        setOtherText("");
      } else {
        onChange([...value, createCustomValue("")]);
      }
    } else {
      const hasValue = hasPresetValue(value, optionValue);
      if (hasValue) {
        onChange(value.filter((v) => !(v.type === "preset" && v.value === optionValue)));
      } else {
        onChange([...value, createPresetValue(optionValue)]);
      }
    }
  };
  const handleOtherTextChange = (text) => {
    setOtherText(text);
    const withoutCustom = value.filter((v) => v.type !== "custom");
    onChange([...withoutCustom, createCustomValue(text)]);
  };
  return /* @__PURE__ */ jsxs(Stack, { gap: "xs", children: [
    options.map((option, index) => {
      const isOther = option.value.toLowerCase() === "other";
      const isSelected = isOther ? isOtherSelected : hasPresetValue(value, option.value);
      const letterKey = String.fromCharCode(65 + index);
      return /* @__PURE__ */ jsx(
        UnstyledButton,
        {
          onClick: () => handleToggle(option.value),
          onMouseEnter: () => setHoveredIndex(index),
          onMouseLeave: () => setHoveredIndex(null),
          style: getCardStyle(isSelected, hoveredIndex === index),
          children: /* @__PURE__ */ jsxs(Group, { gap: "sm", wrap: "nowrap", children: [
            /* @__PURE__ */ jsx(Kbd, { size: "xs", style: getKeyStyle(isSelected, hoveredIndex === index), children: letterKey }),
            /* @__PURE__ */ jsx(
              Box,
              {
                style: {
                  width: 20,
                  height: 20,
                  borderRadius: 4,
                  border: `2px solid ${isSelected ? "var(--color-primary)" : "var(--mantine-color-dark-4)"}`,
                  backgroundColor: isSelected ? "var(--color-primary)" : "transparent",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  transition: "all 150ms ease",
                  flexShrink: 0
                },
                children: isSelected && /* @__PURE__ */ jsx(IconCheck, { size: 14, style: { color: "white" } })
              }
            ),
            /* @__PURE__ */ jsxs(Box, { style: { flex: 1 }, children: [
              /* @__PURE__ */ jsx(Text, { size: "sm", fw: 500, style: styles?.cardLabel, children: option.label }),
              option.description && /* @__PURE__ */ jsx(Text, { size: "xs", c: "dimmed", mt: 2, style: styles?.cardDescription, children: option.description })
            ] })
          ] })
        },
        option.value
      );
    }),
    isOtherSelected && /* @__PURE__ */ jsx(Box, { mt: "md", children: /* @__PURE__ */ jsx(
      TextInput,
      {
        placeholder: "Please specify...",
        value: otherText,
        onChange: (e) => handleOtherTextChange(e.target.value),
        styles: {
          input: {
            ...styles?.input,
            fontSize: 16
          }
        }
      }
    ) }),
    /* @__PURE__ */ jsx(Text, { size: "sm", c: "dimmed", mt: "xs", children: "Select all that apply" }),
    error && /* @__PURE__ */ jsx(Text, { size: "sm", c: "red", mt: "sm", style: styles?.error, children: error })
  ] });
}
function TypeformTextInput({ question, value, onChange, error, onSubmit }) {
  const { config, styles } = useTypeformContext();
  const theme = config.theme;
  const handleKeyDown = (e) => {
    if (e.key === "Enter" && !e.shiftKey && question.type !== "textarea") {
      e.preventDefault();
      onSubmit?.();
    }
  };
  const focusBorderColor = theme?.colors?.primary ?? "var(--mantine-color-blue-6)";
  const textColor = theme?.colors?.text ?? void 0;
  if (question.type === "textarea") {
    const textareaQuestion = question;
    return /* @__PURE__ */ jsx(
      Textarea,
      {
        value,
        onChange: (e) => onChange(e.target.value),
        placeholder: textareaQuestion.placeholder || "Type your answer here...",
        error,
        rows: textareaQuestion.rows || 4,
        autoFocus: true,
        styles: {
          input: {
            ...styles?.textarea,
            color: textColor,
            "&:focus": {
              borderColor: focusBorderColor
            }
          }
        }
      }
    );
  }
  const textQuestion = question;
  return /* @__PURE__ */ jsx(
    TextInput,
    {
      value,
      onChange: (e) => onChange(e.target.value),
      placeholder: textQuestion.placeholder || "Type your answer here...",
      type: textQuestion.inputType || "text",
      error,
      onKeyDown: handleKeyDown,
      autoFocus: true,
      styles: {
        input: {
          ...styles?.input,
          color: textColor,
          "&:focus": {
            borderBottomColor: focusBorderColor
          }
        }
      }
    }
  );
}
function TypeformArrayField({
  question,
  value = [],
  onChange,
  errors,
  renderField,
  theme: _theme
}) {
  const {
    itemTemplate,
    minItems = 0,
    maxItems,
    addLabel = "Add item",
    removeLabel = "Remove",
    itemLabel,
    summaryFields
  } = question;
  const [localErrors, setLocalErrors] = useState({});
  const hasEditingItems = value.some((item) => item._status === "editing");
  const canAdd = (maxItems === void 0 || value.length < maxItems) && !hasEditingItems;
  const getCanRemove = (item) => {
    const completedCount = value.filter((i) => i._status === "completed").length;
    if (item._status === "editing") return true;
    return completedCount > minItems;
  };
  const handleAdd = () => {
    if (!canAdd) return;
    const newItem = { _status: "editing" };
    itemTemplate.fields.forEach((field) => {
      if (field.type !== "content") {
        if (field.type === "checkbox") {
          newItem[field.id] = [];
        } else {
          newItem[field.id] = "";
        }
      }
    });
    onChange([...value, newItem]);
  };
  const handleRemove = (index) => {
    const newValue = value.filter((_, i) => i !== index);
    onChange(newValue);
    const newLocalErrors = { ...localErrors };
    Object.keys(newLocalErrors).forEach((key) => {
      if (key.startsWith(`${question.id}[${index}]`)) {
        delete newLocalErrors[key];
      }
    });
    setLocalErrors(newLocalErrors);
  };
  const handleCancel = (index) => {
    handleRemove(index);
  };
  const handleItemChange = (index, fieldId, fieldValue) => {
    const newValue = [...value];
    newValue[index] = { ...newValue[index], [fieldId]: fieldValue };
    onChange(newValue);
    const errorKey = `${question.id}[${index}].${fieldId}`;
    if (localErrors[errorKey]) {
      const newLocalErrors = { ...localErrors };
      delete newLocalErrors[errorKey];
      setLocalErrors(newLocalErrors);
    }
  };
  const validateItem = (index) => {
    const item = value[index];
    if (!item) return false;
    const newErrors = {};
    let hasError = false;
    for (const field of itemTemplate.fields) {
      if (field.type === "content") continue;
      if (field.required) {
        const fieldValue = item[field.id];
        const isEmpty = !fieldValue || typeof fieldValue === "string" && !fieldValue.trim() || Array.isArray(fieldValue) && fieldValue.length === 0;
        if (isEmpty) {
          const errorKey = `${question.id}[${index}].${field.id}`;
          newErrors[errorKey] = `${field.question || field.id} is required`;
          hasError = true;
        }
      }
    }
    setLocalErrors((prev) => ({ ...prev, ...newErrors }));
    return !hasError;
  };
  const handleComplete = (index) => {
    if (validateItem(index)) {
      const newValue = [...value];
      newValue[index] = { ...newValue[index], _status: "completed" };
      onChange(newValue);
    }
  };
  const handleEdit = (index) => {
    const newValue = [...value];
    newValue[index] = { ...newValue[index], _status: "editing" };
    onChange(newValue);
  };
  const getItemLabel = (index) => {
    if (itemLabel) return itemLabel(index);
    return `Item ${index + 1}`;
  };
  const getFieldError = (index, fieldId) => {
    const errorKey = `${question.id}[${index}].${fieldId}`;
    return localErrors[errorKey] || errors?.[errorKey];
  };
  const getFieldValue = (item, field) => {
    if (field.type === "content") return "";
    const val = item[field.id];
    if (val === void 0) {
      if (field.type === "checkbox") return [];
      return "";
    }
    if (typeof val === "string" || Array.isArray(val)) return val;
    return "";
  };
  const getFieldLabel = (fieldId) => {
    const field = itemTemplate.fields.find((f) => f.id === fieldId);
    if (!field || field.type === "content") return fieldId;
    return field.question || fieldId;
  };
  const renderSummary = (item, index) => {
    const fieldsToShow = summaryFields || itemTemplate.fields.slice(0, 4).map((f) => f.id);
    const summaryLines = [];
    for (const fieldId of fieldsToShow) {
      if (fieldId === "_status") continue;
      const val = item[fieldId];
      if (!val) continue;
      const label = getFieldLabel(fieldId);
      let displayValue = "";
      if (typeof val === "string") {
        displayValue = val.length > 60 ? val.substring(0, 60) + "..." : val;
      } else if (Array.isArray(val)) {
        displayValue = val.join(", ");
      }
      if (displayValue) {
        summaryLines.push({ label, value: displayValue });
      }
    }
    return /* @__PURE__ */ jsxs(
      Card,
      {
        withBorder: true,
        padding: "md",
        style: {
          backgroundColor: "var(--color-surface)",
          borderColor: "rgba(255, 255, 255, 0.12)",
          borderRadius: 12
        },
        children: [
          /* @__PURE__ */ jsxs(Group, { justify: "space-between", align: "flex-start", mb: "xs", children: [
            /* @__PURE__ */ jsx(Text, { fw: 600, size: "sm", c: "dimmed", style: { fontFamily: "var(--mantine-font-family-headings)" }, children: getItemLabel(index) }),
            /* @__PURE__ */ jsxs(Group, { gap: "xs", children: [
              /* @__PURE__ */ jsx(ActionIcon, { variant: "subtle", color: "gray", onClick: () => handleEdit(index), "aria-label": "Edit", size: "sm", children: /* @__PURE__ */ jsx(IconPencil, { size: 14 }) }),
              getCanRemove(item) && /* @__PURE__ */ jsx(
                ActionIcon,
                {
                  variant: "subtle",
                  color: "red",
                  onClick: () => handleRemove(index),
                  "aria-label": removeLabel,
                  size: "sm",
                  children: /* @__PURE__ */ jsx(IconTrash, { size: 14 })
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsx(
            Paper,
            {
              p: "sm",
              style: {
                backgroundColor: "var(--glass-background)",
                borderRadius: 8
              },
              children: summaryLines.length > 0 ? /* @__PURE__ */ jsxs(Stack, { gap: 4, children: [
                summaryLines[0] && /* @__PURE__ */ jsx(Text, { size: "sm", style: { color: "var(--color-text)" }, children: summaryLines[0].value }),
                summaryLines.length > 1 && /* @__PURE__ */ jsx(Text, { size: "xs", c: "dimmed", children: summaryLines.slice(1).map((line) => line.value).join(" \xB7 ") })
              ] }) : /* @__PURE__ */ jsx(Text, { size: "sm", c: "dimmed", fs: "italic", children: "No data" })
            }
          )
        ]
      },
      index
    );
  };
  const renderEditingForm = (item, index) => {
    return /* @__PURE__ */ jsxs(
      Card,
      {
        withBorder: true,
        padding: "md",
        style: {
          backgroundColor: "var(--color-surface)",
          borderColor: "rgba(0, 153, 255, 0.3)",
          borderRadius: 12
        },
        children: [
          /* @__PURE__ */ jsx(Text, { fw: 500, mb: "md", children: getItemLabel(index) }),
          /* @__PURE__ */ jsx(Stack, { gap: "sm", children: itemTemplate.fields.map((field) => /* @__PURE__ */ jsx(Box, { children: renderField(
            field,
            index,
            `${question.id}[${index}].${field.id}`,
            getFieldValue(item, field),
            (fieldValue) => handleItemChange(index, field.id, fieldValue),
            getFieldError(index, field.id)
          ) }, field.id)) }),
          /* @__PURE__ */ jsxs(Group, { justify: "space-between", mt: "lg", children: [
            /* @__PURE__ */ jsx(Button, { variant: "filled", leftSection: /* @__PURE__ */ jsx(IconCheck, { size: 16 }), onClick: () => handleComplete(index), children: "Complete" }),
            /* @__PURE__ */ jsx(Button, { variant: "subtle", color: "gray", leftSection: /* @__PURE__ */ jsx(IconX, { size: 16 }), onClick: () => handleCancel(index), children: "Cancel" })
          ] })
        ]
      },
      index
    );
  };
  return /* @__PURE__ */ jsxs(Stack, { gap: "md", children: [
    value.map(
      (item, index) => item._status === "completed" ? renderSummary(item, index) : renderEditingForm(item, index)
    ),
    canAdd && /* @__PURE__ */ jsx(Button, { variant: "light", leftSection: /* @__PURE__ */ jsx(IconPlus, { size: 16 }), onClick: handleAdd, children: addLabel })
  ] });
}
var TypeformContext = createContext(null);
function useTypeformContext() {
  const context = useContext(TypeformContext);
  if (!context) {
    throw new Error("useTypeformContext must be used within a TypeformSurvey");
  }
  return context;
}
function TypeformSurvey({
  config,
  className,
  styles,
  hideProgress,
  mode = "paginated",
  renderPageSection
}) {
  const typeform = useTypeform(config);
  const {
    currentPage,
    currentPageIndex,
    pages,
    answers,
    errors,
    isFirstPage,
    isLastPage,
    isSubmitting,
    isComplete,
    canProceed,
    direction,
    next,
    back,
    submit,
    setAnswer,
    terminateAndSubmit
  } = typeform;
  const nextRef = useRef(next);
  nextRef.current = next;
  const mergedTheme = mergeTheme(config.theme);
  const isCompact = mergedTheme.options?.compact ?? false;
  const isMultiQuestion = (currentPage?.questions.length ?? 0) > 1;
  const parseMarkdown = (text) => {
    const lines = text.split("\n");
    return lines.map((line, idx) => {
      const parts = line.split(/(\*\*.*?\*\*)/);
      const renderedLine = parts.map((part, partIdx) => {
        if (part.startsWith("**") && part.endsWith("**")) {
          return /* @__PURE__ */ jsx(
            Text,
            {
              component: "span",
              fw: 700,
              style: {
                color: "var(--color-text)"
              },
              children: part.slice(2, -2)
            },
            partIdx
          );
        }
        return part;
      });
      return /* @__PURE__ */ jsxs("span", { children: [
        renderedLine,
        idx < lines.length - 1 && /* @__PURE__ */ jsx("br", {})
      ] }, idx);
    });
  };
  const renderContent = (question) => {
    const { content, style = "default" } = question;
    switch (style) {
      case "callout":
        return /* @__PURE__ */ jsx(
          Paper,
          {
            p: "lg",
            style: {
              backgroundColor: "var(--color-surface)",
              border: "1px solid rgba(255, 255, 255, 0.07)",
              borderRadius: 12,
              backdropFilter: "blur(24px)",
              WebkitBackdropFilter: "blur(24px)"
            },
            children: /* @__PURE__ */ jsx(Text, { size: "sm", style: { lineHeight: 1.6, color: "rgb(212, 212, 216)" }, children: parseMarkdown(content) })
          },
          question.id
        );
      case "script":
        return /* @__PURE__ */ jsx(
          Text,
          {
            fs: "italic",
            size: "sm",
            style: {
              color: "rgb(161, 161, 170)",
              padding: "8px 16px",
              borderLeft: "3px solid rgba(0, 153, 255, 0.3)"
            },
            children: parseMarkdown(content)
          },
          question.id
        );
      case "info":
        return /* @__PURE__ */ jsx(
          Paper,
          {
            p: "lg",
            style: {
              backgroundColor: "var(--color-surface)",
              border: "1px solid rgba(255, 255, 255, 0.07)",
              borderRadius: 12,
              backdropFilter: "blur(24px)",
              WebkitBackdropFilter: "blur(24px)"
            },
            children: /* @__PURE__ */ jsx(Text, { size: "sm", style: { lineHeight: 1.6, color: "rgb(212, 212, 216)" }, children: parseMarkdown(content) })
          },
          question.id
        );
      case "warning":
        return /* @__PURE__ */ jsxs(
          Paper,
          {
            p: "md",
            style: {
              backgroundColor: "color-mix(in srgb, var(--color-warning) 10%, transparent)",
              border: "1px solid rgba(249, 115, 22, 0.2)",
              borderRadius: 12
            },
            children: [
              /* @__PURE__ */ jsx(
                Text,
                {
                  size: "sm",
                  fw: 600,
                  mb: "xs",
                  style: { color: "rgb(251, 146, 60)", fontFamily: "var(--mantine-font-family-headings)" },
                  children: "Note"
                }
              ),
              /* @__PURE__ */ jsx(Text, { size: "sm", style: { lineHeight: 1.6, color: "var(--color-text)" }, children: parseMarkdown(content) })
            ]
          },
          question.id
        );
      default:
        return /* @__PURE__ */ jsx(Text, { style: { color: "var(--color-text)" }, children: parseMarkdown(content) }, question.id);
    }
  };
  const renderField = (question) => {
    const questionId = question.id;
    const error = errors[questionId];
    switch (question.type) {
      case "content":
        return renderContent(question);
      case "radio": {
        const rawValue = answers[questionId];
        let answerValue;
        if (rawValue && typeof rawValue === "object" && "type" in rawValue) {
          answerValue = rawValue;
        } else if (typeof rawValue === "string" && rawValue) {
          answerValue = createPresetValue(rawValue);
        }
        const handleRadioChange = (value) => {
          setAnswer(questionId, value);
          if (mergedTheme.options?.autoAdvance && !isLastPage && !isMultiQuestion && !isCustomValue(value)) {
            setTimeout(() => {
              nextRef.current();
            }, 400);
          }
        };
        return /* @__PURE__ */ jsx(
          TypeformRadioGroup,
          {
            question,
            value: answerValue,
            onChange: handleRadioChange,
            error
          },
          questionId
        );
      }
      case "checkbox": {
        const rawValue = answers[questionId];
        let multiValue = [];
        if (Array.isArray(rawValue)) {
          if (rawValue.length > 0 && typeof rawValue[0] === "object" && "type" in rawValue[0]) {
            multiValue = rawValue;
          } else {
            multiValue = rawValue.map((v) => createPresetValue(v));
          }
        }
        return /* @__PURE__ */ jsx(
          TypeformCheckboxGroup,
          {
            question,
            value: multiValue,
            onChange: (value) => setAnswer(questionId, value),
            error
          },
          questionId
        );
      }
      case "text":
      case "email":
      case "textarea":
        return /* @__PURE__ */ jsx(
          TypeformTextInput,
          {
            question,
            value: answers[questionId] || "",
            onChange: (value) => setAnswer(questionId, value),
            error,
            onSubmit: () => {
              if (isLastPage) {
                submit();
              } else if (canProceed) {
                next();
              }
            }
          },
          questionId
        );
      case "array":
        return /* @__PURE__ */ jsx(
          TypeformArrayField,
          {
            question,
            value: answers[questionId] || [],
            onChange: (value) => setAnswer(questionId, value),
            errors,
            renderField: renderNestedField,
            theme: mergedTheme
          },
          questionId
        );
      default:
        return null;
    }
  };
  const renderNestedField = (field, _itemIndex, fieldId, value, onFieldChange, error) => {
    switch (field.type) {
      case "content":
        return renderContent(field);
      case "radio": {
        const answerValue = typeof value === "string" && value ? createPresetValue(value) : void 0;
        return /* @__PURE__ */ jsxs(Box, { mt: "md", children: [
          /* @__PURE__ */ jsxs(Text, { size: "sm", fw: 500, mb: 4, children: [
            field.question,
            field.required && /* @__PURE__ */ jsx(Text, { component: "span", c: "red", ml: 4, children: "*" })
          ] }),
          /* @__PURE__ */ jsx(
            TypeformRadioGroup,
            {
              question: field,
              value: answerValue,
              onChange: (newValue) => onFieldChange(newValue.value),
              error
            }
          )
        ] }, fieldId);
      }
      case "checkbox": {
        const multiValue = Array.isArray(value) ? value.map((v) => createPresetValue(v)) : [];
        return /* @__PURE__ */ jsxs(Box, { mt: "md", children: [
          /* @__PURE__ */ jsxs(Text, { size: "sm", fw: 500, mb: 4, children: [
            field.question,
            field.required && /* @__PURE__ */ jsx(Text, { component: "span", c: "red", ml: 4, children: "*" })
          ] }),
          /* @__PURE__ */ jsx(
            TypeformCheckboxGroup,
            {
              question: field,
              value: multiValue,
              onChange: (newValue) => onFieldChange(newValue.map((v) => v.value)),
              error
            }
          )
        ] }, fieldId);
      }
      case "text":
      case "email":
      case "textarea":
        return /* @__PURE__ */ jsxs(Box, { mt: "md", children: [
          /* @__PURE__ */ jsxs(Text, { size: "sm", fw: 500, mb: 4, children: [
            field.question,
            field.required && /* @__PURE__ */ jsx(Text, { component: "span", c: "red", ml: 4, children: "*" })
          ] }),
          /* @__PURE__ */ jsx(
            TypeformTextInput,
            {
              question: field,
              value: value || "",
              onChange: onFieldChange,
              error
            }
          )
        ] }, fieldId);
      default:
        return null;
    }
  };
  const handleKeyDown = useCallback(
    (e) => {
      if (isComplete) return;
      if (mode === "all") return;
      if (e.key === "Enter" && !e.shiftKey) {
        const activeElement = document.activeElement;
        if (activeElement?.tagName === "TEXTAREA") return;
        if (isMultiQuestion) return;
        if (isLastPage) {
          submit();
        } else if (canProceed) {
          next();
        }
        return;
      }
      if (!isMultiQuestion && currentPage?.questions[0]) {
        const question = currentPage.questions[0];
        if (question.type === "radio" || question.type === "checkbox") {
          const key = e.key.toUpperCase();
          const index = key.charCodeAt(0) - 65;
          const options = question.type === "radio" ? question.options : question.options;
          if (index >= 0 && index < options.length) {
            const option = options[index];
            if (question.type === "radio") {
              const newValue = createPresetValue(option.value);
              setAnswer(question.id, newValue);
              if (mergedTheme.options?.autoAdvance && !isLastPage && option.value.toLowerCase() !== "other") {
                setTimeout(() => nextRef.current(), 400);
              }
            } else {
              const rawValue = answers[question.id];
              let currentValue = [];
              if (Array.isArray(rawValue)) {
                if (rawValue.length > 0 && typeof rawValue[0] === "object" && "type" in rawValue[0]) {
                  currentValue = rawValue;
                } else {
                  currentValue = rawValue.map((v) => createPresetValue(v));
                }
              }
              const hasValue = currentValue.some((v) => v.type === "preset" && v.value === option.value);
              if (hasValue) {
                setAnswer(
                  question.id,
                  currentValue.filter((v) => !(v.type === "preset" && v.value === option.value))
                );
              } else {
                setAnswer(question.id, [...currentValue, createPresetValue(option.value)]);
              }
            }
          }
        }
      }
    },
    [
      currentPage,
      answers,
      isLastPage,
      isComplete,
      canProceed,
      isMultiQuestion,
      mode,
      next,
      submit,
      setAnswer,
      mergedTheme
    ]
  );
  useEffect(() => {
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [handleKeyDown]);
  useEffect(() => {
    if (typeof window === "undefined") return;
    if (mode === "all") return;
    window.scrollTo({ top: 0, left: 0, behavior: "auto" });
  }, [currentPageIndex, mode]);
  if (isComplete) {
    return /* @__PURE__ */ jsx(Box, { className, style: styles?.container, children: /* @__PURE__ */ jsx(
      Center,
      {
        style: {
          // minHeight: '100vh',
          padding: "var(--mantine-spacing-xl)"
          // ...styles?.completion,
        },
        children: /* @__PURE__ */ jsxs(Stack, { align: "center", gap: "lg", children: [
          /* @__PURE__ */ jsx(
            Box,
            {
              style: {
                width: 80,
                height: 80,
                borderRadius: "50%",
                background: "var(--mantine-color-green-6)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                ...styles?.completionIcon
              },
              children: /* @__PURE__ */ jsx(IconCheck, { size: 40, color: "white" })
            }
          ),
          /* @__PURE__ */ jsx(Title, { order: 3, style: styles?.completionTitle, children: "Thank you!" }),
          /* @__PURE__ */ jsx(Text, { size: "lg", c: "dimmed", ta: "center", maw: 400, style: styles?.completionText, children: "Your response has been recorded." })
        ] })
      }
    ) });
  }
  const contextValue = {
    ...typeform,
    config,
    styles
  };
  return /* @__PURE__ */ jsx(TypeformContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxs(
    Box,
    {
      className,
      style: {
        minHeight: "100vh",
        background: mergedTheme.colors?.background,
        ...styles?.container
      },
      children: [
        !hideProgress && mode !== "all" && /* @__PURE__ */ jsx(TypeformProgress, { current: currentPageIndex + 1, total: pages.length, usePortal: true }),
        errors._form && /* @__PURE__ */ jsx(Box, { px: "xl", pt: "md", children: /* @__PURE__ */ jsx(Alert, { color: "red", variant: "light", title: "Submission Error", children: errors._form }) }),
        mode === "all" ? /* @__PURE__ */ jsx(Fragment, { children: pages.map((page, idx) => {
          const wrapper = /* @__PURE__ */ jsx(
            TypeformPageWrapper,
            {
              page,
              pageNumber: idx + 1,
              isActive: true,
              direction: "forward",
              theme: mergedTheme,
              compact: isCompact,
              styles: {
                // Override minHeight so each section doesn't force full viewport height
                question: { minHeight: "auto", paddingTop: "var(--mantine-spacing-xl)", ...styles?.question },
                questionNumber: styles?.questionNumber,
                questionTitle: styles?.questionTitle,
                questionDescription: styles?.questionDescription,
                error: styles?.error
              },
              errors,
              renderField
            },
            page.id
          );
          return renderPageSection ? renderPageSection(page, wrapper) : wrapper;
        }) }) : currentPage && /* @__PURE__ */ jsx(
          TypeformPageWrapper,
          {
            page: currentPage,
            pageNumber: currentPageIndex + 1,
            isActive: true,
            direction,
            theme: mergedTheme,
            compact: isCompact,
            styles: {
              question: styles?.question,
              questionNumber: styles?.questionNumber,
              questionTitle: styles?.questionTitle,
              questionDescription: styles?.questionDescription,
              error: styles?.error
            },
            errors,
            renderField
          }
        ),
        /* @__PURE__ */ jsx(
          TypeformNavigation,
          {
            onBack: back,
            onNext: next,
            onSubmit: submit,
            canGoBack: mode === "all" ? false : !isFirstPage,
            canGoNext: canProceed,
            isLastQuestion: mode === "all" ? true : isLastPage,
            isSubmitting,
            terminationAction: config.terminationAction,
            onTerminate: terminateAndSubmit
          }
        )
      ]
    }
  ) });
}

// src/components/typeform/presets/brochure-style.ts
var brochureTheme = {
  colors: {
    primary: "#0099ff",
    background: "transparent",
    // Use parent container background
    card: "rgba(24, 24, 27, 0.4)",
    // zinc-900/40
    cardBorder: "rgba(255, 255, 255, 0.07)",
    text: "#ffffff",
    textMuted: "rgb(161, 161, 170)"
    // zinc-400
  },
  spacing: {
    questionGap: 14,
    contentMaxWidth: 900,
    // Wider for better multi-question support
    pageGap: 36
    // Gap between questions on same page
  },
  animation: {
    duration: 400,
    easing: "cubic-bezier(0.4, 0, 0.2, 1)"
  },
  options: {
    autoAdvance: false,
    compact: false
    // Can be enabled for multi-question pages
  }
};
var brochureStyles = {
  // Container - transparent, no min-height when inside glass card
  container: {
    backgroundColor: "transparent",
    minHeight: "auto"
  },
  // Question wrapper - centered content with generous padding
  question: {
    minHeight: "auto",
    padding: "56px 40px",
    paddingBottom: 120
  },
  // Question number - subtle badge style
  questionNumber: {
    fontSize: 13,
    fontWeight: 600,
    textTransform: "uppercase",
    letterSpacing: "0.15em",
    color: "#0099ff",
    marginBottom: 16
  },
  // Question title - cleaner, more modern sizing
  questionTitle: {
    fontSize: "clamp(1.5rem, 3.5vw, 1.875rem)",
    fontWeight: 600,
    letterSpacing: "-0.025em",
    lineHeight: 1.3,
    color: "#ffffff",
    marginBottom: 12
  },
  // Question description - muted text
  questionDescription: {
    fontSize: 16,
    lineHeight: 1.5,
    color: "rgb(161, 161, 170)"
    // zinc-400
  },
  // Option cards - glass morphism effect with comfortable padding
  card: {
    backgroundColor: "rgba(24, 24, 27, 0.4)",
    backdropFilter: "blur(24px)",
    WebkitBackdropFilter: "blur(24px)",
    border: "1px solid rgba(255, 255, 255, 0.07)",
    borderRadius: 12,
    padding: "16px 20px",
    boxShadow: "0 8px 32px rgba(0, 0, 0, 0.2), inset 0 1px 0 rgba(255, 255, 255, 0.03)",
    transition: "all 300ms cubic-bezier(0.4, 0, 0.2, 1)"
  },
  // Selected card - solid blue fill, no glow
  cardSelected: {
    backgroundColor: "rgba(0, 153, 255, 0.32)",
    border: "1px solid rgba(0, 153, 255, 0.85)",
    boxShadow: "none"
  },
  // Hovered card - instant subtle highlight (no transform/lift)
  cardHovered: {
    backgroundColor: "rgba(24, 24, 27, 0.6)",
    border: "1px solid rgba(255, 255, 255, 0.12)"
  },
  // Card label text - more readable
  cardLabel: {
    fontSize: 15,
    fontWeight: 500,
    lineHeight: 1.4,
    color: "#ffffff"
  },
  // Card description text
  cardDescription: {
    fontSize: 14,
    lineHeight: 1.5,
    color: "rgb(113, 113, 122)"
    // zinc-500
  },
  // Keyboard hint badge
  cardKey: {
    backgroundColor: "rgba(255, 255, 255, 0.08)",
    border: "none",
    borderRadius: 6,
    fontSize: 12,
    fontWeight: 600
  },
  // Checkmark icon
  cardCheckmark: {
    color: "#0099ff"
  },
  // Text input styling - cleaner, modern sizing
  input: {
    backgroundColor: "transparent",
    border: "none",
    borderBottom: "2px solid rgba(255, 255, 255, 0.1)",
    borderRadius: 0,
    fontSize: 16,
    fontWeight: 400,
    color: "#ffffff",
    padding: "12px 0",
    transition: "border-color 200ms ease"
  },
  // Textarea styling
  textarea: {
    backgroundColor: "rgba(24, 24, 27, 0.4)",
    backdropFilter: "blur(24px)",
    WebkitBackdropFilter: "blur(24px)",
    border: "1px solid rgba(255, 255, 255, 0.07)",
    borderRadius: 12,
    fontSize: 16,
    lineHeight: 1.5,
    color: "#ffffff",
    padding: 16
  },
  // Progress bar container - fixed at top of viewport
  progress: {
    position: "fixed",
    top: 0,
    left: 0,
    right: 0,
    zIndex: 1e3,
    backgroundColor: "transparent"
  },
  // Progress bar itself
  progressBar: {
    height: 3
  },
  // Progress percentage text
  progressText: {
    color: "rgb(113, 113, 122)",
    // zinc-500
    fontSize: 11
  },
  // Navigation footer - relative positioning inside glass card
  navigation: {
    position: "relative",
    backgroundColor: "rgba(0, 0, 0, 0.4)",
    backdropFilter: "blur(24px)",
    WebkitBackdropFilter: "blur(24px)",
    borderTop: "1px solid rgba(255, 255, 255, 0.05)",
    borderRadius: "0 0 16px 16px",
    padding: "20px 40px"
  },
  // Back button
  buttonBack: {
    color: "rgb(161, 161, 170)",
    // zinc-400
    backgroundColor: "transparent",
    border: "none"
  },
  // Next/Continue button
  buttonNext: {
    backgroundColor: "#0099ff",
    color: "#ffffff",
    border: "none",
    borderRadius: 8,
    padding: "12px 24px",
    fontSize: 15,
    fontWeight: 600,
    boxShadow: "0 4px 20px rgba(0, 153, 255, 0.3)",
    transition: "all 200ms ease"
  },
  // Submit button (uses gradient, so keep background shorthand)
  buttonSubmit: {
    background: "linear-gradient(135deg, #0099ff 0%, #0066cc 100%)",
    color: "#ffffff",
    border: "none",
    borderRadius: 8,
    padding: "12px 28px",
    fontSize: 15,
    fontWeight: 600,
    boxShadow: "0 4px 20px rgba(0, 153, 255, 0.4)",
    transition: "all 200ms ease"
  },
  // Terminate button (No Show) - true red, not pink
  buttonTerminate: {
    backgroundColor: "#dc2626",
    color: "#ffffff",
    border: "none",
    borderRadius: 8,
    padding: "10px 20px",
    fontSize: 14,
    fontWeight: 600,
    transition: "all 200ms ease"
  },
  // Completion screen
  completion: {
    backgroundColor: "transparent"
  },
  // Completion icon (uses gradient, so keep background shorthand)
  completionIcon: {
    width: 100,
    height: 100,
    background: "linear-gradient(135deg, #0099ff 0%, #0066cc 100%)",
    boxShadow: "0 8px 40px rgba(0, 153, 255, 0.4)"
  },
  // Completion title
  completionTitle: {
    fontSize: 32,
    fontWeight: 600,
    color: "#ffffff"
  },
  // Completion text
  completionText: {
    fontSize: 18,
    color: "rgb(161, 161, 170)"
    // zinc-400
  },
  // Error message
  error: {
    color: "rgb(248, 113, 113)",
    // red-400
    fontSize: 14,
    marginTop: 12
  }
};

export { TypeformArrayField, TypeformCheckboxGroup, TypeformNavigation, TypeformProgress, TypeformQuestionWrapper, TypeformRadioGroup, TypeformSurvey, TypeformTextInput, brochureStyles, brochureTheme, createCustomValue, createPresetValue, createSurveyConfig, defaultTheme, extractAnswerValue, extractMultiAnswerValues, getAnswerString, getCustomValueText, getMultiAnswerStrings, hasCustomValue, hasPresetValue, isCustomValue, isPresetValue, mergeTheme, useCardStyle, useTypeform, useTypeformContext };
