"use client";
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/bookings/index.ts
var bookings_exports = {};
__export(bookings_exports, {
  BookingFormClient: () => BookingFormClient,
  useBookingFormConfig: () => useBookingFormConfig
});
module.exports = __toCommonJS(bookings_exports);

// ../blocks/src/system/runtime/utils/api-url.ts
function resolveMultiEnvDashboardUrl() {
  const env = process.env.RIVERBANK_ENV;
  if (!env) return null;
  const envKey = `RIVERBANK_${env.toUpperCase()}_DASHBOARD_URL`;
  const dashboardUrl = process.env[envKey];
  if (dashboardUrl) {
    return dashboardUrl.replace(/\/$/, "");
  }
  return null;
}
function getCmsApiUrl() {
  const multiEnvDashboard = resolveMultiEnvDashboardUrl();
  if (multiEnvDashboard) {
    return `${multiEnvDashboard}/api`;
  }
  const builderApiUrl = process.env.NEXT_PUBLIC_BUILDER_API_URL;
  if (builderApiUrl) {
    return builderApiUrl.replace(/\/$/, "");
  }
  const dashboardUrl = process.env.NEXT_PUBLIC_DASHBOARD_URL;
  if (dashboardUrl) {
    const base = dashboardUrl.replace(/\/$/, "");
    return `${base}/api`;
  }
  const legacyApiUrl = process.env.NEXT_PUBLIC_CMS_API_URL;
  if (legacyApiUrl) {
    return legacyApiUrl.replace(/\/$/, "");
  }
  throw new Error(
    "Dashboard URL not configured. Either:\n  1. Set RIVERBANK_ENV with RIVERBANK_LOCAL_DASHBOARD_URL / RIVERBANK_REMOTE_DASHBOARD_URL\n  2. Set NEXT_PUBLIC_BUILDER_API_URL (SDK sites)\n  3. Set NEXT_PUBLIC_DASHBOARD_URL (frontend app)"
  );
}

// ../blocks/src/system/runtime/nodes/booking-form.client.tsx
var import_react11 = __toESM(require("react"));

// ../blocks/src/system/runtime/components/multi-step/MultiStepForm.tsx
var import_react3 = require("react");

// ../blocks/src/system/runtime/components/multi-step/MultiStepContext.tsx
var import_react = require("react");
var MultiStepContext = (0, import_react.createContext)(null);
function useMultiStepContext() {
  const context = (0, import_react.useContext)(MultiStepContext);
  if (!context) {
    throw new Error(
      "useMultiStepContext must be used within a MultiStepForm component. Make sure your component is wrapped in <MultiStepForm>."
    );
  }
  return context;
}
function useMultiStepData() {
  const { data, updateData } = useMultiStepContext();
  return { data, updateData };
}

// ../blocks/src/system/runtime/components/multi-step/useMultiStep.ts
var import_react2 = require("react");
function useMultiStep({
  steps,
  initialData = {},
  onStepChange,
  onDataChange,
  onComplete,
  persistToUrl = false
}) {
  const [data, setData] = (0, import_react2.useState)(initialData);
  const [currentStepIndex, setCurrentStepIndex] = (0, import_react2.useState)(0);
  const [errors, setErrors] = (0, import_react2.useState)({});
  const [isValidating, setIsValidating] = (0, import_react2.useState)(false);
  const [isSubmitting, setIsSubmitting] = (0, import_react2.useState)(false);
  const visibleSteps = (0, import_react2.useMemo)(() => {
    return steps.filter((step) => {
      if (!step.condition) return true;
      return step.condition(data);
    });
  }, [steps, data]);
  const currentStep = visibleSteps[currentStepIndex];
  const currentStepId = currentStep?.id || "";
  (0, import_react2.useEffect)(() => {
    if (persistToUrl && currentStep) {
      const url = new URL(window.location.href);
      url.searchParams.set("step", currentStep.id);
      window.history.replaceState({}, "", url.toString());
    }
  }, [currentStepIndex, currentStep, persistToUrl]);
  (0, import_react2.useEffect)(() => {
    if (persistToUrl) {
      const url = new URL(window.location.href);
      const stepId = url.searchParams.get("step");
      if (stepId) {
        const stepIndex = visibleSteps.findIndex((s) => s.id === stepId);
        if (stepIndex !== -1) {
          setCurrentStepIndex(stepIndex);
        }
      }
    }
  }, []);
  (0, import_react2.useEffect)(() => {
    if (onStepChange && currentStep) {
      onStepChange(currentStep.id, currentStepIndex);
    }
  }, [currentStepIndex, currentStep, onStepChange]);
  const updateData = (0, import_react2.useCallback)(
    (updates) => {
      setData((prev) => {
        const newData = { ...prev, ...updates };
        onDataChange?.(newData);
        return newData;
      });
      setErrors({});
    },
    [onDataChange]
  );
  const validateCurrentStep = (0, import_react2.useCallback)(async () => {
    if (!currentStep?.validate) return true;
    setIsValidating(true);
    setErrors({});
    try {
      const result = await currentStep.validate(data);
      if (result.valid) {
        return true;
      } else {
        setErrors(result.errors);
        return false;
      }
    } catch (error) {
      console.error("Step validation error:", error);
      setErrors({ _form: "Validation failed. Please try again." });
      return false;
    } finally {
      setIsValidating(false);
    }
  }, [currentStep, data]);
  const goToNext = (0, import_react2.useCallback)(async () => {
    const isValid = await validateCurrentStep();
    if (!isValid) return;
    if (currentStepIndex === visibleSteps.length - 1) {
      if (onComplete) {
        setIsSubmitting(true);
        try {
          await onComplete(data);
        } catch (error) {
          console.error("Form submission error:", error);
          setErrors({ _form: "Submission failed. Please try again." });
        } finally {
          setIsSubmitting(false);
        }
      }
      return;
    }
    setCurrentStepIndex((prev) => Math.min(prev + 1, visibleSteps.length - 1));
    setErrors({});
  }, [currentStepIndex, visibleSteps.length, validateCurrentStep, onComplete, data]);
  const goToPrevious = (0, import_react2.useCallback)(() => {
    setCurrentStepIndex((prev) => Math.max(prev - 1, 0));
    setErrors({});
  }, []);
  const goToStep = (0, import_react2.useCallback)(
    (stepIndex) => {
      if (stepIndex >= 0 && stepIndex < visibleSteps.length) {
        setCurrentStepIndex(stepIndex);
        setErrors({});
      }
    },
    [visibleSteps.length]
  );
  const goToStepById = (0, import_react2.useCallback)(
    (stepId) => {
      const stepIndex = visibleSteps.findIndex((s) => s.id === stepId);
      if (stepIndex !== -1) {
        goToStep(stepIndex);
      }
    },
    [visibleSteps, goToStep]
  );
  const reset = (0, import_react2.useCallback)(() => {
    setData(initialData);
    setCurrentStepIndex(0);
    setErrors({});
    setIsValidating(false);
    setIsSubmitting(false);
  }, [initialData]);
  const canGoNext = !isValidating && !isSubmitting;
  const canGoBack = currentStepIndex > 0 && !isValidating && !isSubmitting;
  const isFirstStep = currentStepIndex === 0;
  const isLastStep = currentStepIndex === visibleSteps.length - 1;
  return {
    currentStepIndex,
    currentStepId,
    visibleSteps,
    data,
    errors,
    isValidating,
    isSubmitting,
    goToNext,
    goToPrevious,
    goToStep,
    goToStepById,
    updateData,
    canGoNext,
    canGoBack,
    isFirstStep,
    isLastStep,
    reset
  };
}

// ../blocks/src/system/runtime/components/multi-step/MultiStepForm.tsx
var import_jsx_runtime = require("react/jsx-runtime");
function MultiStepForm({
  steps,
  initialData,
  onComplete,
  onStepChange,
  onDataChange,
  progressStyle = "dots",
  className = "",
  persistToUrl = false,
  allowSkip = false
}) {
  const context = useMultiStep({
    steps,
    initialData,
    onStepChange,
    onDataChange,
    onComplete,
    persistToUrl
  });
  const {
    visibleSteps,
    currentStepIndex,
    goToNext,
    goToPrevious,
    goToStep,
    canGoNext,
    canGoBack,
    isFirstStep,
    isLastStep,
    errors,
    isValidating,
    isSubmitting
  } = context;
  const currentStep = visibleSteps[currentStepIndex];
  if (!currentStep) {
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "text-center py-12", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "text-muted-foreground", children: "No steps available" }) });
  }
  const stepComponent = (0, import_react3.isValidElement)(currentStep.component) ? (0, import_react3.cloneElement)(currentStep.component, {
    // Step components can access context via hooks, but we also pass key props
    stepId: currentStep.id,
    stepIndex: currentStepIndex
  }) : currentStep.component;
  const showBackButton = !isFirstStep && !currentStep.hideBack && canGoBack;
  const showNextButton = !currentStep.isTerminal;
  const nextButtonLabel = isLastStep ? currentStep.nextLabel || "Complete" : currentStep.nextLabel || "Continue";
  const backButtonLabel = currentStep.backLabel || "Back";
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(MultiStepContext.Provider, { value: context, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: `multi-step-form ${className}`, children: [
    progressStyle !== "none" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "mb-8", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      ProgressIndicator,
      {
        steps: visibleSteps,
        currentIndex: currentStepIndex,
        style: progressStyle,
        onStepClick: allowSkip ? goToStep : void 0
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "step-content", children: stepComponent }),
    Object.keys(errors).length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "mt-6 alert alert-error", children: [
      errors._form && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "text-sm font-medium", children: errors._form }),
      Object.entries(errors).filter(([key]) => key !== "_form").map(([key, message]) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "text-sm", children: message }, key))
    ] }),
    (showBackButton || showNextButton) && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex gap-3 mt-8", children: [
      showBackButton && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        "button",
        {
          type: "button",
          onClick: goToPrevious,
          disabled: !canGoBack,
          className: "outline btn-md",
          children: backButtonLabel
        }
      ),
      showNextButton && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
        "button",
        {
          type: "button",
          onClick: goToNext,
          disabled: !canGoNext,
          className: "primary btn-md flex-1",
          children: [
            isValidating && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "inline-block animate-spin rounded-full h-4 w-4 border-b-2 border-current" }),
            isSubmitting && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "inline-block animate-spin rounded-full h-4 w-4 border-b-2 border-current" }),
            !isValidating && !isSubmitting && nextButtonLabel,
            isValidating && "Validating...",
            isSubmitting && "Submitting..."
          ]
        }
      )
    ] })
  ] }) });
}
function ProgressIndicator({
  steps,
  currentIndex,
  style,
  onStepClick
}) {
  if (style === "dots") {
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex items-center justify-center gap-2", children: steps.map((step, index) => {
      const isActive = index === currentIndex;
      const isCompleted = index < currentIndex;
      const isClickable = onStepClick && index <= currentIndex;
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        "button",
        {
          type: "button",
          onClick: isClickable ? () => onStepClick(index) : void 0,
          disabled: !isClickable,
          className: `
                step-dot transition-all
                ${isActive ? "step-dot-active" : ""}
                ${isCompleted ? "step-dot-complete" : ""}
                ${isClickable ? "cursor-pointer hover:scale-125" : "cursor-default"}
              `,
          "aria-label": step.title
        },
        step.id
      );
    }) });
  }
  if (style === "steps") {
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex items-center justify-between", children: steps.map((step, index) => {
      const isActive = index === currentIndex;
      const isCompleted = index < currentIndex;
      const isClickable = onStepClick && index <= currentIndex;
      const isLast = index === steps.length - 1;
      return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex items-center flex-1", children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
          "button",
          {
            type: "button",
            onClick: isClickable ? () => onStepClick(index) : void 0,
            disabled: !isClickable,
            className: `
                  flex items-center gap-2
                  ${isClickable ? "cursor-pointer" : "cursor-default"}
                `,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                "div",
                {
                  className: `
                    step-circle transition-colors
                    ${isActive ? "step-circle-active" : ""}
                    ${isCompleted ? "step-circle-complete" : ""}
                  `,
                  children: isCompleted ? "\u2713" : index + 1
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                "span",
                {
                  className: `
                    text-sm hidden sm:inline
                    ${isActive ? "font-medium" : ""}
                    ${isCompleted || !isActive ? "status-muted" : ""}
                  `,
                  children: step.title
                }
              )
            ]
          }
        ),
        !isLast && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "step-connector mx-2 hidden sm:block" })
      ] }, step.id);
    }) });
  }
  const progress = (currentIndex + 1) / steps.length * 100;
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "space-y-2", children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex justify-between text-sm status-muted", children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
        "Step ",
        currentIndex + 1,
        " of ",
        steps.length
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
        Math.round(progress),
        "%"
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "progress-bar", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      "div",
      {
        className: "progress-fill",
        style: { width: `${progress}%` }
      }
    ) })
  ] });
}

// ../blocks/src/system/runtime/components/booking/SuccessMessage.tsx
var import_jsx_runtime2 = require("react/jsx-runtime");
var SuccessMessage = ({ message, className }) => {
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
    "div",
    {
      className: `alert alert-success text-sm ${className ?? ""}`,
      role: "alert",
      "aria-live": "polite",
      children: message
    }
  );
};

// ../blocks/src/system/runtime/hooks/useBookingSteps.ts
var import_react9 = __toESM(require("react"));

// ../blocks/src/system/runtime/components/booking/ServiceResourceSelector.tsx
var import_react4 = require("react");
var import_jsx_runtime3 = require("react/jsx-runtime");
function ServiceResourceSelector({
  siteId,
  services,
  preSelectedServiceId,
  preSelectedResourceId,
  onSelect,
  onBack,
  heading = "Select Service",
  description = "Choose the service you'd like to book"
}) {
  const [selectedServiceId, setSelectedServiceId] = (0, import_react4.useState)(
    preSelectedServiceId
  );
  const [selectedResourceId, setSelectedResourceId] = (0, import_react4.useState)(
    preSelectedResourceId
  );
  const [resources, setResources] = (0, import_react4.useState)([]);
  const [isLoadingResources, setIsLoadingResources] = (0, import_react4.useState)(false);
  const [resourceError, setResourceError] = (0, import_react4.useState)(null);
  const showServiceSelect = !preSelectedServiceId && services.length > 1;
  const showResourceSelect = resources.length > 1 && !preSelectedResourceId;
  const handleServiceChange = (0, import_react4.useCallback)(async (serviceId) => {
    setSelectedServiceId(serviceId);
    setSelectedResourceId(void 0);
    setResourceError(null);
    try {
      setIsLoadingResources(true);
      const apiUrl = getCmsApiUrl();
      const response = await fetch(
        `${apiUrl}/sites/${siteId}/bookings/resources/reference?serviceId=${serviceId}`
      );
      if (!response.ok) {
        throw new Error("Failed to load resources");
      }
      const data = await response.json();
      const loadedResources = data.options?.map((opt) => ({
        id: opt.id,
        displayName: opt.label
      })) || [];
      setResources(loadedResources);
    } catch (err) {
      console.error("Failed to load resources:", err);
      setResourceError("Failed to load practitioners. Please try again.");
      setResources([]);
    } finally {
      setIsLoadingResources(false);
    }
  }, [siteId]);
  const handleContinue = () => {
    if (selectedServiceId) {
      onSelect({
        serviceId: selectedServiceId,
        resourceId: selectedResourceId === "__any__" ? void 0 : selectedResourceId
      });
    }
  };
  const canContinue = selectedServiceId && !isLoadingResources;
  (0, import_react4.useEffect)(() => {
    if (services.length === 1 && !selectedServiceId) {
      handleServiceChange(services[0].id);
    }
  }, [services, selectedServiceId, handleServiceChange]);
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "space-y-6 max-w-2xl mx-auto", children: [
    /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { children: [
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("h2", { className: "text-2xl font-bold", children: heading }),
      description && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "text-muted-foreground mt-2", children: description })
    ] }),
    showServiceSelect && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "space-y-3", children: [
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("label", { className: "text-sm font-medium", children: "Service" }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "grid gap-3", children: services.map((service) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
        "button",
        {
          type: "button",
          onClick: () => handleServiceChange(service.id),
          className: `
                  relative p-4 rounded-lg border-2 text-left transition-all
                  ${selectedServiceId === service.id ? "border-primary bg-primary/5" : "border-border hover:border-primary/50"}
                `,
          children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "flex items-start justify-between", children: [
            /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { children: [
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "font-medium", children: service.title }),
              service.description && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "text-sm text-muted-foreground mt-1", children: service.description }),
              service.durationMinutes && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "text-sm text-muted-foreground mt-1", children: [
                service.durationMinutes,
                " minutes"
              ] })
            ] }),
            selectedServiceId === service.id && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "flex-shrink-0 w-5 h-5 rounded-full bg-primary flex items-center justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
              "svg",
              {
                className: "w-3 h-3 text-primary-foreground",
                fill: "none",
                strokeLinecap: "round",
                strokeLinejoin: "round",
                strokeWidth: "2",
                viewBox: "0 0 24 24",
                stroke: "currentColor",
                children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("path", { d: "M5 13l4 4L19 7" })
              }
            ) })
          ] })
        },
        service.id
      )) })
    ] }),
    showResourceSelect && selectedServiceId && !isLoadingResources && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "space-y-3", children: [
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("label", { className: "text-sm font-medium", children: "Practitioner (Optional)" }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "text-sm text-muted-foreground", children: 'Choose a specific practitioner or select "Any Available"' }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "grid gap-3", children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
          "button",
          {
            type: "button",
            onClick: () => setSelectedResourceId("__any__"),
            className: `
                relative p-4 rounded-lg border-2 text-left transition-all
                ${selectedResourceId === "__any__" ? "border-primary bg-primary/5" : "border-border hover:border-primary/50"}
              `,
            children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "flex items-center justify-between", children: [
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "font-medium", children: "Any Available" }),
              selectedResourceId === "__any__" && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "flex-shrink-0 w-5 h-5 rounded-full bg-primary flex items-center justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
                "svg",
                {
                  className: "w-3 h-3 text-primary-foreground",
                  fill: "none",
                  strokeLinecap: "round",
                  strokeLinejoin: "round",
                  strokeWidth: "2",
                  viewBox: "0 0 24 24",
                  stroke: "currentColor",
                  children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("path", { d: "M5 13l4 4L19 7" })
                }
              ) })
            ] })
          }
        ),
        resources.map((resource) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
          "button",
          {
            type: "button",
            onClick: () => setSelectedResourceId(resource.id),
            className: `
                  relative p-4 rounded-lg border-2 text-left transition-all
                  ${selectedResourceId === resource.id ? "border-primary bg-primary/5" : "border-border hover:border-primary/50"}
                `,
            children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "flex items-center justify-between", children: [
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "font-medium", children: resource.displayName }),
              selectedResourceId === resource.id && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "flex-shrink-0 w-5 h-5 rounded-full bg-primary flex items-center justify-center", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
                "svg",
                {
                  className: "w-3 h-3 text-primary-foreground",
                  fill: "none",
                  strokeLinecap: "round",
                  strokeLinejoin: "round",
                  strokeWidth: "2",
                  viewBox: "0 0 24 24",
                  stroke: "currentColor",
                  children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("path", { d: "M5 13l4 4L19 7" })
                }
              ) })
            ] })
          },
          resource.id
        ))
      ] })
    ] }),
    isLoadingResources && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "text-center py-8", children: [
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary" }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "text-sm text-muted-foreground mt-2", children: "Loading practitioners..." })
    ] }),
    resourceError && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "alert alert-error text-sm", children: resourceError }),
    /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "flex gap-3", children: [
      onBack && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
        "button",
        {
          type: "button",
          onClick: onBack,
          className: "px-6 py-2 rounded-lg border border-border hover:bg-muted transition-colors",
          children: "Back"
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
        "button",
        {
          type: "button",
          onClick: handleContinue,
          disabled: !canContinue,
          className: "flex-1 px-6 py-2 rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",
          children: "Continue to Date Selection"
        }
      )
    ] })
  ] });
}

// ../blocks/src/system/runtime/components/booking/ServiceSelectionStep.tsx
var import_jsx_runtime4 = require("react/jsx-runtime");
function ServiceSelectionStep({
  siteId,
  services
}) {
  const { updateData } = useMultiStepData();
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
    ServiceResourceSelector,
    {
      siteId,
      services,
      onSelect: ({ serviceId, resourceId }) => {
        updateData({ serviceId, resourceId });
      }
    }
  );
}

// ../blocks/src/system/runtime/components/booking/DateTimeSelectionStep.tsx
var import_react7 = require("react");

// ../blocks/src/utils/date-formatting.ts
var BOOKING_FETCH_CHUNK_DAYS = 30;
function formatDate(dateStr) {
  const date = /* @__PURE__ */ new Date(dateStr + "T00:00:00");
  return date.toLocaleDateString(void 0, {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric"
  });
}
function formatTime(isoString) {
  const date = new Date(isoString);
  return date.toLocaleTimeString(void 0, {
    hour: "numeric",
    minute: "2-digit",
    timeZoneName: "short"
  });
}

// ../blocks/src/system/runtime/components/booking/DatePicker.tsx
var import_jsx_runtime5 = require("react/jsx-runtime");
var DatePicker = ({
  value,
  onChange,
  dateOptions,
  required = true,
  isLoading = false,
  isEmpty = false,
  hasMore = false,
  onLoadMore
}) => {
  if (isLoading) {
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "space-y-2", children: [
      /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("label", { className: "form-label", children: [
        "Select Date",
        required && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "required-marker", children: "*" })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "h-10 w-full animate-pulse rounded-control card-surface" }),
      /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { className: "text-xs status-muted", children: "Loading available dates..." })
    ] });
  }
  if (isEmpty) {
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "space-y-2", children: [
      /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("label", { className: "form-label", children: [
        "Select Date",
        required && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "required-marker", children: "*" })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "alert alert-warning", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("p", { className: "text-sm", children: [
        "No available dates in this period.",
        hasMore && onLoadMore && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
          "button",
          {
            type: "button",
            onClick: onLoadMore,
            className: "ml-2 underline hover:no-underline",
            children: "Check later dates"
          }
        )
      ] }) })
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "space-y-2", children: [
    /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("label", { htmlFor: "booking-date", className: "form-label", children: [
      "Select Date",
      required && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "required-marker", children: "*" })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
      "select",
      {
        id: "booking-date",
        value,
        onChange: (e) => onChange(e.target.value),
        required,
        className: "form-select",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: "", children: "Choose a date..." }),
          dateOptions.map((date) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: date, children: formatDate(date) }, date))
        ]
      }
    ),
    hasMore && onLoadMore && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
      "button",
      {
        type: "button",
        onClick: onLoadMore,
        className: "button-link text-sm",
        children: "Load more dates \u2192"
      }
    )
  ] });
};

// ../blocks/src/system/runtime/components/booking/TimeSlotSelector.tsx
var import_jsx_runtime6 = require("react/jsx-runtime");
var TimeSlotSelector = ({
  value,
  onChange,
  slots,
  isLoading,
  required = true
}) => {
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "space-y-2", children: [
    /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("label", { htmlFor: "booking-slot", className: "form-label", children: [
      "Select Time",
      required && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "required-marker", children: "*" })
    ] }),
    isLoading ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("div", { className: "alert alert-info text-sm text-center", children: "Loading available times..." }) : slots.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("div", { className: "alert text-sm text-center status-muted", children: "No available times for this date" }) : /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
      "select",
      {
        id: "booking-slot",
        value,
        onChange: (e) => onChange(e.target.value),
        required,
        className: "form-select",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("option", { value: "", children: "Choose a time..." }),
          slots.map((slot) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("option", { value: slot.startAt, children: formatTime(slot.startAt) }, slot.startAt))
        ]
      }
    )
  ] });
};

// ../blocks/src/system/runtime/hooks/useAvailableSlots.ts
var import_react5 = require("react");
function useAvailableSlots({
  siteId,
  serviceId,
  resourceId,
  selectedDate,
  timezone
}) {
  const [slots, setSlots] = (0, import_react5.useState)([]);
  const [isLoading, setIsLoading] = (0, import_react5.useState)(false);
  const [error, setError] = (0, import_react5.useState)(null);
  (0, import_react5.useEffect)(() => {
    if (!selectedDate || !serviceId) {
      setSlots([]);
      return;
    }
    const fetchSlots = async () => {
      setIsLoading(true);
      setError(null);
      setSlots([]);
      try {
        const params = new URLSearchParams({
          siteId,
          serviceId,
          startDate: selectedDate,
          endDate: selectedDate,
          timezone
        });
        if (resourceId) {
          params.append("resourceId", resourceId);
        }
        const apiUrl = getCmsApiUrl();
        const response = await fetch(`${apiUrl}/public/bookings/availability/slots?${params}`, {
          method: "GET",
          headers: {
            "Content-Type": "application/json"
          }
        });
        if (!response.ok) {
          const errorData = await response.json().catch(() => ({}));
          throw new Error(errorData.error || "Failed to load available times");
        }
        const data = await response.json();
        setSlots(data.slots);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Failed to load available times");
      } finally {
        setIsLoading(false);
      }
    };
    fetchSlots();
  }, [selectedDate, serviceId, resourceId, timezone, siteId]);
  return { slots, isLoading, error };
}

// ../blocks/src/system/runtime/hooks/useAvailableDates.ts
var import_react6 = require("react");
function useAvailableDates({
  siteId,
  serviceId,
  resourceId,
  timezone = "UTC",
  initialDays = 30
}) {
  const [availableDates, setAvailableDates] = (0, import_react6.useState)(/* @__PURE__ */ new Set());
  const [isLoading, setIsLoading] = (0, import_react6.useState)(false);
  const [error, setError] = (0, import_react6.useState)(null);
  const [hasMore, setHasMore] = (0, import_react6.useState)(false);
  const [loadedRange, setLoadedRange] = (0, import_react6.useState)(null);
  const nextStartDateRef = (0, import_react6.useRef)(null);
  const requestIdRef = (0, import_react6.useRef)(0);
  const fetchDates = (0, import_react6.useCallback)(
    async (startDate, endDate, append = false) => {
      if (!serviceId) {
        console.log("[useAvailableDates] No serviceId, skipping fetch");
        return;
      }
      const requestId = ++requestIdRef.current;
      setIsLoading(true);
      setError(null);
      try {
        const apiUrl = getCmsApiUrl();
        const params = new URLSearchParams({
          siteId,
          serviceId,
          startDate,
          endDate,
          timezone
        });
        if (resourceId) {
          params.append("resourceId", resourceId);
        }
        const url = `${apiUrl}/public/bookings/availability/dates?${params}`;
        console.log("[useAvailableDates] Fetching:", url);
        const res = await fetch(url, {
          method: "GET",
          headers: {
            "Content-Type": "application/json"
          }
        });
        console.log("[useAvailableDates] Response status:", res.status);
        if (requestId !== requestIdRef.current) return;
        if (!res.ok) {
          const errorData = await res.json().catch(() => ({}));
          console.log("[useAvailableDates] Error response:", errorData);
          throw new Error(errorData.error || "Failed to fetch available dates");
        }
        const data = await res.json();
        console.log("[useAvailableDates] Received dates:", data);
        setAvailableDates((prev) => {
          const newSet = append ? new Set(prev) : /* @__PURE__ */ new Set();
          data.dates.forEach((d) => newSet.add(d));
          console.log("[useAvailableDates] Updated availableDates Set size:", newSet.size);
          return newSet;
        });
        setHasMore(data.hasMore);
        nextStartDateRef.current = data.nextStartDate || null;
        setLoadedRange((prev) => ({
          start: append && prev ? prev.start : data.startDate,
          end: data.endDate
        }));
      } catch (err) {
        if (requestId !== requestIdRef.current) return;
        setError(err instanceof Error ? err.message : "Failed to load available dates");
      } finally {
        if (requestId === requestIdRef.current) {
          setIsLoading(false);
        }
      }
    },
    [siteId, serviceId, resourceId, timezone]
  );
  (0, import_react6.useEffect)(() => {
    if (!serviceId) {
      setAvailableDates(/* @__PURE__ */ new Set());
      setLoadedRange(null);
      setHasMore(false);
      return;
    }
    const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
    const endDate = new Date(Date.now() + initialDays * 24 * 60 * 60 * 1e3).toISOString().split("T")[0];
    fetchDates(today, endDate, false);
  }, [serviceId, fetchDates, initialDays]);
  const loadMore = (0, import_react6.useCallback)(() => {
    if (!nextStartDateRef.current || isLoading) return;
    const start = nextStartDateRef.current;
    const msPerDay = 24 * 60 * 60 * 1e3;
    const end = new Date(new Date(start).getTime() + BOOKING_FETCH_CHUNK_DAYS * msPerDay).toISOString().split("T")[0];
    fetchDates(start, end, true);
  }, [fetchDates, isLoading]);
  return {
    availableDates,
    isLoading,
    error,
    hasMore,
    loadMore,
    loadedRange
  };
}

// ../blocks/src/system/runtime/components/booking/DateTimeSelectionStep.tsx
var import_jsx_runtime7 = require("react/jsx-runtime");
function DateTimeSelectionStep({
  siteId,
  preSelectedServiceId,
  preSelectedResourceId,
  singleService
}) {
  const { data, updateData } = useMultiStepData();
  const serviceId = data.serviceId || preSelectedServiceId;
  const resourceId = data.resourceId || preSelectedResourceId;
  const selectedDate = data.selectedDate || "";
  const selectedSlot = data.selectedSlot || "";
  (0, import_react7.useEffect)(() => {
    if (preSelectedServiceId && !data.serviceId) {
      updateData({ serviceId: preSelectedServiceId });
    }
  }, [preSelectedServiceId, data.serviceId, updateData]);
  const {
    availableDates,
    isLoading: isLoadingDates,
    error: datesError,
    hasMore,
    loadMore
  } = useAvailableDates({
    siteId,
    serviceId,
    resourceId,
    timezone: "UTC",
    initialDays: 30
  });
  const { slots, isLoading: isLoadingSlots, error: slotsError } = useAvailableSlots({
    siteId,
    serviceId,
    resourceId,
    selectedDate,
    timezone: "UTC"
  });
  const filteredDateOptions = (0, import_react7.useMemo)(() => {
    if (isLoadingDates || availableDates.size === 0) {
      return [];
    }
    return [...availableDates].sort();
  }, [availableDates, isLoadingDates]);
  const handleDateChange = (date) => {
    updateData({ selectedDate: date, selectedSlot: "" });
  };
  const handleSlotChange = (slot) => {
    updateData({ selectedSlot: slot });
  };
  const error = datesError || slotsError;
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: "space-y-6", children: [
    singleService && /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: "rounded-lg border border-border bg-muted/30 p-4", children: [
      /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("h3", { className: "font-medium text-foreground", children: singleService.title }),
      singleService.description && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("p", { className: "mt-1 text-sm text-muted-foreground", children: singleService.description }),
      singleService.durationMinutes && /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("p", { className: "mt-1 text-sm text-muted-foreground", children: [
        "Duration: ",
        singleService.durationMinutes,
        " minutes"
      ] })
    ] }),
    error && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("div", { className: "alert alert-error text-sm", children: error }),
    /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
      DatePicker,
      {
        value: selectedDate,
        onChange: handleDateChange,
        dateOptions: filteredDateOptions,
        isLoading: isLoadingDates,
        isEmpty: !isLoadingDates && filteredDateOptions.length === 0,
        hasMore,
        onLoadMore: loadMore
      }
    ),
    selectedDate && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
      TimeSlotSelector,
      {
        value: selectedSlot,
        onChange: handleSlotChange,
        slots,
        isLoading: isLoadingSlots
      }
    )
  ] });
}

// ../blocks/src/system/runtime/components/multi-step/DynamicFormFields.tsx
var import_react8 = require("react");
var import_jsx_runtime8 = require("react/jsx-runtime");
function DynamicFormFields({
  fields,
  showLabels = true,
  className = ""
}) {
  const { data, updateData } = useMultiStepData();
  const [touched, setTouched] = (0, import_react8.useState)({});
  const handleChange = (0, import_react8.useCallback)(
    (fieldId, value) => {
      updateData({ [fieldId]: value });
    },
    [updateData]
  );
  const handleBlur = (0, import_react8.useCallback)((fieldId) => {
    setTouched((prev) => ({ ...prev, [fieldId]: true }));
  }, []);
  const getFieldError = (0, import_react8.useCallback)(
    (field) => {
      const value = data[field.id];
      const isTouched = touched[field.id];
      if (!isTouched) return null;
      if (field.required && !value) {
        return `${field.label} is required`;
      }
      if (value) {
        switch (field.type) {
          case "email":
            if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
              return "Please enter a valid email address";
            }
            break;
          case "url":
            try {
              new URL(value);
            } catch {
              return "Please enter a valid URL";
            }
            break;
          case "tel":
            if (!/^[+\d\s\-()]+$/.test(value)) {
              return "Please enter a valid phone number";
            }
            break;
          case "number":
            const num = Number(value);
            if (isNaN(num)) {
              return "Please enter a valid number";
            }
            if (field.min !== void 0 && num < field.min) {
              return `Value must be at least ${field.min}`;
            }
            if (field.max !== void 0 && num > field.max) {
              return `Value must be at most ${field.max}`;
            }
            break;
        }
        if (typeof value === "string") {
          if (field.minLength && value.length < field.minLength) {
            return `Must be at least ${field.minLength} characters`;
          }
          if (field.maxLength && value.length > field.maxLength) {
            return `Must be at most ${field.maxLength} characters`;
          }
        }
        if (field.pattern && typeof value === "string") {
          const regex = new RegExp(field.pattern);
          if (!regex.test(value)) {
            return "Please match the required format";
          }
        }
      }
      return null;
    },
    [data, touched]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("div", { className: `space-y-6 ${className}`, children: fields.map((field) => {
    const error = getFieldError(field);
    const value = data[field.id] ?? "";
    return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "space-y-2", children: [
      showLabels && /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("label", { htmlFor: field.id, className: "form-label", children: [
        field.label,
        field.required && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", { className: "required-marker", children: "*" })
      ] }),
      field.helpText && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("p", { className: "text-sm status-muted", children: field.helpText }),
      /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
        FieldInput,
        {
          field,
          value,
          onChange: (val) => handleChange(field.id, val),
          onBlur: () => handleBlur(field.id),
          error
        }
      ),
      error && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("p", { className: "text-sm status-error", children: error })
    ] }, field.id);
  }) });
}
function FieldInput({
  field,
  value,
  onChange,
  onBlur,
  error
}) {
  const inputClass = "form-input";
  const textareaClass = "form-textarea";
  const selectClass = "form-select";
  const checkboxClass = "form-checkbox";
  const radioClass = "form-radio";
  switch (field.type) {
    case "textarea":
      return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
        "textarea",
        {
          id: field.id,
          name: field.id,
          value,
          onChange: (e) => onChange(e.target.value),
          onBlur,
          placeholder: field.placeholder,
          required: field.required,
          minLength: field.minLength,
          maxLength: field.maxLength,
          rows: 4,
          "aria-invalid": error ? "true" : void 0,
          className: textareaClass
        }
      );
    case "select":
      if (field.multiple) {
        return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
          "select",
          {
            id: field.id,
            name: field.id,
            value: Array.isArray(value) ? value : [],
            onChange: (e) => {
              const selected = Array.from(e.target.selectedOptions, (opt) => opt.value);
              onChange(selected);
            },
            onBlur,
            required: field.required,
            multiple: true,
            "aria-invalid": error ? "true" : void 0,
            className: `${selectClass} h-32`,
            children: field.options?.map((opt) => /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("option", { value: opt.value, children: opt.label }, opt.value))
          }
        );
      }
      return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(
        "select",
        {
          id: field.id,
          name: field.id,
          value,
          onChange: (e) => onChange(e.target.value),
          onBlur,
          required: field.required,
          "aria-invalid": error ? "true" : void 0,
          className: selectClass,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("option", { value: "", children: "Select an option..." }),
            field.options?.map((opt) => /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("option", { value: opt.value, children: opt.label }, opt.value))
          ]
        }
      );
    case "radio":
      return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("div", { className: "space-y-2", children: field.options?.map((opt) => /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("label", { className: "flex items-center gap-2 cursor-pointer", children: [
        /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
          "input",
          {
            type: "radio",
            name: field.id,
            value: opt.value,
            checked: value === opt.value,
            onChange: (e) => onChange(e.target.value),
            onBlur,
            required: field.required,
            className: radioClass
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", { className: "text-sm", children: opt.label })
      ] }, opt.value)) });
    case "checkbox":
      if (field.options && field.options.length > 1) {
        const checkedValues = Array.isArray(value) ? value : [];
        return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("div", { className: "space-y-2", children: field.options.map((opt) => /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("label", { className: "flex items-center gap-2 cursor-pointer", children: [
          /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
            "input",
            {
              type: "checkbox",
              name: field.id,
              value: opt.value,
              checked: checkedValues.includes(opt.value),
              onChange: (e) => {
                const newValues = e.target.checked ? [...checkedValues, opt.value] : checkedValues.filter((v) => v !== opt.value);
                onChange(newValues);
              },
              onBlur,
              className: checkboxClass
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", { className: "text-sm", children: opt.label })
        ] }, opt.value)) });
      }
      return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("label", { className: "flex items-center gap-2 cursor-pointer", children: [
        /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
          "input",
          {
            type: "checkbox",
            id: field.id,
            name: field.id,
            checked: !!value,
            onChange: (e) => onChange(e.target.checked),
            onBlur,
            required: field.required,
            className: checkboxClass
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", { className: "text-sm", children: field.placeholder || field.label })
      ] });
    case "consent":
      return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("label", { className: "flex items-start gap-2 cursor-pointer", children: [
        /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
          "input",
          {
            type: "checkbox",
            id: field.id,
            name: field.id,
            checked: !!value,
            onChange: (e) => onChange(e.target.checked),
            onBlur,
            required: field.required,
            className: `${checkboxClass} mt-0.5`
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", { className: "text-sm", children: field.placeholder || field.label })
      ] });
    case "number":
      return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
        "input",
        {
          type: "number",
          id: field.id,
          name: field.id,
          value,
          onChange: (e) => onChange(e.target.value),
          onBlur,
          placeholder: field.placeholder,
          required: field.required,
          min: field.min,
          max: field.max,
          "aria-invalid": error ? "true" : void 0,
          className: inputClass
        }
      );
    case "date":
      return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
        "input",
        {
          type: "date",
          id: field.id,
          name: field.id,
          value,
          onChange: (e) => onChange(e.target.value),
          onBlur,
          required: field.required,
          min: field.min ? String(field.min) : void 0,
          max: field.max ? String(field.max) : void 0,
          "aria-invalid": error ? "true" : void 0,
          className: inputClass
        }
      );
    case "time":
      return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
        "input",
        {
          type: "time",
          id: field.id,
          name: field.id,
          value,
          onChange: (e) => onChange(e.target.value),
          onBlur,
          required: field.required,
          "aria-invalid": error ? "true" : void 0,
          className: inputClass
        }
      );
    // text, email, tel, url
    default:
      return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
        "input",
        {
          type: field.type,
          id: field.id,
          name: field.id,
          value,
          onChange: (e) => onChange(e.target.value),
          onBlur,
          placeholder: field.placeholder,
          required: field.required,
          minLength: field.minLength,
          maxLength: field.maxLength,
          pattern: field.pattern,
          "aria-invalid": error ? "true" : void 0,
          className: inputClass
        }
      );
  }
}

// ../blocks/src/system/runtime/hooks/useBookingSteps.ts
function useBookingSteps(siteId, formConfig, services) {
  return (0, import_react9.useMemo)(() => {
    if (!formConfig) return [];
    const stepsArray = [];
    const effectiveServiceId = formConfig.settings?.serviceId || (services.length === 1 ? services[0].id : void 0);
    const needsServiceSelection = !formConfig.settings?.serviceId && services.length > 1 || formConfig.settings?.serviceIds && formConfig.settings.serviceIds.length > 1;
    if (needsServiceSelection) {
      stepsArray.push({
        id: "service-selection",
        title: "Select Service",
        component: import_react9.default.createElement(ServiceSelectionStep, { siteId, services }),
        condition: () => needsServiceSelection,
        validate: (data) => {
          if (!data.serviceId) {
            return { valid: false, errors: { _form: "Please select a service" } };
          }
          return { valid: true };
        }
      });
    }
    const singleService = services.length === 1 ? services[0] : void 0;
    stepsArray.push({
      id: "datetime-selection",
      title: "Select Date & Time",
      component: import_react9.default.createElement(DateTimeSelectionStep, {
        siteId,
        preSelectedServiceId: effectiveServiceId,
        preSelectedResourceId: formConfig.settings?.resourceId,
        singleService
      }),
      validate: (data) => {
        if (!data.selectedSlot) {
          return { valid: false, errors: { _form: "Please select a date and time" } };
        }
        return { valid: true };
      }
    });
    if (formConfig.schema?.fields && formConfig.schema.fields.length > 0) {
      stepsArray.push({
        id: "custom-fields",
        title: "Your Information",
        component: import_react9.default.createElement(DynamicFormFields, { fields: formConfig.schema.fields }),
        validate: (data) => {
          const errors = {};
          for (const field of formConfig.schema.fields) {
            if (field.required && !data[field.id]) {
              errors[field.id] = `${field.label} is required`;
            }
          }
          if (Object.keys(errors).length > 0) {
            return { valid: false, errors };
          }
          return { valid: true };
        }
      });
    }
    return stepsArray;
  }, [formConfig, services, siteId]);
}

// ../blocks/src/system/runtime/hooks/useBookingSubmission.ts
var import_react10 = require("react");
function useBookingSubmission(siteId) {
  const [isSubmitting, setIsSubmitting] = (0, import_react10.useState)(false);
  const [error, setError] = (0, import_react10.useState)(null);
  const [isSuccess, setIsSuccess] = (0, import_react10.useState)(false);
  const submit = async (data) => {
    setIsSubmitting(true);
    setError(null);
    try {
      const apiUrl = getCmsApiUrl();
      const response = await fetch(`${apiUrl}/public/bookings/appointments`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          formId: data.formId,
          serviceId: data.serviceId,
          resourceId: data.resourceId || null,
          startAt: data.startAt,
          endAt: data.endAt,
          customFields: data.customFields,
          timezone: data.timezone
        })
      });
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.error || "Failed to book appointment");
      }
      setIsSuccess(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to book appointment");
      throw err;
    } finally {
      setIsSubmitting(false);
    }
  };
  return { submit, isSubmitting, error, isSuccess };
}

// ../blocks/src/system/runtime/nodes/booking-form.client.tsx
var import_jsx_runtime9 = require("react/jsx-runtime");
var BookingFormClient = ({
  siteId: siteIdProp,
  formId,
  className,
  form,
  services = []
}) => {
  const [isSuccess, setIsSuccess] = (0, import_react11.useState)(false);
  const siteId = siteIdProp || form?.siteId || "";
  import_react11.default.useEffect(() => {
    if (!siteId) {
      console.error("[BookingFormClient] ERROR: siteId is missing!");
    }
    if (!form) {
      console.warn("[BookingFormClient] Form data not loaded");
    }
    console.log("[BookingFormClient] Loaded with:", {
      siteId,
      formId,
      hasForm: !!form,
      servicesCount: Array.isArray(services) ? services.length : "not an array",
      servicesData: services
    });
  }, [siteId, formId, form, services]);
  const formConfig = form ? {
    id: form.id,
    name: form.name,
    slug: "",
    // Not needed for booking form
    settings: form.settingsJson,
    schema: form.schemaJson
  } : null;
  const normalizedServices = import_react11.default.useMemo(() => {
    if (Array.isArray(services)) {
      return services;
    }
    if (services && typeof services === "object") {
      if ("services" in services) {
        return services.services || [];
      }
      return Object.values(services);
    }
    return [];
  }, [services]);
  const steps = useBookingSteps(siteId, formConfig, normalizedServices);
  const { submit } = useBookingSubmission(siteId);
  if (!form) {
    return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("div", { className: `rounded-lg border border-destructive bg-destructive/10 p-4 ${className ?? ""}`, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("p", { className: "text-sm text-destructive", children: "Booking form not found. Please check your configuration." }) });
  }
  const handleComplete = async (data) => {
    try {
      const serviceId = data.serviceId || formConfig?.settings?.serviceId;
      const resourceId = data.resourceId || formConfig?.settings?.resourceId;
      if (!serviceId || !data.selectedSlot) {
        throw new Error("Missing required booking information");
      }
      console.log("[BookingFormClient] Looking for service:", {
        serviceId,
        availableServices: normalizedServices
      });
      const selectedService = normalizedServices.find((s) => s.id === serviceId);
      console.log("[BookingFormClient] Selected service:", selectedService);
      if (!selectedService) {
        throw new Error(`Service not found: ${serviceId}`);
      }
      if (!selectedService.durationMinutes) {
        throw new Error(
          `Service "${selectedService.title || serviceId}" is missing duration. Please update the service in the dashboard to include a duration (e.g., 30 minutes).`
        );
      }
      const startDate = new Date(data.selectedSlot);
      const endDate = new Date(startDate.getTime() + selectedService.durationMinutes * 60 * 1e3);
      const bookingFields = /* @__PURE__ */ new Set(["serviceId", "resourceId", "selectedDate", "selectedSlot"]);
      const customFields = {};
      for (const [key, value] of Object.entries(data)) {
        if (!bookingFields.has(key)) {
          customFields[key] = value;
        }
      }
      await submit({
        formId,
        serviceId,
        resourceId,
        startAt: data.selectedSlot,
        endAt: endDate.toISOString(),
        customFields,
        timezone: "UTC"
        // TODO: Get from resource or user preference
      });
      setIsSuccess(true);
    } catch (err) {
      console.error("Booking submission failed:", err);
      throw err;
    }
  };
  if (isSuccess) {
    const successMessage = formConfig?.settings?.successMessage || "Your appointment has been booked! Check your email for confirmation.";
    return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(SuccessMessage, { message: successMessage, className });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("div", { className, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
    MultiStepForm,
    {
      steps,
      initialData: {
        serviceId: formConfig?.settings?.serviceId,
        resourceId: formConfig?.settings?.resourceId
      },
      onComplete: handleComplete,
      progressStyle: "steps",
      persistToUrl: false,
      allowSkip: false
    }
  ) });
};

// ../blocks/src/system/runtime/hooks/useBookingFormConfig.ts
var import_react12 = require("react");
var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function useBookingFormConfig(siteId, formId) {
  const [formConfig, setFormConfig] = (0, import_react12.useState)(null);
  const [services, setServices] = (0, import_react12.useState)([]);
  const [isLoading, setIsLoading] = (0, import_react12.useState)(true);
  const [error, setError] = (0, import_react12.useState)(null);
  (0, import_react12.useEffect)(() => {
    let mounted = true;
    async function loadFormAndServices() {
      try {
        setIsLoading(true);
        setError(null);
        const apiUrl = getCmsApiUrl();
        const isUUID = UUID_REGEX.test(formId);
        const formUrl = isUUID ? `${apiUrl}/public/forms/${formId}` : `${apiUrl}/public/forms/${formId}?siteId=${encodeURIComponent(siteId)}`;
        const response = await fetch(formUrl);
        if (!response.ok) {
          throw new Error("Failed to load booking form");
        }
        const { form: rawData } = await response.json();
        if (!mounted) return;
        const normalizedForm = {
          id: rawData.id,
          name: rawData.name,
          slug: rawData.slug,
          settings: rawData.settingsJson ?? rawData.settings,
          schema: rawData.schemaJson ?? rawData.schema
        };
        setFormConfig(normalizedForm);
        if (!normalizedForm.settings?.serviceId && !normalizedForm.settings?.serviceIds) {
          const servicesResponse = await fetch(
            `${apiUrl}/public/bookings/services?siteId=${encodeURIComponent(siteId)}`
          );
          if (servicesResponse.ok) {
            const servicesData = await servicesResponse.json();
            if (mounted) {
              setServices(servicesData.services || []);
            }
          }
        } else if (normalizedForm.settings?.serviceIds && normalizedForm.settings.serviceIds.length > 0) {
          const servicesResponse = await fetch(
            `${apiUrl}/public/bookings/services?siteId=${encodeURIComponent(siteId)}&ids=${normalizedForm.settings.serviceIds.join(",")}`
          );
          if (servicesResponse.ok) {
            const servicesData = await servicesResponse.json();
            if (mounted) {
              setServices(servicesData.services || []);
            }
          }
        } else if (normalizedForm.settings?.serviceId) {
          const serviceResponse = await fetch(
            `${apiUrl}/public/bookings/services/${normalizedForm.settings.serviceId}?siteId=${encodeURIComponent(siteId)}`
          );
          if (serviceResponse.ok) {
            const serviceData = await serviceResponse.json();
            if (mounted) {
              setServices([serviceData.service || serviceData]);
            }
          }
        }
      } catch (err) {
        console.error("Failed to load form:", err);
        if (mounted) {
          setError("Failed to load booking form. Please try again later.");
        }
      } finally {
        if (mounted) {
          setIsLoading(false);
        }
      }
    }
    loadFormAndServices();
    return () => {
      mounted = false;
    };
  }, [siteId, formId]);
  return { formConfig, services, isLoading, error };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  BookingFormClient,
  useBookingFormConfig
});
//# sourceMappingURL=bookings.js.map