// atmosphere.jsx — premium background system.
// Modes:
//   'off'     → pure flat black, no motion
//   'minimal' → sparse drifting pixel motes (existing PixelField look)
//   'luxe'    → warm near-black + slow drifting teal blob + film noise +
//               sparser pixels + edge vignette + 1px top hairline
//
// Drop <Atmosphere mode={...} accent={...} /> as the FIRST child of any
// dark surface that has position:relative. It paints itself absolutely
// behind everything else (zIndex 0). Wrap real content in
// position:relative; zIndex:1 so it sits above.

const ATM_C = {
  // Slightly warm near-black — reads richer than pure #000.
  bgWarm: '#0c0b0d',
  bgFlat: '#0a0a0b',
};

// ── Drifting blob (luxe mode only) ──────────────────────────────────
function AtmBlob({ accent, mobile }) {
  // Two soft, very low-opacity blurred discs that drift slowly.
  // Pure CSS animation, no canvas needed.
  const size = mobile ? 460 : 720;
  const blur = mobile ? 90 : 140;
  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none', zIndex: 0 }}>
      <div style={{
        position: 'absolute', width: size, height: size, borderRadius: '50%',
        background: `radial-gradient(circle at center, ${accent}, transparent 60%)`,
        opacity: 0.10, filter: `blur(${blur}px)`,
        top: '-20%', left: '-15%',
        animation: `atm-drift1 ${mobile ? 28 : 36}s ease-in-out infinite`,
      }}/>
      <div style={{
        position: 'absolute', width: size * 0.85, height: size * 0.85, borderRadius: '50%',
        background: `radial-gradient(circle at center, ${accent}, transparent 60%)`,
        opacity: 0.07, filter: `blur(${blur}px)`,
        bottom: '-25%', right: '-20%',
        animation: `atm-drift2 ${mobile ? 32 : 44}s ease-in-out infinite`,
      }}/>
    </div>
  );
}

// ── Film grain (luxe mode only) ─────────────────────────────────────
// Generated once via canvas, reused as a tiled SVG-data-uri background.
// Cached on window so we don't redo work per mount.
function makeNoiseUrl() {
  if (typeof window === 'undefined') return '';
  if (window.__atm_noise) return window.__atm_noise;
  const size = 128;
  const cv = document.createElement('canvas');
  cv.width = size; cv.height = size;
  const ctx = cv.getContext('2d');
  const img = ctx.createImageData(size, size);
  for (let i = 0; i < img.data.length; i += 4) {
    const v = Math.random() * 255;
    img.data[i] = v; img.data[i + 1] = v; img.data[i + 2] = v;
    img.data[i + 3] = 18; // very faint
  }
  ctx.putImageData(img, 0, 0);
  const url = cv.toDataURL('image/png');
  window.__atm_noise = url;
  return url;
}

function AtmGrain() {
  const [url, setUrl] = React.useState('');
  React.useEffect(() => { setUrl(makeNoiseUrl()); }, []);
  if (!url) return null;
  return (
    <div style={{
      position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 0,
      backgroundImage: `url(${url})`, backgroundSize: '128px 128px',
      mixBlendMode: 'overlay', opacity: 0.55,
    }}/>
  );
}

// ── Vignette (luxe mode only) ───────────────────────────────────────
function AtmVignette() {
  return (
    <div style={{
      position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 0,
      background: 'radial-gradient(ellipse at center, transparent 50%, rgba(0,0,0,0.45) 100%)',
    }}/>
  );
}

// ── Top hairline (luxe mode only) ───────────────────────────────────
function AtmHairline({ accent }) {
  return (
    <div style={{
      position: 'absolute', top: 0, left: 0, right: 0, height: 1,
      background: `linear-gradient(90deg, transparent, ${accent}, transparent)`,
      opacity: 0.5, pointerEvents: 'none', zIndex: 1,
    }}/>
  );
}

// ── Public API ──────────────────────────────────────────────────────
function Atmosphere({ mode = 'minimal', accent = '#14b8a6', mobile = false }) {
  // Background tint layer (always present so the artboard is correctly colored)
  const tint = mode === 'luxe' ? ATM_C.bgWarm : ATM_C.bgFlat;
  return (
    <>
      <div style={{
        position: 'absolute', inset: 0, background: tint,
        pointerEvents: 'none', zIndex: 0,
      }}/>
      {mode === 'luxe' && <AtmBlob accent={accent} mobile={mobile} />}
      {mode === 'luxe' && <AtmVignette />}
      {(mode === 'minimal' || mode === 'luxe') && (
        <PixelField
          enabled
          count={mode === 'luxe' ? (mobile ? 8 : 14) : (mobile ? 14 : 24)}
          maxOpacity={mode === 'luxe' ? 0.35 : 0.55}
          color="#ffffff"
        />
      )}
      {mode === 'luxe' && <AtmGrain />}
      {mode === 'luxe' && <AtmHairline accent={accent} />}
    </>
  );
}

if (typeof document !== 'undefined' && !document.getElementById('atm-anim')) {
  const s = document.createElement('style');
  s.id = 'atm-anim';
  s.textContent = `
    @keyframes atm-drift1 {
      0%, 100% { transform: translate(0, 0); }
      50% { transform: translate(8%, 6%); }
    }
    @keyframes atm-drift2 {
      0%, 100% { transform: translate(0, 0); }
      50% { transform: translate(-6%, -8%); }
    }
  `;
  document.head.appendChild(s);
}

Object.assign(window, { Atmosphere });
