export interface GlassMaterialSettings {
  version?: 4;
  tintHex: string;
  tintOpacity: number;
  blur: number;
  saturation: number;
  brightness: number;
  outlineOpacity: number;
  shadowOpacity: number;
}

export const defaultGlassMaterial: GlassMaterialSettings = {
  version: 4,
  tintHex: "#0b0b0e",
  tintOpacity: 94,
  blur: 44,
  saturation: 112,
  brightness: 105,
  outlineOpacity: 11,
  shadowOpacity: 64,
};

function normalizeHex(value: string) {
  const match = /^#?([0-9a-f]{6})$/i.exec(value.trim());
  return match ? `#${match[1].toLowerCase()}` : defaultGlassMaterial.tintHex;
}

function clamp(value: number, min: number, max: number) {
  return Math.max(min, Math.min(max, value));
}

export function createGlassMaterialVariables(settings: GlassMaterialSettings): Record<string, string> {
  const tintHex = normalizeHex(settings.tintHex);
  const red = Number.parseInt(tintHex.slice(1, 3), 16);
  const green = Number.parseInt(tintHex.slice(3, 5), 16);
  const blue = Number.parseInt(tintHex.slice(5, 7), 16);
  return {
    "--nodedc-modal-glass-tint-rgb": `${red} ${green} ${blue}`,
    "--nodedc-modal-glass-tint-opacity": String(clamp(settings.tintOpacity, 0, 100) / 100),
    "--nodedc-blur-modal": `${clamp(settings.blur, 0, 120)}px`,
    "--nodedc-modal-glass-saturation": String(clamp(settings.saturation, 70, 220) / 100),
    "--nodedc-modal-glass-brightness": String(clamp(settings.brightness, 70, 160) / 100),
    "--nodedc-modal-glass-outline-opacity": String(clamp(settings.outlineOpacity, 0, 40) / 100),
    "--nodedc-modal-glass-outline-soft-opacity": String((clamp(settings.outlineOpacity, 0, 40) / 100) * 0.45),
    "--nodedc-modal-glass-shadow-opacity": String(clamp(settings.shadowOpacity, 0, 100) / 100),
    "--nodedc-modal-glass-shadow-light-opacity": String((clamp(settings.shadowOpacity, 0, 100) / 100) * 0.375),
  };
}

export function applyGlassMaterial(target: HTMLElement, settings: GlassMaterialSettings) {
  for (const [name, value] of Object.entries(createGlassMaterialVariables(settings))) {
    target.style.setProperty(name, value);
  }
}
