import { __ } from "@wordpress/i18n";
import { RangeControl } from "@wordpress/components";
import { getEnabledBreakpoints } from "../../../../../core/breakpoints";

const getDefaultRadius = () => ({
  pc: { value: "0", unit: "px" },
  md: { value: "", unit: "px" },
  tb: { value: "", unit: "px" },
  sp: { value: "", unit: "px" }
});

const StylingRadiusSimpleSettingV8 = ({ 
  attributes, 
  setAttributes, 
  label,
  attrName = "radiusV2",
  defaultValue = "0",
  min = 0,
  max = 50
}) => {
  const enabledBreakpoints = getEnabledBreakpoints();
  const radiusData = attributes[attrName] || getDefaultRadius();
  const pcData = radiusData.pc || { value: defaultValue, unit: "px" };
  const currentValue = parseInt(pcData.value) || parseInt(defaultValue);

  const handleRadiusChange = (value) => {
    const newData = JSON.parse(JSON.stringify(radiusData));
    enabledBreakpoints.forEach((bp) => {
      newData[bp] = { ...newData[bp], value: String(value) };
    });
    setAttributes({ [attrName]: newData });
  };

  return (
    <div className="zenblocks-radius-setting">
      <RangeControl
        label={label || __("Border Radius", "zenblocks")}
        value={currentValue}
        onChange={handleRadiusChange}
        min={min}
        max={max}
      />
    </div>
  );
};

export const getDirectRadiusSimpleV8 = (attributes, attrName = "radiusV2", device = 'pc') => {
  const radiusData = attributes[attrName];
  
  if (!radiusData || !radiusData[device]) return undefined;
  
  const { value, unit } = radiusData[device];
  
  if (value && value !== '') {
    return `${value}${unit || 'px'}`;
  }
  
  return undefined;
};

export const getRadiusSimpleV8 = (attributes, attrName = "radiusV2", device = 'pc', defaultValue = '0px') => {
  const radiusData = attributes[attrName];
  
  if (!radiusData) return defaultValue;
  
  const enabledBreakpoints = getEnabledBreakpoints();
  const currentIndex = enabledBreakpoints.indexOf(device);
  
  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = radiusData[bp];
    if (bpData && bpData.value && bpData.value !== '') {
      return `${bpData.value}${bpData.unit || 'px'}`;
    }
  }
  
  return defaultValue;
};

export default StylingRadiusSimpleSettingV8;
