import { useMemo } from "react";

const toBoolean = (value: unknown, fallback: boolean): boolean => {
  if (typeof value === "boolean") return value;
  if (typeof value === "number") return value !== 0;
  if (typeof value === "string") {
    const normalized = value.trim().toLowerCase();
    if (["1", "true", "yes", "on"].includes(normalized)) return true;
    if (["0", "false", "no", "off", ""].includes(normalized)) return false;
  }
  return fallback;
};

const clampInt = (
  value: unknown,
  min: number,
  max: number,
  fallback: number,
): number => {
  const candidate = Number(value);
  if (!Number.isFinite(candidate)) return fallback;
  return Math.max(min, Math.min(max, Math.round(candidate)));
};

const clampPadding = (value: unknown, fallback: number): number =>
  clampInt(value, 0, 48, fallback);

export function useSwatchSettings(settings: Record<string, unknown>) {
  return useMemo(() => {
    const swatchWidth = clampInt(settings.swatch_width, 24, 60, 32);
    const swatchHeight = clampInt(settings.swatch_height, 24, 60, 32);

    return {
      tooltipsEnabled: toBoolean(settings.enable_tooltips, true),
      layoutPaddingTop: clampPadding(settings.layout_padding_top, 5),
      layoutPaddingRight: clampPadding(settings.layout_padding_right, 5),
      layoutPaddingBottom: clampPadding(settings.layout_padding_bottom, 5),
      layoutPaddingLeft: clampPadding(settings.layout_padding_left, 5),
      externalPaddingTop: clampPadding(settings.external_padding_top, 5),
      externalPaddingRight: clampPadding(settings.external_padding_right, 5),
      externalPaddingBottom: clampPadding(settings.external_padding_bottom, 5),
      externalPaddingLeft: clampPadding(settings.external_padding_left, 5),
      paddingTop: clampPadding(settings.padding_top, 8),
      paddingRight: clampPadding(settings.padding_right, 16),
      paddingBottom: clampPadding(settings.padding_bottom, 8),
      paddingLeft: clampPadding(settings.padding_left, 16),
      showLabels: toBoolean(settings.show_labels, true),
      showLabelsColors: toBoolean(settings.show_labels_colors, true),
      selectedColor:
        typeof settings.selected_color === "string" &&
        settings.selected_color.trim()
          ? settings.selected_color
          : "#46a5e5",
      swatchWidth,
      swatchHeight,
      swatchGap: clampInt(settings.swatch_gap, 0, 40, 12),
      labelFontSize: clampInt(settings.label_font_size, 10, 24, 14),
      buttonSwatchWidth: swatchWidth,
      buttonSwatchHeight: swatchHeight,
    };
  }, [settings]);
}
