/* global React */
/* ============================================================
   OptimizePage v2 — Phenological cycle navigation.
   Hero: block-development arrow flowing into a 3D phenological wheel.
   Centre: practice card for the active stage.
   Below: data-service Gantt strip across stages.
   ============================================================ */

(function () {
  const { useState, useRef, useEffect } = React;

  // ---- PRACTICE DATA --------------------------------------------
  // Each stage has: practices (verbs the grower does), and which data
  // services power each practice.
  // Data service ids: emi, ndvi, scout, sizer, toolbox, probe
  const PRACTICES = {
    dormancy: [
    { name: 'Block development', services: ['emi', 'toolbox'] },
    { name: 'EMI soil scan', services: ['emi', 'toolbox'] },
    { name: 'Zonal soil sampling', services: ['emi', 'toolbox'] },
    { name: 'Drainage / structure decisions', services: ['emi', 'toolbox'] },
    { name: 'Probe placement plan', services: ['emi', 'probe'] },
    { name: 'Variable-rate lime / gypsum', services: ['emi', 'toolbox'] }],

    budbreak: [
    { name: 'Bud-break uniformity check', services: ['ndvi'] },
    { name: 'Early canopy vigour read', services: ['ndvi'] },
    { name: 'Bud-break VRA mapping', services: ['ndvi', 'toolbox'] },
    { name: 'First-pass irrigation tuning', services: ['probe', 'ndvi'] }],

    flowering: [
    { name: 'Blossom density mapping', services: ['scout', 'toolbox'] },
    { name: 'Google Earth field calibration', services: ['scout', 'toolbox'] },
    { name: 'VRA flower-thinning spray', services: ['scout', 'toolbox'] }],

    fruitset: [
    { name: 'Early counts + thinning guidance', services: ['scout', 'revfield'] },
    { name: 'In-season NDVI VRA mapping', services: ['ndvi', 'toolbox'] },
    { name: 'Irrigation block monitoring', services: ['ndvi', 'probe'] }],

    celldivision: [
    { name: 'Fruit size monitoring', services: ['scout', 'sizer'] },
    { name: 'Fruit size growth increments', services: ['sizer', 'probe'] },
    { name: 'Variable-rate K application', services: ['toolbox', 'emi'] },
    { name: 'Targeted leaf sampling', services: ['ndvi', 'toolbox'] }],

    cellexpansion: [
    { name: 'Weekly fruit size measurements', services: ['sizer', 'probe'] },
    { name: 'Canopy stress monitoring', services: ['ndvi', 'probe'] },
    { name: 'Late thinning correction', services: ['scout', 'toolbox'] }],

    veraison: [
    { name: 'Sugar / colour development', services: ['ndvi', 'toolbox'] },
    { name: 'Harvest planning', services: ['toolbox', 'sizer'] },
    { name: 'Precision sprays', services: ['toolbox', 'ndvi'] }],

    harvest: [
    { name: 'Zonal harvesting', services: ['ndvi', 'toolbox'] },
    { name: 'Pre-harvest scan for bin planning', services: ['scout', 'toolbox'] },
    { name: 'Post-harvest VRA N \u0026 K', services: ['toolbox', 'ndvi'] }]

  };

  // Data services metadata
  const DATA_SERVICES = {
    emi: { id: 'emi', name: 'EMI soil scan', short: 'EMI', route: 'services', color: '#A89060' },
    ndvi: { id: 'ndvi', name: 'NDVI canopy', short: 'NDVI', route: 'services', color: '#7BA644' },
    scout: { id: 'scout', name: 'RevScout', short: 'Scout', route: 'revscout-s', color: '#B8DC73' },
    sizer: { id: 'sizer', name: 'Rev-Sizer', short: 'Sizer', route: 'revscout-s', color: '#83B535' },
    toolbox: { id: 'toolbox', name: 'RevToolbox', short: 'Toolbox', route: 'services', color: '#5C7E2C' },
    probe: { id: 'probe', name: 'Probe data', short: 'Probe', route: 'services', color: '#3F5F1F' },
    revfield: { id: 'revfield', name: 'RevField', short: 'RevField', route: 'revfield', color: '#6E8A3A' }
  };

  // Which stages each service is "active" through (Gantt strip below)
  // Index map (0..8): dormancy, budbreak, flowering, fruitset, celldivision, cellexpansion, veraison, harvest, postharvest
  const SERVICE_RANGES = {
    emi: [{ from: 0, to: 0, intensity: 1 }, { from: 7, to: 7, intensity: 0.8 }],
    ndvi: [{ from: 1, to: 7, intensity: 1 }],
    scout: [{ from: 2, to: 5, intensity: 1 }, { from: 7, to: 7, intensity: 0.7 }],
    sizer: [{ from: 4, to: 6, intensity: 0.6 }, { from: 5, to: 6, intensity: 1 }],
    toolbox: [{ from: 0, to: 7, intensity: 0.7 }],
    probe: [{ from: 1, to: 7, intensity: 0.85 }, { from: 0, to: 0, intensity: 0.4 }]
  };

  // Block-development steps (pre-cycle, one-time)
  const BLOCK_DEV = [
  { tag: '01', label: 'Site selection', note: 'EMI before you plant' },
  { tag: '02', label: 'Soil prep', note: 'Lime · Gypsum · Drainage' },
  { tag: '03', label: 'Cultivar / rootstock', note: 'Match to soil class' },
  { tag: '04', label: 'Planting & trellis', note: 'Row direction by EC' },
  { tag: '05', label: 'First 2 yrs · canopy', note: 'Establish, monitor, refine' }];


  // ---- COMPONENT ------------------------------------------------
  window.OptimizePage = function OptimizePage({ setRoute }) {
    const [activeStage, setActiveStage] = useState(window.PHENOLOGICAL_STAGES?.[0] || { id: 'dormancy', label: 'Dormancy' });
    const [expandedPractice, setExpandedPractice] = useState(null); // practice.name or null
    const wheelRef = useRef(null);
    const detailRef = useRef(null);

    function go(routeId) {
      if (routeId === 'case-study') setRoute('case-study');else
      setRoute(routeId);
    }

    const stagePractices = PRACTICES[activeStage.id] || [];
    const expandedData = expandedPractice ?
    window.PRACTICE_CONTENT?.[expandedPractice] || null :
    null;
    const expandedSpec = expandedPractice ?
    stagePractices.find((p) => p.name === expandedPractice) :
    null;

    // When stage changes, collapse any expanded practice
    function handleStageChange(stage) {
      setActiveStage(stage);
      setExpandedPractice(null);
    }

    // When stage is "activated" (clicked twice on wheel) → open first practice
    function handleStageActivate(stage) {
      setActiveStage(stage);
      const list = PRACTICES[stage.id] || [];
      if (list.length > 0) setExpandedPractice(list[0].name);
    }

    // Scroll detail into view when it opens
    useEffect(() => {
      if (expandedPractice && detailRef.current) {
        const el = detailRef.current;
        const rect = el.getBoundingClientRect();
        const targetTop = window.scrollY + rect.top - 80;
        window.scrollTo({ top: targetTop, behavior: 'smooth' });
      }
    }, [expandedPractice]);

    return (
      <>
        {/* HEADER */}
        <header className="page-head" style={{ paddingBottom: 'var(--space-2)' }}>
          <div className="container-wide">
            <div className="crumbs">
              <a href="#" onClick={(e) => {e.preventDefault();setRoute('home');}}>Home</a>
              <span>/</span>
              <a href="#" onClick={(e) => {e.preventDefault();setRoute('revscout-s');}}>Tools</a>
              <span>/</span>
              <span>Precision Go-to Guide</span>
            </div>
            <h1>The orchard runs in <em>cycles.</em></h1>
            <p className="lede">
              Every fruit crop moves through the same arc — dormancy, bud break, set, sizing, harvest, recovery — and at each stage a different question matters most. The wheel below is how Revolute organises the work: pick the stage your orchard is in, and we'll show you what to do, what data drives it, and which of our services to lean on.
            </p>
          </div>
        </header>

        {/* HERO — block-development arrow + 3D wheel */}
        <section className="section opt-hero" style={{ paddingTop: 'var(--space-3)' }}>
          <div className="container-wide">
            <div className="opt-hero-grid">

              {/* The wheel */}
              <div className="phw-col">
                {window.AppleTreeBackground &&
                <window.AppleTreeBackground
                  stageIndex={window.PHENOLOGICAL_STAGES.findIndex((s) => s.id === activeStage.id)} />

                }
                {/* Stage photo behind the ring's inner disc — fades between stages */}
                <div className="phw-photo-disc" aria-hidden="true">
                  {window.PHENOLOGICAL_STAGES.map((s) =>
                  <div
                    key={s.id}
                    className={'phw-photo-disc-img' + (s.id === activeStage.id ? ' is-active' : '')}
                    style={{ backgroundImage: `url("${s.photo}")` }} />

                  )}
                  <div className="phw-photo-disc-vignette" />
                </div>
                <window.PhenologicalWheel
                  ref={wheelRef}
                  onStageChange={handleStageChange}
                  onStageActivate={handleStageActivate}
                  initialStage={0} />
                
              </div>
            </div>
          </div>
        </section>

        {/* PRACTICE CARD — for the active stage */}
        <section className="section warm" style={{ paddingTop: 'var(--space-4)' }}>
          <div className="container-wide">
            <div className="opt-stage-card">
              {/* Stage header */}
              <div className="opt-stage-head">
                {activeStage.photo &&
                <div className="opt-stage-hero" key={activeStage.id}>
                    <img src={activeStage.photo} alt="" />
                    <div className="opt-stage-hero-badge">
                      {String(window.PHENOLOGICAL_STAGES?.findIndex((s) => s.id === activeStage.id) + 1).padStart(2, '0')}
                    </div>
                  </div>
                }
                <div className="opt-stage-head-text">
                  <div className="opt-stage-eyebrow">
                    Active stage · {String(window.PHENOLOGICAL_STAGES?.findIndex((s) => s.id === activeStage.id) + 1).padStart(2, '0')} of 08
                  </div>
                  <h2 className="opt-stage-title">
                    {activeStage.label}
                    <span className="opt-stage-sub">— {activeStage.sub}</span>
                  </h2>
                  <p className="opt-stage-blurb">{activeStage.blurb}</p>
                </div>
                <div className="opt-stage-nav">
                  <button type="button" className="opt-stage-nav-btn"
                  onClick={() => {
                    const idx = window.PHENOLOGICAL_STAGES.findIndex((s) => s.id === activeStage.id);
                    const prev = (idx - 1 + 8) % 8;
                    wheelRef.current?.snapTo(prev);
                    setExpandedPractice(null);
                  }}
                  aria-label="Previous stage">←</button>
                  <button type="button" className="opt-stage-nav-btn"
                  onClick={() => {
                    const idx = window.PHENOLOGICAL_STAGES.findIndex((s) => s.id === activeStage.id);
                    const next = (idx + 1) % 8;
                    wheelRef.current?.snapTo(next);
                    setExpandedPractice(null);
                  }}
                  aria-label="Next stage">→</button>
                </div>
              </div>

              {/* Practices list — always visible */}
              <div className="opt-stage-body">
                <div className="opt-stage-bodyhead">
                  <div className="opt-stage-bodyhead-eyebrow">Agronomic practices we help with at this stage</div>
                  <div className="opt-stage-bodyhead-count">
                    {stagePractices.length} {stagePractices.length === 1 ? 'practice' : 'practices'} · click any to expand
                  </div>
                </div>

                <div className="opt-practices">
                  {stagePractices.map((p, i) => {
                    const hasDetail = !!window.PRACTICE_CONTENT?.[p.name];
                    const isOpen = expandedPractice === p.name;
                    return (
                      <button
                        key={p.name}
                        type="button"
                        className={`opt-practice opt-practice-btn ${hasDetail ? 'has-detail' : ''} ${isOpen ? 'is-open' : ''}`}
                        onClick={() => hasDetail && setExpandedPractice(isOpen ? null : p.name)}
                        disabled={!hasDetail}>
                        
                        <div className="opt-practice-num">{(i + 1).toString().padStart(2, '0')}</div>
                        <div className="opt-practice-body">
                          <div className="opt-practice-name">
                            {p.name}
                            {hasDetail && <span className="opt-practice-arrow" aria-hidden="true">→</span>}
                          </div>
                          <div className="opt-practice-services">
                            {p.services.map((svId) => {
                              const sv = DATA_SERVICES[svId];
                              return (
                                <span key={svId}
                                className="opt-practice-chip"
                                style={{ '--chip-accent': sv.color }}>
                                  <span className="opt-practice-chip-dot" style={{ background: sv.color }}></span>
                                  {sv.short}
                                </span>);

                            })}
                          </div>
                        </div>
                      </button>);

                  })}
                </div>
              </div>

              {/* Practice detail — slide-in side panel */}
              {expandedPractice && expandedData && expandedSpec &&
              <>
                  <div
                  className="opt-detail-backdrop"
                  onClick={() => setExpandedPractice(null)}
                  aria-hidden="true" />
                
                  <aside className="opt-detail-panel" ref={detailRef}
                role="dialog"
                aria-label={`${expandedPractice} — practice detail`}>

                    {/* Close button */}
                    <button
                    type="button"
                    className="opt-detail-close"
                    onClick={() => setExpandedPractice(null)}
                    aria-label="Close practice detail">
                      <span aria-hidden="true">×</span>
                    </button>

                    <div className="opt-detail-scroll">
                      {/* Top: stage chip + pager */}
                      <div className="opt-detail-topbar">
                        <button
                        type="button"
                        className="opt-detail-stagechip"
                        onClick={() => setExpandedPractice(null)}>
                          <span aria-hidden="true">←</span>
                          <span>{activeStage.label}</span>
                        </button>
                        <div className="opt-detail-pager">
                          {(() => {
                          const idx = stagePractices.findIndex((p) => p.name === expandedPractice);
                          const prev = stagePractices[(idx - 1 + stagePractices.length) % stagePractices.length];
                          const next = stagePractices[(idx + 1) % stagePractices.length];
                          return (
                            <>
                                <button type="button" className="opt-stage-nav-btn opt-stage-nav-btn-sm"
                              title={`Previous: ${prev.name}`}
                              onClick={() => { setExpandedPractice(prev.name); detailRef.current?.scrollTo(0, 0); }}
                              aria-label="Previous practice">←</button>
                                <div className="opt-detail-pager-counter">
                                  {String(idx + 1).padStart(2, '0')} / {String(stagePractices.length).padStart(2, '0')}
                                </div>
                                <button type="button" className="opt-stage-nav-btn opt-stage-nav-btn-sm"
                              title={`Next: ${next.name}`}
                              onClick={() => { setExpandedPractice(next.name); detailRef.current?.scrollTo(0, 0); }}>→</button>
                              </>);

                        })()}
                        </div>
                      </div>

                      {/* Detail header */}
                      <div className="opt-detail-head">
                        <div className="opt-detail-eyebrow">
                          Practice
                          {expandedData.timing && <span> · {expandedData.timing}</span>}
                        </div>
                        <h3 className="opt-detail-title">{expandedPractice}</h3>
                        <div className="opt-detail-services">
                          <span className="opt-detail-services-label">Powered by</span>
                          {(expandedData.services || expandedSpec.services).map((svId) => {
                          const sv = DATA_SERVICES[svId];
                          return (
                            <button key={svId} type="button"
                            className="opt-practice-chip is-link"
                            onClick={() => go(sv.route)}
                            style={{ '--chip-accent': sv.color }}>
                                <span className="opt-practice-chip-dot" style={{ background: sv.color }}></span>
                                {sv.name}
                              </button>);

                        })}
                        </div>
                      </div>

                      {/* Body — single column inside panel */}
                      <div className="opt-detail-block">
                        <div className="opt-detail-block-eyebrow">The problem</div>
                        <p className="opt-detail-problem-text">{expandedData.problem}</p>
                      </div>

                      <div className="opt-detail-block">
                        <div className="opt-detail-block-eyebrow">The Revolute method</div>
                        <ol className="opt-detail-steps">
                          {expandedData.method.map((step, i) =>
                        <li key={i} className="opt-detail-step">
                              <span className="opt-detail-step-num">{String(i + 1).padStart(2, '0')}</span>
                              <div>
                                <div className="opt-detail-step-h">{step.h}</div>
                                <div className="opt-detail-step-t">{step.t}</div>
                              </div>
                            </li>
                        )}
                        </ol>
                      </div>

                      {/* Imagery */}
                      {expandedData.imagery && expandedData.imagery.length > 0 &&
                    <div className="opt-detail-block">
                          <div className="opt-detail-block-eyebrow">In the field</div>
                          <div className="opt-detail-imggrid panel-stack">
                            {expandedData.imagery.map((im, i) =>
                        <figure key={i}
                        data-img-file={im.src || undefined}
                        data-img-placeholder={im.src ? undefined : 'true'}
                        className={`opt-detail-img ${im.type === 'placeholder' ? 'is-placeholder' : ''} ${im.type === 'data' ? 'is-data' : ''}`}>
                                <div className="opt-detail-img-imgwrap"
                          style={{ aspectRatio: im.ratio || '16/10' }}>
                                  {im.src ?
                            <img src={im.src} alt={im.caption || ''} loading="lazy" style={im.objectPos ? { objectPosition: im.objectPos } : undefined} /> :

                            <div className="opt-detail-img-placeholder">
                                      <div className="opt-detail-img-placeholder-icon">📷</div>
                                      <div className="opt-detail-img-placeholder-label">Photo needed: {im.placeholder}</div>
                                    </div>
                            }
                                </div>
                                {im.caption &&
                          <figcaption className="opt-detail-img-cap">
                                    {im.type === 'data' && <span className="opt-detail-img-cap-tag">Data</span>}
                                    {im.caption}
                                  </figcaption>
                          }
                              </figure>
                        )}
                          </div>
                        </div>
                    }

                      {/* Footer */}
                      <div className="opt-detail-foot">
                        {(() => {
                        const idx = stagePractices.findIndex((p) => p.name === expandedPractice);
                        if (idx < stagePractices.length - 1) {
                          const next = stagePractices[idx + 1];
                          return (
                            <button type="button"
                            className="opt-detail-next opt-detail-next-block"
                            onClick={() => { setExpandedPractice(next.name); detailRef.current?.scrollTo(0, 0); }}>
                                <span className="opt-detail-next-label">Next practice</span>
                                <span className="opt-detail-next-name">{next.name} →</span>
                              </button>);

                        } else {
                          const sIdx = window.PHENOLOGICAL_STAGES.findIndex((s) => s.id === activeStage.id);
                          const nextStage = window.PHENOLOGICAL_STAGES[(sIdx + 1) % 8];
                          return (
                            <button type="button"
                            className="opt-detail-next opt-detail-next-block"
                            onClick={() => {
                              wheelRef.current?.snapTo((sIdx + 1) % 8);
                              setExpandedPractice(null);
                            }}>
                                <span className="opt-detail-next-label">Next stage</span>
                                <span className="opt-detail-next-name">{nextStage.label} →</span>
                              </button>);

                        }
                      })()}
                      </div>
                    </div>
                  </aside>
                </>
              }
            </div>
          </div>
        </section>

        {/* CTA strip — kept */}
        <section className="cta-banner">
          <div className="container-wide" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 'var(--space-3)' }}>
            <div>
              <h2 style={{ marginBottom: 0 }}>See what precision is <em style={{ fontFamily: "'Instrument Serif', serif", color: '#B8DC73' }}>actually worth.</em></h2>
              <p style={{ marginTop: 12 }}>Eight farms, 313 ha, five years of layers — and R 5.14 M of fertiliser put where it actually needs to go.</p>
            </div>
            <a className="btn btn-primary btn-lg" href="#" onClick={(e) => {e.preventDefault();setRoute('case-study');}}>Read the case study →</a>
          </div>
        </section>
      </>);

  };
})();