import React, { useRef, useState } from "react";
import { PanResponder, Platform, Pressable, Text as RNText, useWindowDimensions, View, } from "react-native";
import * as DialogPrimitive from "@rn-primitives/dialog";
import { Ionicons } from "@expo/vector-icons";
import { useColorScheme } from "nativewind";
import { cn } from "../utils/cn";
export function Dialog({ visible, onClose, title, children, showCloseButton = true, draggable = false, maxWidth = 400, dismissOnBackdrop = true, }) {
    const { colorScheme } = useColorScheme();
    const isDark = colorScheme === "dark";
    const { width: winW, height: winH } = useWindowDimensions();
    // Drag state
    const [offset, setOffset] = useState({ x: 0, y: 0 });
    const offsetRef = useRef({ x: 0, y: 0 });
    const dragStart = useRef({ x: 0, y: 0 });
    // Reset position when the dialog opens.
    const prevVisible = useRef(visible);
    if (visible && !prevVisible.current) {
        offsetRef.current = { x: 0, y: 0 };
        setOffset({ x: 0, y: 0 });
    }
    prevVisible.current = visible;
    const winWRef = useRef(winW);
    const winHRef = useRef(winH);
    const maxWidthRef = useRef(maxWidth);
    winWRef.current = winW;
    winHRef.current = winH;
    maxWidthRef.current = maxWidth;
    const dialogLayoutRef = useRef({ width: 0, height: 0 });
    // Measured height also lives in state: the centering transform reads it at
    // render time, and a ref alone never re-renders after onLayout — so tall
    // dialogs (e.g. the legal popup) stayed pinned at the fallback height and
    // rendered vertically off-center until a drag forced a re-render.
    const [dialogH, setDialogH] = useState(0);
    const onDialogLayout = React.useCallback((e) => {
        const { width, height } = e.nativeEvent.layout;
        dialogLayoutRef.current = { width, height };
        if (height > 0) {
            setDialogH(height);
        }
    }, []);
    const clampOffset = (raw) => {
        const w = winWRef.current;
        const h = winHRef.current;
        const dw = dialogLayoutRef.current.width || Math.min(maxWidthRef.current, w * 0.9);
        const dh = dialogLayoutRef.current.height || 200;
        const pad = 0.25;
        const maxX = (w - dw * pad) / 2;
        const maxY = (h - dh * pad) / 2;
        return {
            x: Math.max(-maxX, Math.min(maxX, raw.x)),
            y: Math.max(-maxY, Math.min(maxY, raw.y)),
        };
    };
    const activePanResponder = useRef(PanResponder.create({
        onStartShouldSetPanResponder: (evt) => {
            if (Platform.OS === "web") {
                const webEvent = evt.nativeEvent;
                const target = webEvent.target;
                if (target && typeof target.closest === "function") {
                    const interactive = target.closest('input, textarea, select, button, a, label, [role="button"], [role="textbox"], [contenteditable="true"]');
                    if (interactive) {
                        return false;
                    }
                }
            }
            return true;
        },
        onMoveShouldSetPanResponder: (_, gesture) => Math.abs(gesture.dx) > 8 || Math.abs(gesture.dy) > 8,
        onPanResponderGrant: () => {
            dragStart.current = { x: offsetRef.current.x, y: offsetRef.current.y };
        },
        onPanResponderMove: (_, gesture) => {
            const next = {
                x: dragStart.current.x + gesture.dx,
                y: dragStart.current.y + gesture.dy,
            };
            const clamped = clampOffset(next);
            offsetRef.current = clamped;
            setOffset(clamped);
        },
    })).current;
    return (<DialogPrimitive.Root open={visible} onOpenChange={(open) => {
            if (!open) {
                onClose();
            }
        }}>
      <DialogPrimitive.Portal>
        <DialogPrimitive.Overlay className="absolute inset-0 bg-black/50" closeOnPress={dismissOnBackdrop}/>
        <DialogPrimitive.Content onLayout={onDialogLayout} className={cn("absolute self-center rounded-xl p-5", isDark ? "bg-neutral-900" : "bg-white", Platform.OS === "web" && "shadow-lg")} style={{
            width: "90%",
            maxWidth,
            top: "50%",
            left: "50%",
            // Web: center with a CSS percentage translate of the element's
            // OWN size — no height measurement (onLayout doesn't reliably
            // fire for the portaled content, which left tall dialogs like the
            // legal popup pinned to a stale fallback height and off-center).
            // Native: RN has no % translate, so keep the measured math.
            transform: Platform.OS === "web"
                ? `translate(calc(-50% + ${offset.x}px), calc(-50% + ${offset.y}px))`
                : [
                    { translateX: -(Math.min(maxWidth, winW * 0.9) / 2) + offset.x },
                    { translateY: -(dialogH || 100) / 2 + offset.y },
                ],
        }}>
          {/* Radix accessibility: always render a Title. */}
          {title ? null : (<DialogPrimitive.Title className="absolute h-px w-px overflow-hidden" style={{ clip: "rect(0,0,0,0)" }}>
              Dialog
            </DialogPrimitive.Title>)}

          {title || showCloseButton ? (<View className="mb-4 flex-row items-center justify-between" {...(draggable ? activePanResponder.panHandlers : {})} {...(draggable && Platform.OS === "web"
            ? {
                draggable: false,
                onDragStart: (e) => {
                    e.preventDefault?.();
                },
            }
            : {})} style={draggable
                ? {
                    cursor: "grab",
                    userSelect: "none",
                    WebkitUserDrag: "none",
                    userDrag: "none",
                }
                : undefined}>
              {title ? (<DialogPrimitive.Title className="flex-1 text-xl font-bold text-foreground dark:text-white">
                  {title}
                </DialogPrimitive.Title>) : null}
              {showCloseButton ? (<DialogPrimitive.Close asChild>
                  <Pressable onPress={onClose} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }} className="rounded p-2 active:opacity-70">
                    <Ionicons name="close" size={24} color={isDark ? "#999999" : "#666666"}/>
                  </Pressable>
                </DialogPrimitive.Close>) : null}
            </View>) : null}

          {children}
        </DialogPrimitive.Content>
      </DialogPrimitive.Portal>
    </DialogPrimitive.Root>);
}
export function DialogContent({ children, className }) {
    return <View className={cn("py-2", className)}>{children}</View>;
}
export function DialogFooter({ children, className, style }) {
    return (<View className={cn("mt-5 flex-row items-center justify-end gap-3", className)} style={style}>
      {children}
    </View>);
}
export function DialogButton({ onPress, variant = "primary", children, accessibilityLabel, accessibilityRole, }) {
    const { colorScheme } = useColorScheme();
    const isDark = colorScheme === "dark";
    const base = "rounded-lg px-4 py-2.5 active:opacity-70";
    const variantClass = (() => {
        switch (variant) {
            case "primary":
                return isDark ? "bg-white" : "bg-black";
            case "secondary":
                return cn("border", isDark ? "border-neutral-600" : "border-neutral-300");
            case "ghost":
                return "";
            case "destructive":
                return isDark ? "bg-red-900" : "bg-red-500";
        }
    })();
    const textColor = (() => {
        switch (variant) {
            case "primary":
                return isDark ? "#000000" : "#FFFFFF";
            case "secondary":
            case "ghost":
                return isDark ? "#FFFFFF" : "#000000";
            case "destructive":
                return "#FFFFFF";
        }
    })();
    return (<Pressable onPress={onPress} className={cn(base, variantClass)} accessibilityLabel={accessibilityLabel} accessibilityRole={accessibilityRole}>
      <RNText style={{ color: textColor, fontSize: 14, fontWeight: "600", textAlign: "center" }}>
        {children}
      </RNText>
    </Pressable>);
}
export function ConfirmDialog({ visible, title, message, confirmLabel = "Confirm", cancelLabel = "Cancel", destructive = false, hideCancel = false, onConfirm, onCancel, }) {
    return (<Dialog visible={visible} onClose={onCancel} title={title} maxWidth={400}>
      {message ? (<DialogContent>
          <RNText className="text-sm text-foreground dark:text-white">{message}</RNText>
        </DialogContent>) : null}
      <DialogFooter>
        {!hideCancel && (<DialogButton variant="secondary" onPress={onCancel} accessibilityLabel={cancelLabel}>
            {cancelLabel}
          </DialogButton>)}
        <DialogButton variant={destructive ? "destructive" : "primary"} onPress={onConfirm} accessibilityLabel={confirmLabel}>
          {confirmLabel}
        </DialogButton>
      </DialogFooter>
    </Dialog>);
}
//# sourceMappingURL=dialog.jsx.map