/* global React, gsap, ScrollTrigger, prefersReduced, ChevronDown */
const { useRef: useRefF, useLayoutEffect: useLayoutEffectF } = React;

/* ---------- Deterministic forest silhouette generator (CSS/SVG) ----------- */
function mulberry32(seed) {
  return function () {
    seed |= 0; seed = (seed + 0x6D2B79F5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

// A single tapered trunk path rooted at the bottom of a 1920x1080 viewBox.
function trunkPath(x, baseW, topW, height, lean, sway) {
  const ground = 1086;
  const topY = ground - height;
  const lx0 = x - baseW / 2, rx0 = x + baseW / 2;
  const lx1 = x + lean - topW / 2, rx1 = x + lean + topW / 2;
  const midY = ground - height * 0.5;
  const cLx = lx0 - sway, cRx = rx0 - sway; // gentle S
  return (
    `M ${lx0.toFixed(1)} ${ground} ` +
    `C ${cLx.toFixed(1)} ${midY.toFixed(1)} ${(lx1 - sway).toFixed(1)} ${(topY + height * 0.25).toFixed(1)} ${lx1.toFixed(1)} ${topY.toFixed(1)} ` +
    `L ${rx1.toFixed(1)} ${topY.toFixed(1)} ` +
    `C ${(rx1 - sway).toFixed(1)} ${(topY + height * 0.25).toFixed(1)} ${cRx.toFixed(1)} ${midY.toFixed(1)} ${rx0.toFixed(1)} ${ground} Z`
  );
}

// Thin branch as a slim tapering quad.
function branchPath(x, y, len, ang, w) {
  const ex = x + Math.cos(ang) * len;
  const ey = y - Math.sin(ang) * len;
  const nx = Math.cos(ang + Math.PI / 2), ny = -Math.sin(ang + Math.PI / 2);
  return (
    `M ${(x + nx * w).toFixed(1)} ${(y + ny * w).toFixed(1)} ` +
    `Q ${((x + ex) / 2 - 14).toFixed(1)} ${((y + ey) / 2).toFixed(1)} ${ex.toFixed(1)} ${ey.toFixed(1)} ` +
    `Q ${((x + ex) / 2 + 14).toFixed(1)} ${((y + ey) / 2).toFixed(1)} ${(x - nx * w).toFixed(1)} ${(y - ny * w).toFixed(1)} Z`
  );
}

// Build one layer's SVG markup string.
function buildLayer({ seed, count, color, baseW, topW, hMin, hMax, fadeTop, branches, xJitter }) {
  const rnd = mulberry32(seed);
  const gid = 'g' + seed;
  let trees = '';
  for (let i = 0; i < count; i++) {
    const x = (i + 0.5) * (1920 / count) + (rnd() - 0.5) * xJitter;
    const h = hMin + rnd() * (hMax - hMin);
    const bw = baseW * (0.7 + rnd() * 0.6);
    const tw = topW * (0.7 + rnd() * 0.6);
    const lean = (rnd() - 0.5) * 60;
    const sway = (rnd() - 0.5) * 40;
    trees += `<path d="${trunkPath(x, bw, tw, h, lean, sway)}" fill="url(#${gid})"/>`;
    if (branches && rnd() > 0.35) {
      const by = 1086 - h * (0.62 + rnd() * 0.28);
      const dir = rnd() > 0.5 ? 1 : -1;
      // slender, upward-reaching limbs — gentler angle, thinner taper
      trees += `<path d="${branchPath(x + lean * 0.5, by, 150 + rnd() * 170, Math.PI / 2 + dir * (0.32 + rnd() * 0.32), bw * 0.1)}" fill="url(#${gid})"/>`;
      if (rnd() > 0.5) {
        trees += `<path d="${branchPath(x + lean * 0.5, by - 90, 110 + rnd() * 120, Math.PI / 2 - dir * (0.3 + rnd() * 0.3), bw * 0.075)}" fill="url(#${gid})"/>`;
      }
    }
  }
  return (
    `<svg viewBox="0 0 1920 1080" preserveAspectRatio="xMidYMax slice" xmlns="http://www.w3.org/2000/svg">` +
    `<defs><linearGradient id="${gid}" x1="0" y1="1" x2="0" y2="0">` +
    `<stop offset="0" stop-color="${color}" stop-opacity="1"/>` +
    `<stop offset="${(1 - fadeTop) * 0.6}" stop-color="${color}" stop-opacity="0.92"/>` +
    `<stop offset="${1 - fadeTop}" stop-color="${color}" stop-opacity="0.5"/>` +
    `<stop offset="1" stop-color="${color}" stop-opacity="0"/>` +
    `</linearGradient></defs>${trees}</svg>`
  );
}

const FOREST_LAYERS = [
  // index 1 — distant trees, dissolved into fog
  { key: 'far',  seed: 11, count: 16, color: '#26302b', baseW: 34,  topW: 12, hMin: 360, hMax: 620, fadeTop: 0.72, branches: false, xJitter: 70 },
  // index 2 — mid forest
  { key: 'mid',  seed: 27, count: 11, color: '#161e1a', baseW: 64,  topW: 20, hMin: 540, hMax: 880, fadeTop: 0.52, branches: true,  xJitter: 110 },
  // index 3 — foreground LEFT-weighted dark trunks
  { key: 'near', seed: 43, count: 6,  color: '#0a0e0c', baseW: 130, topW: 40, hMin: 820, hMax: 1140, fadeTop: 0.34, branches: true,  xJitter: 150 },
];

/* --------------------------- Forest ground (layer 4) --------------------- */
const GROUND_SVG =
  `<svg viewBox="0 0 1920 1080" preserveAspectRatio="xMidYMax slice" xmlns="http://www.w3.org/2000/svg">` +
  `<defs><linearGradient id="grd" x1="0" y1="1" x2="0" y2="0">` +
  `<stop offset="0" stop-color="#050806" stop-opacity="1"/>` +
  `<stop offset="0.5" stop-color="#050806" stop-opacity="0.95"/>` +
  `<stop offset="1" stop-color="#050806" stop-opacity="0"/></linearGradient></defs>` +
  `<path d="M0 1080 L0 920 Q 360 860 720 905 Q 1180 960 1920 880 L1920 1080 Z" fill="url(#grd)"/>` +
  // a few fern-like fronds rising from the floor edges
  `<g fill="#050806">` +
  `<path d="M120 1080 Q 90 980 150 905 Q 175 980 160 1080 Z"/>` +
  `<path d="M210 1080 Q 250 1000 215 920 Q 180 1000 195 1080 Z"/>` +
  `<path d="M1760 1080 Q 1800 985 1740 905 Q 1700 990 1720 1080 Z"/>` +
  `<path d="M1660 1080 Q 1630 995 1690 930 Q 1735 1000 1700 1080 Z"/>` +
  `</g></svg>`;

const SKY_BG =
  'radial-gradient(130% 90% at 50% 8%, #2b352f 0%, #1c2521 30%, #111714 58%, #0B0F0D 100%)';

/* ------------------------------ ForestJourney ----------------------------- */
function ForestJourney() {
  const root = useRefF(null);
  const scene = useRefF(null);
  const num1 = useRefF(null);
  const num2 = useRefF(null);

  useLayoutEffectF(() => {
    const el = root.current;
    if (!el) return;
    const q = (s) => el.querySelector(s);
    const layer = (k) => el.querySelector(`[data-layer="${k}"]`);

    if (prefersReduced) {
      gsap.set([q('.station-1')], { opacity: 1, y: 0 });
      gsap.set([q('.station-2'), q('.station-3'), q('.dark-fade')], { opacity: 0 });
      if (num1.current) num1.current.textContent = '5';
      if (num2.current) num2.current.textContent = '100';
      return;
    }

    const ctx = gsap.context(() => {
      // initial states
      gsap.set(q('.station-1'), { opacity: 1, y: 0 });
      gsap.set([q('.station-2'), q('.station-3')], { opacity: 0, y: 60 });
      gsap.set(q('.dark-fade'), { opacity: 0 });

      const tl = gsap.timeline({
        scrollTrigger: {
          trigger: el,
          start: 'top top',
          end: '+=3000',
          pin: true,
          scrub: 1,
          anticipatePin: 1,
          refreshPriority: 50,
        },
      });

      // Continuous "walking into the forest" — scale + foreground spread
      tl.to(layer('sky'),  { scale: 1.05, duration: 10 }, 0);
      tl.to(layer('far'),  { scale: 1.08, yPercent: 3, duration: 10 }, 0);
      tl.to(layer('mid'),  { scale: 1.13, yPercent: 5, duration: 10 }, 0);
      tl.to(layer('near'), { scale: 1.22, xPercent: -10, yPercent: 7, duration: 10 }, 0);
      tl.to(layer('ground'), { scale: 1.18, xPercent: 8, yPercent: 4, duration: 10 }, 0);

      // scroll hint vanishes immediately
      tl.to(q('.scroll-hint'), { opacity: 0, duration: 0.4 }, 0);

      // Station 1 out
      tl.to(q('.station-1'), { opacity: 0, y: -70, duration: 0.9, ease: 'power2.in' }, 2.5);

      // Station 2 in + counters
      tl.fromTo(q('.station-2'), { opacity: 0, y: 60 }, { opacity: 1, y: 0, duration: 0.9, ease: 'power2.out' }, 3.5);
      tl.fromTo({ v: 0 }, { v: 0 }, {
        v: 5, duration: 1.2, ease: 'power1.out',
        onUpdate() { if (num1.current) num1.current.textContent = Math.round(this.targets()[0].v); },
      }, 3.6);
      tl.fromTo({ v: 0 }, { v: 0 }, {
        v: 100, duration: 1.4, ease: 'power1.out',
        onUpdate() { if (num2.current) num2.current.textContent = Math.round(this.targets()[0].v); },
      }, 3.6);
      tl.to(q('.station-2'), { opacity: 0, y: -70, duration: 0.9, ease: 'power2.in' }, 6.1);

      // Station 3 in
      tl.fromTo(q('.station-3'), { opacity: 0, y: 60 }, { opacity: 1, y: 0, duration: 0.9, ease: 'power2.out' }, 7.0);

      // Fade to night for clean handoff into About
      tl.to(q('.dark-fade'), { opacity: 0.96, duration: 1.6, ease: 'power2.in' }, 8.2);
    }, el);

    return () => ctx.revert();
  }, []);

  return (
    <section ref={root} className="relative h-screen w-full overflow-hidden" style={{ background: SKY_BG }}>
      {/* Sky / fog base (layer 0) */}
      <div data-layer="sky" className="forest-layer" style={{ background: SKY_BG }} />
      <div data-layer="sky-fog" className="forest-layer" style={{
        background: 'radial-gradient(80% 60% at 50% 30%, rgba(232,237,233,0.10), transparent 70%)',
      }} />

      {/* Tree layers 1-3 */}
      {FOREST_LAYERS.map((L) => (
        <div
          key={L.key}
          data-layer={L.key}
          className="forest-layer"
          dangerouslySetInnerHTML={{ __html: buildLayer(L) }}
        />
      ))}

      {/* Ground / foreground (layer 4) */}
      <div data-layer="ground" className="forest-layer" dangerouslySetInnerHTML={{ __html: GROUND_SVG }} />

      {/* Animated fog + cinematic vignette */}
      <div ref={scene} className="fog-pulse" />
      <div className="vignette" />

      {/* ---- Narrative stations ---- */}
      <div className="absolute inset-0 z-20 flex items-center justify-center px-5 text-center">
        {/* Station 1 */}
        <div className="station-1 absolute max-w-[1100px] px-2">
          <h1 className="display-heading" style={{ fontSize: 'clamp(3rem, 11vw, 11rem)' }}>
            Mathys Da&nbsp;Cunha
          </h1>
          <p className="mx-auto mt-6 max-w-[640px] font-light uppercase tracking-[0.18em] text-bone/85"
             style={{ fontSize: 'clamp(0.78rem, 1.7vw, 1.15rem)', lineHeight: 1.6 }}>
            Développeur Full Stack — je conçois des produits web rapides, soignés et propulsés par l'IA.
          </p>
        </div>

        {/* Station 2 — stats */}
        <div className="station-2 absolute w-full max-w-[1100px]">
          <div className="grid grid-cols-1 gap-12 sm:grid-cols-3 sm:gap-6">
            <div>
              <div className="stat-num" style={{ fontSize: 'clamp(2.5rem, 7vw, 6rem)' }}>
                <span ref={num1}>0</span>+
              </div>
              <div className="mt-3 text-xs md:text-sm uppercase tracking-[0.25em] text-bone/70">Années d'expérience</div>
            </div>
            <div>
              <div className="stat-num" style={{ fontSize: 'clamp(2.5rem, 7vw, 6rem)' }}>
                <span ref={num2}>0</span>%
              </div>
              <div className="mt-3 text-xs md:text-sm uppercase tracking-[0.25em] text-bone/70">Full stack</div>
            </div>
            <div>
              <div className="stat-num" style={{ fontSize: 'clamp(2.5rem, 7vw, 6rem)' }}>IA</div>
              <div className="mt-3 text-xs md:text-sm uppercase tracking-[0.25em] text-bone/70">Intégrée</div>
            </div>
          </div>
        </div>

        {/* Station 3 — transition */}
        <div className="station-3 absolute max-w-[820px] px-2">
          <p className="font-light text-bone" style={{ fontSize: 'clamp(1.6rem, 5vw, 3.6rem)', lineHeight: 1.2 }}>
            Sortons de la forêt.<br />
            <span className="text-sage">Voici ce que je construis.</span>
          </p>
        </div>
      </div>

      {/* Scroll hint */}
      <div className="scroll-hint absolute bottom-8 left-1/2 z-20 -translate-x-1/2 flex flex-col items-center gap-2 text-bone/70">
        <span className="text-[0.65rem] uppercase tracking-[0.4em]">Scroll</span>
        <ChevronDown size={20} className="bounce-soft" />
      </div>

      {/* Night fade for handoff into About */}
      <div className="dark-fade absolute inset-0 z-30 bg-night" />
    </section>
  );
}

Object.assign(window, { ForestJourney });
