// Animated pine-forest hero scene.
// Three parallax SVG layers + fog + embers.
// Reusable: <ForestScene height={620} density="full" />

const PineSilhouette = ({ trees, viewBoxW = 1200, viewBoxH = 300, fill = "#0a1812" }) => (
  <svg viewBox={`0 0 ${viewBoxW} ${viewBoxH}`} preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg">
    <defs>
      <linearGradient id={`pg-${fill.replace('#','')}`} x1="0" y1="0" x2="0" y2="1">
        <stop offset="0%" stopColor={fill} stopOpacity="0.85"/>
        <stop offset="100%" stopColor={fill} stopOpacity="1"/>
      </linearGradient>
    </defs>
    {/* ground silhouette */}
    <path d={`M0 ${viewBoxH} L0 ${viewBoxH - 20} ${trees.map(t => `L${t.x - t.w*0.7} ${viewBoxH - 20}`).join(' ')} L${viewBoxW} ${viewBoxH - 20} L${viewBoxW} ${viewBoxH} Z`} fill={fill}/>
    {trees.map((t, i) => {
      // jagged pine: zigzag triangle stack
      const { x, h, w } = t;
      const baseY = viewBoxH - 20;
      const tipY = baseY - h;
      // build asymmetric jagged outline
      const segs = 5;
      const pts = [];
      pts.push(`${x} ${tipY}`);
      for (let s = 1; s <= segs; s++) {
        const ratio = s / segs;
        const y = tipY + ratio * h;
        const widthAtY = w * ratio;
        pts.push(`${x + widthAtY * 0.6} ${y - 4}`);
        pts.push(`${x + widthAtY * 0.4} ${y + 6}`);
      }
      pts.push(`${x + w * 0.5} ${baseY}`);
      pts.push(`${x - w * 0.5} ${baseY}`);
      for (let s = segs; s >= 1; s--) {
        const ratio = s / segs;
        const y = tipY + ratio * h;
        const widthAtY = w * ratio;
        pts.push(`${x - widthAtY * 0.4} ${y + 6}`);
        pts.push(`${x - widthAtY * 0.6} ${y - 4}`);
      }
      return <polygon key={i} points={pts.join(' ')} fill={`url(#pg-${fill.replace('#','')})`} />;
    })}
  </svg>
);

// deterministic pseudo-random tree array
const makeTrees = (count, seed, opts = {}) => {
  const { minH = 80, maxH = 240, minW = 30, maxW = 90, span = 1200 } = opts;
  const trees = [];
  let s = seed;
  const rand = () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
  for (let i = 0; i < count; i++) {
    trees.push({
      x: (i / count) * span + rand() * (span / count) * 0.6,
      h: minH + rand() * (maxH - minH),
      w: minW + rand() * (maxW - minW),
    });
  }
  return trees.sort((a, b) => a.x - b.x);
};

const Embers = ({ count = 14 }) => {
  const dots = [];
  for (let i = 0; i < count; i++) {
    dots.push(
      <span
        key={i}
        className="ember-dot"
        style={{
          left: `${(i * 7.3) % 100}%`,
          bottom: `${10 + (i * 13) % 30}%`,
          animationDelay: `${(i * 0.5) % 6}s`,
          animationDuration: `${5 + (i % 4)}s`,
        }}
      />
    );
  }
  return <div className="embers">{dots}</div>;
};

// Campfire — sits inside a parallax layer and tiles like the trees do.
// Renders nothing positional itself; the wrapping .pine-layer carries the drift.
const CampfireUnit = () => (
  <div style={{
    position: 'relative',
    flex: '0 0 50%',
    height: '100%',
  }}>
    <div style={{
      position: 'absolute',
      left: '78%',
      bottom: 18,
      width: 80, height: 100,
      pointerEvents: 'none',
    }}>
      {/* warm light pool on the ground */}
      <div style={{
        position: 'absolute',
        left: '50%', bottom: -36,
        transform: 'translateX(-50%)',
        width: 260, height: 160,
        background: 'radial-gradient(ellipse 50% 50% at 50% 50%, rgba(240,160,96,0.32), rgba(240,160,96,0.1) 42%, transparent 72%)',
        animation: 'fire-glow 2.4s ease-in-out infinite alternate',
      }}/>
      {/* logs */}
      <svg width="80" height="100" viewBox="0 0 80 100" style={{ position: 'absolute', bottom: 0 }}>
        <g transform="translate(40,82)">
          <rect x="-26" y="-3" width="52" height="6" rx="2" fill="#1a0e08" transform="rotate(-12)"/>
          <rect x="-26" y="-3" width="52" height="6" rx="2" fill="#0f0805" transform="rotate(14)"/>
          <rect x="-22" y="-2" width="44" height="4" rx="1.5" fill="#2a1810" transform="rotate(-2) translate(0,-4)"/>
        </g>
      </svg>
      <div className="flame flame-outer"/>
      <div className="flame flame-mid"/>
      <div className="flame flame-inner"/>
      <div className="campfire-sparks">
        {[0,1,2,3,4,5].map(i => (
          <span key={i} style={{
            position: 'absolute',
            left: `${30 + (i*9)%40}%`,
            bottom: '50%',
            width: 2, height: 2,
            background: '#ffcb88',
            borderRadius: '50%',
            boxShadow: '0 0 6px 2px rgba(240,160,96,0.7)',
            animation: `spark-rise ${2.5 + (i%3)*0.7}s ease-in infinite`,
            animationDelay: `${i*0.4}s`,
            opacity: 0,
          }}/>
        ))}
      </div>
    </div>
  </div>
);

const ForestScene = ({ children, height = 620, showMoon = true, showCampfire = true }) => {
  const back = makeTrees(30, 1, { minH: 60, maxH: 140, minW: 20, maxW: 50 });
  const mid = makeTrees(22, 7, { minH: 100, maxH: 200, minW: 30, maxW: 70 });
  const front = makeTrees(14, 13, { minH: 160, maxH: 280, minW: 50, maxW: 110 });

  return (
    <div className="scene" style={{ height }}>
      {showMoon && (
        <div style={{
          position: 'absolute',
          top: '8%', right: '12%',
          width: 90, height: 90,
          borderRadius: '50%',
          background: 'radial-gradient(circle, #f4ecd8 0%, #e8c46e 50%, transparent 75%)',
          filter: 'blur(1px)',
          opacity: 0.55,
          zIndex: 1,
        }}/>
      )}

      <div className="scene-fog"/>

      <div className="pine-layer pine-back">
        <PineSilhouette trees={back} fill="#1a3326"/>
        <PineSilhouette trees={back} fill="#1a3326"/>
      </div>

      {/* Campfire layer — drifts at the same speed as the mid pines, so the
          fire sits BEHIND the front trees and ahead of the mid/back ones. */}
      {showCampfire && (
        <div className="pine-layer pine-mid" style={{ height: '48%' }}>
          <CampfireUnit/>
          <CampfireUnit/>
        </div>
      )}

      <div className="pine-layer pine-mid">
        <PineSilhouette trees={mid} fill="#0f2419"/>
        <PineSilhouette trees={mid} fill="#0f2419"/>
      </div>
      <div className="pine-layer pine-front">
        <PineSilhouette trees={front} fill="#050d09"/>
        <PineSilhouette trees={front} fill="#050d09"/>
      </div>

      <Embers count={16}/>

      {/* content overlay */}
      <div style={{ position: 'relative', zIndex: 10, height: '100%' }}>
        {children}
      </div>
    </div>
  );
};

window.ForestScene = ForestScene;
window.PineSilhouette = PineSilhouette;
