/**
 * Background: mesh gradient — Stripe / Linear-style 4-corner radials.
 *
 * Industry pattern: a deterministic 4-corner radial mesh. One hue per
 * corner, each blob at ~55% slide diameter, positioned partially
 * off-canvas so only the soft arc bleeds onto the slide. From a
 * distance reads as a continuous mesh; up close it's four overlapping
 * orbs. Hue assignment uses palette roles so the same palette always
 * produces the same mesh.
 */
import { SLIDE_DIMENSIONS } from '../grid.js';
import { shade } from '../palettes.js';

function isDarkHex(hex) {
  const s = String(hex).replace(/^#/, '');
  if (!/^[0-9A-Fa-f]{6}$/.test(s)) return false;
  const r = parseInt(s.slice(0, 2), 16);
  const g = parseInt(s.slice(2, 4), 16);
  const b = parseInt(s.slice(4, 6), 16);
  return (0.299 * r + 0.587 * g + 0.114 * b) < 110;
}

export default function applyMesh(slide, resolved, _opts = {}) {
  const palette = resolved.palette;
  slide.background = { color: palette.bg };

  const saturation = resolved.decoration?.mesh?.saturation || 'vivid';
  const blur = resolved.decoration?.mesh?.blur || 'normal';
  const bgIsDark = isDarkHex(palette.bg);
  const baseTrans = bgIsDark ? 65 : 80;
  const blurAdj = blur === 'high' ? 8 : blur === 'low' ? -8 : 0;
  const transparency = baseTrans + blurAdj;

  const W = SLIDE_DIMENSIONS.width;
  const H = SLIDE_DIMENSIONS.height;
  const diameter = W * 0.55;
  const offset = -W * 0.12;
  const corners = [
    { x: offset,                  y: offset,                  color: palette.primary },
    { x: W - diameter - offset,   y: offset,                  color: palette.accent  },
    { x: offset,                  y: H - diameter - offset,   color: shade(palette.primary, -20) },
    { x: W - diameter - offset,   y: H - diameter - offset,   color: palette.highlight || palette.accent },
  ];

  if (saturation === 'muted') {
    for (const c of corners) c.color = shade(c.color, bgIsDark ? -25 : 35);
  }

  for (const c of corners) {
    slide.addShape('ellipse', {
      x: c.x, y: c.y, w: diameter, h: diameter,
      fill: { color: c.color, transparency },
      line: { type: 'none' },
    });
  }
}

