import { jsx, jsxs } from "react/jsx-runtime";
import { s as sprintf } from "../../sprintf-DmNrJSYG.js";
import { _ as __ } from "../../default-i18n-CN_q3KUs.js";
import { useMemo, useState } from "react";
import { ButtonGroup, Button } from "../button/button.js";
import { icons } from "../../icons/icons.js";
import { SolidColorPicker } from "./solid-color-picker.js";
import { Slider } from "../slider/slider.js";
import { NumberPicker } from "../number-picker/number-picker.js";
import { $ as $251c695a52d94a8d$export$cae13e90592f246a } from "../../ColorSwatch-xVS3rMYS.js";
import { Menu, MenuItem } from "../menu/menu.js";
import { MatrixAlign } from "../matrix-align/matrix-align.js";
import { Spacer } from "../spacer/spacer.js";
import { Toggle } from "../toggle/toggle.js";
import { OptionSelect } from "../option-select/option-select.js";
import { DraggableList } from "../draggable-list/draggable-list.js";
import { DraggableListItem } from "../draggable-list/draggable-list-item.js";
import { TriggeredPopover } from "../popover/popover.js";
import { c as clsx } from "../../lite-DVmmD_-j.js";
function c(e, o = ",") {
  let t = [], n = 0, i = 0;
  o = new RegExp(o);
  for (let r = 0; r < e.length; r++) e[r] === "(" ? i++ : e[r] === ")" && i--, i === 0 && o.test(e[r]) && (t.push(e.slice(n, r).trim()), n = r + 1);
  return t.push(e.slice(n).trim()), t;
}
function g(e) {
  let o = [];
  for (let t = 0, n = e.length; t < n; ) {
    let [i, r] = c(e[t], /\s+/);
    m(e[t + 1]) ? (o.push({ color: i, offset: l(r), hint: l(e[t + 1]) }), t += 2) : (o.push({ color: i, offset: l(r) }), t++);
  }
  return o;
}
var u = /^(-?\d+\.?\d*)(%|vw|vh|px|em|rem|deg|rad|grad|turn|ch|vmin|vmax)?$/;
function m(e) {
  return u.test(e);
}
function l(e) {
  if (!e) return;
  let [, o, t] = e.trim().match(u) || [];
  return { value: o, unit: t ?? "px" };
}
function P(e) {
  if (!/^(repeating-)?linear-gradient/.test(e)) throw new SyntaxError(`could not find syntax for this item: ${e}`);
  let [, o, t] = e.match(/(repeating-)?linear-gradient\((.+)\)/), n = { orientation: { type: "directional", value: "bottom" }, repeating: !!o, stops: [] }, i = c(t), r = x(i[0]);
  return r && (n.orientation = r, i.shift()), { ...n, stops: g(i) };
}
function x(e) {
  return e.startsWith("to ") ? { type: "directional", value: e.replace("to ", "") } : ["turn", "deg", "grad", "rad"].some((o) => e.endsWith(o)) ? { type: "angular", value: l(e) } : null;
}
var v = /* @__PURE__ */ new Set(["closest-corner", "closest-side", "farthest-corner", "farthest-side"]), w = /* @__PURE__ */ new Set(["center", "left", "top", "right", "bottom"]);
function d(e) {
  return v.has(e);
}
function h(e) {
  return w.has(e);
}
function R(e) {
  let o = Array(2).fill("");
  for (let t = 0; t < 2; t++) e[t] ? o[t] = e[t] : o[t] = "center";
  return o;
}
function K(e) {
  if (!/(repeating-)?radial-gradient/.test(e)) throw new SyntaxError(`could not find syntax for this item: ${e}`);
  let [, o, t] = e.match(/(repeating-)?radial-gradient\((.+)\)/), n = { shape: "ellipse", repeating: !!o, size: [{ type: "keyword", value: "farthest-corner" }], position: { x: { type: "keyword", value: "center" }, y: { type: "keyword", value: "center" } }, stops: [] }, i = c(t);
  if (S(i[0])) return { ...n, stops: g(i) };
  let r = i[0].split("at").map((f) => f.trim()), p = ((r[0] || "").match(/(circle|ellipse)/) || [])[1], a = (r[0] || "").match(/(-?\d+\.?\d*(vw|vh|px|em|rem|%|rad|grad|turn|deg)?|closest-corner|closest-side|farthest-corner|farthest-side)/g) || [], s = R((r[1] || "").split(" "));
  return p ? n.shape = p : a.length === 1 && !d(a[0]) ? n.shape = "circle" : n.shape = "ellipse", a.length === 0 && a.push("farthest-corner"), n.size = a.map((f) => d(f) ? { type: "keyword", value: f } : { type: "length", value: l(f) }), n.position.x = h(s[0]) ? { type: "keyword", value: s[0] } : { type: "length", value: l(s[0]) }, n.position.y = h(s[1]) ? { type: "keyword", value: s[1] } : { type: "length", value: l(s[1]) }, (p || a.length > 0 || r[1]) && i.shift(), { ...n, stops: g(i) };
}
function S(e) {
  return /(circle|ellipse|at)/.test(e) ? false : /^(rgba?|hwb|hsla?|lab|lch|oklab|color|#|[a-zA-Z]+)/.test(e);
}
var C = /* @__PURE__ */ new Set(["from", "in", "at"]);
function j(e) {
  if (!/(repeating-)?conic-gradient/.test(e)) throw new SyntaxError(`could not find syntax for this item: ${e}`);
  let [, o, t] = e.match(/(repeating-)?conic-gradient\((.+)\)/), n = { angle: "0deg", repeating: !!o, position: "center", stops: [] }, i = c(t).map((s) => s.trim()), r = c(i[0], /\s+/), p = "", a = 0;
  for (let s = 0, f = r.length; s < f; s++) C.has(r[s]) && (s > 0 && Object.assign(n, y(p, r, a, s)), p = r[s], a = s + 1);
  return p && (Object.assign(n, y(p, r, a, r.length)), i.shift()), { ...n, stops: g(i) };
}
function y(e, o, t, n) {
  switch (e) {
    case "from":
      return { angle: o.slice(t, n).join(" ") };
    case "at":
      return { position: o.slice(t, n).join(" ") };
    case "in": {
      let [i, ...r] = o.slice(t, n);
      return { color: { space: i, method: r.length > 0 ? r.join(" ") : void 0 } };
    }
  }
}
const getGradientResult = (input, type) => {
  if (!input || !type) {
    return "";
  }
  if (typeof input === "string" || !input?.stops) {
    return "";
  }
  let output = "";
  const { repeating } = input;
  if (repeating) {
    output += "repeating-";
  }
  output += `${type}-gradient(`;
  if (type === "linear") {
    const { orientation } = input;
    if (orientation?.type === "angular") {
      output += `${orientation.value.value}${orientation.value.unit}, `;
    } else if (orientation?.type === "directional") {
      output += `to ${orientation.value}, `;
    }
  }
  if (type === "radial") {
    const { shape, position } = input;
    output += `${shape ?? "circle"} at ${position?.x?.value ?? "center"} ${position?.y?.value ?? "center"}, `;
  }
  if (type === "conic") {
    const { angle, position } = input;
    output += `from ${angle ?? "0deg"} at ${position ?? "center"}, `;
  }
  output += input.stops.map((stop) => {
    return `${stop.color} ${stop.offset?.value ?? ""}${stop.offset?.unit ?? ""}`.trim();
  }).join(", ");
  output += ")";
  return output;
};
const gradientTypes = [
  {
    label: __("Linear"),
    value: "linear",
    icon: /* @__PURE__ */ jsx("div", { className: "es:transparent es:size-4 es:rounded-full es:bg-linear-to-br es:from-current" })
  },
  {
    label: __("Radial"),
    value: "radial",
    icon: /* @__PURE__ */ jsx("div", { className: "es:transparent es:size-4 es:rounded-full es:bg-radial es:from-current/75 es:to-current/10" })
  },
  {
    label: __("Conic"),
    value: "conic",
    icon: /* @__PURE__ */ jsx("div", { className: "es:transparent es:size-4 es:rounded-full es:bg-conic es:from-current" })
  }
];
const linearDirections = [
  {
    label: __("Right"),
    value: "right",
    iconClass: "es:bg-linear-to-r",
    valueDegrees: 90
  },
  {
    label: __("Left"),
    value: "left",
    iconClass: "es:bg-linear-to-l",
    valueDegrees: 180
  },
  {
    label: __("Top"),
    value: "top",
    iconClass: "es:bg-linear-to-t",
    valueDegrees: 270
  },
  {
    label: __("Bottom"),
    value: "bottom",
    iconClass: "es:bg-linear-to-b",
    valueDegrees: 90
  },
  {
    label: __("Top-right"),
    value: "top right",
    iconClass: "es:bg-linear-to-tr",
    valueDegrees: 45
  },
  {
    label: __("Top-left"),
    value: "top left",
    iconClass: "es:bg-linear-to-tl",
    valueDegrees: 315
  },
  {
    label: __("Bottom-right"),
    value: "bottom right",
    iconClass: "es:bg-linear-to-br",
    valueDegrees: 135
  },
  {
    label: __("Bottom-left"),
    value: "bottom left",
    iconClass: "es:bg-linear-to-bl",
    valueDegrees: 225
  }
];
/**
 * A simple gradient editor.
 * Allows editing linear, radial, and conic gradients.
 *
 * @component
 * @param {Object} props - Component props.
 * @param {string} props.value - The gradient definition.
 * @param {Function} props.onChange - Function to run when the gradient changes.
 * @param {boolean} [props.hidden] - If `true`, the component is not rendered.
 *
 * @returns {JSX.Element} The GradientEditor component.
 *
 * @example
 * <GradientEditor
 * 	value='linear-gradient(90deg, #000000 0%, #ffffff 100%)'
 * 	onChange={setGradient}
 * />
 *
 * @preserve
 */
const GradientEditor = (props) => {
  const { value, onChange, hidden } = props;
  const gradientData = useMemo(() => {
    if (value?.startsWith("radial-gradient") || value?.startsWith("repeating-radial-gradient")) {
      return K(value ?? "");
    }
    if (value?.startsWith("conic-gradient") || value?.startsWith("repeating-conic-gradient")) {
      return j(value ?? "");
    }
    return P(value ?? "");
  }, [value]);
  const gradientType = useMemo(() => {
    if (typeof value === "string" && value?.startsWith("radial-gradient") || value?.startsWith("repeating-radial-gradient")) {
      return "radial";
    }
    if (typeof value === "string" && value?.startsWith("conic-gradient") || value?.startsWith("repeating-conic-gradient")) {
      return "conic";
    }
    return "linear";
  }, [value]);
  const setGradientData = (data) => {
    onChange(getGradientResult(data, gradientType));
  };
  const outputGradient = useMemo(() => getGradientResult(gradientData, gradientType), [gradientData, gradientType]);
  const [squarePreview, setSquarePreview] = useState(false);
  if (hidden) {
    return null;
  }
  return /* @__PURE__ */ jsxs("div", { className: "es:w-full es:space-y-2.5", children: [
    /* @__PURE__ */ jsx(
      "button",
      {
        className: clsx(
          "es:shadow-sm, es:mx-auto es:block es:h-40 es:cursor-pointer es:rounded-lg es:border es:border-secondary-300 es:transition-[width]",
          squarePreview ? "es:w-40" : "es:w-full"
        ),
        style: { backgroundImage: outputGradient },
        onClick: () => setSquarePreview((prev) => !prev),
        "aria-label": __("Toggle preview size", "eightshift-ui-components")
      }
    ),
    /* @__PURE__ */ jsx(
      OptionSelect,
      {
        "aria-label": __("Gradient type", "eightshift-ui-components"),
        value: gradientType,
        onChange: (value2) => onChange(getGradientResult({ stops: gradientData.stops }, value2)),
        options: gradientTypes,
        wrapperProps: { className: "es:mx-auto es:w-fit" },
        type: "toggleButtons"
      }
    ),
    gradientType === "linear" && /* @__PURE__ */ jsxs("div", { className: "es:flex es:items-center es:gap-1", children: [
      /* @__PURE__ */ jsx(
        NumberPicker,
        {
          inline: true,
          icon: icons.angle,
          label: __("Angle", "eightshift-ui-components"),
          min: 0,
          max: 360,
          step: 1,
          value: gradientData?.orientation?.type === "angular" ? gradientData?.orientation?.value?.value : null,
          onChange: (angle) => {
            setGradientData({
              ...gradientData,
              orientation: { type: "angular", value: { value: angle, unit: "deg" } }
            });
          },
          suffix: "°",
          size: "small",
          className: "es:grow",
          placeholder: linearDirections.find(({ value: value2 }) => value2 === gradientData?.orientation?.value)?.valueDegrees ?? ""
        }
      ),
      /* @__PURE__ */ jsx(
        Menu,
        {
          triggerIcon: icons.sliders,
          triggerProps: {
            tooltip: __("Presets", "eightshift-ui-components")
          },
          keepOpen: true,
          children: linearDirections.map(({ label, value: value2, iconClass }) => {
            return /* @__PURE__ */ jsx(
              MenuItem,
              {
                icon: /* @__PURE__ */ jsx("div", { className: clsx("es:size-5 es:rounded-sm es:from-secondary-700 es:to-secondary-200", iconClass) }),
                onClick: () => {
                  setGradientData({
                    ...gradientData,
                    orientation: { type: "directional", value: value2 }
                  });
                },
                children: label
              },
              value2
            );
          })
        }
      )
    ] }),
    gradientType === "radial" && /* @__PURE__ */ jsxs("div", { className: "es:space-y-2", children: [
      /* @__PURE__ */ jsx(
        OptionSelect,
        {
          label: __("Shape", "eightshift-ui-components"),
          icon: icons.genericShapesAlt,
          inline: true,
          options: [
            { label: __("Circle", "eightshift-ui-components"), value: "circle" },
            { label: __("Ellipse", "eightshift-ui-components"), value: "ellipse" }
          ],
          value: gradientData.shape,
          onChange: (value2) => {
            setGradientData({
              ...gradientData,
              shape: value2
            });
          }
        }
      ),
      /* @__PURE__ */ jsx(
        MatrixAlign,
        {
          icon: icons.centerPoint,
          label: __("Center point", "eightshift-ui-components"),
          value: `${gradientData?.position?.y?.value ?? "center"} ${gradientData?.position?.x?.value ?? "center"}`,
          onChange: (position) => {
            const [x2, y2] = position.split(" ");
            setGradientData({
              ...gradientData,
              position: {
                x: { type: "keyword", value: x2 },
                y: { type: "keyword", value: y2 }
              }
            });
          }
        }
      )
    ] }),
    gradientType === "conic" && /* @__PURE__ */ jsxs("div", { className: "es:space-y-2", children: [
      /* @__PURE__ */ jsx(
        NumberPicker,
        {
          inline: true,
          icon: icons.angle,
          label: __("Angle", "eightshift-ui-components"),
          min: 0,
          max: 360,
          step: 1,
          value: parseInt(gradientData?.angle.replace("deg", "")),
          onChange: (value2) => {
            setGradientData({
              ...gradientData,
              angle: `${value2}deg`
            });
          },
          size: "small",
          suffix: "°",
          className: "es:grow"
        }
      ),
      /* @__PURE__ */ jsx(
        MatrixAlign,
        {
          icon: icons.centerPoint,
          label: __("Center point", "eightshift-ui-components"),
          value: `${gradientData?.position?.y?.value ?? "center"} ${gradientData?.position?.x?.value ?? "center"}`,
          onChange: (value2) => {
            setGradientData({
              ...gradientData,
              position: value2
            });
          }
        }
      )
    ] }),
    /* @__PURE__ */ jsx(
      Toggle,
      {
        checked: gradientData.repeating,
        onChange: (value2) => {
          setGradientData({
            ...gradientData,
            repeating: value2
          });
        },
        label: __("Repeating", "eightshift-ui-components"),
        icon: icons.gradientRepeat
      }
    ),
    /* @__PURE__ */ jsx(Spacer, { border: true }),
    /* @__PURE__ */ jsx(
      DraggableList,
      {
        items: gradientData?.stops,
        onChange: (items) => {
          setGradientData({
            ...gradientData,
            stops: items.map(({ color }, i) => ({
              ...gradientData.stops[i] ?? {},
              color
            }))
          });
        },
        icon: icons.gradientStop,
        label: __("Gradient stops", "eightshift-ui-components"),
        actions: /* @__PURE__ */ jsx(
          Button,
          {
            icon: icons.add,
            size: "small",
            onPress: () => {
              setGradientData({
                ...gradientData,
                stops: [...gradientData.stops, { color: "#000000FF" }]
              });
            },
            "aria-label": __("Add stop", "eightshift-ui-components")
          }
        ),
        children: (item) => {
          const { color, updateData, itemIndex } = item;
          return /* @__PURE__ */ jsx(
            DraggableListItem,
            {
              label: sprintf(__("Stop %s", "eightshift-ui-components"), itemIndex + 1),
              subtitle: color,
              icon: /* @__PURE__ */ jsx(
                $251c695a52d94a8d$export$cae13e90592f246a,
                {
                  className: "es:size-5 es:rounded-full es:border es:border-white es:ring-1 es:ring-black",
                  color
                }
              ),
              textValue: sprintf(__("Stop %s", "eightshift-ui-components"), itemIndex + 1),
              children: /* @__PURE__ */ jsxs(ButtonGroup, { children: [
                /* @__PURE__ */ jsx(
                  TriggeredPopover,
                  {
                    triggerButtonIcon: icons.color,
                    triggerButtonProps: { size: "small" },
                    children: /* @__PURE__ */ jsx(
                      SolidColorPicker,
                      {
                        value: color,
                        onChange: (color2) => {
                          updateData({ color: color2 });
                        },
                        allowTransparency: true,
                        outputFormat: "rgba"
                      }
                    )
                  }
                ),
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    onPress: () => {
                      setGradientData({
                        ...gradientData,
                        stops: gradientData.stops.filter((_, i) => i !== itemIndex)
                      });
                    },
                    icon: icons.trash,
                    size: "small",
                    "aria-label": __("Delete stop", "eightshift-ui-components"),
                    disabled: gradientData.stops.length <= 2
                  }
                )
              ] })
            }
          );
        }
      },
      gradientData?.stops?.length
    ),
    /* @__PURE__ */ jsx(
      Slider,
      {
        "aria-label": __("Stop positions", "eightshift-ui-components"),
        min: 0,
        max: 100,
        step: 1,
        value: gradientData?.stops?.map(({ offset }, i) => {
          if (!offset) {
            return i * 100 / (gradientData.stops.length - 1);
          }
          return parseInt(offset?.value);
        }),
        onChange: (value2) => {
          setGradientData({
            ...gradientData,
            stops: gradientData.stops.map((stop, i) => {
              return {
                ...stop,
                offset: { value: value2[i], unit: "%" }
              };
            })
          });
        },
        thumbContent: (index) => /* @__PURE__ */ jsx("div", { className: "es:pointer-events-none es:absolute es:inset-0 es:flex es:size-3 es:items-center es:justify-center es:text-center es:text-xs es:font-semibold es:text-white", children: index + 1 }),
        trackStyle: {
          backgroundImage: getGradientResult({ orientation: { type: "directional", value: "right" }, stops: gradientData.stops }, "linear"),
          height: "1.125rem",
          borderRadius: "0.5rem"
        },
        noActiveHighlight: true
      }
    )
  ] });
};
export {
  GradientEditor
};
