// ============================================================
// KENNISBANK · Procedural cover generator
// ------------------------------------------------------------
// A deterministic SVG "cover" derived from a string seed (e.g.
// the blog slug). Always uses brand-gradient colors only.
// No bitmap images needed — every blog gets a unique-but-on-brand
// visual automatically.
// ============================================================

(function () {
  // ---- Seeded RNG ----------------------------------------------------------
  function hashStr(s) {
    let h = 5381;
    for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) | 0;
    return Math.abs(h) || 1;
  }
  function makeRng(seed) {
    let s = seed || 1;
    return () => {
      s = (s * 9301 + 49297) % 233280;
      return s / 233280;
    };
  }

  // ---- Brand palettes (only on-brand combos) -------------------------------
  // Each palette is ordered as a gradient ramp (≥2 stops).
  const PALETTES = [
    { id: 'sunset',  stops: ['#FFC031', '#FB993F', '#F83C72'],         accent: '#4D01B4' },
    { id: 'magma',   stops: ['#FB993F', '#F83C72', '#8D0D9C'],          accent: '#FFC031' },
    { id: 'cosmos',  stops: ['#F83C72', '#8D0D9C', '#4D01B4'],          accent: '#FFC031' },
    { id: 'spectrum',stops: ['#FFC031', '#FB993F', '#F83C72', '#4D01B4'], accent: '#FFFFFF' },
    { id: 'plum',    stops: ['#8D0D9C', '#4D01B4', '#1C1C1C'],          accent: '#FB993F' },
    { id: 'amber',   stops: ['#FFC031', '#FB993F'],                     accent: '#F83C72' },
    { id: 'orchid',  stops: ['#F83C72', '#4D01B4'],                     accent: '#FFC031' },
  ];
  const VARIANTS = ['orbs', 'arcs', 'rings', 'swoosh', 'dots'];

  // ---- Component -----------------------------------------------------------
  function KbCover({ seed, paletteId, variant, className, aspect = '16/10', children }) {
    const uid = React.useId().replace(/[^a-zA-Z0-9]/g, '');
    const { pal, vrnt, layers, angle } = React.useMemo(() => {
      const rng = makeRng(hashStr(seed || 'kennisbank'));
      // first few rng calls are unstable; warm it up
      rng(); rng(); rng();

      const palIdx = paletteId
        ? Math.max(0, PALETTES.findIndex(p => p.id === paletteId))
        : Math.floor(rng() * PALETTES.length);
      const pal = PALETTES[palIdx];
      const vrnt = variant || VARIANTS[Math.floor(rng() * VARIANTS.length)];
      const angle = Math.floor(rng() * 360);

      // generate per-variant decorative shapes
      const N = vrnt === 'orbs' ? 4 : vrnt === 'dots' ? 1 : vrnt === 'rings' ? 1 : 2;
      const layers = [];
      for (let i = 0; i < N; i++) {
        layers.push({
          cx: 6 + rng() * 88,            // 6–94%
          cy: 8 + rng() * 84,            // 8–92%
          r:  18 + rng() * 32,           // 18–50%
          color: pal.stops[Math.floor(rng() * pal.stops.length)],
          rot: rng() * 360,
        });
      }
      return { pal, vrnt, layers, angle };
    }, [seed, paletteId, variant]);

    const aspectStyle = { aspectRatio: aspect.replace('/', ' / ') };
    const accent = pal.accent;
    const stops = pal.stops;

    return (
      <div className={`kb-cover ${className || ''}`} data-variant={vrnt} data-palette={pal.id} style={aspectStyle}>
        <svg viewBox="0 0 400 250" preserveAspectRatio="xMidYMid slice" className="kb-cover-svg" aria-hidden="true">
          <defs>
            {/* base gradient */}
            <linearGradient id={`g-base-${uid}`} gradientTransform={`rotate(${angle} 0.5 0.5)`}>
              {stops.map((c, i) => (
                <stop key={i} offset={`${(i / (stops.length - 1)) * 100}%`} stopColor={c} />
              ))}
            </linearGradient>
            {/* soft radial for blobs */}
            {layers.map((L, i) => (
              <radialGradient key={i} id={`g-orb-${uid}-${i}`} cx="50%" cy="50%" r="50%">
                <stop offset="0%" stopColor={L.color} stopOpacity="0.95" />
                <stop offset="60%" stopColor={L.color} stopOpacity="0.35" />
                <stop offset="100%" stopColor={L.color} stopOpacity="0" />
              </radialGradient>
            ))}
            {/* grain mask: subtle dot pattern, used for some variants */}
            <pattern id={`pat-dots-${uid}`} x="0" y="0" width="14" height="14" patternUnits="userSpaceOnUse">
              <circle cx="2" cy="2" r="1" fill="rgba(255,255,255,0.18)" />
            </pattern>
          </defs>

          {/* base */}
          <rect x="0" y="0" width="400" height="250" fill={`url(#g-base-${uid})`} />

          {/* decorative blobs (always present, softened) */}
          {layers.map((L, i) => (
            <circle
              key={`orb-${i}`}
              cx={(L.cx / 100) * 400}
              cy={(L.cy / 100) * 250}
              r={(L.r / 100) * 320}
              fill={`url(#g-orb-${uid}-${i})`}
              style={{ mixBlendMode: 'screen' }}
            />
          ))}

          {/* variant overlays */}
          {vrnt === 'arcs' && (
            <g style={{ mixBlendMode: 'screen', opacity: 0.85 }}>
              <circle cx={layers[0].cx * 4} cy={layers[0].cy * 2.5} r="220" fill="none"
                      stroke={accent} strokeWidth="1.5" strokeOpacity="0.55" />
              <circle cx={layers[0].cx * 4} cy={layers[0].cy * 2.5} r="160" fill="none"
                      stroke={accent} strokeWidth="1.5" strokeOpacity="0.4" />
              <circle cx={layers[0].cx * 4} cy={layers[0].cy * 2.5} r="100" fill="none"
                      stroke={accent} strokeWidth="1.5" strokeOpacity="0.3" />
            </g>
          )}
          {vrnt === 'rings' && (() => {
            const cx = (layers[0].cx / 100) * 400;
            const cy = (layers[0].cy / 100) * 250;
            const rings = [40, 78, 116, 154, 192];
            return (
              <g style={{ mixBlendMode: 'screen' }}>
                {rings.map((r, i) => (
                  <circle key={i} cx={cx} cy={cy} r={r} fill="none"
                          stroke={accent} strokeWidth="1.2"
                          strokeOpacity={0.55 - i * 0.08} />
                ))}
              </g>
            );
          })()}
          {vrnt === 'swoosh' && (
            <path
              d={`M -40 ${130 + layers[0].cy * 0.5}
                  C 90 ${80 - layers[0].cy * 0.3}, 230 ${230 + layers[1].cy * 0.3}, 460 ${110 - layers[1].cy * 0.3}`}
              fill="none"
              stroke={accent}
              strokeWidth="42"
              strokeOpacity="0.55"
              strokeLinecap="round"
              style={{ mixBlendMode: 'screen' }}
            />
          )}
          {vrnt === 'dots' && (
            <rect x="0" y="0" width="400" height="250" fill={`url(#pat-dots-${uid})`} />
          )}

          {/* gentle highlight at top-left */}
          <rect x="0" y="0" width="400" height="80" fill="white" opacity="0.06" />
        </svg>
        {children}
      </div>
    );
  }

  Object.assign(window, { KbCover, KB_PALETTES: PALETTES, KB_VARIANTS: VARIANTS, kbHash: hashStr });
})();
