formanitor 0.0.10 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,19 +1,20 @@
1
1
  import * as React11 from 'react';
2
- import React11__default, { createContext, useRef, useEffect, useContext, useState, useMemo } from 'react';
2
+ import React11__default, { createContext, useContext, useRef, useEffect, useState, useMemo, useCallback } from 'react';
3
3
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
4
4
  import { clsx } from 'clsx';
5
5
  import { twMerge } from 'tailwind-merge';
6
6
  import * as LabelPrimitive from '@radix-ui/react-label';
7
7
  import { cva } from 'class-variance-authority';
8
8
  import * as SelectPrimitive from '@radix-ui/react-select';
9
- import { ChevronDown, ChevronUp, Check, Circle, X, Image, Upload, Trash2, PenTool, Plus, ChevronRight, Calendar as Calendar$1, Clock, ChevronLeft } from 'lucide-react';
9
+ import { ChevronDown, ChevronUp, Check, Circle, X, Image, Upload, Trash2, Plus, PenTool, ChevronRight, Calendar as Calendar$1, ChevronLeft, RefreshCw, Clock } from 'lucide-react';
10
10
  import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
11
11
  import { Slot } from '@radix-ui/react-slot';
12
- import { format } from 'date-fns';
12
+ import { format, addDays, addWeeks, addMonths, differenceInCalendarDays, parseISO } from 'date-fns';
13
13
  import { DayPicker } from 'react-day-picker';
14
14
  import * as PopoverPrimitive from '@radix-ui/react-popover';
15
15
  import { useReactTable, getCoreRowModel, flexRender } from '@tanstack/react-table';
16
16
  import * as RadioGroupPrimitive from '@radix-ui/react-radio-group';
17
+ import * as DialogPrimitive from '@radix-ui/react-dialog';
17
18
 
18
19
  // src/core/validate.ts
19
20
  var EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
@@ -178,6 +179,7 @@ var FormStore = class {
178
179
  config;
179
180
  // Cache for debounce
180
181
  saveTimeout = null;
182
+ draftCallbackTimeout = null;
181
183
  constructor(schema, config = {}) {
182
184
  this.schema = schema;
183
185
  this.config = config;
@@ -247,6 +249,34 @@ var FormStore = class {
247
249
  this.checkEvents(fieldId, "onValueChange", value);
248
250
  this.evaluate();
249
251
  this.notify();
252
+ this.scheduleDraftCallback();
253
+ if (!this.config.onDraftChange) {
254
+ this.scheduleSave();
255
+ }
256
+ }
257
+ /**
258
+ * Set multiple values at once (e.g. from AI analysis). Only updates keys that
259
+ * exist in the schema. Runs evaluate/notify/save once.
260
+ * @param partial Map of fieldId -> value
261
+ * @param options.touch If false, do not mark fields as touched (e.g. for AI-suggested values)
262
+ */
263
+ setValues(partial, options) {
264
+ const touch = options?.touch !== false;
265
+ let changed = false;
266
+ const newValues = { ...this.state.values };
267
+ const newTouched = { ...this.state.touched };
268
+ for (const [fieldId, value] of Object.entries(partial)) {
269
+ if (!this.fieldMap[fieldId]) continue;
270
+ if (newValues[fieldId] === value) continue;
271
+ newValues[fieldId] = value;
272
+ if (touch) newTouched[fieldId] = true;
273
+ changed = true;
274
+ }
275
+ if (!changed) return;
276
+ this.state.values = newValues;
277
+ this.state.touched = newTouched;
278
+ this.evaluate();
279
+ this.notify();
250
280
  this.scheduleSave();
251
281
  }
252
282
  setTouched(fieldId) {
@@ -283,6 +313,26 @@ var FormStore = class {
283
313
  this.save();
284
314
  }, 1e3);
285
315
  }
316
+ scheduleDraftCallback() {
317
+ if (!this.config.onDraftChange) return;
318
+ if (this.draftCallbackTimeout) {
319
+ clearTimeout(this.draftCallbackTimeout);
320
+ }
321
+ this.draftCallbackTimeout = setTimeout(() => {
322
+ const payload = {
323
+ // For consumer callbacks, send values in the same
324
+ // serialized shape used for outbound submissions so
325
+ // media/signature fields are wrapped consistently.
326
+ values: this.serializeValuesForSubmission(this.state.values),
327
+ meta: {
328
+ updatedAt: Date.now(),
329
+ workflowState: this.state.workflowState,
330
+ version: this.schema.version
331
+ }
332
+ };
333
+ this.config.onDraftChange?.(payload);
334
+ }, 2500);
335
+ }
286
336
  async save() {
287
337
  const payload = {
288
338
  values: this.state.values,
@@ -378,6 +428,36 @@ var FormStore = class {
378
428
  this.state.values[comp.target] = 0;
379
429
  }
380
430
  }
431
+ } else if (comp.type === "formula") {
432
+ const evalExpr = (expr) => {
433
+ if (expr.type === "field") {
434
+ return Number(this.state.values[expr.field]) || 0;
435
+ }
436
+ if (expr.type === "number") {
437
+ return expr.value;
438
+ }
439
+ const left = evalExpr(expr.left);
440
+ const right = evalExpr(expr.right);
441
+ switch (expr.op) {
442
+ case "+":
443
+ return left + right;
444
+ case "-":
445
+ return left - right;
446
+ case "*":
447
+ return left * right;
448
+ case "/":
449
+ return right === 0 ? 0 : left / right;
450
+ case "**":
451
+ return Math.pow(left, right);
452
+ default:
453
+ return 0;
454
+ }
455
+ };
456
+ const result = evalExpr(comp.expression);
457
+ const value = Number.isFinite(result) ? Math.round(result * 10) / 10 : "";
458
+ if (this.state.values[comp.target] !== value) {
459
+ this.state.values[comp.target] = value;
460
+ }
381
461
  }
382
462
  });
383
463
  }
@@ -470,6 +550,7 @@ var FormStore = class {
470
550
  let needsReeval = false;
471
551
  if (next.onUpload !== void 0) this.config.onUpload = next.onUpload;
472
552
  if (next.onEvent !== void 0) this.config.onEvent = next.onEvent;
553
+ if (next.onDraftChange !== void 0) this.config.onDraftChange = next.onDraftChange;
473
554
  if (next.role !== void 0 && next.role !== this.config.role) {
474
555
  this.config.role = next.role;
475
556
  needsReeval = true;
@@ -532,7 +613,12 @@ var FormStore = class {
532
613
  }
533
614
  };
534
615
  var FormContext = createContext(null);
535
- var FormProvider = ({ schema, config, children }) => {
616
+ var FieldHandlersContext = createContext({});
617
+ function useFieldHandlers(fieldId) {
618
+ const map = useContext(FieldHandlersContext);
619
+ return map[fieldId] ?? { onSearch: async () => [], recentlyUsed: [] };
620
+ }
621
+ var FormProvider = ({ schema, config, fieldHandlers, children }) => {
536
622
  const storeRef = useRef(null);
537
623
  if (!storeRef.current) {
538
624
  storeRef.current = new FormStore(schema, config);
@@ -545,7 +631,7 @@ var FormProvider = ({ schema, config, children }) => {
545
631
  useEffect(() => {
546
632
  storeRef.current?.load();
547
633
  }, []);
548
- return /* @__PURE__ */ jsx(FormContext.Provider, { value: storeRef.current, children });
634
+ return /* @__PURE__ */ jsx(FormContext.Provider, { value: storeRef.current, children: /* @__PURE__ */ jsx(FieldHandlersContext.Provider, { value: fieldHandlers ?? {}, children }) });
549
635
  };
550
636
  function useFormStore() {
551
637
  const context = useContext(FormContext);
@@ -638,8 +724,9 @@ var Textarea = React11.forwardRef(
638
724
  return /* @__PURE__ */ jsx(
639
725
  "textarea",
640
726
  {
727
+ spellCheck: false,
641
728
  className: cn(
642
- "flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
729
+ "flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",
643
730
  height == null && "min-h-[80px]",
644
731
  className
645
732
  ),
@@ -651,6 +738,28 @@ var Textarea = React11.forwardRef(
651
738
  }
652
739
  );
653
740
  Textarea.displayName = "Textarea";
741
+
742
+ // src/ui/themes/textareaThemes.ts
743
+ var textareaThemes = {
744
+ "highlight-label": {
745
+ wrapperClassName: "rounded-md overflow-hidden flex flex-col border border-[#D0D0D0]",
746
+ labelClassName: "rounded-t-md bg-[#FEE8EC] px-3 py-1 text-sm shrink-0 z-[1] text-slate-600",
747
+ inputClassName: "rounded-t-none rounded-b-md border-0 border-t border-[#D0D0D0] text-xs resize-none -mt-1 min-w-0 bg-white text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-offset-0 disabled:cursor-not-allowed disabled:opacity-50"
748
+ }
749
+ };
750
+
751
+ // src/ui/themes/index.ts
752
+ var themeRegistries = {
753
+ textarea: textareaThemes,
754
+ text: textareaThemes
755
+ // same themes can apply to single-line text if desired
756
+ };
757
+ function getThemeConfig(fieldType, themeName) {
758
+ if (!themeName) return void 0;
759
+ const registry = themeRegistries[fieldType];
760
+ if (!registry) return void 0;
761
+ return registry[themeName];
762
+ }
654
763
  var TextWidget = ({ fieldId }) => {
655
764
  const { fieldDef, value, setValue, setTouched, error, disabled, touched } = useField(fieldId);
656
765
  const { state } = useForm();
@@ -659,12 +768,20 @@ var TextWidget = ({ fieldId }) => {
659
768
  const Component = fieldDef.type === "textarea" || fieldDef.type === "richtext" ? Textarea : Input;
660
769
  const isTextarea = fieldDef.type === "textarea" || fieldDef.type === "richtext";
661
770
  const height = isTextarea && "height" in fieldDef ? fieldDef.height : void 0;
662
- return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
663
- /* @__PURE__ */ jsxs(Label, { htmlFor: fieldId, children: [
664
- fieldDef.label,
665
- " ",
666
- fieldDef.required && /* @__PURE__ */ jsx("span", { className: "text-red-500", children: "*" })
667
- ] }),
771
+ const theme = getThemeConfig(
772
+ isTextarea ? "textarea" : "text",
773
+ fieldDef.theme
774
+ );
775
+ const wrapperClass = theme?.wrapperClassName ?? "space-y-2";
776
+ const labelClass = theme?.labelClassName;
777
+ const inputClass = cn(theme?.inputClassName, showError && "border-red-500");
778
+ const labelContent = /* @__PURE__ */ jsxs(Fragment, { children: [
779
+ fieldDef.label,
780
+ " ",
781
+ fieldDef.required && /* @__PURE__ */ jsx("span", { className: "text-red-500", children: "*" })
782
+ ] });
783
+ return /* @__PURE__ */ jsxs("div", { className: wrapperClass, children: [
784
+ theme ? /* @__PURE__ */ jsx(Label, { htmlFor: fieldId, className: labelClass, children: labelContent }) : /* @__PURE__ */ jsx(Label, { htmlFor: fieldId, children: labelContent }),
668
785
  /* @__PURE__ */ jsx(
669
786
  Component,
670
787
  {
@@ -674,7 +791,7 @@ var TextWidget = ({ fieldId }) => {
674
791
  onBlur: setTouched,
675
792
  disabled,
676
793
  type: fieldDef.type === "number" ? "number" : "text",
677
- className: showError ? "border-red-500" : "",
794
+ className: inputClass,
678
795
  ...isTextarea && { height }
679
796
  }
680
797
  ),
@@ -2250,135 +2367,1898 @@ var CheckboxWidget = ({ fieldId }) => {
2250
2367
  showError && /* @__PURE__ */ jsx("p", { className: "text-xs text-red-500", children: error })
2251
2368
  ] });
2252
2369
  };
2253
- var FieldRenderer = ({ fieldId }) => {
2254
- const { fieldDef, visible } = useField(fieldId);
2255
- if (!visible || !fieldDef) {
2256
- return null;
2370
+ var AISuggestionsContext = createContext({});
2371
+ function useAISuggestions() {
2372
+ return useContext(AISuggestionsContext);
2373
+ }
2374
+ var AISuggestionsProvider = AISuggestionsContext.Provider;
2375
+ var Dialog = DialogPrimitive.Root;
2376
+ var DialogPortal = DialogPrimitive.Portal;
2377
+ var DialogOverlay = React11.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
2378
+ DialogPrimitive.Overlay,
2379
+ {
2380
+ ref,
2381
+ className: cn(
2382
+ "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
2383
+ className
2384
+ ),
2385
+ ...props
2257
2386
  }
2258
- switch (fieldDef.type) {
2259
- case "text":
2260
- case "number":
2261
- return /* @__PURE__ */ jsx(TextWidget, { fieldId });
2262
- case "textarea":
2263
- case "richtext":
2264
- return /* @__PURE__ */ jsx(TextWidget, { fieldId });
2265
- case "date":
2266
- return /* @__PURE__ */ jsx(DateWidget, { fieldId });
2267
- case "datetime":
2268
- return /* @__PURE__ */ jsx(DateTimeWidget, { fieldId });
2269
- case "select":
2270
- return /* @__PURE__ */ jsx(SelectWidget, { fieldId });
2271
- case "radio":
2272
- return /* @__PURE__ */ jsx(RadioWidget, { fieldId });
2273
- case "checkbox":
2274
- return /* @__PURE__ */ jsx(CheckboxWidget, { fieldId });
2275
- case "multiselect":
2276
- return /* @__PURE__ */ jsx(MultiSelectWidget, { fieldId });
2277
- case "repeatable":
2278
- return /* @__PURE__ */ jsx(RepeatableWidget, { fieldId });
2279
- case "image_upload":
2280
- return /* @__PURE__ */ jsx(ImageUploadWidget, { fieldId });
2281
- case "signature":
2282
- return /* @__PURE__ */ jsx(SignatureUploadWidget, { fieldId });
2283
- case "editable_table":
2284
- return /* @__PURE__ */ jsx(EditableTableWidget, { fieldId });
2285
- case "static_text": {
2286
- const def = fieldDef;
2287
- const size = def.size ?? "regular";
2288
- const labelClass = size === "large" ? "text-base" : "text-sm";
2289
- const descClass = size === "large" ? "text-sm" : "text-xs";
2290
- return /* @__PURE__ */ jsxs("div", { className: `${labelClass} text-muted-foreground`, children: [
2291
- def.label,
2292
- def.description && /* @__PURE__ */ jsx("p", { className: `mt-1 ${descClass} opacity-90`, children: def.description })
2293
- ] });
2387
+ ));
2388
+ DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
2389
+ var DialogContent = React11.forwardRef(({ className, children, ...props }, ref) => /* @__PURE__ */ jsxs(DialogPortal, { children: [
2390
+ /* @__PURE__ */ jsx(DialogOverlay, {}),
2391
+ /* @__PURE__ */ jsxs(
2392
+ DialogPrimitive.Content,
2393
+ {
2394
+ ref,
2395
+ className: cn(
2396
+ "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
2397
+ className
2398
+ ),
2399
+ ...props,
2400
+ children: [
2401
+ children,
2402
+ /* @__PURE__ */ jsxs(DialogPrimitive.Close, { className: "absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground", children: [
2403
+ /* @__PURE__ */ jsx(X, { className: "h-4 w-4" }),
2404
+ /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Close" })
2405
+ ] })
2406
+ ]
2294
2407
  }
2295
- default:
2296
- return /* @__PURE__ */ jsxs("div", { className: "text-red-500", children: [
2297
- "Unknown field type: ",
2298
- fieldDef.type
2299
- ] });
2408
+ )
2409
+ ] }));
2410
+ DialogContent.displayName = DialogPrimitive.Content.displayName;
2411
+ var DialogHeader = ({
2412
+ className,
2413
+ ...props
2414
+ }) => /* @__PURE__ */ jsx(
2415
+ "div",
2416
+ {
2417
+ className: cn(
2418
+ "flex flex-col space-y-1.5 text-center sm:text-left",
2419
+ className
2420
+ ),
2421
+ ...props
2422
+ }
2423
+ );
2424
+ DialogHeader.displayName = "DialogHeader";
2425
+ var DialogTitle = React11.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
2426
+ DialogPrimitive.Title,
2427
+ {
2428
+ ref,
2429
+ className: cn(
2430
+ "text-lg font-semibold leading-none tracking-tight",
2431
+ className
2432
+ ),
2433
+ ...props
2434
+ }
2435
+ ));
2436
+ DialogTitle.displayName = DialogPrimitive.Title.displayName;
2437
+ var DialogDescription = React11.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
2438
+ DialogPrimitive.Description,
2439
+ {
2440
+ ref,
2441
+ className: cn("text-sm text-muted-foreground", className),
2442
+ ...props
2300
2443
  }
2444
+ ));
2445
+ DialogDescription.displayName = DialogPrimitive.Description.displayName;
2446
+ var AddEntityDialog = ({
2447
+ open,
2448
+ onClose,
2449
+ title,
2450
+ recentlyUsedSlot,
2451
+ children,
2452
+ actionSlot
2453
+ }) => {
2454
+ return /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: (o) => !o && onClose(), children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-lg w-full p-0 gap-0 flex flex-col max-h-[90vh] overflow-hidden", children: [
2455
+ /* @__PURE__ */ jsx(DialogHeader, { className: "px-6 pt-6 pb-4 shrink-0", children: /* @__PURE__ */ jsx(DialogTitle, { className: "text-lg font-semibold", children: title }) }),
2456
+ /* @__PURE__ */ jsxs("div", { className: "px-6 flex flex-col gap-4 overflow-y-auto flex-1 min-h-0 pb-4", children: [
2457
+ recentlyUsedSlot && /* @__PURE__ */ jsxs("div", { children: [
2458
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mb-2", children: "Recently Used" }),
2459
+ /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: recentlyUsedSlot })
2460
+ ] }),
2461
+ children
2462
+ ] }),
2463
+ actionSlot != null && /* @__PURE__ */ jsx("div", { className: "px-6 py-4 flex justify-end shrink-0 border-t border-border bg-background", children: actionSlot })
2464
+ ] }) });
2301
2465
  };
2302
- var Section = ({ title, children }) => {
2303
- const [expanded, setExpanded] = useState(true);
2304
- const handleToggle = () => setExpanded((prev) => !prev);
2305
- const contentClassName = cn(
2306
- "overflow-hidden transition-[height] duration-200 ease-in-out",
2307
- !expanded && "hidden"
2308
- );
2309
- return /* @__PURE__ */ jsxs("div", { className: "mb-6 border rounded-lg bg-white shadow-sm overflow-hidden", children: [
2310
- /* @__PURE__ */ jsxs(
2466
+ function mapToMedication(result) {
2467
+ return {
2468
+ id: result.id,
2469
+ brand_name: result.name,
2470
+ generic_name: result.generic_name ?? "",
2471
+ frequency: "custom",
2472
+ is_custom: false,
2473
+ duration_value: "3",
2474
+ duration_unit: "days",
2475
+ before_after: "AFTER FOOD",
2476
+ morning: "0",
2477
+ afternoon: "0",
2478
+ night: "0",
2479
+ notes: ""
2480
+ };
2481
+ }
2482
+ function mapAIMedicationToMedication(ai) {
2483
+ const id = typeof ai.id === "string" ? Number.parseInt(ai.id, 10) || 0 : Number(ai.id);
2484
+ return {
2485
+ id: Number.isNaN(id) ? 0 : id,
2486
+ brand_name: ai.brand_name ?? "",
2487
+ generic_name: ai.generic_name ?? "",
2488
+ frequency: "custom",
2489
+ is_custom: false,
2490
+ duration_value: "3",
2491
+ duration_unit: "days",
2492
+ before_after: "AFTER FOOD",
2493
+ morning: "1",
2494
+ afternoon: "0",
2495
+ night: "1",
2496
+ notes: ai.reason ?? ""
2497
+ };
2498
+ }
2499
+ function createCustomMedication(name, customId) {
2500
+ return {
2501
+ id: customId,
2502
+ brand_name: name.trim(),
2503
+ generic_name: "",
2504
+ frequency: "custom",
2505
+ is_custom: true,
2506
+ duration_value: "3",
2507
+ duration_unit: "days",
2508
+ before_after: "AFTER FOOD",
2509
+ morning: "0",
2510
+ afternoon: "0",
2511
+ night: "0",
2512
+ notes: ""
2513
+ };
2514
+ }
2515
+ function Spinner({
2516
+ value,
2517
+ onChange
2518
+ }) {
2519
+ const num = parseInt(value, 10) || 0;
2520
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center", children: [
2521
+ /* @__PURE__ */ jsx(
2311
2522
  "button",
2312
2523
  {
2313
2524
  type: "button",
2314
- onClick: handleToggle,
2315
- className: "w-full flex items-center justify-between gap-2 p-4 text-left border-b hover:bg-gray-50/80 transition-colors",
2316
- children: [
2317
- /* @__PURE__ */ jsx("h3", { className: "text-lg font-medium", children: title }),
2318
- /* @__PURE__ */ jsx("span", { className: "flex-shrink-0 text-muted-foreground", "aria-hidden": true, children: expanded ? /* @__PURE__ */ jsx(ChevronDown, { className: "h-5 w-5" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "h-5 w-5" }) })
2319
- ]
2525
+ className: "text-muted-foreground hover:text-foreground cursor-pointer",
2526
+ onClick: () => onChange(String(num + 1)),
2527
+ children: /* @__PURE__ */ jsx(ChevronUp, { className: "h-3 w-3" })
2320
2528
  }
2321
2529
  ),
2322
- /* @__PURE__ */ jsx("div", { className: contentClassName, children: /* @__PURE__ */ jsx("div", { className: "p-4 pt-4 space-y-4 border-t-0", children }) })
2323
- ] });
2324
- };
2325
- var ColumnLayout = ({
2326
- columns,
2327
- label,
2328
- children
2329
- }) => {
2330
- const gridCols = Math.max(1, Math.min(columns, 12));
2331
- const gridClass = `grid gap-4 w-full`;
2332
- const style = {
2333
- gridTemplateColumns: `repeat(${gridCols}, minmax(0, 1fr))`
2334
- };
2335
- return /* @__PURE__ */ jsxs("div", { className: "mb-6", children: [
2336
- label != null && label !== "" && /* @__PURE__ */ jsx("div", { className: "mb-2 text-sm font-medium text-gray-700", children: label }),
2337
- /* @__PURE__ */ jsx("div", { className: gridClass, style, children })
2530
+ /* @__PURE__ */ jsx("span", { className: "text-sm w-4 text-center leading-none", children: num }),
2531
+ /* @__PURE__ */ jsx(
2532
+ "button",
2533
+ {
2534
+ type: "button",
2535
+ className: "text-muted-foreground hover:text-foreground cursor-pointer",
2536
+ onClick: () => onChange(String(Math.max(0, num - 1))),
2537
+ children: /* @__PURE__ */ jsx(ChevronDown, { className: "h-3 w-3" })
2538
+ }
2539
+ )
2338
2540
  ] });
2339
- };
2340
- var DynamicForm = () => {
2341
- const store = useFormStore();
2342
- const schema = store.getSchema();
2343
- const { state } = useForm();
2344
- return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
2345
- /* @__PURE__ */ jsxs("div", { className: "mb-4", children: [
2346
- /* @__PURE__ */ jsx("h1", { className: "text-2xl font-bold", children: schema.title }),
2347
- /* @__PURE__ */ jsxs("div", { className: "text-sm text-gray-500", children: [
2348
- "Version: ",
2349
- schema.version,
2350
- " | State: ",
2351
- state.workflowState
2352
- ] })
2541
+ }
2542
+ function MedicationCard({
2543
+ med,
2544
+ onUpdate,
2545
+ onRemove
2546
+ }) {
2547
+ const [notesOpen, setNotesOpen] = useState(false);
2548
+ function set(key, val) {
2549
+ onUpdate({ ...med, [key]: val });
2550
+ }
2551
+ return /* @__PURE__ */ jsxs("div", { className: "bg-gray-50 rounded-lg p-3 space-y-2", children: [
2552
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 flex-wrap", children: [
2553
+ /* @__PURE__ */ jsx("span", { className: "font-semibold text-sm flex-1 min-w-0 truncate", children: med.brand_name }),
2554
+ /* @__PURE__ */ jsxs(
2555
+ "select",
2556
+ {
2557
+ className: "text-xs border border-border rounded px-2 py-1 bg-white shrink-0",
2558
+ value: med.frequency,
2559
+ onChange: (e) => set("frequency", e.target.value),
2560
+ children: [
2561
+ /* @__PURE__ */ jsx("option", { value: "custom", children: "select frequency" }),
2562
+ /* @__PURE__ */ jsx("option", { value: "OD", children: "OD" }),
2563
+ /* @__PURE__ */ jsx("option", { value: "BD", children: "BD" }),
2564
+ /* @__PURE__ */ jsx("option", { value: "TDS", children: "TDS" }),
2565
+ /* @__PURE__ */ jsx("option", { value: "QID", children: "QID" }),
2566
+ /* @__PURE__ */ jsx("option", { value: "SOS", children: "SOS" })
2567
+ ]
2568
+ }
2569
+ ),
2570
+ /* @__PURE__ */ jsx("div", { className: "flex gap-4 items-center shrink-0", children: ["morning", "afternoon", "night"].map((slot) => /* @__PURE__ */ jsx(
2571
+ "span",
2572
+ {
2573
+ className: "text-[10px] font-semibold uppercase text-muted-foreground tracking-wide",
2574
+ children: slot === "afternoon" ? "AFTERNOON" : slot === "morning" ? "MORNING" : "NIGHT"
2575
+ },
2576
+ slot
2577
+ )) }),
2578
+ /* @__PURE__ */ jsx(
2579
+ "button",
2580
+ {
2581
+ type: "button",
2582
+ onClick: onRemove,
2583
+ className: "text-red-400 hover:text-red-600 shrink-0 p-1 cursor-pointer",
2584
+ children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" })
2585
+ }
2586
+ )
2353
2587
  ] }),
2354
- schema.layout.map((node) => {
2355
- if (node.type === "section") {
2356
- return /* @__PURE__ */ jsx(Section, { title: node.title, children: node.children.map(
2357
- (child, index) => typeof child === "string" ? /* @__PURE__ */ jsx(FieldRenderer, { fieldId: child }, child) : child.type === "column_layout" ? /* @__PURE__ */ jsx(
2358
- ColumnLayout,
2588
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 flex-wrap", children: [
2589
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1 shrink-0", children: [
2590
+ /* @__PURE__ */ jsx(
2591
+ "input",
2592
+ {
2593
+ type: "text",
2594
+ inputMode: "numeric",
2595
+ pattern: "[0-9]*",
2596
+ className: "w-11 text-sm border border-border rounded px-2 py-1 bg-white",
2597
+ value: med.duration_value,
2598
+ onChange: (e) => {
2599
+ const v = e.target.value.replace(/\D/g, "");
2600
+ set("duration_value", v === "" ? "" : v);
2601
+ }
2602
+ }
2603
+ ),
2604
+ /* @__PURE__ */ jsxs(
2605
+ "select",
2606
+ {
2607
+ className: "text-xs border border-border rounded px-2 py-1 bg-white",
2608
+ value: med.duration_unit,
2609
+ onChange: (e) => set("duration_unit", e.target.value),
2610
+ children: [
2611
+ /* @__PURE__ */ jsx("option", { value: "days", children: "days" }),
2612
+ /* @__PURE__ */ jsx("option", { value: "weeks", children: "weeks" }),
2613
+ /* @__PURE__ */ jsx("option", { value: "months", children: "months" })
2614
+ ]
2615
+ }
2616
+ )
2617
+ ] }),
2618
+ /* @__PURE__ */ jsx("div", { className: "flex gap-2 items-center flex-1 min-w-0 justify-end", children: ["morning", "afternoon", "night"].map((slot) => /* @__PURE__ */ jsx("div", { className: "flex flex-col items-center gap-0.5", children: /* @__PURE__ */ jsx(Spinner, { value: med[slot], onChange: (v) => set(slot, v) }) }, slot)) }),
2619
+ /* @__PURE__ */ jsxs(
2620
+ "select",
2621
+ {
2622
+ className: "text-xs border border-border rounded px-2 py-1 bg-white shrink-0",
2623
+ value: med.before_after === "AFTER FOOD" ? "AF" : "BF",
2624
+ onChange: (e) => set("before_after", e.target.value === "AF" ? "AFTER FOOD" : "BEFORE FOOD"),
2625
+ children: [
2626
+ /* @__PURE__ */ jsx("option", { value: "AF", children: "AF" }),
2627
+ /* @__PURE__ */ jsx("option", { value: "BF", children: "BF" })
2628
+ ]
2629
+ }
2630
+ )
2631
+ ] }),
2632
+ /* @__PURE__ */ jsxs(
2633
+ "div",
2634
+ {
2635
+ role: "button",
2636
+ tabIndex: 0,
2637
+ onClick: () => setNotesOpen((o) => !o),
2638
+ onKeyDown: (e) => {
2639
+ if (e.key === "Enter" || e.key === " ") {
2640
+ e.preventDefault();
2641
+ setNotesOpen((o) => !o);
2642
+ }
2643
+ },
2644
+ className: cn(
2645
+ "flex items-center gap-2 w-full text-left text-xs text-muted-foreground hover:text-foreground",
2646
+ "cursor-pointer py-2 px-2 rounded border border-transparent hover:bg-gray-100/80 transition-colors"
2647
+ ),
2648
+ children: [
2649
+ /* @__PURE__ */ jsx(
2650
+ ChevronRight,
2359
2651
  {
2360
- columns: child.columns,
2361
- label: child.label,
2362
- children: child.children.map((fieldId) => /* @__PURE__ */ jsx(FieldRenderer, { fieldId }, fieldId))
2363
- },
2364
- child.id
2365
- ) : /* @__PURE__ */ jsx(React11__default.Fragment, {}, child.id ?? index)
2366
- ) }, node.id);
2652
+ className: cn("h-3 w-3 shrink-0 transition-transform", notesOpen && "rotate-90")
2653
+ }
2654
+ ),
2655
+ /* @__PURE__ */ jsx("span", { children: "Medicine Notes" })
2656
+ ]
2367
2657
  }
2368
- if (node.type === "column_layout") {
2369
- return /* @__PURE__ */ jsx(
2370
- ColumnLayout,
2371
- {
2372
- columns: node.columns,
2373
- label: node.label,
2374
- children: node.children.map((fieldId) => /* @__PURE__ */ jsx(FieldRenderer, { fieldId }, fieldId))
2375
- },
2376
- node.id
2377
- );
2658
+ ),
2659
+ notesOpen && /* @__PURE__ */ jsx("div", { className: "relative z-10 mt-0.5", children: /* @__PURE__ */ jsx(
2660
+ "textarea",
2661
+ {
2662
+ className: "block w-full text-xs border border-border rounded px-2 py-1 resize-none bg-white min-h-0",
2663
+ rows: 2,
2664
+ placeholder: "Add notes...",
2665
+ value: med.notes,
2666
+ onChange: (e) => set("notes", e.target.value)
2378
2667
  }
2379
- return null;
2380
- })
2668
+ ) })
2381
2669
  ] });
2670
+ }
2671
+ var ADD_FEEDBACK_MS = 320;
2672
+ function SearchResultCard({
2673
+ result,
2674
+ isAdding,
2675
+ onSelect
2676
+ }) {
2677
+ return /* @__PURE__ */ jsxs(
2678
+ "button",
2679
+ {
2680
+ type: "button",
2681
+ onClick: onSelect,
2682
+ className: cn(
2683
+ "w-full text-left border rounded-lg px-3 py-2 transition-all duration-300 ease-out cursor-pointer flex items-center justify-between gap-2",
2684
+ isAdding ? "border-green-400 bg-green-50 scale-[0.98]" : "border-border bg-white hover:bg-gray-50"
2685
+ ),
2686
+ children: [
2687
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1 text-left", children: [
2688
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold leading-tight truncate", children: result.name }),
2689
+ result.generic_name && /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground mt-0.5 truncate", children: [
2690
+ "Generic: ",
2691
+ result.generic_name
2692
+ ] })
2693
+ ] }),
2694
+ isAdding && /* @__PURE__ */ jsx(Check, { className: "h-4 w-4 shrink-0 text-green-600" })
2695
+ ]
2696
+ }
2697
+ );
2698
+ }
2699
+ var AddMedicationField = ({
2700
+ label = "Medications",
2701
+ value,
2702
+ onChange,
2703
+ onSearch,
2704
+ recentlyUsed = [],
2705
+ suggestedMedications = []
2706
+ }) => {
2707
+ const [open, setOpen] = useState(false);
2708
+ const [query, setQuery] = useState("");
2709
+ const [results, setResults] = useState([]);
2710
+ const [loading, setLoading] = useState(false);
2711
+ const [addingResultId, setAddingResultId] = useState(null);
2712
+ const debounceRef = useRef(null);
2713
+ const customIdRef = useRef(-1);
2714
+ const valueRef = useRef([]);
2715
+ const searchInputRef = useRef(null);
2716
+ const safeValue = Array.isArray(value) ? value : [];
2717
+ valueRef.current = safeValue;
2718
+ const addedIds = new Set(safeValue.map((m) => String(m.id)));
2719
+ useEffect(() => {
2720
+ if (!open) {
2721
+ setQuery("");
2722
+ setResults([]);
2723
+ setAddingResultId(null);
2724
+ }
2725
+ }, [open]);
2726
+ function handleQueryChange(q) {
2727
+ setQuery(q);
2728
+ if (debounceRef.current) clearTimeout(debounceRef.current);
2729
+ if (!q.trim()) {
2730
+ setResults([]);
2731
+ return;
2732
+ }
2733
+ debounceRef.current = setTimeout(async () => {
2734
+ setLoading(true);
2735
+ try {
2736
+ const res = await onSearch(q);
2737
+ setResults(res);
2738
+ } finally {
2739
+ setLoading(false);
2740
+ }
2741
+ }, 500);
2742
+ }
2743
+ function handleRecentlyUsedToggle(result) {
2744
+ if (addedIds.has(String(result.id))) {
2745
+ onChange(safeValue.filter((m) => String(m.id) !== String(result.id)));
2746
+ } else {
2747
+ onChange([...safeValue, mapToMedication(result)]);
2748
+ }
2749
+ }
2750
+ function handleResultClick(result) {
2751
+ if (addedIds.has(String(result.id))) return;
2752
+ setAddingResultId(result.id);
2753
+ setTimeout(() => {
2754
+ onChange([...valueRef.current, mapToMedication(result)]);
2755
+ setAddingResultId(null);
2756
+ setQuery("");
2757
+ setResults([]);
2758
+ setTimeout(() => searchInputRef.current?.focus(), 0);
2759
+ }, ADD_FEEDBACK_MS);
2760
+ }
2761
+ function handleSave() {
2762
+ const trimmed = query.trim();
2763
+ if (!trimmed) return;
2764
+ const customId = customIdRef.current--;
2765
+ onChange([...safeValue, createCustomMedication(trimmed, customId)]);
2766
+ setQuery("");
2767
+ setResults([]);
2768
+ }
2769
+ function handleAddSuggestion(ai) {
2770
+ if (addedIds.has(String(ai.id))) return;
2771
+ onChange([...safeValue, mapAIMedicationToMedication(ai)]);
2772
+ }
2773
+ function updateMed(index, updated) {
2774
+ const next = [...safeValue];
2775
+ next[index] = updated;
2776
+ onChange(next);
2777
+ }
2778
+ function removeMed(index) {
2779
+ onChange(safeValue.filter((_, i) => i !== index));
2780
+ }
2781
+ const recentlyUsedChips = recentlyUsed.map((r) => {
2782
+ const isAdded = addedIds.has(String(r.id));
2783
+ return /* @__PURE__ */ jsxs(
2784
+ "button",
2785
+ {
2786
+ type: "button",
2787
+ onClick: () => handleRecentlyUsedToggle(r),
2788
+ className: cn(
2789
+ "rounded-full border text-xs px-3 py-1 transition-colors cursor-pointer",
2790
+ isAdded ? "border-green-300 bg-green-50 text-green-700" : "border-border bg-white hover:bg-gray-50"
2791
+ ),
2792
+ children: [
2793
+ isAdded && /* @__PURE__ */ jsx("span", { className: "mr-1", children: "\u2713" }),
2794
+ r.name
2795
+ ]
2796
+ },
2797
+ r.id
2798
+ );
2799
+ });
2800
+ return /* @__PURE__ */ jsxs("div", { className: "rounded-md overflow-hidden flex flex-col border bg-white border-[#D0D0D0] space-y-3 p-3 h-fit", children: [
2801
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
2802
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold", children: label }),
2803
+ /* @__PURE__ */ jsx(
2804
+ "button",
2805
+ {
2806
+ type: "button",
2807
+ onClick: () => setOpen(true),
2808
+ className: "text-sm font-semibold text-purple-600 hover:text-purple-800 cursor-pointer",
2809
+ children: "ADD"
2810
+ }
2811
+ )
2812
+ ] }),
2813
+ suggestedMedications.length > 0 && /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-1.5 items-center", children: [
2814
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground mr-1", children: "Suggestions:" }),
2815
+ suggestedMedications.filter((s) => !addedIds.has(String(s.id))).map((s) => /* @__PURE__ */ jsxs(
2816
+ "button",
2817
+ {
2818
+ type: "button",
2819
+ onClick: () => handleAddSuggestion(s),
2820
+ className: "inline-flex items-center gap-1 rounded-full border border-dashed border-purple-300 bg-purple-50/80 text-purple-800 text-xs px-2.5 py-1 hover:bg-purple-100 transition-colors cursor-pointer",
2821
+ children: [
2822
+ /* @__PURE__ */ jsx(Plus, { className: "h-3 w-3" }),
2823
+ s.brand_name || s.generic_name || String(s.id)
2824
+ ]
2825
+ },
2826
+ String(s.id)
2827
+ ))
2828
+ ] }),
2829
+ /* @__PURE__ */ jsx("div", { className: "space-y-2", children: safeValue.map((med, i) => /* @__PURE__ */ jsx(
2830
+ MedicationCard,
2831
+ {
2832
+ med,
2833
+ onUpdate: (u) => updateMed(i, u),
2834
+ onRemove: () => removeMed(i)
2835
+ },
2836
+ med.id
2837
+ )) }),
2838
+ /* @__PURE__ */ jsx(
2839
+ AddEntityDialog,
2840
+ {
2841
+ open,
2842
+ onClose: () => setOpen(false),
2843
+ title: "Add Medication",
2844
+ recentlyUsedSlot: recentlyUsedChips.length > 0 ? recentlyUsedChips : void 0,
2845
+ actionSlot: /* @__PURE__ */ jsx(
2846
+ "button",
2847
+ {
2848
+ type: "button",
2849
+ disabled: !query.trim(),
2850
+ onClick: handleSave,
2851
+ className: cn(
2852
+ "rounded-md px-5 py-2 text-sm font-semibold bg-primary text-primary-foreground hover:bg-primary/90 transition-opacity cursor-pointer",
2853
+ !query.trim() && "opacity-40 cursor-not-allowed"
2854
+ ),
2855
+ children: "Save Medicine"
2856
+ }
2857
+ ),
2858
+ children: /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
2859
+ /* @__PURE__ */ jsx(
2860
+ Input,
2861
+ {
2862
+ ref: searchInputRef,
2863
+ value: query,
2864
+ onChange: (e) => handleQueryChange(e.target.value),
2865
+ placeholder: "Search medicines...",
2866
+ className: "border border-border rounded-md focus-visible:ring-0"
2867
+ }
2868
+ ),
2869
+ loading && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground text-center py-2", children: "Searching\u2026" }),
2870
+ !loading && results.length > 0 && /* @__PURE__ */ jsx("div", { className: "grid grid-cols-2 gap-2 max-h-64 overflow-y-auto", children: results.map((r) => /* @__PURE__ */ jsx(
2871
+ SearchResultCard,
2872
+ {
2873
+ result: r,
2874
+ isAdding: addingResultId === r.id,
2875
+ onSelect: () => handleResultClick(r)
2876
+ },
2877
+ r.id
2878
+ )) })
2879
+ ] })
2880
+ }
2881
+ )
2882
+ ] });
2883
+ };
2884
+ var AddMedicationWidget = ({ fieldId }) => {
2885
+ const { value, setValue } = useField(fieldId);
2886
+ const handlers = useFieldHandlers(fieldId);
2887
+ const { medications: suggestedMedications } = useAISuggestions();
2888
+ const safeValue = Array.isArray(value) ? value : [];
2889
+ return /* @__PURE__ */ jsx(
2890
+ AddMedicationField,
2891
+ {
2892
+ value: safeValue,
2893
+ onChange: setValue,
2894
+ onSearch: handlers.onSearch,
2895
+ recentlyUsed: handlers.recentlyUsed,
2896
+ suggestedMedications
2897
+ }
2898
+ );
2899
+ };
2900
+ var ADD_FEEDBACK_MS2 = 320;
2901
+ function mapToInvestigation(result) {
2902
+ return {
2903
+ ...result,
2904
+ label: result.name,
2905
+ is_custom: false,
2906
+ fromAI: false
2907
+ };
2908
+ }
2909
+ var AddInvestigationField = ({
2910
+ label = "Investigations",
2911
+ value,
2912
+ onChange,
2913
+ onSearch,
2914
+ recentlyUsed = []
2915
+ }) => {
2916
+ const [open, setOpen] = useState(false);
2917
+ const [query, setQuery] = useState("");
2918
+ const [results, setResults] = useState([]);
2919
+ const [loading, setLoading] = useState(false);
2920
+ const [addingId, setAddingId] = useState(null);
2921
+ const debounceRef = useRef(null);
2922
+ const valueRef = useRef([]);
2923
+ const searchInputRef = useRef(null);
2924
+ valueRef.current = value;
2925
+ const addedIds = new Set(value.map((inv) => inv.id));
2926
+ useEffect(() => {
2927
+ if (!open) {
2928
+ setQuery("");
2929
+ setResults([]);
2930
+ setAddingId(null);
2931
+ }
2932
+ }, [open]);
2933
+ function handleQueryChange(q) {
2934
+ setQuery(q);
2935
+ if (debounceRef.current) clearTimeout(debounceRef.current);
2936
+ if (!q.trim()) {
2937
+ setResults([]);
2938
+ return;
2939
+ }
2940
+ debounceRef.current = setTimeout(async () => {
2941
+ setLoading(true);
2942
+ try {
2943
+ const res = await onSearch(q);
2944
+ setResults(res);
2945
+ } finally {
2946
+ setLoading(false);
2947
+ }
2948
+ }, 500);
2949
+ }
2950
+ function addInvestigation(result) {
2951
+ if (!addedIds.has(result.id)) {
2952
+ onChange([...valueRef.current, mapToInvestigation(result)]);
2953
+ }
2954
+ setQuery("");
2955
+ setResults([]);
2956
+ }
2957
+ function handleResultClick(result) {
2958
+ if (addedIds.has(result.id)) return;
2959
+ setAddingId(result.id);
2960
+ setTimeout(() => {
2961
+ addInvestigation(result);
2962
+ setAddingId(null);
2963
+ setTimeout(() => searchInputRef.current?.focus(), 0);
2964
+ }, ADD_FEEDBACK_MS2);
2965
+ }
2966
+ function removeInvestigation(id) {
2967
+ onChange(value.filter((inv) => inv.id !== id));
2968
+ }
2969
+ function handleRecentlyUsedToggle(result) {
2970
+ if (addedIds.has(result.id)) {
2971
+ removeInvestigation(result.id);
2972
+ } else {
2973
+ addInvestigation(result);
2974
+ }
2975
+ }
2976
+ const recentlyUsedChips = recentlyUsed.map((r) => {
2977
+ const isAdded = addedIds.has(r.id);
2978
+ return /* @__PURE__ */ jsxs(
2979
+ "button",
2980
+ {
2981
+ type: "button",
2982
+ onClick: () => handleRecentlyUsedToggle(r),
2983
+ className: cn(
2984
+ "rounded-full border text-xs px-3 py-1 transition-colors",
2985
+ isAdded ? "border-green-300 bg-green-50 text-green-700" : "border-border bg-white hover:bg-gray-50"
2986
+ ),
2987
+ children: [
2988
+ isAdded && /* @__PURE__ */ jsx("span", { className: "mr-1", children: "\u2713" }),
2989
+ r.name
2990
+ ]
2991
+ },
2992
+ r.id
2993
+ );
2994
+ });
2995
+ return /* @__PURE__ */ jsxs("div", { className: "rounded-md overflow-hidden flex flex-col bg-white border border-[#D0D0D0] space-y-3 p-3 h-fit", children: [
2996
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mb-3", children: [
2997
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold", children: label }),
2998
+ /* @__PURE__ */ jsx(
2999
+ "button",
3000
+ {
3001
+ type: "button",
3002
+ onClick: () => setOpen(true),
3003
+ className: "text-sm font-semibold text-purple-600 hover:text-purple-800 cursor-pointer",
3004
+ children: "ADD"
3005
+ }
3006
+ )
3007
+ ] }),
3008
+ value.length > 0 && /* @__PURE__ */ jsx("div", { className: "divide-y divide-border rounded-lg border border-border overflow-hidden", children: value.map((inv) => /* @__PURE__ */ jsxs(
3009
+ "div",
3010
+ {
3011
+ className: "flex items-center justify-between px-3 py-2 bg-white hover:bg-gray-50",
3012
+ children: [
3013
+ /* @__PURE__ */ jsx("span", { className: "text-sm", children: inv.name }),
3014
+ /* @__PURE__ */ jsx(
3015
+ "button",
3016
+ {
3017
+ type: "button",
3018
+ onClick: () => removeInvestigation(inv.id),
3019
+ className: "text-muted-foreground hover:text-red-500 transition-colors cursor-pointer",
3020
+ children: /* @__PURE__ */ jsx(X, { className: "h-4 w-4" })
3021
+ }
3022
+ )
3023
+ ]
3024
+ },
3025
+ inv.id
3026
+ )) }),
3027
+ /* @__PURE__ */ jsx(
3028
+ AddEntityDialog,
3029
+ {
3030
+ open,
3031
+ onClose: () => setOpen(false),
3032
+ title: "Add Investigation",
3033
+ recentlyUsedSlot: recentlyUsedChips.length > 0 ? recentlyUsedChips : void 0,
3034
+ children: /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
3035
+ /* @__PURE__ */ jsx(
3036
+ Input,
3037
+ {
3038
+ ref: searchInputRef,
3039
+ value: query,
3040
+ onChange: (e) => handleQueryChange(e.target.value),
3041
+ placeholder: "Search for an investigation...",
3042
+ className: "border border-border rounded-md focus-visible:ring-0"
3043
+ }
3044
+ ),
3045
+ loading && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground py-1", children: "Searching\u2026" }),
3046
+ !loading && results.length > 0 && /* @__PURE__ */ jsx("div", { className: "border border-border rounded-md overflow-hidden", children: results.map((r) => {
3047
+ const isAdding = addingId === r.id;
3048
+ return /* @__PURE__ */ jsxs(
3049
+ "button",
3050
+ {
3051
+ type: "button",
3052
+ onClick: () => handleResultClick(r),
3053
+ className: cn(
3054
+ "w-full text-left px-3 py-2 text-sm transition-all duration-300 ease-out border-b border-border last:border-b-0 cursor-pointer flex items-center justify-between gap-2",
3055
+ isAdding ? "bg-green-50 border-green-200" : "hover:bg-gray-50"
3056
+ ),
3057
+ children: [
3058
+ /* @__PURE__ */ jsx("span", { className: "truncate", children: r.name }),
3059
+ isAdding && /* @__PURE__ */ jsx(Check, { className: "h-4 w-4 shrink-0 text-green-600" })
3060
+ ]
3061
+ },
3062
+ r.id
3063
+ );
3064
+ }) })
3065
+ ] })
3066
+ }
3067
+ )
3068
+ ] });
3069
+ };
3070
+ var AddInvestigationWidget = ({ fieldId }) => {
3071
+ const { value, setValue } = useField(fieldId);
3072
+ const handlers = useFieldHandlers(fieldId);
3073
+ return /* @__PURE__ */ jsx(
3074
+ AddInvestigationField,
3075
+ {
3076
+ value: value ?? [],
3077
+ onChange: setValue,
3078
+ onSearch: handlers.onSearch,
3079
+ recentlyUsed: handlers.recentlyUsed
3080
+ }
3081
+ );
3082
+ };
3083
+ var ADD_FEEDBACK_MS3 = 320;
3084
+ function mapToProcedure(result) {
3085
+ return {
3086
+ ...result,
3087
+ label: result.name,
3088
+ is_custom: false,
3089
+ fromAI: false
3090
+ };
3091
+ }
3092
+ var AddProcedureField = ({
3093
+ label = "Procedures",
3094
+ value,
3095
+ onChange,
3096
+ onSearch,
3097
+ recentlyUsed = []
3098
+ }) => {
3099
+ const [open, setOpen] = useState(false);
3100
+ const [query, setQuery] = useState("");
3101
+ const [results, setResults] = useState([]);
3102
+ const [loading, setLoading] = useState(false);
3103
+ const [addingId, setAddingId] = useState(null);
3104
+ const debounceRef = useRef(null);
3105
+ const valueRef = useRef([]);
3106
+ const searchInputRef = useRef(null);
3107
+ valueRef.current = value;
3108
+ const addedIds = new Set(value.map((proc) => proc.id));
3109
+ useEffect(() => {
3110
+ if (!open) {
3111
+ setQuery("");
3112
+ setResults([]);
3113
+ setAddingId(null);
3114
+ }
3115
+ }, [open]);
3116
+ function handleQueryChange(q) {
3117
+ setQuery(q);
3118
+ if (debounceRef.current) clearTimeout(debounceRef.current);
3119
+ if (!q.trim()) {
3120
+ setResults([]);
3121
+ return;
3122
+ }
3123
+ debounceRef.current = setTimeout(async () => {
3124
+ setLoading(true);
3125
+ try {
3126
+ const res = await onSearch(q);
3127
+ setResults(res);
3128
+ } finally {
3129
+ setLoading(false);
3130
+ }
3131
+ }, 500);
3132
+ }
3133
+ function addProcedure(result) {
3134
+ if (!addedIds.has(result.id)) {
3135
+ onChange([...valueRef.current, mapToProcedure(result)]);
3136
+ }
3137
+ setQuery("");
3138
+ setResults([]);
3139
+ }
3140
+ function handleResultClick(result) {
3141
+ if (addedIds.has(result.id)) return;
3142
+ setAddingId(result.id);
3143
+ setTimeout(() => {
3144
+ addProcedure(result);
3145
+ setAddingId(null);
3146
+ setTimeout(() => searchInputRef.current?.focus(), 0);
3147
+ }, ADD_FEEDBACK_MS3);
3148
+ }
3149
+ function removeProcedure(id) {
3150
+ onChange(value.filter((proc) => proc.id !== id));
3151
+ }
3152
+ function handleRecentlyUsedToggle(result) {
3153
+ if (addedIds.has(result.id)) {
3154
+ removeProcedure(result.id);
3155
+ } else {
3156
+ addProcedure(result);
3157
+ }
3158
+ }
3159
+ const recentlyUsedChips = recentlyUsed.map((r) => {
3160
+ const isAdded = addedIds.has(r.id);
3161
+ return /* @__PURE__ */ jsxs(
3162
+ "button",
3163
+ {
3164
+ type: "button",
3165
+ onClick: () => handleRecentlyUsedToggle(r),
3166
+ className: cn(
3167
+ "rounded-full border text-xs px-3 py-1 transition-colors",
3168
+ isAdded ? "border-green-300 bg-green-50 text-green-700" : "border-border bg-white hover:bg-gray-50"
3169
+ ),
3170
+ children: [
3171
+ isAdded && /* @__PURE__ */ jsx("span", { className: "mr-1", children: "\u2713" }),
3172
+ r.name
3173
+ ]
3174
+ },
3175
+ r.id
3176
+ );
3177
+ });
3178
+ return /* @__PURE__ */ jsxs("div", { className: "rounded-md overflow-hidden flex flex-col bg-white border border-[#D0D0D0] space-y-3 p-3 h-fit", children: [
3179
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mb-3", children: [
3180
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold", children: label }),
3181
+ /* @__PURE__ */ jsx(
3182
+ "button",
3183
+ {
3184
+ type: "button",
3185
+ onClick: () => setOpen(true),
3186
+ className: "text-sm font-semibold text-purple-600 hover:text-purple-800 cursor-pointer",
3187
+ children: "ADD"
3188
+ }
3189
+ )
3190
+ ] }),
3191
+ value.length > 0 && /* @__PURE__ */ jsx("div", { className: "divide-y divide-border rounded-lg border border-border overflow-hidden", children: value.map((proc) => /* @__PURE__ */ jsxs(
3192
+ "div",
3193
+ {
3194
+ className: "flex items-center justify-between px-3 py-2 bg-white hover:bg-gray-50",
3195
+ children: [
3196
+ /* @__PURE__ */ jsx("span", { className: "text-sm", children: proc.name }),
3197
+ /* @__PURE__ */ jsx(
3198
+ "button",
3199
+ {
3200
+ type: "button",
3201
+ onClick: () => removeProcedure(proc.id),
3202
+ className: "text-muted-foreground hover:text-red-500 transition-colors cursor-pointer",
3203
+ children: /* @__PURE__ */ jsx(X, { className: "h-4 w-4" })
3204
+ }
3205
+ )
3206
+ ]
3207
+ },
3208
+ proc.id
3209
+ )) }),
3210
+ /* @__PURE__ */ jsx(
3211
+ AddEntityDialog,
3212
+ {
3213
+ open,
3214
+ onClose: () => setOpen(false),
3215
+ title: "Add Procedure",
3216
+ recentlyUsedSlot: recentlyUsedChips.length > 0 ? recentlyUsedChips : void 0,
3217
+ children: /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
3218
+ /* @__PURE__ */ jsx(
3219
+ Input,
3220
+ {
3221
+ ref: searchInputRef,
3222
+ value: query,
3223
+ onChange: (e) => handleQueryChange(e.target.value),
3224
+ placeholder: "Search for a procedure...",
3225
+ className: "border border-border rounded-md focus-visible:ring-0"
3226
+ }
3227
+ ),
3228
+ loading && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground py-1", children: "Searching\u2026" }),
3229
+ !loading && results.length > 0 && /* @__PURE__ */ jsx("div", { className: "border border-border rounded-md overflow-hidden", children: results.map((r) => {
3230
+ const isAdding = addingId === r.id;
3231
+ return /* @__PURE__ */ jsxs(
3232
+ "button",
3233
+ {
3234
+ type: "button",
3235
+ onClick: () => handleResultClick(r),
3236
+ className: cn(
3237
+ "w-full text-left px-3 py-2 text-sm transition-all duration-300 ease-out border-b border-border last:border-b-0 cursor-pointer flex items-center justify-between gap-2",
3238
+ isAdding ? "bg-green-50 border-green-200" : "hover:bg-gray-50"
3239
+ ),
3240
+ children: [
3241
+ /* @__PURE__ */ jsx("span", { className: "truncate", children: r.name }),
3242
+ isAdding && /* @__PURE__ */ jsx(Check, { className: "h-4 w-4 shrink-0 text-green-600" })
3243
+ ]
3244
+ },
3245
+ r.id
3246
+ );
3247
+ }) })
3248
+ ] })
3249
+ }
3250
+ )
3251
+ ] });
3252
+ };
3253
+ var AddProcedureWidget = ({ fieldId }) => {
3254
+ const { value, setValue } = useField(fieldId);
3255
+ const handlers = useFieldHandlers(fieldId);
3256
+ return /* @__PURE__ */ jsx(
3257
+ AddProcedureField,
3258
+ {
3259
+ value: value ?? [],
3260
+ onChange: setValue,
3261
+ onSearch: handlers.onSearch,
3262
+ recentlyUsed: handlers.recentlyUsed
3263
+ }
3264
+ );
3265
+ };
3266
+ function getStatusBasedClass(status) {
3267
+ switch ((status || "").toLowerCase()) {
3268
+ case "high":
3269
+ return "bg-red-100 text-red-500";
3270
+ case "medium":
3271
+ return "bg-yellow-100 text-yellow-600";
3272
+ case "low":
3273
+ return "bg-green-100 text-green-600";
3274
+ default:
3275
+ return "bg-gray-200 text-gray-600";
3276
+ }
3277
+ }
3278
+ function DiagnosisCard({ item, defaultOpen = false }) {
3279
+ const [open, setOpen] = useState(defaultOpen);
3280
+ return /* @__PURE__ */ jsxs("div", { className: "border border-gray-200 rounded-lg bg-[#F2F2F2] mb-2 last:mb-0 overflow-hidden", children: [
3281
+ /* @__PURE__ */ jsxs(
3282
+ "button",
3283
+ {
3284
+ type: "button",
3285
+ onClick: () => setOpen((o) => !o),
3286
+ className: cn(
3287
+ "w-full text-left flex items-center gap-2 py-2 px-3 rounded-lg",
3288
+ "cursor-pointer hover:bg-gray-200/60 transition-colors"
3289
+ ),
3290
+ children: [
3291
+ /* @__PURE__ */ jsx(
3292
+ ChevronRight,
3293
+ {
3294
+ className: cn("h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform", open && "rotate-90")
3295
+ }
3296
+ ),
3297
+ /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0", children: [
3298
+ /* @__PURE__ */ jsx("div", { className: "text-xs text-gray-500 font-medium", children: item.category.charAt(0).toUpperCase() + item.category.slice(1) }),
3299
+ /* @__PURE__ */ jsx("div", { className: "text-sm text-black font-semibold mt-0.5 leading-tight", children: item.condition })
3300
+ ] })
3301
+ ]
3302
+ }
3303
+ ),
3304
+ open && /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 px-3 pb-3 pt-0 pl-9", children: [
3305
+ /* @__PURE__ */ jsxs("div", { className: "flex justify-between text-xs font-semibold text-gray-500", children: [
3306
+ /* @__PURE__ */ jsx("span", { children: "LIKELIHOOD" }),
3307
+ /* @__PURE__ */ jsx("span", { children: "SEVERITY" }),
3308
+ /* @__PURE__ */ jsx("span", { children: "TREATABILITY" })
3309
+ ] }),
3310
+ /* @__PURE__ */ jsxs("div", { className: "flex justify-between gap-2", children: [
3311
+ /* @__PURE__ */ jsx("span", { className: cn("px-2.5 py-0.5 rounded-full text-xs font-bold shrink-0", getStatusBasedClass(item.likelihood)), children: item.likelihood }),
3312
+ /* @__PURE__ */ jsx("span", { className: cn("px-2.5 py-0.5 rounded-full text-xs font-bold shrink-0", getStatusBasedClass(item.severity)), children: item.severity }),
3313
+ /* @__PURE__ */ jsx("span", { className: cn("px-2.5 py-0.5 rounded-full text-xs font-bold shrink-0", getStatusBasedClass(item.treatability)), children: item.treatability })
3314
+ ] }),
3315
+ item.keyFeatures && item.keyFeatures.length > 0 && /* @__PURE__ */ jsxs("div", { className: "pt-1", children: [
3316
+ /* @__PURE__ */ jsx("div", { className: "text-xs font-semibold text-gray-500 mb-0.5 uppercase tracking-wider", children: "Key Features" }),
3317
+ /* @__PURE__ */ jsx("ul", { className: "list-disc pl-4 text-xs text-gray-700 space-y-0.5", children: item.keyFeatures.map((feature, i) => /* @__PURE__ */ jsx("li", { children: feature }, i)) })
3318
+ ] }),
3319
+ item.nextSteps && item.nextSteps.length > 0 && /* @__PURE__ */ jsxs("div", { className: "pt-1", children: [
3320
+ /* @__PURE__ */ jsx("div", { className: "text-xs font-semibold text-gray-500 mb-0.5 uppercase tracking-wider", children: "Next Steps" }),
3321
+ /* @__PURE__ */ jsx("ul", { className: "list-disc pl-4 text-xs text-gray-700 space-y-0.5", children: item.nextSteps.map((step, i) => /* @__PURE__ */ jsx("li", { children: step }, i)) })
3322
+ ] })
3323
+ ] })
3324
+ ] });
3325
+ }
3326
+ var DifferentialDiagnosis = ({
3327
+ differentialDiagnosis,
3328
+ className = "",
3329
+ height = "300px"
3330
+ }) => {
3331
+ const hasItems = Array.isArray(differentialDiagnosis) && differentialDiagnosis.length > 0;
3332
+ return /* @__PURE__ */ jsxs(
3333
+ "div",
3334
+ {
3335
+ className: cn(
3336
+ "rounded-md overflow-hidden flex flex-col border border-[#D0D0D0]",
3337
+ className
3338
+ ),
3339
+ children: [
3340
+ /* @__PURE__ */ jsx("div", { className: "rounded-t-md bg-[#FEE8EC] px-3 py-1.5 text-xs shrink-0 z-[1] text-slate-600 flex items-center font-semibold", children: /* @__PURE__ */ jsx("span", { children: "Differential Diagnosis" }) }),
3341
+ /* @__PURE__ */ jsxs(
3342
+ "div",
3343
+ {
3344
+ className: cn(
3345
+ "relative bg-white rounded-b-md border-t border-[#D0D0D0] overflow-y-auto p-3",
3346
+ "focus-visible:outline-none"
3347
+ ),
3348
+ style: { minHeight: height, maxHeight: height },
3349
+ children: [
3350
+ hasItems ? differentialDiagnosis.map((item, idx) => /* @__PURE__ */ jsx(DiagnosisCard, { item, defaultOpen: idx === 0 }, idx)) : /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "No differential diagnosis yet." }),
3351
+ /* @__PURE__ */ jsx("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 h-[30%] bg-gradient-to-t from-white via-white/80 to-transparent" })
3352
+ ]
3353
+ }
3354
+ )
3355
+ ]
3356
+ }
3357
+ );
3358
+ };
3359
+ var DifferentialDiagnosisWidget = ({ fieldId }) => {
3360
+ const { value } = useField(fieldId);
3361
+ const items = Array.isArray(value) ? value : [];
3362
+ return /* @__PURE__ */ jsx(DifferentialDiagnosis, { differentialDiagnosis: items });
3363
+ };
3364
+ var Spinner2 = React11.forwardRef(
3365
+ ({ className, size = "md", ...props }, ref) => {
3366
+ const sizeClasses = {
3367
+ sm: "h-4 w-4 border-2",
3368
+ md: "h-6 w-6 border-2",
3369
+ lg: "h-8 w-8 border-3"
3370
+ };
3371
+ return /* @__PURE__ */ jsx(
3372
+ "div",
3373
+ {
3374
+ ref,
3375
+ className: cn(
3376
+ "animate-spin rounded-full border-primary border-t-transparent",
3377
+ sizeClasses[size],
3378
+ className
3379
+ ),
3380
+ ...props,
3381
+ children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Loading..." })
3382
+ }
3383
+ );
3384
+ }
3385
+ );
3386
+ Spinner2.displayName = "Spinner";
3387
+ function buildItems(data) {
3388
+ const items = [];
3389
+ const hasBP = data.blood_pressure_systolic != null || data.blood_pressure_diastolic != null;
3390
+ if (hasBP) {
3391
+ const sys = data.blood_pressure_systolic ?? "\u2013";
3392
+ const dia = data.blood_pressure_diastolic ?? "\u2013";
3393
+ items.push({ label: "BP", value: `${sys}/${dia}` });
3394
+ }
3395
+ if (data.heart_rate != null)
3396
+ items.push({ label: "Heart Rate", value: `${data.heart_rate} bpm` });
3397
+ if (data.respiratory_rate != null)
3398
+ items.push({ label: "Resp. Rate", value: `${data.respiratory_rate}/min` });
3399
+ if (data.oxygen_saturation != null)
3400
+ items.push({ label: "SpO\u2082", value: `${data.oxygen_saturation}%` });
3401
+ if (data.temperature != null)
3402
+ items.push({ label: "Temp", value: `${data.temperature} \xB0F` });
3403
+ if (data.height != null)
3404
+ items.push({ label: "Height", value: `${data.height} cm` });
3405
+ if (data.weight != null)
3406
+ items.push({ label: "Weight", value: `${data.weight} kg` });
3407
+ if (data.bmi != null)
3408
+ items.push({ label: "BMI", value: `${data.bmi}` });
3409
+ if (data.blood_sugar != null)
3410
+ items.push({ label: "Blood Sugar", value: `${data.blood_sugar} mg/dL` });
3411
+ if (data.circumference_of_head_in_cms != null)
3412
+ items.push({ label: "Head Circ.", value: `${data.circumference_of_head_in_cms} cm` });
3413
+ if (data.circumference_of_waist_in_cms != null)
3414
+ items.push({ label: "Waist Circ.", value: `${data.circumference_of_waist_in_cms} cm` });
3415
+ return items;
3416
+ }
3417
+ function formatRecordedAt(iso) {
3418
+ if (!iso) return "";
3419
+ try {
3420
+ return new Date(iso).toLocaleString(void 0, {
3421
+ day: "2-digit",
3422
+ month: "short",
3423
+ year: "numeric",
3424
+ hour: "2-digit",
3425
+ minute: "2-digit"
3426
+ });
3427
+ } catch {
3428
+ return iso;
3429
+ }
3430
+ }
3431
+ function VitalChip({ label, value }) {
3432
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-0 rounded-md min-w-fit px-1.5", children: [
3433
+ /* @__PURE__ */ jsx("span", { className: "text-[10px] font-sm text-gray-500 uppercase tracking-wide leading-none", children: label }),
3434
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-gray-900 leading-tight", children: value })
3435
+ ] });
3436
+ }
3437
+ var Vitals = ({
3438
+ data,
3439
+ loading = false,
3440
+ error = null,
3441
+ onRefresh,
3442
+ className
3443
+ }) => {
3444
+ const items = data ? buildItems(data) : [];
3445
+ const hasItems = items.length > 0;
3446
+ const recordedAt = data?.recorded_at ? formatRecordedAt(data.recorded_at) : null;
3447
+ const notes = data?.notes?.trim() || null;
3448
+ return /* @__PURE__ */ jsx(
3449
+ "div",
3450
+ {
3451
+ className: cn(
3452
+ "rounded-md overflow-hidden border border-[#D0D0D0] bg-white px-2 py-2",
3453
+ className
3454
+ ),
3455
+ children: loading && !hasItems ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5 py-1", children: [
3456
+ /* @__PURE__ */ jsx(Spinner2, { size: "sm" }),
3457
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "Loading vitals\u2026" })
3458
+ ] }) : error ? /* @__PURE__ */ jsx("p", { className: "text-xs text-red-500 py-1", children: error }) : hasItems ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
3459
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-x-3 gap-y-1", children: [
3460
+ /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-x-2 gap-y-0.5", children: items.map((item) => /* @__PURE__ */ jsx(VitalChip, { ...item }, item.label)) }),
3461
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-end gap-0.5 shrink-0", children: [
3462
+ recordedAt && /* @__PURE__ */ jsx("span", { className: "text-[10px] text-slate-500", children: recordedAt }),
3463
+ onRefresh && /* @__PURE__ */ jsxs(
3464
+ "button",
3465
+ {
3466
+ type: "button",
3467
+ onClick: onRefresh,
3468
+ disabled: loading,
3469
+ className: cn(
3470
+ "flex items-center gap-0.5 text-[10px] font-medium text-slate-600",
3471
+ "hover:text-slate-900 transition-colors disabled:opacity-50 cursor-pointer"
3472
+ ),
3473
+ "aria-label": "Refresh vitals",
3474
+ children: [
3475
+ /* @__PURE__ */ jsx(RefreshCw, { className: cn("h-2.5 w-2.5", loading && "animate-spin") }),
3476
+ /* @__PURE__ */ jsx("span", { children: "Refresh" })
3477
+ ]
3478
+ }
3479
+ )
3480
+ ] })
3481
+ ] }),
3482
+ notes && /* @__PURE__ */ jsx("p", { className: "text-xs text-gray-600 pt-1.5 mt-0.5", children: notes })
3483
+ ] }) : /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2 py-1", children: [
3484
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "No vitals recorded." }),
3485
+ onRefresh && /* @__PURE__ */ jsxs(
3486
+ "button",
3487
+ {
3488
+ type: "button",
3489
+ onClick: onRefresh,
3490
+ disabled: loading,
3491
+ className: cn(
3492
+ "flex items-center gap-0.5 text-[10px] font-medium text-slate-600",
3493
+ "hover:text-slate-900 transition-colors disabled:opacity-50 shrink-0"
3494
+ ),
3495
+ "aria-label": "Refresh vitals",
3496
+ children: [
3497
+ /* @__PURE__ */ jsx(RefreshCw, { className: cn("h-2.5 w-2.5", loading && "animate-spin") }),
3498
+ /* @__PURE__ */ jsx("span", { children: "Refresh" })
3499
+ ]
3500
+ }
3501
+ )
3502
+ ] })
3503
+ }
3504
+ );
3505
+ };
3506
+ var VitalsWidget = ({ fieldId }) => {
3507
+ const { value, setValue, fieldDef } = useField(fieldId);
3508
+ const handlers = useFieldHandlers(fieldId);
3509
+ const [loading, setLoading] = useState(false);
3510
+ const [error, setError] = useState(null);
3511
+ console.log("[VitalsWidget] fieldId:", fieldId, "| onFetch present:", !!handlers.onFetch, "| value:", value);
3512
+ const fetchVitals = useCallback(async () => {
3513
+ if (!handlers.onFetch) return;
3514
+ setLoading(true);
3515
+ setError(null);
3516
+ try {
3517
+ const data = await handlers.onFetch();
3518
+ console.log("[VitalsWidget] fetched data:", data);
3519
+ setValue(data);
3520
+ } catch {
3521
+ setError("Failed to load vitals. Please try again.");
3522
+ } finally {
3523
+ setLoading(false);
3524
+ }
3525
+ }, [handlers, setValue]);
3526
+ useEffect(() => {
3527
+ fetchVitals();
3528
+ }, []);
3529
+ return /* @__PURE__ */ jsx(
3530
+ Vitals,
3531
+ {
3532
+ label: fieldDef?.label ?? "Vitals",
3533
+ data: value ?? null,
3534
+ loading,
3535
+ error,
3536
+ onRefresh: handlers.onFetch ? fetchVitals : void 0
3537
+ }
3538
+ );
3539
+ };
3540
+ function normalizeOptions(response) {
3541
+ if (Array.isArray(response)) {
3542
+ return response.map((o) => ({ label: String(o.label), value: String(o.value) }));
3543
+ }
3544
+ if (response?.specializations?.length) {
3545
+ return response.specializations.map((s) => ({ label: s, value: s }));
3546
+ }
3547
+ return [];
3548
+ }
3549
+ function normalizeValue(value) {
3550
+ if (!value || !Array.isArray(value)) return [];
3551
+ return value.map((item) => {
3552
+ if (item && typeof item === "object" && "specialization" in item) {
3553
+ const s = item.specialization;
3554
+ const u = item.is_urgent;
3555
+ return { specialization: String(s), is_urgent: Boolean(u) };
3556
+ }
3557
+ return { specialization: String(item), is_urgent: false };
3558
+ });
3559
+ }
3560
+ var ReferralWidget = ({ fieldId }) => {
3561
+ const { fieldDef, value, setValue, setTouched, error, disabled, touched } = useField(fieldId);
3562
+ const handlers = useFieldHandlers(fieldId);
3563
+ const [options, setOptions] = useState([]);
3564
+ const [loading, setLoading] = useState(false);
3565
+ const { state } = useForm();
3566
+ const showError = !!error && (touched || state.submitAttempted);
3567
+ const selectedItems = normalizeValue(value);
3568
+ const availableOptions = options.filter(
3569
+ (opt) => !selectedItems.some((item) => item.specialization === opt.value)
3570
+ );
3571
+ const loadOptions = useCallback(async () => {
3572
+ if (handlers.onFetchOptions) {
3573
+ setLoading(true);
3574
+ try {
3575
+ const res = await handlers.onFetchOptions();
3576
+ setOptions(normalizeOptions(res));
3577
+ } finally {
3578
+ setLoading(false);
3579
+ }
3580
+ return;
3581
+ }
3582
+ const def = fieldDef;
3583
+ if (def?.options?.length) {
3584
+ setOptions(def.options.map((o) => ({ label: String(o.label), value: String(o.value) })));
3585
+ } else if (def?.dataSource) {
3586
+ setLoading(true);
3587
+ fetchOptions(def.dataSource.source, def.dataSource.params).then((opts) => setOptions(opts.map((o) => ({ label: String(o.label), value: String(o.value) })))).finally(() => setLoading(false));
3588
+ } else {
3589
+ setOptions([]);
3590
+ }
3591
+ }, [fieldDef, handlers]);
3592
+ useEffect(() => {
3593
+ if (!fieldDef) return;
3594
+ loadOptions();
3595
+ }, [fieldDef, loadOptions]);
3596
+ const handleAdd = useCallback(
3597
+ (specialization) => {
3598
+ const next = [...selectedItems, { specialization, is_urgent: false }];
3599
+ setValue(next);
3600
+ setTouched();
3601
+ },
3602
+ [selectedItems, setValue, setTouched]
3603
+ );
3604
+ const handleRemove = useCallback(
3605
+ (specialization) => {
3606
+ const next = selectedItems.filter((item) => item.specialization !== specialization);
3607
+ setValue(next);
3608
+ setTouched();
3609
+ },
3610
+ [selectedItems, setValue, setTouched]
3611
+ );
3612
+ const handleToggleUrgent = useCallback(
3613
+ (specialization) => {
3614
+ const next = selectedItems.map(
3615
+ (item) => item.specialization === specialization ? { ...item, is_urgent: !item.is_urgent } : item
3616
+ );
3617
+ setValue(next);
3618
+ setTouched();
3619
+ },
3620
+ [selectedItems, setValue, setTouched]
3621
+ );
3622
+ if (!fieldDef) return null;
3623
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
3624
+ /* @__PURE__ */ jsxs(Label, { htmlFor: fieldId, children: [
3625
+ "Referral to ",
3626
+ fieldDef.required && /* @__PURE__ */ jsx("span", { className: "text-red-500", children: "*" })
3627
+ ] }),
3628
+ loading && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "Loading..." }),
3629
+ !loading && /* @__PURE__ */ jsxs(Fragment, { children: [
3630
+ /* @__PURE__ */ jsxs(
3631
+ Select,
3632
+ {
3633
+ disabled,
3634
+ value: "",
3635
+ onValueChange: (val) => {
3636
+ if (val) {
3637
+ handleAdd(val);
3638
+ }
3639
+ },
3640
+ children: [
3641
+ /* @__PURE__ */ jsx(SelectTrigger, { id: fieldId, className: showError ? "border-red-500" : "", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Select specializations..." }) }),
3642
+ /* @__PURE__ */ jsxs(SelectContent, { children: [
3643
+ availableOptions.map((opt) => /* @__PURE__ */ jsx(SelectItem, { value: opt.value, children: opt.label }, opt.value)),
3644
+ availableOptions.length === 0 && /* @__PURE__ */ jsx("div", { className: "py-2 px-2 text-sm text-muted-foreground", children: "All specializations selected" })
3645
+ ] })
3646
+ ]
3647
+ },
3648
+ `referral-${selectedItems.map((i) => i.specialization).join(",")}`
3649
+ ),
3650
+ selectedItems.length > 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5 mt-1.5", children: selectedItems.map((item) => {
3651
+ const isUrgent = item.is_urgent;
3652
+ const chipClass = isUrgent ? "inline-flex items-center gap-0.5 px-2 py-0.5 bg-red-100 text-red-800 border border-red-300 rounded-full text-xs max-w-full cursor-pointer hover:bg-red-200 transition-colors" : "inline-flex items-center gap-0.5 px-2 py-0.5 bg-blue-100 text-blue-800 rounded-full text-xs max-w-full cursor-pointer hover:bg-blue-200 transition-colors";
3653
+ return /* @__PURE__ */ jsxs(
3654
+ "div",
3655
+ {
3656
+ className: chipClass,
3657
+ onClick: (e) => {
3658
+ if (e.target instanceof HTMLElement && e.target.closest("button")) return;
3659
+ handleToggleUrgent(item.specialization);
3660
+ },
3661
+ children: [
3662
+ isUrgent && /* @__PURE__ */ jsx("span", { className: "flex-shrink-0 bg-red-600 text-white text-[10px] font-bold px-1 py-0.5 rounded mr-1", children: "U" }),
3663
+ /* @__PURE__ */ jsx("span", { className: "truncate max-w-[120px]", children: item.specialization }),
3664
+ /* @__PURE__ */ jsx(
3665
+ "button",
3666
+ {
3667
+ type: "button",
3668
+ onClick: (e) => {
3669
+ e.stopPropagation();
3670
+ handleRemove(item.specialization);
3671
+ },
3672
+ className: "ml-0.5 text-blue-600 hover:text-blue-800 focus:outline-none flex-shrink-0 text-sm leading-none",
3673
+ "aria-label": `Remove ${item.specialization}`,
3674
+ children: "\xD7"
3675
+ }
3676
+ )
3677
+ ]
3678
+ },
3679
+ item.specialization
3680
+ );
3681
+ }) }),
3682
+ selectedItems.length === 0 && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-1", children: "No specializations selected" }),
3683
+ selectedItems.length > 0 && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-1.5", children: "Click a chip to mark as urgent" })
3684
+ ] }),
3685
+ showError && /* @__PURE__ */ jsx("p", { className: "text-xs text-red-500", children: error })
3686
+ ] });
3687
+ };
3688
+ var Card = React11.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
3689
+ "div",
3690
+ {
3691
+ ref,
3692
+ className: cn(
3693
+ "rounded-lg border bg-card text-card-foreground shadow-sm",
3694
+ className
3695
+ ),
3696
+ ...props
3697
+ }
3698
+ ));
3699
+ Card.displayName = "Card";
3700
+ var CardHeader = React11.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
3701
+ "div",
3702
+ {
3703
+ ref,
3704
+ className: cn("flex flex-col space-y-1.5 p-6", className),
3705
+ ...props
3706
+ }
3707
+ ));
3708
+ CardHeader.displayName = "CardHeader";
3709
+ var CardTitle = React11.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
3710
+ "h3",
3711
+ {
3712
+ ref,
3713
+ className: cn(
3714
+ "text-2xl font-semibold leading-none tracking-tight",
3715
+ className
3716
+ ),
3717
+ ...props
3718
+ }
3719
+ ));
3720
+ CardTitle.displayName = "CardTitle";
3721
+ var CardDescription = React11.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
3722
+ "p",
3723
+ {
3724
+ ref,
3725
+ className: cn("text-sm text-muted-foreground", className),
3726
+ ...props
3727
+ }
3728
+ ));
3729
+ CardDescription.displayName = "CardDescription";
3730
+ var CardContent = React11.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx("div", { ref, className: cn("p-6 pt-0", className), ...props }));
3731
+ CardContent.displayName = "CardContent";
3732
+ var CardFooter = React11.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
3733
+ "div",
3734
+ {
3735
+ ref,
3736
+ className: cn("flex items-center p-6 pt-0", className),
3737
+ ...props
3738
+ }
3739
+ ));
3740
+ CardFooter.displayName = "CardFooter";
3741
+ var FOLLOWUP_TYPE_OPTIONS = [
3742
+ { value: "no followup", label: "No Follow-up" },
3743
+ { value: "one time", label: "One Time" }
3744
+ ];
3745
+ var UNIT_OPTIONS = [
3746
+ { value: "days", label: "Days" },
3747
+ { value: "weeks", label: "Weeks" },
3748
+ { value: "months", label: "Months" }
3749
+ ];
3750
+ function durationToDays(valueNum, unit) {
3751
+ const today = /* @__PURE__ */ new Date();
3752
+ today.setHours(0, 0, 0, 0);
3753
+ let target;
3754
+ if (unit === "days") target = addDays(today, valueNum);
3755
+ else if (unit === "weeks") target = addWeeks(today, valueNum);
3756
+ else target = addMonths(today, valueNum);
3757
+ return Math.max(0, differenceInCalendarDays(target, today));
3758
+ }
3759
+ function dateToDays(date) {
3760
+ const today = /* @__PURE__ */ new Date();
3761
+ today.setHours(0, 0, 0, 0);
3762
+ const d = new Date(date);
3763
+ d.setHours(0, 0, 0, 0);
3764
+ return Math.max(0, differenceInCalendarDays(d, today));
3765
+ }
3766
+ function daysToDate(days) {
3767
+ const today = /* @__PURE__ */ new Date();
3768
+ today.setHours(0, 0, 0, 0);
3769
+ return addDays(today, days);
3770
+ }
3771
+ function normalizeFollowup(value) {
3772
+ if (value === false || value === null || value === void 0) return false;
3773
+ if (typeof value !== "object") return false;
3774
+ const o = value;
3775
+ if (o.followupType !== "one time") return false;
3776
+ if (typeof o.value === "string" && o.unit === "days") {
3777
+ return { followupType: "one time", value: o.value, unit: "days" };
3778
+ }
3779
+ const today = /* @__PURE__ */ new Date();
3780
+ today.setHours(0, 0, 0, 0);
3781
+ if (o.mode === "date" && typeof o.date === "string") {
3782
+ const d = parseLocalDate(o.date);
3783
+ if (d) {
3784
+ const days2 = dateToDays(d);
3785
+ return { followupType: "one time", value: String(days2), unit: "days" };
3786
+ }
3787
+ }
3788
+ const val = o.value != null ? Number(String(o.value)) : 7;
3789
+ const u = o.unit === "weeks" || o.unit === "months" ? o.unit : "days";
3790
+ const days = durationToDays(Number.isNaN(val) ? 7 : val, u);
3791
+ return { followupType: "one time", value: String(days), unit: "days" };
3792
+ }
3793
+ function getDefaultDate() {
3794
+ const d = /* @__PURE__ */ new Date();
3795
+ d.setDate(d.getDate() + 7);
3796
+ return d;
3797
+ }
3798
+ function parseLocalDate(dateString) {
3799
+ if (!dateString) return null;
3800
+ try {
3801
+ return parseISO(dateString);
3802
+ } catch {
3803
+ const parts = dateString.split("-");
3804
+ if (parts.length === 3) {
3805
+ const y = parseInt(parts[0], 10);
3806
+ const m = parseInt(parts[1], 10) - 1;
3807
+ const d = parseInt(parts[2], 10);
3808
+ if (!Number.isNaN(y) && !Number.isNaN(m) && !Number.isNaN(d)) {
3809
+ return new Date(y, m, d);
3810
+ }
3811
+ }
3812
+ return null;
3813
+ }
3814
+ }
3815
+ var FollowupWidget = ({ fieldId }) => {
3816
+ const { fieldDef, value, setValue, setTouched, error, disabled, visible } = useField(fieldId);
3817
+ const followup = normalizeFollowup(value);
3818
+ const [calendarOpen, setCalendarOpen] = useState(false);
3819
+ const currentFollowupType = followup ? followup.followupType : "no followup";
3820
+ const hasFollowup = followup !== false;
3821
+ const [displayMode, setDisplayMode] = useState("duration");
3822
+ const [displayUnit, setDisplayUnit] = useState("days");
3823
+ const daysNum = hasFollowup ? parseInt(followup.value, 10) || 7 : 7;
3824
+ const currentDate = hasFollowup ? daysToDate(daysNum) : null;
3825
+ const followupMode = displayMode;
3826
+ const currentValue = hasFollowup && displayUnit === "days" ? followup.value : hasFollowup ? String(
3827
+ displayUnit === "weeks" ? Math.round(daysNum / 7) || 1 : Math.round(daysNum / 30) || 1
3828
+ ) : "7";
3829
+ const currentUnit = displayUnit;
3830
+ const handleFollowupTypeChange = useCallback(
3831
+ (newType) => {
3832
+ setTouched();
3833
+ if (newType === "no followup") {
3834
+ setValue(false);
3835
+ setCalendarOpen(false);
3836
+ return;
3837
+ }
3838
+ setValue({
3839
+ followupType: "one time",
3840
+ value: hasFollowup ? followup.value : "7",
3841
+ unit: "days"
3842
+ });
3843
+ },
3844
+ [followup, hasFollowup, setValue, setTouched]
3845
+ );
3846
+ const handleModeChange = useCallback((newMode) => {
3847
+ setDisplayMode(newMode);
3848
+ if (newMode === "date") setCalendarOpen(false);
3849
+ }, []);
3850
+ const handleValueChange = useCallback(
3851
+ (newValue) => {
3852
+ setTouched();
3853
+ const num = parseInt(newValue, 10);
3854
+ const min = displayUnit === "days" ? 0 : 1;
3855
+ const valid = (Number.isNaN(num) ? min : num) >= min || newValue === "";
3856
+ if (!valid && newValue !== "") {
3857
+ setValue({ followupType: "one time", value: String(displayUnit === "days" ? 0 : durationToDays(1, displayUnit)), unit: "days" });
3858
+ return;
3859
+ }
3860
+ const days = durationToDays(Number.isNaN(num) ? displayUnit === "days" ? 0 : 1 : num, displayUnit);
3861
+ setValue({ followupType: "one time", value: String(days), unit: "days" });
3862
+ },
3863
+ [displayUnit, setValue, setTouched]
3864
+ );
3865
+ const handleUnitChange = useCallback((newUnit) => {
3866
+ setDisplayUnit(newUnit);
3867
+ }, []);
3868
+ const handleDateSelect = useCallback(
3869
+ (selected) => {
3870
+ setTouched();
3871
+ setCalendarOpen(false);
3872
+ if (!selected) return;
3873
+ const days = dateToDays(selected);
3874
+ setValue({ followupType: "one time", value: String(days), unit: "days" });
3875
+ },
3876
+ [setValue, setTouched]
3877
+ );
3878
+ if (!visible || !fieldDef) return null;
3879
+ const minDate = /* @__PURE__ */ new Date();
3880
+ minDate.setHours(0, 0, 0, 0);
3881
+ const selectedDate = currentDate || getDefaultDate();
3882
+ return /* @__PURE__ */ jsx(Card, { className: cn(error && "border-destructive"), children: /* @__PURE__ */ jsxs(CardContent, { className: "space-y-1 p-2", children: [
3883
+ /* @__PURE__ */ jsx("div", { className: "flex items-center justify-between gap-2", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center flex-shrink-0 gap-2", children: [
3884
+ /* @__PURE__ */ jsx(Label, { className: "text-xs font-semibold text-muted-foreground", children: "Follow-up" }),
3885
+ /* @__PURE__ */ jsxs(
3886
+ Select,
3887
+ {
3888
+ value: currentFollowupType,
3889
+ onValueChange: (v) => handleFollowupTypeChange(v),
3890
+ disabled,
3891
+ children: [
3892
+ /* @__PURE__ */ jsx(SelectTrigger, { className: "w-[140px] border-none bg-muted/50 text-xs py-1 focus:outline-none focus:ring-0 focus:ring-offset-0", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
3893
+ /* @__PURE__ */ jsx(SelectContent, { children: FOLLOWUP_TYPE_OPTIONS.map((opt) => /* @__PURE__ */ jsx(SelectItem, { value: opt.value, className: "text-xs", children: opt.label }, opt.value)) })
3894
+ ]
3895
+ }
3896
+ )
3897
+ ] }) }),
3898
+ currentFollowupType !== "no followup" && /* @__PURE__ */ jsxs(Fragment, { children: [
3899
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
3900
+ /* @__PURE__ */ jsx(Label, { className: "text-xs font-medium text-muted-foreground", children: "Schedule by:" }),
3901
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
3902
+ /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 cursor-pointer", children: [
3903
+ /* @__PURE__ */ jsx(
3904
+ "input",
3905
+ {
3906
+ type: "radio",
3907
+ name: `followup-mode-${fieldId}`,
3908
+ value: "duration",
3909
+ checked: followupMode === "duration",
3910
+ onChange: () => handleModeChange("duration"),
3911
+ className: "h-4 w-4 text-primary focus:ring-primary",
3912
+ disabled
3913
+ }
3914
+ ),
3915
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "Duration" })
3916
+ ] }),
3917
+ /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 cursor-pointer", children: [
3918
+ /* @__PURE__ */ jsx(
3919
+ "input",
3920
+ {
3921
+ type: "radio",
3922
+ name: `followup-mode-${fieldId}`,
3923
+ value: "date",
3924
+ checked: followupMode === "date",
3925
+ onChange: () => handleModeChange("date"),
3926
+ className: "h-4 w-4 text-primary focus:ring-primary",
3927
+ disabled
3928
+ }
3929
+ ),
3930
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "Date" })
3931
+ ] })
3932
+ ] })
3933
+ ] }),
3934
+ followupMode === "duration" && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
3935
+ /* @__PURE__ */ jsx("span", { className: "text-xs font-semibold text-muted-foreground", children: "In" }),
3936
+ /* @__PURE__ */ jsx(
3937
+ "input",
3938
+ {
3939
+ type: "number",
3940
+ min: currentUnit === "days" ? 0 : 1,
3941
+ value: currentValue,
3942
+ onChange: (e) => handleValueChange(e.target.value),
3943
+ disabled,
3944
+ className: "w-16 py-1.5 px-2 border border-input rounded-md text-center text-sm focus:outline-none focus:ring-2 focus:ring-ring",
3945
+ placeholder: "7"
3946
+ }
3947
+ ),
3948
+ /* @__PURE__ */ jsxs(
3949
+ Select,
3950
+ {
3951
+ value: currentUnit,
3952
+ onValueChange: (v) => handleUnitChange(v),
3953
+ disabled,
3954
+ children: [
3955
+ /* @__PURE__ */ jsx(SelectTrigger, { className: "w-[100px] h-8 text-xs", children: /* @__PURE__ */ jsx(SelectValue, { className: "text-xs" }) }),
3956
+ /* @__PURE__ */ jsx(SelectContent, { children: UNIT_OPTIONS.map((opt) => /* @__PURE__ */ jsx(SelectItem, { value: opt.value, className: "text-xs", children: opt.label }, opt.value)) })
3957
+ ]
3958
+ }
3959
+ )
3960
+ ] }),
3961
+ followupMode === "date" && /* @__PURE__ */ jsxs(Popover, { open: calendarOpen, onOpenChange: setCalendarOpen, children: [
3962
+ /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
3963
+ Button,
3964
+ {
3965
+ type: "button",
3966
+ variant: "outline",
3967
+ className: "w-full justify-start text-left font-normal h-9",
3968
+ disabled,
3969
+ children: [
3970
+ /* @__PURE__ */ jsx(Calendar$1, { className: "mr-2 h-4 w-4 text-muted-foreground" }),
3971
+ /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: hasFollowup && currentDate ? format(currentDate, "MMM d, yyyy") : "Select date" })
3972
+ ]
3973
+ }
3974
+ ) }),
3975
+ /* @__PURE__ */ jsx(PopoverContent, { className: "w-auto p-0", align: "start", children: /* @__PURE__ */ jsx(
3976
+ Calendar,
3977
+ {
3978
+ mode: "single",
3979
+ selected: selectedDate,
3980
+ onSelect: handleDateSelect,
3981
+ disabled: (date) => date < minDate,
3982
+ initialFocus: true
3983
+ }
3984
+ ) })
3985
+ ] }),
3986
+ /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
3987
+ "One-time appointment",
3988
+ " ",
3989
+ followupMode === "duration" ? `in ${currentValue} ${currentUnit}` : hasFollowup && currentDate ? `on ${format(currentDate, "MMM d, yyyy")}` : "date to be selected"
3990
+ ] })
3991
+ ] }),
3992
+ error && /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: error })
3993
+ ] }) });
3994
+ };
3995
+ var FieldRenderer = ({ fieldId }) => {
3996
+ const { fieldDef, visible } = useField(fieldId);
3997
+ if (!visible || !fieldDef) {
3998
+ return null;
3999
+ }
4000
+ switch (fieldDef.type) {
4001
+ case "text":
4002
+ case "number":
4003
+ return /* @__PURE__ */ jsx(TextWidget, { fieldId });
4004
+ case "textarea":
4005
+ case "richtext":
4006
+ return /* @__PURE__ */ jsx(TextWidget, { fieldId });
4007
+ case "date":
4008
+ return /* @__PURE__ */ jsx(DateWidget, { fieldId });
4009
+ case "datetime":
4010
+ return /* @__PURE__ */ jsx(DateTimeWidget, { fieldId });
4011
+ case "select":
4012
+ return /* @__PURE__ */ jsx(SelectWidget, { fieldId });
4013
+ case "radio":
4014
+ return /* @__PURE__ */ jsx(RadioWidget, { fieldId });
4015
+ case "checkbox":
4016
+ return /* @__PURE__ */ jsx(CheckboxWidget, { fieldId });
4017
+ case "multiselect":
4018
+ return /* @__PURE__ */ jsx(MultiSelectWidget, { fieldId });
4019
+ case "repeatable":
4020
+ return /* @__PURE__ */ jsx(RepeatableWidget, { fieldId });
4021
+ case "image_upload":
4022
+ return /* @__PURE__ */ jsx(ImageUploadWidget, { fieldId });
4023
+ case "signature":
4024
+ return /* @__PURE__ */ jsx(SignatureUploadWidget, { fieldId });
4025
+ case "editable_table":
4026
+ return /* @__PURE__ */ jsx(EditableTableWidget, { fieldId });
4027
+ case "medications":
4028
+ return /* @__PURE__ */ jsx(AddMedicationWidget, { fieldId });
4029
+ case "investigations":
4030
+ return /* @__PURE__ */ jsx(AddInvestigationWidget, { fieldId });
4031
+ case "procedures":
4032
+ return /* @__PURE__ */ jsx(AddProcedureWidget, { fieldId });
4033
+ case "differential_diagnosis":
4034
+ return /* @__PURE__ */ jsx(DifferentialDiagnosisWidget, { fieldId });
4035
+ case "vitals":
4036
+ return /* @__PURE__ */ jsx(VitalsWidget, { fieldId });
4037
+ case "referral":
4038
+ return /* @__PURE__ */ jsx(ReferralWidget, { fieldId });
4039
+ case "followup":
4040
+ return /* @__PURE__ */ jsx(FollowupWidget, { fieldId });
4041
+ case "static_text": {
4042
+ const def = fieldDef;
4043
+ const size = def.size ?? "regular";
4044
+ const labelClass = size === "large" ? "text-base" : "text-sm";
4045
+ const descClass = size === "large" ? "text-sm" : "text-xs";
4046
+ return /* @__PURE__ */ jsxs("div", { className: `${labelClass} text-muted-foreground`, children: [
4047
+ def.label,
4048
+ def.description && /* @__PURE__ */ jsx("p", { className: `mt-1 ${descClass} opacity-90`, children: def.description })
4049
+ ] });
4050
+ }
4051
+ default:
4052
+ return /* @__PURE__ */ jsxs("div", { className: "text-red-500", children: [
4053
+ "Unknown field type: ",
4054
+ fieldDef.type
4055
+ ] });
4056
+ }
4057
+ };
4058
+ var Section = ({ title, children }) => {
4059
+ const [expanded, setExpanded] = useState(true);
4060
+ const handleToggle = () => setExpanded((prev) => !prev);
4061
+ const contentClassName = cn(
4062
+ "overflow-hidden transition-[height] duration-200 ease-in-out",
4063
+ !expanded && "hidden"
4064
+ );
4065
+ return /* @__PURE__ */ jsxs("div", { className: "mb-6 border rounded-lg bg-white shadow-sm overflow-hidden", children: [
4066
+ /* @__PURE__ */ jsxs(
4067
+ "button",
4068
+ {
4069
+ type: "button",
4070
+ onClick: handleToggle,
4071
+ className: "w-full flex items-center justify-between gap-2 p-4 text-left border-b hover:bg-gray-50/80 transition-colors",
4072
+ children: [
4073
+ /* @__PURE__ */ jsx("h3", { className: "text-lg font-medium", children: title }),
4074
+ /* @__PURE__ */ jsx("span", { className: "flex-shrink-0 text-muted-foreground", "aria-hidden": true, children: expanded ? /* @__PURE__ */ jsx(ChevronDown, { className: "h-5 w-5" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "h-5 w-5" }) })
4075
+ ]
4076
+ }
4077
+ ),
4078
+ /* @__PURE__ */ jsx("div", { className: contentClassName, children: /* @__PURE__ */ jsx("div", { className: "p-4 pt-4 space-y-4 border-t-0", children }) })
4079
+ ] });
4080
+ };
4081
+ var ColumnLayout = ({
4082
+ columns,
4083
+ label,
4084
+ children
4085
+ }) => {
4086
+ const gridCols = Math.max(1, Math.min(columns, 12));
4087
+ const gridClass = `grid gap-4 w-full`;
4088
+ const style = {
4089
+ gridTemplateColumns: `repeat(${gridCols}, minmax(0, 1fr))`
4090
+ };
4091
+ return /* @__PURE__ */ jsxs("div", { className: "mb-6", children: [
4092
+ label != null && label !== "" && /* @__PURE__ */ jsx("div", { className: "mb-2 text-sm font-medium text-gray-700", children: label }),
4093
+ /* @__PURE__ */ jsx("div", { className: gridClass, style, children })
4094
+ ] });
4095
+ };
4096
+ var DynamicForm = () => {
4097
+ const store = useFormStore();
4098
+ const schema = store.getSchema();
4099
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
4100
+ /* @__PURE__ */ jsx("div", { className: "mb-4", children: /* @__PURE__ */ jsx("h1", { className: "text-2xl font-bold", children: schema.title }) }),
4101
+ schema.layout.map((node) => {
4102
+ if (node.type === "section") {
4103
+ return /* @__PURE__ */ jsx(Section, { title: node.title, children: node.children.map(
4104
+ (child, index) => typeof child === "string" ? /* @__PURE__ */ jsx(FieldRenderer, { fieldId: child }, child) : child.type === "column_layout" ? /* @__PURE__ */ jsx(
4105
+ ColumnLayout,
4106
+ {
4107
+ columns: child.columns,
4108
+ label: child.label,
4109
+ children: child.children.map((fieldId) => /* @__PURE__ */ jsx(FieldRenderer, { fieldId }, fieldId))
4110
+ },
4111
+ child.id
4112
+ ) : /* @__PURE__ */ jsx(React11__default.Fragment, {}, child.id ?? index)
4113
+ ) }, node.id);
4114
+ }
4115
+ if (node.type === "column_layout") {
4116
+ return /* @__PURE__ */ jsx(
4117
+ ColumnLayout,
4118
+ {
4119
+ columns: node.columns,
4120
+ label: node.label,
4121
+ children: node.children.map((fieldId) => /* @__PURE__ */ jsx(FieldRenderer, { fieldId }, fieldId))
4122
+ },
4123
+ node.id
4124
+ );
4125
+ }
4126
+ return null;
4127
+ })
4128
+ ] });
4129
+ };
4130
+ var SUGGESTION_KEYS = /* @__PURE__ */ new Set(["medications", "investigations", "procedures"]);
4131
+ function shallowEqualKeys(a, b) {
4132
+ const keysA = Object.keys(a);
4133
+ const keysB = Object.keys(b);
4134
+ if (keysA.length !== keysB.length) return false;
4135
+ for (const k of keysA) {
4136
+ if (!keysB.includes(k) || a[k] !== b[k]) return false;
4137
+ }
4138
+ return true;
4139
+ }
4140
+ function normalizeAIMedications(arr) {
4141
+ let parsed = arr;
4142
+ if (typeof arr === "string") {
4143
+ try {
4144
+ parsed = JSON.parse(arr);
4145
+ } catch {
4146
+ return [];
4147
+ }
4148
+ }
4149
+ if (!Array.isArray(parsed)) return [];
4150
+ return parsed.filter((item) => item != null && typeof item === "object" && "id" in item && "brand_name" in item);
4151
+ }
4152
+ function normalizeDifferentialDiagnosis(val) {
4153
+ let parsed = val;
4154
+ if (typeof val === "string") {
4155
+ try {
4156
+ parsed = JSON.parse(val);
4157
+ } catch {
4158
+ return [];
4159
+ }
4160
+ }
4161
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
4162
+ const result = [];
4163
+ for (const [category, group] of Object.entries(parsed)) {
4164
+ if (!group || typeof group !== "object") continue;
4165
+ const conditions = Array.isArray(group.conditions) ? group.conditions : [];
4166
+ for (const cond of conditions) {
4167
+ if (!cond || typeof cond !== "object") continue;
4168
+ const {
4169
+ condition,
4170
+ likelihood,
4171
+ severity,
4172
+ treatability,
4173
+ keyFeatures,
4174
+ nextSteps
4175
+ } = cond;
4176
+ if (!condition || !likelihood || !severity || !treatability) continue;
4177
+ result.push({
4178
+ category,
4179
+ condition,
4180
+ likelihood,
4181
+ severity,
4182
+ treatability,
4183
+ keyFeatures: Array.isArray(keyFeatures) ? keyFeatures : void 0,
4184
+ nextSteps: Array.isArray(nextSteps) ? nextSteps : void 0
4185
+ });
4186
+ }
4187
+ }
4188
+ return result;
4189
+ }
4190
+ if (!Array.isArray(parsed)) return [];
4191
+ return parsed.filter(
4192
+ (item) => item != null && typeof item === "object" && "category" in item && "condition" in item && "likelihood" in item && "severity" in item && "treatability" in item
4193
+ );
4194
+ }
4195
+ var SmartForm = ({
4196
+ aiAnalysisResult
4197
+ }) => {
4198
+ const store = useFormStore();
4199
+ const schema = store.getSchema();
4200
+ const prevAiResultRef = useRef(void 0);
4201
+ const aiSuggestions = useMemo(() => {
4202
+ if (aiAnalysisResult == null) return { medications: [] };
4203
+ const medications = normalizeAIMedications(aiAnalysisResult.medications);
4204
+ return { medications };
4205
+ }, [aiAnalysisResult]);
4206
+ useEffect(() => {
4207
+ if (aiAnalysisResult == null || Object.keys(aiAnalysisResult).length === 0) return;
4208
+ const prev = prevAiResultRef.current;
4209
+ if (prev != null && prev === aiAnalysisResult && shallowEqualKeys(prev, aiAnalysisResult)) return;
4210
+ prevAiResultRef.current = { ...aiAnalysisResult };
4211
+ const DD_KEYS = /* @__PURE__ */ new Set(["differentialDiagnosis", "differentialdiagnosis"]);
4212
+ const toApply = {};
4213
+ for (const [key, val] of Object.entries(aiAnalysisResult)) {
4214
+ if (!SUGGESTION_KEYS.has(key) && !DD_KEYS.has(key)) toApply[key] = val;
4215
+ }
4216
+ const rawDd = aiAnalysisResult.differentialDiagnosis ?? aiAnalysisResult.differentialdiagnosis;
4217
+ if (rawDd != null) {
4218
+ toApply.differentialdiagnosis = normalizeDifferentialDiagnosis(rawDd);
4219
+ }
4220
+ if (Object.keys(toApply).length > 0) store.setValues(toApply, { touch: false });
4221
+ }, [store, aiAnalysisResult]);
4222
+ const fieldIds = [];
4223
+ function collect(child) {
4224
+ if (typeof child === "string") {
4225
+ fieldIds.push(child);
4226
+ } else if (child.type === "column_layout") {
4227
+ child.children.forEach((id) => fieldIds.push(id));
4228
+ }
4229
+ }
4230
+ schema.layout.forEach((node) => {
4231
+ if (node.type === "section") {
4232
+ node.children.forEach(collect);
4233
+ } else if (node.type === "column_layout") {
4234
+ node.children.forEach((id) => fieldIds.push(id));
4235
+ }
4236
+ });
4237
+ return /* @__PURE__ */ jsx(AISuggestionsProvider, { value: aiSuggestions, children: /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-4 gap-2 w-full items-start", children: [
4238
+ /* @__PURE__ */ jsx("div", { className: "col-span-1 flex flex-col gap-2", children: fieldIds.map((fieldId) => {
4239
+ const fieldDef = store.getFieldDef(fieldId);
4240
+ if (!fieldDef) return null;
4241
+ const position = fieldDef.position ?? "center";
4242
+ if (position !== "left") return null;
4243
+ return /* @__PURE__ */ jsx(FieldRenderer, { fieldId }, fieldId);
4244
+ }) }),
4245
+ /* @__PURE__ */ jsx("div", { className: "col-span-2 grid grid-cols-2 gap-x-2 space-y-2", children: fieldIds.map((fieldId) => {
4246
+ const fieldDef = store.getFieldDef(fieldId);
4247
+ if (!fieldDef) return null;
4248
+ const position = fieldDef.position ?? "center";
4249
+ if (position !== "center") return null;
4250
+ const colSpanRaw = fieldDef.colSpan ?? 1;
4251
+ const colSpan = colSpanRaw === 2 ? 2 : 1;
4252
+ return /* @__PURE__ */ jsx("div", { className: colSpan === 2 ? "col-span-2" : "col-span-1", children: /* @__PURE__ */ jsx(FieldRenderer, { fieldId }) }, fieldId);
4253
+ }) }),
4254
+ /* @__PURE__ */ jsx("div", { className: "col-span-1 flex flex-col gap-2", children: fieldIds.map((fieldId) => {
4255
+ const fieldDef = store.getFieldDef(fieldId);
4256
+ if (!fieldDef) return null;
4257
+ const position = fieldDef.position ?? "center";
4258
+ if (position !== "right") return null;
4259
+ return /* @__PURE__ */ jsx(FieldRenderer, { fieldId }, fieldId);
4260
+ }) })
4261
+ ] }) });
2382
4262
  };
2383
4263
  var ReadOnlyText = ({ fieldDef, value }) => {
2384
4264
  if (!fieldDef) return null;
@@ -2906,6 +4786,6 @@ function createUploadHandler(options) {
2906
4786
  };
2907
4787
  }
2908
4788
 
2909
- export { DynamicForm, EMAIL_REGEX, FieldRenderer, FormControls, FormProvider, FormStore, ImageUploadWidget, ReadOnlyForm, ReadOnlyImageUpload, ReadOnlySignature, ReadOnlyTable, SignatureUploadWidget, createUploadHandler, evaluateRules, useField, useForm, useFormStore, validateField, validateForm };
4789
+ export { AddInvestigationField, AddMedicationField, DifferentialDiagnosis, DynamicForm, EMAIL_REGEX, FieldRenderer, FormControls, FormProvider, FormStore, ImageUploadWidget, ReadOnlyForm, ReadOnlyImageUpload, ReadOnlySignature, ReadOnlyTable, SignatureUploadWidget, SmartForm, createUploadHandler, evaluateRules, useField, useFieldHandlers, useForm, useFormStore, validateField, validateForm };
2910
4790
  //# sourceMappingURL=index.mjs.map
2911
4791
  //# sourceMappingURL=index.mjs.map