/* global React */
/* ============================================================
   MYTHOS HOME — the orchard season told as a chaptered record.
   Prologue → Chapters I–IV (the layers) → Chapter V (the
   prescription) → The Instruments → The Ledger → Epilogue.
   Same facts as the original home; new voice and structure.
   ============================================================ */
const { useEffect } = React;

const MYTH_CHAPTERS = [
  {
    numeral: 'I', glyph: 'soil', phase: 'Chapter I · The Soil', tool: 'emi', toolLabel: 'EMI Soil Scanning',
    title: <>Where the story <em>begins</em>.</>,
    copy: 'Before a single tree is judged, electromagnetic induction reads the ground itself — soil conductivity at 25, 50 and 90 cm. Clay, moisture and structure: the terms every root must accept, mapped at 5×5 m.',
    ramp: 'linear-gradient(90deg,#FFF7EC,#F6C68A,#E08A3C,#B5651D,#6B3410)',
    img: 'assets/home-block-ec.png',
    aspect: '679 / 548',
    caption: ['Plate I — Soil EC · Block 110', '8 zones · 18.9–22.8 mS/m'],
    alt: 'Soil EC zone map of Block 110 — orange conductivity ramp, eight zones over the orchard footprint',
  },
  {
    numeral: 'II', glyph: 'canopy', phase: 'Chapter II · The Canopy', tool: 'revtoolbox', toolLabel: 'RevToolbox & Satellite',
    title: <>How each tree <em>answers</em>.</>,
    copy: 'Canopy vigour every few days across the season, read from above. Four years of NDVI history at 10 m, sharpened to 0.5 m on demand — the same ground, retold in green.',
    ramp: 'linear-gradient(90deg,#F2F8EC,#B7D89A,#6FA84C,#2F7A2E,#14532D)',
    img: 'assets/home-block-vigour.png',
    aspect: '679 / 548',
    caption: ['Plate II — Canopy NDVI · Block 110', '8 zones · 0.33–0.59 idx'],
    alt: 'Canopy vigour zone map of the same block — green NDVI ramp, eight zones',
  },
  {
    numeral: 'III', glyph: 'fruit', phase: 'Chapter III · The Fruit', tool: 'revscout-s', toolLabel: 'RevScout S',
    title: <>What the season <em>carries</em>.</>,
    copy: 'RevScout S stereo-sizes every fruit on every tree as it drives the row. Mean diameter lands per tree, mapped straight to GPS — the block again, this time in millimetres.',
    ramp: 'linear-gradient(90deg,#A50026,#F46D43,#FEE08B,#A6D96A,#1A9850)',
    img: 'assets/home-block-fruitsize.png',
    aspect: '679 / 548',
    caption: ['Plate III — Mean diameter · Block 110', '8 zones · 57–65 mm'],
    alt: 'Fruit size zone map of the same block — eight zones, 57 to 65 mm',
  },
  {
    numeral: 'IV', glyph: 'yield', phase: 'Chapter IV · The Yield', tool: 'revscout-s', toolLabel: 'RevScout S',
    title: <>What the ground <em>pays back</em>.</>,
    copy: 'Count times size becomes modelled yield, mapped tree by tree — the top of the stack, where the soil signal at the very bottom finally shows its return.',
    ramp: 'linear-gradient(90deg,#A50026,#F46D43,#FEE08B,#A6D96A,#1A9850)',
    img: 'assets/home-block-yield.png',
    aspect: '679 / 548',
    caption: ['Plate IV — Modelled yield · Block 110', '8 zones · 65–152'],
    alt: 'Yield zone map of the same block — red-to-green ramp, eight zones',
  },
];

const MYTH_INSTRUMENTS = [
  {
    num: 'Instrument 01', glyph: 'soil', route: 'emi', title: <>EMI Soil <em>Scanning</em></>,
    role: 'The foundation',
    copy: 'Soil conductivity at three depths, 16,000 readings per block. It tells you where to put the chemistry sample — not the other way round.',
  },
  {
    num: 'Instrument 02', glyph: 'prescription', route: 'revtoolbox', title: <>Rev<em>Toolbox</em></>,
    role: 'The record-keeper',
    copy: 'Every layer converges in one portal — soil, satellite, fruit and calibration — and leaves as a prescription file for Trimble, John Deere and AGCO.',
  },
  {
    num: 'Instrument 03', glyph: 'fruit', route: 'revscout-s', title: <>RevScout <em>S</em></>,
    role: 'The witness',
    copy: 'An AI field camera that counts and sizes every fruit on every tree in a single drive. ±1 mm; R² = 0.94 against actual harvest after calibration.',
  },
  {
    num: 'Instrument 04', glyph: 'caliper', route: 'revsizer', title: <>Rev-<em>Sizer</em></>,
    role: 'The measure',
    copy: 'A banded-trigger caliper reading fruit on the tree to 0.5 mm — no picking, 3,000 fruit a day, growth curves that predict harvest size by market class.',
  },
  {
    num: 'Instrument 05', glyph: 'pin', route: 'revfield', title: <>Rev<em>Field</em></>,
    role: 'The scout',
    copy: 'Offline scouting on a phone: GPS-tagged pins for pests, disease and irrigation trouble, synced to the portal — and ground-truth for the camera.',
  },
  {
    num: 'Instrument 06', glyph: 'wheel', route: 'optimize', title: <>The Go-to <em>Guide</em></>,
    role: 'The almanac',
    copy: 'Dormancy to post-harvest — which question matters at each stage of the cycle, and which layer answers it.',
  },
];

window.MythosHomePage = function MythosHomePage({ setRoute, heroMedia, mode }) {
  // Reveal fallback — guarantees [data-reveal] content appears on scroll
  useEffect(() => {
    const reveal = () => {
      const vh = window.innerHeight || 800;
      document.querySelectorAll('[data-reveal]:not(.is-revealed)').forEach(el => {
        if (el.getBoundingClientRect().top < vh * 0.92) el.classList.add('is-revealed');
      });
    };
    reveal();
    window.addEventListener('scroll', reveal, { passive: true });
    window.addEventListener('resize', reveal);
    const t = setTimeout(reveal, 200);
    return () => {
      window.removeEventListener('scroll', reveal);
      window.removeEventListener('resize', reveal);
      clearTimeout(t);
    };
  }, []);

  const goChapter = (i) => {
    const el = document.getElementById('myth-ch-' + i);
    if (el) {
      const y = el.getBoundingClientRect().top + window.scrollY - 90;
      window.scrollTo({ top: y, behavior: 'smooth' });
    }
  };

  return (
    <main data-screen-label="Mythos Home">
      {/* ===== PROLOGUE — the Block 110 scroll-driven 3D hero ===== */}
      {heroMedia === 'block110' ? (
        <section data-screen-label="Prologue hero — Block 110 3D">
          <window.HeroBlock110V3
            skin={mode === 'dark' ? 'dark' : 'light'}
            key={'b110-' + mode}
            title="Every orchard is a story"
            sub="written in the soil."
            meta="WESTERN CAPE · SEASON 2025–26 · SOIL TO FRUIT · TREE BY TREE" />
        </section>
      ) : (
      <section className="myth-hero" data-screen-label="Prologue hero">
        <div className="myth-hero-media" aria-hidden="true">
          {heroMedia === 'still' ? (
            <div className="myth-hero-still" style={{ backgroundImage: "url('assets/farm-overview-aerial.png')" }}></div>
          ) : (
            <video src="assets/home-hero-field.mp4" autoPlay muted loop playsInline preload="auto"
              ref={(el) => { if (el) { try { el.muted = true; el.volume = 0; el.play().catch(() => {}); } catch (_) {} } }}>
            </video>
          )}
        </div>
        <div className="myth-hero-scrim" aria-hidden="true"></div>
        <div className="myth-hero-content">
          <div className="myth-kicker">Revolute Systems · Stellenbosch · 33°55′S</div>
          <h1>Every orchard is a story <em>written in the soil</em>.</h1>
          <p className="myth-hero-sub">
            We read it — soil, canopy, fruit and yield, layer by layer — and write the
            next chapter as a prescription your spreader runs, tree by tree.
          </p>
          <div className="myth-hero-actions">
            <a className="myth-btn myth-btn-primary" href="#" onClick={(e) => { e.preventDefault(); setRoute('contact'); }}>Begin the reading →</a>
            <button className="myth-btn myth-btn-ghost" onClick={() => goChapter(0)}>The chapters ↓</button>
          </div>
        </div>
      </section>
      )}

      {/* ===== TABLE OF CONTENTS ===== */}
      <div className="myth-toc" data-screen-label="Chapter index">
        <div className="myth-toc-inner">
          {['The Soil', 'The Canopy', 'The Fruit', 'The Yield'].map((label, i) => (
            <button key={label} className="myth-toc-item" onClick={() => goChapter(i)}>
              <span className="myth-toc-num">{MYTH_CHAPTERS[i].numeral}.</span>
              <span className="myth-toc-label">{label}</span>
            </button>
          ))}
          <button className="myth-toc-item" onClick={() => goChapter(4)}>
            <span className="myth-toc-num">V.</span>
            <span className="myth-toc-label">The Prescription</span>
          </button>
        </div>
      </div>

      {/* ===== CHAPTERS I–IV ===== */}
      <section className="myth-section" data-screen-label="Chapters I–IV">
        <div className="myth-container">
          <div className="myth-section-head" data-reveal>
            <window.MythDivider />
            <div className="myth-kicker" style={{ justifyContent: 'center' }}>One block · read four ways</div>
            <h2>Block 110, told <em>from the soil up</em>.</h2>
            <p>
              A single orchard block, scanned the way we scan every block. Each chapter is the
              same ground, measured again — aligned, stacked, and finally turned into one decision.
            </p>
          </div>

          {MYTH_CHAPTERS.map((ch, i) => (
            <div key={ch.numeral} id={'myth-ch-' + i} className={'myth-chapter' + (i % 2 === 1 ? ' flip' : '')} data-reveal>
              <div className="myth-chapter-numeral" aria-hidden="true">{ch.numeral}</div>
              <div className="myth-chapter-text">
                <div className="myth-chapter-glyph"><window.MythGlyph kind={ch.glyph} /></div>
                <div className="myth-chapter-phase">{ch.phase}</div>
                <h3>{ch.title}</h3>
                <p>{ch.copy}</p>
                <div className="myth-ramp" style={{ background: ch.ramp, maxWidth: 360 }} aria-hidden="true"></div>
                <div className="myth-chapter-foot">
                  <button className="myth-chapter-link" onClick={() => setRoute(ch.tool)}>{ch.toolLabel} →</button>
                </div>
              </div>
              <div className="myth-plate">
                <div className="myth-plate-frame">
                  <div className="myth-plate-img">
                    <div className="myth-plate-visual" role="img" aria-label={ch.alt}
                      data-img-file={ch.img}
                      style={{ backgroundImage: "url('" + ch.img + "')", aspectRatio: ch.aspect, backgroundColor: '#0d140c' }}></div>
                  </div>
                </div>
                <div className="myth-plate-caption">
                  <strong>{ch.caption[0]}</strong>
                  <span>{ch.caption[1]}</span>
                </div>
              </div>
            </div>
          ))}

          {/* The forecast — the thread points forward */}
          <div className="myth-chapter" data-reveal>
            <div className="myth-chapter-numeral" aria-hidden="true">＊</div>
            <div className="myth-chapter-text">
              <div className="myth-chapter-glyph"><window.MythGlyph kind="forecast" /></div>
              <div className="myth-chapter-phase">Interlude · The Forecast</div>
              <h3>And where it is all <em>heading</em>.</h3>
              <p>
                Weekly caliper and camera readings build a growth curve per season. Plotted on
                days-after-bloom, this season sits against last — and the dashed projection lands
                a final harvest size weeks before the pick.
              </p>
              <div className="myth-chapter-foot">
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, letterSpacing: '0.14em', color: 'var(--muted)' }}>
                  FUJI SUPREMA · 2025 → 71.0 MM · 2026 → 66.5 MM
                </span>
                <button className="myth-chapter-link" onClick={() => setRoute('revsizer')}>Rev-Sizer &amp; RevSizing →</button>
              </div>
            </div>
            <div className="myth-plate">
              <div className="myth-plate-frame">
                <div className="myth-plate-img">
                  <div className="myth-plate-visual" role="img"
                    aria-label="Fruit size timeseries — two seasons plotted on days-after-bloom with dashed harvest-size projections"
                    data-img-file="assets/home-block-fruitsize-graph.png"
                    style={{ backgroundImage: "url('assets/home-block-fruitsize-graph.png')", aspectRatio: '1019 / 652', backgroundColor: '#fff', backgroundSize: 'contain', backgroundRepeat: 'no-repeat', backgroundPosition: 'center' }}></div>
                </div>
              </div>
              <div className="myth-plate-caption">
                <strong>Figure — Growth curves · Block 110</strong>
                <span>Two seasons · days after bloom</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* ===== CHAPTER V — THE PRESCRIPTION ===== */}
      <section className="myth-prescription" id="myth-ch-4" data-screen-label="Chapter V — The Prescription">
        <div className="myth-container">
          <div className="myth-prescription-grid">
            <div data-reveal>
              <div className="myth-chapter-glyph"><window.MythGlyph kind="prescription" /></div>
              <div className="myth-chapter-phase">Chapter V · The Prescription</div>
              <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 'clamp(36px, 4vw, 56px)', lineHeight: 1.06, color: 'var(--charcoal)', margin: '0 0 18px', textWrap: 'balance' }}>
                The story writes <em style={{ fontStyle: 'italic', fontWeight: 400, color: 'var(--myth-lumen)' }}>back</em>.
              </h2>
              <p style={{ fontSize: 15.5, lineHeight: 1.75, color: 'var(--muted)', maxWidth: 480, margin: 0, textWrap: 'pretty' }}>
                The stack you just read becomes a prescription map. Vigorous trees get less,
                weak trees get more — the spreader follows it row by row, and the block evens
                out by next season. Exported for Trimble, John Deere, AGCO and Google Earth,
                straight from the portal.
              </p>
              <div className="myth-stat-pair" data-reveal>
                <div className="myth-stat">
                  <div className="myth-stat-num">−18%</div>
                  <span className="myth-stat-lab">Nitrogen use · avg reduction</span>
                </div>
                <div className="myth-stat">
                  <div className="myth-stat-num">+24%</div>
                  <span className="myth-stat-lab">Yield uniformity</span>
                </div>
              </div>
              <div className="myth-chapter-foot">
                <button className="myth-chapter-link" onClick={() => setRoute('revtoolbox')}>RevToolbox &amp; prescriptions →</button>
              </div>
            </div>
            <div className="myth-plate" data-reveal>
              <div className="myth-plate-frame">
                <div className="myth-plate-img">
                  <div className="myth-plate-visual" role="img"
                    aria-label="High-resolution canopy vigour driving a variable-rate prescription map"
                    data-img-file="assets/vigour-hr-prescription.png"
                    style={{ backgroundImage: "url('assets/vigour-hr-prescription.png')", aspectRatio: '16 / 10' }}></div>
                </div>
              </div>
              <div className="myth-plate-caption">
                <strong>Plate V — Variable-rate prescription</strong>
                <span>Nitrogen by tree, not by block</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* ===== THE INSTRUMENTS ===== */}
      <section className="myth-section" data-screen-label="The Instruments">
        <div className="myth-container">
          <div className="myth-section-head" data-reveal>
            <window.MythDivider />
            <div className="myth-kicker" style={{ justifyContent: 'center' }}>The Instruments</div>
            <h2>Six ways of <em>reading</em>.</h2>
            <p>Each instrument reads a different layer of the same ground. Together they keep one record — RevToolbox — and one record keeps the whole farm honest.</p>
          </div>
          <div className="myth-instruments" data-reveal>
            {MYTH_INSTRUMENTS.map((ins) => (
              <button key={ins.num} className="myth-instrument" onClick={() => setRoute(ins.route)}
                aria-label={ins.num + ' — open page'}>
                <window.MythGlyph kind={ins.glyph} size={40} />
                <span className="myth-instrument-num">{ins.num}</span>
                <h3>{ins.title}</h3>
                <span className="myth-instrument-role">{ins.role}</span>
                <p>{ins.copy}</p>
                <span className="myth-instrument-go">Read more →</span>
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* ===== THE LEDGER ===== */}
      <section className="myth-ledger" data-screen-label="The Ledger">
        <div className="myth-container">
          <div className="myth-section-head" data-reveal style={{ marginBottom: 0 }}>
            <window.MythDivider />
            <div className="myth-kicker" style={{ justifyContent: 'center' }}>The Ledger · Orange River · 5 seasons</div>
            <h2>The record, <em>audited</em>.</h2>
            <p>
              Eight table-grape farms, 301 hectares of alluvial soils, 954 zone-level chemistry
              samples over five years. Precision zonal soil management against blanket application —
              the ledger balances in precision's favour on every farm.
            </p>
          </div>
          <div className="myth-ledger-grid" data-reveal>
            <div className="myth-ledger-cell">
              <div className="myth-ledger-num">R<em>5.0</em>M</div>
              <span className="myth-ledger-lab">Misallocated amendments avoided</span>
            </div>
            <div className="myth-ledger-cell">
              <div className="myth-ledger-num"><em>9.1</em>×</div>
              <span className="myth-ledger-lab">Return on scanning &amp; sampling spend</span>
            </div>
            <div className="myth-ledger-cell">
              <div className="myth-ledger-num">954</div>
              <span className="myth-ledger-lab">Zone-level soil samples · 5 years</span>
            </div>
            <div className="myth-ledger-cell">
              <div className="myth-ledger-num">≥<em>2.1</em>×</div>
              <span className="myth-ledger-lab">Worst-case return · every farm</span>
            </div>
          </div>
          <div style={{ textAlign: 'center', marginTop: 36 }} data-reveal>
            <button className="myth-chapter-link" onClick={() => setRoute('case-study')}>Read the full ledger →</button>
          </div>
        </div>
      </section>

      {/* ===== EPILOGUE ===== */}
      <section className="myth-epilogue" data-screen-label="Epilogue CTA" data-reveal>
        <window.MythDivider />
        <div className="myth-kicker" style={{ justifyContent: 'center' }}>Epilogue</div>
        <h2>Your blocks have a story. <em>We'll read it back to you.</em></h2>
        <p>
          Book a 30-minute walk-through with one of our agronomists. We load your farm into
          RevToolbox and read it layer by layer — soil, canopy and fruit. The first
          conversation is free.
        </p>
        <div className="myth-hero-actions">
          <a className="myth-btn myth-btn-primary" href="#" onClick={(e) => { e.preventDefault(); setRoute('contact'); }}>Book a demo →</a>
          <a className="myth-btn myth-btn-ghost" href="#" onClick={(e) => { e.preventDefault(); setRoute('pricing'); }}>See pricing</a>
        </div>
      </section>
    </main>
  );
};
