import { j as jsxRuntimeExports } from "../../../../../../../_virtual/jsx-runtime.js";
import { useState, useRef } from "react";
import "../../../../../../../node_modules/.pnpm/@formkit_auto-animate@0.8.2/node_modules/@formkit/auto-animate/index.js";
import "../../../../../../../node_modules/.pnpm/react-hot-toast@2.5.2_react-dom@19.1.1_react@19.1.1__react@19.1.1/node_modules/react-hot-toast/dist/index.js";
import { TbSlash } from "../../../../../../../node_modules/.pnpm/react-icons@5.5.0_react@19.1.1/node_modules/react-icons/tb/index.js";
import { useDebounceCallback } from "../../../../../../../node_modules/.pnpm/usehooks-ts@3.1.1_react@19.1.1/node_modules/usehooks-ts/dist/index.js";
import { FieldTitle } from "../field-factory.js";
import { tx as D } from "../../../../../../style-system/dist/twind.js";
import { usePageQueries, useSitemap, usePagePathParams, useDraftHelpers } from "../../../../../../../use-page-data.js";
import { useDynamicTextEditor } from "../../../hooks/use-editable-text.js";
import { TextArea as r } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/text-area.js";
import { Root as p, Item as l } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/segmented-control.js";
import { Root as C, Trigger as u$1, Content as g, Group as y, Item as v } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/select.js";
import { Root as u, Slot as c } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/text-field.js";
const StringField = (props) => {
  const { currentValue, onChange, title, description, placeholder, schema, brickId, noDynamic } = props;
  const pageQueries = usePageQueries();
  const onChangeDebounced = useDebounceCallback(onChange, 300);
  const DynamicTextEditor = useDynamicTextEditor(props);
  if (pageQueries.length && !noDynamic && !schema["ui:no-dynamic"]) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "field field-string basis-full flex flex-col gap-1 max-w-full", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(FieldTitle, { title, description }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "field field-string flex items-start gap-1.5", children: DynamicTextEditor })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "field field-string basis-full", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(FieldTitle, { title, description }),
    schema["ui:multiline"] ? /* @__PURE__ */ jsxRuntimeExports.jsx(
      r,
      {
        defaultValue: currentValue,
        onChange: (e) => onChangeDebounced(e.target.value),
        className: D("!mt-1.5 scrollbar-thin p-1", schema["ui:textarea-class"] ?? "min-h-24"),
        placeholder,
        size: schema["ui:textarea-font-size"] ?? "2",
        spellCheck: !!schema["ui:spellcheck"]
      }
    ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
      u,
      {
        defaultValue: currentValue,
        onChange: (e) => onChangeDebounced(e.target.value),
        className: "!mt-1",
        size: "2",
        placeholder,
        spellCheck: !!schema["ui:spellcheck"]
      }
    )
  ] });
};
const PathField = (props) => {
  const { currentValue, onChange, title, description, placeholder } = props;
  const onChangeDebounced = useDebounceCallback(onChange, 300);
  const path = (currentValue || "").toString().replace(/^\//, "");
  const params = usePagePathParams();
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "field field-path basis-full", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(FieldTitle, { withIcon: true, title, description }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      u,
      {
        defaultValue: path,
        onChange: (e) => onChangeDebounced(e.target.value),
        className: "!mt-1",
        placeholder,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(c, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(TbSlash, { className: "bg-transparent h-5 w-5 rounded-md stroke-1 !-ml-1 !-mr-2 -rotate-[20deg]" }) })
      }
    ),
    params.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-1.5 text-xs text-gray-500", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
        "You'll be able to use the variable",
        params.length > 1 ? "s" : "",
        " "
      ] }),
      " ",
      params.map((param, index) => /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "font-medium", children: [
        param,
        index === params.length - 2 ? " and " : index < params.length - 1 ? ", " : "",
        " "
      ] }, param)),
      "in queries."
    ] })
  ] });
};
const UrlOrPageIdField = (props) => {
  const { currentValue, onChange, title, description, placeholder, schema, brickId } = props;
  const sitemap = useSitemap();
  const [type, setType] = useState(
    currentValue?.startsWith("http") || sitemap.length === 1 ? "url" : "pageId"
  );
  const pageQueries = usePageQueries();
  const externalLabel = pageQueries.length ? "External / Dynamic" : "External link";
  const DynamicTextEditor = useDynamicTextEditor(props);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 max-w-full", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between flex-1 gap-1", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(FieldTitle, { title, description }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        p,
        {
          onValueChange: (value) => {
            setType(value);
            onChange(null);
          },
          defaultValue: type,
          size: "1",
          className: "mt-0.5",
          radius: "medium",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(l, { value: "url", className: "[&_.rt-SegmentedControlItemLabel]:!px-2.5", children: externalLabel }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(l, { value: "pageId", className: "[&_.rt-SegmentedControlItemLabel]:!px-0", children: "Internal" })
          ]
        }
      )
    ] }),
    type === "url" ? pageQueries.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "field field-string basis-full flex items-start gap-1.5 mt-2", children: DynamicTextEditor }) : /* @__PURE__ */ jsxRuntimeExports.jsx(
      u,
      {
        defaultValue: currentValue?.startsWith("http") ? currentValue : "",
        onChange: (e) => onChange(e.target.value),
        className: "!mt-2 max-w-full",
        placeholder: "https://example.com",
        spellCheck: !!schema["ui:spellcheck"]
      }
    ) : /* @__PURE__ */ jsxRuntimeExports.jsxs(
      C,
      {
        defaultValue: currentValue ?? void 0,
        size: "2",
        onValueChange: (value) => onChange(value),
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            u$1,
            {
              radius: "large",
              variant: "surface",
              className: "!mt-2 !w-full !flex-1 !max-w-full truncate",
              placeholder: "Select a page"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(g, { position: "popper", children: /* @__PURE__ */ jsxRuntimeExports.jsx(y, { children: Object.entries(sitemap).map(([, page]) => /* @__PURE__ */ jsxRuntimeExports.jsx(v, { value: page.label, children: page.label }, page.id)) }) })
        ]
      }
    )
  ] });
};
const GeoAddressField = (props) => {
  const { currentValue, onChange, title, description, placeholder, formData, brickId } = props;
  const { updateBrickProps } = useDraftHelpers();
  const [searchResults, setSearchResults] = useState([]);
  const abortControllerRef = useRef(null);
  const handleAddressChange = (event) => {
    const value = event.target.value;
    const matchedResult = searchResults.find((result) => result.label === value);
    if (matchedResult) {
      console.log("Matched result:", matchedResult);
      onChange(matchedResult.label);
      console.log("address changed for brick %s", brickId);
      if (brickId) {
        updateBrickProps(brickId, {
          address: matchedResult.label,
          lat: matchedResult.lat,
          lng: matchedResult.lng,
          tooltip: ""
        });
      }
      const customEvent = new CustomEvent("geoAddressSelected", {
        detail: {
          address: matchedResult.label,
          placeId: matchedResult.placeId,
          lat: matchedResult.lat,
          lng: matchedResult.lng
        }
      });
      window.dispatchEvent(customEvent);
      setSearchResults([]);
      return;
    }
    console.log("No match found for %s, continuing search...", value);
    onAddressChangeDebounced(event);
  };
  const onAddressChangeDebounced = useDebounceCallback((event) => {
    const query = event.target.value.trim();
    if (!query) {
      setSearchResults([]);
      return;
    }
    if (abortControllerRef.current) {
      abortControllerRef.current.abort("New search initiated");
    }
    const newAbortController = new AbortController();
    abortControllerRef.current = newAbortController;
    searchGeolocation(event.target.value, abortControllerRef.current.signal).then((results) => {
      setSearchResults(results);
    }).catch((error) => {
      console.error("Error fetching geolocation data:", error);
      setSearchResults([]);
    });
  }, 300);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "field field-address basis-full", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(FieldTitle, { title, description }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("datalist", { id: "search-results", children: searchResults.map((result) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: result.label }, result.placeId)) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      u,
      {
        defaultValue: currentValue,
        onChange: handleAddressChange,
        className: "!mt-1",
        placeholder,
        list: "search-results"
      }
    )
  ] });
};
function searchGeolocation(query, abortSignal = null) {
  const url = `https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(query)}&format=jsonv2&layer=address&limit=8`;
  return fetch(url, {
    signal: abortSignal
  }).then((response) => {
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
    return response.json();
  }).then((data) => {
    return data.map((item) => ({
      label: item.display_name,
      placeId: item.place_id,
      lat: item.lat,
      lng: item.lon
    }));
  });
}
export {
  GeoAddressField,
  PathField,
  StringField,
  UrlOrPageIdField
};
//# sourceMappingURL=string.js.map
