/**
 * Background: orb — Linear-style single soft orb (not Stripe-4-corner-mesh).
 *
 * Reference: Linear's product launch decks. ONE big purple-blue blur
 * orb anchored in the lower-right, positioned partially off-canvas
 * so only its soft arc bleeds onto the slide. A smaller cyan accent
 * orb sits diagonally opposite for visual rhythm.
 *
 * Distinguished from `mesh` (which uses 4 corner-anchored orbs in
 * the Stripe Sessions pattern): orb has the orbs in deliberate
 * dramatic positions, not a uniform corner-fill.
 */
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 applyOrb(slide, resolved, _opts = {}) {
  const palette = resolved.palette;
  slide.background = { color: palette.bg };

  const W = SLIDE_DIMENSIONS.width;
  const H = SLIDE_DIMENSIONS.height;
  const bgIsDark = isDarkHex(palette.bg);
  // On dark themes the orbs need lower transparency to read; on light
  // themes they need higher (or they overpower content).
  const mainTrans = bgIsDark ? 55 : 78;
  const accentTrans = bgIsDark ? 70 : 85;

  // Primary orb — lower-right, large. Drama anchor for the slide.
  const mainSize = W * 0.7;
  slide.addShape('ellipse', {
    x: W * 0.55, y: H * 0.45,
    w: mainSize, h: mainSize,
    fill: { color: palette.primary, transparency: mainTrans },
    line: { type: 'none' },
  });

  // Accent orb — upper-left, smaller. Counterweight for composition.
  const accentSize = W * 0.42;
  slide.addShape('ellipse', {
    x: -accentSize * 0.4, y: -accentSize * 0.3,
    w: accentSize, h: accentSize,
    fill: { color: palette.highlight || palette.accent, transparency: accentTrans },
    line: { type: 'none' },
  });

  // Optional darker shaded primary tucked behind the main orb — adds
  // depth without a second visible orb.
  if (bgIsDark) {
    const depthSize = W * 0.5;
    slide.addShape('ellipse', {
      x: W * 0.7, y: H * 0.3,
      w: depthSize, h: depthSize,
      fill: { color: shade(palette.primary, -30), transparency: 60 },
      line: { type: 'none' },
    });
  }
}
