// Shared utility functions for widget rendering
import { fontSizes } from '../../../constants';
import { clamp, hexToRgba } from '../../../utils';

export { clamp, hexToRgba };

// Text alignment helpers
export function justifyForAlign(align) {
  if (align === 0) return 'flex-start';
  if (align === 2) return 'flex-end';
  return 'center';
}

export function textAlignCss(align) {
  if (align === 0) return 'left';
  if (align === 2) return 'right';
  return 'center';
}

// Base style for all widgets
export function getBaseStyle(widget, scale) {
  return {
    left: `${widget.x * scale}px`,
    top: `${widget.y * scale}px`,
    width: `${widget.w * scale}px`,
    height: `${widget.h * scale}px`,
    fontSize: `${(fontSizes[widget.fontSize] || 14) * scale}px`,
    color: widget.textColor,
    position: 'absolute',
    zIndex: 1,
    cursor: 'move',
    userSelect: 'none',
    touchAction: 'none'
  };
}

// Shadow style helper
export function getShadowStyle(widget, scale) {
  if (!widget.shadow || !widget.shadow.enabled) return {};

  const sx = (widget.shadow.x || 0) * scale;
  const sy = (widget.shadow.y || 0) * scale;
  const blur = (widget.shadow.blur || 0) * scale;
  const spread = (widget.shadow.spread || 0) * scale;

  return {
    boxShadow: `${sx}px ${sy}px ${blur}px ${spread}px ${widget.shadow.color}`
  };
}

// Border style helper (0-255 opacity, width in widget px)
export function getBorderStyle(widget, scale) {
  const width = Math.max(0, (widget.borderWidth || 0) * scale);
  const alpha = clamp((widget.borderOpacity ?? 0) / 255, 0, 1);
  if (width <= 0 || alpha <= 0) {
    return { border: 'none' };
  }
  return {
    border: `${width}px solid ${hexToRgba(widget.borderColor || '#ffffff', alpha)}`
  };
}

// PowerNode text splitting
export function splitPowerNodeText(text) {
  if (typeof text !== 'string') return { label: '', value: '' };
  const parts = text.split('\n');
  const label = parts[0] ?? '';
  const value = parts.slice(1).join('\n');
  return { label, value };
}
