import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Input } from "../components/ui/input";
import { Button } from "../components/ui/button";
import { Switch } from "../components/ui/switch";
import { CloseButton } from "../components/ui/close-button";
import ItemSearch from "./ui/ItemSearch";
import { ScrollingContentTree } from "./ScrollingContentTree";
import { useEditContext } from "./client/editContext";
import { normalizeUrl } from "./utils/urlUtils";
import DialogButtons from "./ui/DialogButtons";
import { Globe2, Link2, Mail, Phone } from "lucide-react";
import { MultiSwitchButton } from "../components/ui/multi-switch-button";
function normalizeItemId(id) {
    if (!id)
        return undefined;
    return id.toLowerCase().replace(/[{}]/g, "");
}
function getInitialLinkType(link) {
    if (link.type === "internal")
        return "internal";
    if (link.type === "email" || link.url?.startsWith("mailto:"))
        return "email";
    if (link.type === "phone" || link.url?.startsWith("tel:"))
        return "phone";
    return "external";
}
function stripLinkScheme(value, scheme) {
    if (!value)
        return "";
    const prefix = `${scheme}:`;
    return value.startsWith(prefix) ? value.slice(prefix.length) : value;
}
function formatSpecialLinkUrl(type, value) {
    const trimmed = value.trim();
    if (!trimmed)
        return "";
    if (type === "email") {
        return trimmed.startsWith("mailto:") ? trimmed : `mailto:${trimmed}`;
    }
    return trimmed.startsWith("tel:") ? trimmed : `tel:${trimmed}`;
}
export function LinkEditorDialog({ linkValue, onCancel, onOk, showText, position, }) {
    const [url, setUrl] = useState("");
    const [emailAddress, setEmailAddress] = useState("");
    const [phoneNumber, setPhoneNumber] = useState("");
    const [targetWindow, setTargetWindow] = useState();
    const [customTarget, setCustomTarget] = useState();
    const [queryString, setQueryString] = useState();
    const [text, setText] = useState();
    const [title, setTitle] = useState("");
    const [nofollow, setNofollow] = useState(false);
    const [activeLinkType, setActiveLinkType] = useState("internal");
    const [selectedItemId, setSelectedItemId] = useState("");
    const [hoveredItemId, setHoveredItemId] = useState();
    const editContext = useEditContext();
    const workspaceId = editContext?.workspaceId;
    const lastInitKeyRef = useRef(null);
    const popoverRef = useRef(null);
    const initialWorkspaceIdRef = useRef(workspaceId);
    useEffect(() => {
        if (!workspaceId)
            return;
        if (initialWorkspaceIdRef.current === undefined) {
            initialWorkspaceIdRef.current = workspaceId;
            return;
        }
        if (workspaceId !== initialWorkspaceIdRef.current) {
            onCancel();
        }
    }, [workspaceId, onCancel]);
    useEffect(() => {
        const initKey = [
            linkValue.type,
            linkValue.itemId ?? "",
            linkValue.url ?? "",
            linkValue.target ?? "",
            linkValue.queryString ?? "",
            linkValue.text ?? "",
            linkValue.title ?? "",
            linkValue.nofollow ? "nofollow" : "",
            linkValue.originalHref ?? "",
        ].join("|");
        if (lastInitKeyRef.current === initKey)
            return;
        lastInitKeyRef.current = initKey;
        const initialLinkType = getInitialLinkType(linkValue);
        setUrl(linkValue.url ?? "");
        setEmailAddress(stripLinkScheme(linkValue.url, "mailto"));
        setPhoneNumber(stripLinkScheme(linkValue.url, "tel"));
        setTargetWindow(linkValue.target ?? "");
        setCustomTarget(undefined);
        setActiveLinkType(initialLinkType);
        if (linkValue.target &&
            linkValue.target != "_blank" &&
            linkValue.target != "_self") {
            setTargetWindow("custom");
            setCustomTarget(linkValue.target);
        }
        setSelectedItemId(linkValue.itemId ?? "");
        setQueryString(linkValue.queryString);
        setText(linkValue.text);
        setTitle(linkValue.title ?? "");
        setNofollow(!!linkValue.nofollow);
    }, [linkValue]);
    useEffect(() => {
        // Trigger a resize event to recalculate layouts when dialog opens
        window.dispatchEvent(new Event("resize"));
    }, []);
    useEffect(() => {
        const handlePointerDown = (event) => {
            const target = event.target;
            if (target instanceof Node &&
                popoverRef.current &&
                !popoverRef.current.contains(target)) {
                onCancel();
            }
        };
        const handleKeyDown = (event) => {
            if (event.key === "Escape") {
                event.preventDefault();
                onCancel();
            }
        };
        document.addEventListener("pointerdown", handlePointerDown, true);
        document.addEventListener("keydown", handleKeyDown, true);
        return () => {
            document.removeEventListener("pointerdown", handlePointerDown, true);
            document.removeEventListener("keydown", handleKeyDown, true);
        };
    }, [onCancel]);
    function getTargetWindow() {
        if (targetWindow == "custom")
            return customTarget;
        if (targetWindow === "_self")
            return "";
        return targetWindow;
    }
    if (!editContext)
        return null;
    const selectedExpansionId = normalizeItemId(selectedItemId || linkValue.itemId);
    const currentItemExpansionId = normalizeItemId(editContext.currentItemDescriptor?.id);
    const expandedItemId = selectedExpansionId || currentItemExpansionId;
    const linkTypeOptions = [
        { value: "internal", label: "Internal", icon: Link2 },
        { value: "external", label: "External", icon: Globe2 },
        { value: "email", label: "E-Mail", icon: Mail },
        { value: "phone", label: "Phone", icon: Phone },
    ];
    // Tab targets and nofollow only apply to page/url links, not mailto:/tel:.
    const supportsTargetOptions = activeLinkType === "internal" || activeLinkType === "external";
    const showTextExtras = showText && (_jsxs("div", { className: "grid grid-cols-2 gap-2", children: [_jsx(Input, { value: text || "", onChange: (e) => setText(e.target.value), className: "h-9 bg-white text-xs", placeholder: "Link description", "aria-label": "Link description", "data-testid": "link-description" }), _jsx(Input, { value: queryString || "", onChange: (e) => setQueryString(e.target.value), className: "h-9 bg-white text-xs", placeholder: "Query string", "aria-label": "Query string", "data-testid": "link-query-string" })] }));
    const linkOptionsContent = (_jsxs("div", { className: "flex flex-col gap-3", children: [_jsx(Input, { value: title, onChange: (e) => setTitle(e.target.value), className: "h-9 bg-white text-xs", placeholder: "Link title", "aria-label": "Link title", "data-testid": "link-title" }), supportsTargetOptions && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "flex items-center justify-between gap-3", children: [_jsx("span", { className: "text-neutral-grey-100 text-xs font-medium", children: "Open in new Tab" }), _jsx(Switch, { checked: targetWindow === "_blank", onCheckedChange: (checked) => 
                                // Toggling off restores a pre-existing custom frame target
                                // instead of discarding it.
                                setTargetWindow(checked ? "_blank" : customTarget ? "custom" : ""), "aria-label": "Open in new Tab", "data-testid": "link-open-new-tab" })] }), _jsxs("div", { className: "flex items-start justify-between gap-3", children: [_jsxs("div", { className: "flex min-w-0 flex-col", children: [_jsx("span", { className: "text-neutral-grey-100 text-xs font-medium", children: "Make link no follow" }), _jsx("span", { className: "text-neutral-grey-50 text-xs", children: "Searchengines will ignore a nofollow link." })] }), _jsx(Switch, { checked: nofollow, onCheckedChange: setNofollow, "aria-label": "Make link no follow", "data-testid": "link-nofollow", className: "mt-0.5" })] })] }))] }));
    const internalContent = (_jsxs("div", { className: "flex h-full flex-col overflow-hidden", "data-testid": "internal-tab", children: [_jsx("div", { className: "shrink-0 bg-white px-3 pb-2 [&_[data-slot=input]]:h-9 [&_[data-slot=input]]:text-xs", children: _jsx(ItemSearch, { resultClassName: "badge-pad", placeholder: "Find page", itemSelected: (item) => {
                        setSelectedItemId(item.id);
                    }, setHoveredItem: (item) => ((item) => {
                        if (!item)
                            return;
                        setHoveredItemId(item.id);
                    })(item) }) }), _jsx("div", { className: "relative min-h-0 flex-1", children: _jsx("div", { className: "absolute inset-0 overflow-auto px-2 py-1", children: _jsx(ScrollingContentTree, { selectedItemId: hoveredItemId || selectedItemId, expandedItemId: expandedItemId, onSelectionChange: (selection) => {
                            setSelectedItemId(selection[0]?.id || "");
                        } }) }) })] }));
    const renderFieldContent = () => {
        if (activeLinkType === "internal")
            return internalContent;
        const field = activeLinkType === "external"
            ? {
                id: "link-url-external",
                label: "External URL",
                placeholder: "Add url",
                value: url,
                testId: "link-url-external",
                onChange: setUrl,
                onBlur: (value) => setUrl(normalizeUrl(value.trim())),
            }
            : activeLinkType === "email"
                ? {
                    id: "link-url-email",
                    label: "E-Mail address",
                    placeholder: "name@example.com",
                    value: emailAddress,
                    testId: "link-url-email",
                    onChange: setEmailAddress,
                    onBlur: (value) => setEmailAddress(value.trim()),
                }
                : {
                    id: "link-url-phone",
                    label: "Phone number",
                    placeholder: "+1 555 0100",
                    value: phoneNumber,
                    testId: "link-url-phone",
                    onChange: setPhoneNumber,
                    onBlur: (value) => setPhoneNumber(value.trim()),
                };
        return (_jsxs("div", { className: "flex h-full flex-col gap-3 p-3 pt-0", "data-testid": `${activeLinkType}-tab`, children: [_jsx(Input, { id: field.id, value: field.value, onChange: (e) => field.onChange(e.target.value), onBlur: (e) => {
                        field.onBlur(e.target.value);
                    }, className: "h-9 w-full bg-white text-xs", placeholder: field.placeholder, "aria-label": field.label, "data-testid": field.testId }), showTextExtras, linkOptionsContent] }));
    };
    if (typeof document === "undefined") {
        return null;
    }
    const viewportWidth = typeof window === "undefined" ? 1024 : window.innerWidth;
    const viewportHeight = typeof window === "undefined" ? 768 : window.innerHeight;
    const popoverLeft = position
        ? position.x
        : Math.max(16, viewportWidth / 2 - 243);
    const popoverTop = position
        ? position.y
        : Math.max(16, viewportHeight / 2 - 296);
    const content = (_jsx("div", { ref: popoverRef, role: "dialog", "aria-modal": "false", "aria-label": "Link settings", "data-slot": "dialog-content", "data-testid": "dialog-content", className: "border-border-default animate-in fade-in-0 zoom-in-95 fixed z-[1100] flex flex-col overflow-hidden rounded-[12px] border bg-white p-0 shadow-2xl duration-200 ease-out", style: {
            left: popoverLeft,
            top: popoverTop,
            width: "486px",
            maxWidth: "calc(100vw - 32px)",
            height: activeLinkType === "internal" ? "592px" : "auto",
            maxHeight: "calc(100vh - 48px)",
        }, onMouseDown: (event) => event.stopPropagation(), onClick: (event) => event.stopPropagation(), children: _jsxs("div", { "data-testid": "link-editor-dialog", className: "contents", children: [_jsxs("div", { className: "flex h-12 shrink-0 items-center gap-2 px-4 pt-2", children: [_jsx("div", { className: "text-neutral-grey-100 min-w-0 flex-1 text-sm font-medium tracking-normal", children: "Link settings" }), _jsx(CloseButton, { onClick: onCancel, showTooltip: false })] }), _jsxs("div", { className: "flex min-h-0 flex-1 flex-col overflow-hidden", children: [_jsx("div", { className: "bg-white p-3", children: _jsx(MultiSwitchButton, { value: activeLinkType, options: linkTypeOptions.map((option) => ({
                                    ...option,
                                    testId: `link-type-${option.value}`,
                                })), onValueChange: setActiveLinkType, "aria-label": "Link type" }) }), _jsx("div", { className: "min-h-0 flex-1 overflow-hidden", children: renderFieldContent() }), activeLinkType === "internal" && (_jsxs("div", { className: "border-border-default flex shrink-0 flex-col gap-3 border-t p-3", children: [showTextExtras, linkOptionsContent] })), _jsxs(DialogButtons, { buttonSize: "default", hideBorder: activeLinkType !== "internal", className: "shrink-0 bg-white px-4 py-3", children: [_jsx(Button, { variant: "ghost", onClick: onCancel, "data-testid": "dialog-cancel", children: "Cancel" }), _jsx(Button, { onClick: () => {
                                        const resolvedUrl = activeLinkType === "email"
                                            ? formatSpecialLinkUrl("email", emailAddress)
                                            : activeLinkType === "phone"
                                                ? formatSpecialLinkUrl("phone", phoneNumber)
                                                : activeLinkType === "external"
                                                    ? normalizeUrl(url || "")
                                                    : url;
                                        onOk({
                                            url: resolvedUrl,
                                            target: supportsTargetOptions ? getTargetWindow() : "",
                                            customTarget: supportsTargetOptions
                                                ? customTarget
                                                : undefined,
                                            itemId: selectedItemId,
                                            queryString: queryString,
                                            text: text,
                                            title: title.trim() || undefined,
                                            nofollow: supportsTargetOptions && nofollow ? true : undefined,
                                            type: activeLinkType,
                                        });
                                    }, "data-testid": "dialog-ok", className: "min-w-[64px]", children: "Save" })] })] })] }) }));
    return createPortal(content, document.body);
}
//# sourceMappingURL=LinkEditorDialog.js.map