import { Box, Button, Divider, Dropdown, IconButton, Text } from "@wix/design-system";
import { Add, Replace } from "@wix/wix-ui-icons-common";
import React, { useContext, useEffect, useState } from "react";
import { RicosContext } from "./../../../../../ricos-context/index.js";
import { ColorStops } from "./color-stops.js";
import { MAX_GRADIENT_STOPS } from "./consts.js";
import { CustomGradients } from "./custom-gradients.js";
import {
  areGradientsEqual,
  findLargestGapMidpoint,
  roundPosition
} from "./gradient-picker-utils.js";
import { GradientPreview } from "./gradient-preview.js";
import { GradientStopEditor } from "./gradient-stop-editor.js";
const getGradientAngle = (gradient) => gradient.type === "LINEAR" ? gradient.angle ?? 90 : void 0;
const getGradientCenter = (gradient) => gradient.type === "RADIAL" ? { x: gradient.centerX ?? 50, y: gradient.centerY ?? 50 } : void 0;
const getGradientValueForType = ({
  currentGradient,
  nextType,
  lastAngle,
  lastCenter
}) => nextType === "LINEAR" ? {
  type: "LINEAR",
  stops: currentGradient.stops,
  angle: lastAngle ?? 90
} : {
  type: "RADIAL",
  stops: currentGradient.stops,
  centerX: lastCenter?.x ?? 50,
  centerY: lastCenter?.y ?? 50
};
const GradientPicker = ({
  value,
  onChange,
  customGradients = [],
  onGradientAdded,
  onGradientDeleted,
  onColorPickerOpen
}) => {
  const { t } = useContext(RicosContext);
  const [containerElement, setContainerElement] = useState(null);
  const [lastAngle, setLastAngle] = useState(() => getGradientAngle(value));
  const [lastCenter, setLastCenter] = useState(
    () => getGradientCenter(value)
  );
  useEffect(() => {
    if (value.type === "LINEAR") {
      setLastAngle(getGradientAngle(value));
    } else {
      setLastCenter(getGradientCenter(value));
    }
  }, [value]);
  const handlePreviewChange = (newValue) => {
    onChange(newValue);
    if (newValue.type === "LINEAR") {
      setLastAngle(newValue.angle);
    } else {
      setLastCenter({ x: newValue.centerX ?? 50, y: newValue.centerY ?? 50 });
    }
  };
  const handleTypeChange = (option) => {
    if (option.id === value.type) {
      return;
    }
    onChange(
      getGradientValueForType({
        currentGradient: value,
        nextType: option.id,
        lastAngle,
        lastCenter
      })
    );
  };
  const handleAddGradient = () => {
    if (onGradientAdded) {
      const gradientExists = customGradients.some((gradient) => areGradientsEqual(gradient, value));
      if (!gradientExists) {
        onGradientAdded(value);
      }
    }
  };
  const hasCustomGradients = customGradients.length > 0;
  const canAddStop = (value.stops?.length ?? 0) < MAX_GRADIENT_STOPS;
  return /* @__PURE__ */ React.createElement(Box, { direction: "vertical", width: "100%", ref: setContainerElement }, /* @__PURE__ */ React.createElement(GradientPreview, { value, onChange: handlePreviewChange }), /* @__PURE__ */ React.createElement(Box, { direction: "vertical", gap: "SP3", padding: "SP3" }, /* @__PURE__ */ React.createElement(Box, { align: "space-between" }, /* @__PURE__ */ React.createElement(Box, { width: "50%" }, /* @__PURE__ */ React.createElement(
    Dropdown,
    {
      ariaLabel: t("GradientPicker_Type_Label"),
      size: "small",
      selectedId: value.type,
      options: [
        {
          id: "LINEAR",
          value: t("GradientPicker_Type_Linear")
        },
        {
          id: "RADIAL",
          value: t("GradientPicker_Type_Radial")
        }
      ],
      onSelect: handleTypeChange,
      popoverProps: { placement: "bottom-start" }
    }
  )), /* @__PURE__ */ React.createElement(
    IconButton,
    {
      ariaLabel: t("GradientPicker_Flip_Tooltip"),
      priority: "secondary",
      size: "small",
      onClick: () => {
        onChange({
          ...value,
          stops: value.stops?.slice().reverse().map((stop) => ({
            ...stop,
            position: roundPosition(1 - (stop.position ?? 0))
          }))
        });
      }
    },
    /* @__PURE__ */ React.createElement(Replace, null)
  )), /* @__PURE__ */ React.createElement(
    ColorStops,
    {
      value,
      onChange,
      onStopClick: (index) => {
        const stop = value.stops?.[index];
        if (stop) {
          onColorPickerOpen?.({
            originalIndex: index,
            stop,
            referenceElement: containerElement
          });
        }
      },
      canAddStop
    }
  ), /* @__PURE__ */ React.createElement(Box, { align: "space-between", verticalAlign: "middle" }, /* @__PURE__ */ React.createElement(Text, { size: "small", weight: "bold" }, t("GradientPicker_ColorStops_Title")), /* @__PURE__ */ React.createElement(
    IconButton,
    {
      ariaLabel: t("GradientPicker_AddStop_Tooltip"),
      priority: "secondary",
      size: "small",
      disabled: !canAddStop,
      onClick: () => {
        if (!canAddStop) {
          return;
        }
        const stops = value.stops ?? [];
        const newPosition = findLargestGapMidpoint(stops);
        const sorted = [...stops].sort((a, b) => (a.position ?? 0) - (b.position ?? 0));
        const after = sorted.find((s) => (s.position ?? 0) >= newPosition);
        const newColor = after?.color ?? sorted[sorted.length - 1]?.color;
        onChange({
          ...value,
          stops: [...stops, { color: newColor, position: newPosition }]
        });
      }
    },
    /* @__PURE__ */ React.createElement(Add, null)
  )), /* @__PURE__ */ React.createElement(Box, { direction: "vertical", gap: "SP3" }, value.stops?.map((stop, index) => ({ ...stop, originalIndex: index })).sort((a, b) => (a.position ?? 0) - (b.position ?? 0)).map((stop) => /* @__PURE__ */ React.createElement(
    GradientStopEditor,
    {
      key: stop.originalIndex,
      value,
      stop,
      onChange,
      originalIndex: stop.originalIndex,
      onColorPickerOpen
    }
  ))), onGradientAdded && /* @__PURE__ */ React.createElement(Button, { size: "small", fullWidth: true, priority: "secondary", onClick: handleAddGradient }, t("GradientPicker_SaveGradient_Button"))), hasCustomGradients && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement(Box, { direction: "vertical", padding: "SP3", gap: "SP3" }, /* @__PURE__ */ React.createElement(Text, { size: "small", weight: "bold" }, t("GradientPicker_SavedGradients_Title")), /* @__PURE__ */ React.createElement(
    CustomGradients,
    {
      gradients: customGradients,
      selectedGradient: value,
      onGradientSelected: onChange,
      onGradientDeleted
    }
  ))));
};
export {
  GradientPicker,
  getGradientValueForType
};
//# sourceMappingURL=gradient-picker.js.map
