/* global React */
/* ============================================================
   AppleTreeBackground — pure SVG seasonal apple tree.
   Rolls through 9 phenological states matching the wheel.
   Sits behind the wheel as a subtle, animated atmosphere.
   ============================================================ */

(function () {
  const { useMemo } = React;

  // Per-stage parameters. Index aligns with PHENOLOGICAL_STAGES.
  // 0 dormancy · 1 budbreak · 2 flowering · 3 fruitset · 4 celldivision
  // 5 cellexpansion · 6 veraison · 7 harvest
  const STAGE_PARAMS = [
    // 0 — Dormancy
    { sky: ['#0E1A12', '#08120A'], ground: '#0B140C', leafFill: 0,    leafColor: '#3D5226', blossom: 0, fruit: 0, fruitColor: '#7FAA3A', fruitSize: 0,   snow: 0.55 },
    // 1 — Bud break
    { sky: ['#10221A', '#0A1810'], ground: '#0E1B0E', leafFill: 0.20, leafColor: '#7FAA3A', blossom: 0, fruit: 0, fruitColor: '#7FAA3A', fruitSize: 0,   snow: 0.10 },
    // 2 — Flowering
    { sky: ['#152A1F', '#0C1E12'], ground: '#0F1F10', leafFill: 0.55, leafColor: '#9CC257', blossom: 1, fruit: 0, fruitColor: '#7FAA3A', fruitSize: 0,   snow: 0    },
    // 3 — Fruit set
    { sky: ['#163024', '#0E2114'], ground: '#102310', leafFill: 0.85, leafColor: '#A6CC5E', blossom: 0.25, fruit: 1, fruitColor: '#7FAA3A', fruitSize: 0.25, snow: 0 },
    // 4 — Cell division
    { sky: ['#173526', '#0F2415'], ground: '#112613', leafFill: 0.95, leafColor: '#A6CC5E', blossom: 0, fruit: 1, fruitColor: '#9DBE5A', fruitSize: 0.45, snow: 0 },
    // 5 — Cell expansion
    { sky: ['#193F2A', '#102816'], ground: '#122A14', leafFill: 1.0,  leafColor: '#A8CE60', blossom: 0, fruit: 1, fruitColor: '#B6CD60', fruitSize: 0.70, snow: 0 },
    // 6 — Veraison
    { sky: ['#1B3A24', '#0F2613'], ground: '#142712', leafFill: 0.95, leafColor: '#A0BE53', blossom: 0, fruit: 1, fruitColor: '#D9A24A', fruitSize: 0.88, snow: 0 },
    // 7 — Harvest
    { sky: ['#2A2E16', '#1A1E0E'], ground: '#1F2010', leafFill: 0.70, leafColor: '#C4A348', blossom: 0, fruit: 1, fruitColor: '#C84A2C', fruitSize: 1.0,  snow: 0 },
  ];

  // Pre-computed fixed positions (deterministic so animations between
  // stages morph the same elements rather than reshuffling).
  function seededRand(seed) {
    let s = seed;
    return () => {
      s = (s * 9301 + 49297) % 233280;
      return s / 233280;
    };
  }

  // Branch endpoints (canopy positions) — anchored on the canopy
  const CANOPY_POINTS = (() => {
    const r = seededRand(7);
    const pts = [];
    for (let i = 0; i < 26; i++) {
      const a = (i / 26) * Math.PI * 2 + r() * 0.4;
      const radX = 110 + r() * 38;
      const radY = 92  + r() * 30;
      const cx = 200 + Math.cos(a) * radX;
      const cy = 165 + Math.sin(a) * radY * 0.85 - 30; // squash + offset up
      pts.push({ cx, cy, scatter: r() });
    }
    return pts;
  })();

  // Fixed leaf cluster positions (more numerous than canopy points)
  const LEAF_POINTS = (() => {
    const r = seededRand(13);
    const pts = [];
    for (let i = 0; i < 70; i++) {
      const a = r() * Math.PI * 2;
      const radX = 60 + r() * 90;
      const radY = 50 + r() * 70;
      const cx = 200 + Math.cos(a) * radX;
      const cy = 140 + Math.sin(a) * radY * 0.85;
      const size = 4 + r() * 6;
      const rot = r() * 360;
      pts.push({ cx, cy, size, rot, phase: r() * Math.PI * 2 });
    }
    return pts;
  })();

  // Blossom positions — distributed similarly to fruits
  const BLOSSOM_POINTS = (() => {
    const r = seededRand(31);
    const pts = [];
    for (let i = 0; i < 40; i++) {
      const a = r() * Math.PI * 2;
      const radX = 60 + r() * 80;
      const radY = 45 + r() * 60;
      const cx = 200 + Math.cos(a) * radX;
      const cy = 140 + Math.sin(a) * radY * 0.85;
      const size = 3 + r() * 2;
      pts.push({ cx, cy, size });
    }
    return pts;
  })();

  // Fruit positions — fewer, scattered through canopy
  const FRUIT_POINTS = (() => {
    const r = seededRand(53);
    const pts = [];
    for (let i = 0; i < 24; i++) {
      const a = r() * Math.PI * 2;
      const radX = 55 + r() * 75;
      const radY = 40 + r() * 55;
      const cx = 200 + Math.cos(a) * radX;
      const cy = 140 + Math.sin(a) * radY * 0.85 + 8; // hang slightly down
      pts.push({ cx, cy, drop: r() });
    }
    return pts;
  })();

  // Snow patches on ground
  const SNOW_PATCHES = (() => {
    const r = seededRand(71);
    const pts = [];
    for (let i = 0; i < 14; i++) {
      const cx = r() * 400;
      const cy = 270 + r() * 28;
      const w  = 30 + r() * 70;
      pts.push({ cx, cy, w });
    }
    return pts;
  })();

  // Fallen apples on ground (post-harvest)
  const FALLEN_FRUITS = (() => {
    const r = seededRand(89);
    const pts = [];
    for (let i = 0; i < 6; i++) {
      const cx = 100 + r() * 200;
      const cy = 278 + r() * 14;
      pts.push({ cx, cy });
    }
    return pts;
  })();

  window.AppleTreeBackground = function AppleTreeBackground({ stageIndex = 0 }) {
    const p = STAGE_PARAMS[stageIndex] || STAGE_PARAMS[0];
    const gradId = useMemo(() => `apple-sky-${Math.random().toString(36).slice(2, 8)}`, []);

    // How many leaves are visible based on leafFill (0..1)
    const visibleLeafCount = Math.floor(LEAF_POINTS.length * p.leafFill);

    return (
      <svg
        className="apple-tree-bg"
        viewBox="0 0 400 320"
        preserveAspectRatio="xMidYMid slice"
        aria-hidden="true"
      >
        <defs>
          <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={p.sky[0]} />
            <stop offset="100%" stopColor={p.sky[1]} />
          </linearGradient>
          <radialGradient id={`${gradId}-glow`} cx="50%" cy="35%" r="55%">
            <stop offset="0%" stopColor="rgba(184,220,115,0.10)" />
            <stop offset="100%" stopColor="rgba(184,220,115,0)" />
          </radialGradient>
        </defs>

        {/* Sky */}
        <rect x="0" y="0" width="400" height="320" fill={`url(#${gradId})`} className="atb-fade-fill" />

        {/* Ambient glow */}
        <rect x="0" y="0" width="400" height="320" fill={`url(#${gradId}-glow)`} />

        {/* Distant horizon line (subtle) */}
        <line x1="0" y1="265" x2="400" y2="265"
          stroke="rgba(184,220,115,0.08)" strokeWidth="0.5" />

        {/* Ground */}
        <rect x="0" y="265" width="400" height="55" fill={p.ground} className="atb-fade-fill" />

        {/* Snow patches */}
        {p.snow > 0 && (
          <g style={{ opacity: p.snow }}>
            {SNOW_PATCHES.map((s, i) => (
              <ellipse key={i} cx={s.cx} cy={s.cy} rx={s.w} ry={2.5}
                fill="rgba(220,232,240,0.45)" />
            ))}
          </g>
        )}

        {/* Trunk */}
        <g>
          <path
            d="M 196 270
               C 196 260, 197 240, 198 220
               C 199 200, 200 180, 200 165"
            stroke="#2A1F12"
            strokeWidth="9"
            strokeLinecap="round"
            fill="none"
          />
          {/* Trunk highlight */}
          <path
            d="M 198 268 C 199 248, 200 218, 201 168"
            stroke="rgba(120, 85, 50, 0.35)"
            strokeWidth="2"
            strokeLinecap="round"
            fill="none"
          />
        </g>

        {/* Branches — radiate from a node ~165 */}
        <g stroke="#2A1F12" strokeLinecap="round" fill="none">
          {CANOPY_POINTS.map((c, i) => {
            // Bezier from trunk top to branch end
            const startX = 200, startY = 165;
            const midX = (startX + c.cx) / 2 + (c.scatter - 0.5) * 24;
            const midY = (startY + c.cy) / 2 - 14;
            const w = 1.2 + (1 - i / CANOPY_POINTS.length) * 1.6;
            return (
              <path
                key={i}
                d={`M ${startX} ${startY} Q ${midX} ${midY} ${c.cx} ${c.cy}`}
                strokeWidth={w}
                opacity="0.95"
              />
            );
          })}
        </g>

        {/* Leaf clusters */}
        <g className="atb-leaves">
          {LEAF_POINTS.slice(0, visibleLeafCount).map((l, i) => (
            <ellipse
              key={i}
              cx={l.cx} cy={l.cy}
              rx={l.size} ry={l.size * 0.72}
              fill={p.leafColor}
              opacity={0.55 + (i % 5) * 0.06}
              transform={`rotate(${l.rot} ${l.cx} ${l.cy})`}
              className="atb-fade-fill"
            />
          ))}
        </g>

        {/* Blossoms */}
        {p.blossom > 0 && (
          <g style={{ opacity: p.blossom }}>
            {BLOSSOM_POINTS.map((b, i) => (
              <g key={i} transform={`translate(${b.cx} ${b.cy})`}>
                {/* 5 petals */}
                {[0, 72, 144, 216, 288].map((rot, j) => (
                  <ellipse
                    key={j}
                    cx="0" cy={-b.size * 0.65}
                    rx={b.size * 0.5} ry={b.size * 0.85}
                    fill="rgba(245, 230, 235, 0.85)"
                    transform={`rotate(${rot})`}
                  />
                ))}
                <circle cx="0" cy="0" r={b.size * 0.32} fill="#D9A24A" opacity="0.8" />
              </g>
            ))}
          </g>
        )}

        {/* Fruit on tree */}
        {p.fruit > 0 && p.fruitSize > 0 && (
          <g className="atb-fruits">
            {FRUIT_POINTS.map((f, i) => {
              const r = 1.5 + p.fruitSize * 4.5 + (f.drop - 0.5) * 0.8;
              return (
                <g key={i}>
                  <circle cx={f.cx} cy={f.cy} r={r}
                    fill={p.fruitColor}
                    className="atb-fade-fill" />
                  {/* Highlight */}
                  <circle cx={f.cx - r * 0.35} cy={f.cy - r * 0.35} r={r * 0.28}
                    fill="rgba(255,255,255,0.35)" />
                </g>
              );
            })}
          </g>
        )}

        {/* Fallen fruits (post-harvest) */}
        {stageIndex === 8 && (
          <g style={{ opacity: 0.7 }}>
            {FALLEN_FRUITS.map((f, i) => (
              <g key={i}>
                <ellipse cx={f.cx} cy={f.cy + 3} rx={4} ry={1.2} fill="rgba(0,0,0,0.4)" />
                <circle cx={f.cx} cy={f.cy} r={3.2} fill="#8B3A22" />
              </g>
            ))}
          </g>
        )}

        {/* Tiny vignette top */}
        <rect x="0" y="0" width="400" height="80" fill="url(#vignetteGrad)" opacity="0.5" />
        <defs>
          <linearGradient id="vignetteGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="rgba(0,0,0,0.45)" />
            <stop offset="100%" stopColor="rgba(0,0,0,0)" />
          </linearGradient>
        </defs>
      </svg>
    );
  };
})();
