/* Nature Fresh Farms email creative — merged inline (native React, no iframe).
   Markup is window.__NFF_EMAIL_HTML (machine-extracted from the original Design
   Component); the animation is a direct port of that component's tour logic,
   driving the real DOM nodes by [data-role]. */
(function () {
  const NATIVE_W = 1200, NATIVE_H = 800;
  const ACCENTS = ['#e6237a', '#143d2b', '#f29130'];
  const SUBJECTS = ['Organic strawberries, evolved \uD83C\uDF53', 'Why our produce tastes just as fresh in January \uD83C\uDF31', 'Meet Hiiros\u2122 & Dramas\u2122: two tomatoes worth the hype \uD83C\uDF45'];
  const DATES = ['9:14 AM', 'Yesterday', 'Mon'];
  const ROW_COMMON = { display: 'flex', gap: '12px', padding: '15px 16px', borderBottom: '1px solid #ededf0', alignItems: 'flex-start', transition: 'background .25s' };

  class NFFEmail extends React.Component {
    constructor(props) {
      super(props);
      this.wrapRef = React.createRef();
      this.stageRef = React.createRef();
      this.alive = false;
      this._s = 1;
      this.scale = this.scale.bind(this);
    }

    componentDidMount() {
      this.alive = true;
      // Recompute on any size change of the wrapper — fires once width is known,
      // so we never get stuck at scale(0) if the section is offscreen at mount.
      if (typeof ResizeObserver !== 'undefined' && this.wrapRef.current) {
        this._ro = new ResizeObserver(() => this.scale());
        this._ro.observe(this.wrapRef.current);
      }
      window.addEventListener('resize', this.scale);
      this.scale();
      const c = this.q('[data-role=cursor]');
      if (c) { c.style.left = '64%'; c.style.top = '48%'; }
      this.runTour();
    }
    componentWillUnmount() {
      this.alive = false;
      if (this._ro) { this._ro.disconnect(); this._ro = null; }
      window.removeEventListener('resize', this.scale);
    }

    q(sel) { const r = this.stageRef.current; return r ? r.querySelector(sel) : null; }
    delay(ms) { return new Promise((r) => setTimeout(r, ms)); }
    raf() { return new Promise((r) => requestAnimationFrame(() => r())); }

    scale() {
      const wrap = this.wrapRef.current, stage = this.stageRef.current;
      if (!wrap || !stage) return;
      const w = wrap.clientWidth;
      // width not known yet (section offscreen / not laid out) — retry next frame
      // instead of locking in scale(0), which would make the email invisible.
      if (w <= 0) { if (this.alive) requestAnimationFrame(this.scale); return; }
      const s = w / NATIVE_W;
      this._s = s;
      stage.style.transform = 'scale(' + s + ')';
      wrap.style.height = (NATIVE_H * s) + 'px';
    }

    selectEmail(i) {
      for (let j = 0; j < 3; j++) {
        const body = this.q('[data-email="' + j + '"]');
        if (body) body.style.display = j === i ? 'block' : 'none';
        const row = this.q('[data-nav="' + j + '"]');
        if (row) {
          row.style.background = j === i ? '#ffffff' : 'transparent';
          row.style.boxShadow = j === i ? 'inset 3px 0 0 ' + ACCENTS[j] : 'none';
        }
      }
      const subj = this.q('[data-role=subject]'); if (subj) subj.textContent = SUBJECTS[i];
      const date = this.q('[data-role=date]'); if (date) date.textContent = DATES[i];
    }

    setScroll(y) {
      const s = this.q('[data-role=scroll]');
      if (s) { s.style.transition = 'none'; s.style.transform = 'translateY(' + (-y) + 'px)'; }
    }

    async autoScrollThrough() {
      const vp = this.q('[data-role=viewport]'), s = this.q('[data-role=scroll]');
      if (!vp || !s) return;
      const max = Math.max(0, s.scrollHeight - vp.clientHeight);
      if (max < 8) return;
      const dur = Math.min(5500, Math.max(3000, max * 3.5));
      const t0 = performance.now();
      await new Promise((res) => {
        const step = (now) => {
          if (!this.alive) return res();
          let p = (now - t0) / dur; if (p > 1) p = 1;
          const e = 0.5 - Math.cos(p * Math.PI) / 2; // easeInOutSine
          s.style.transform = 'translateY(' + (-(max * e)) + 'px)';
          if (p < 1) requestAnimationFrame(step); else res();
        };
        requestAnimationFrame(step);
      });
    }

    rowCenter(i) {
      const win = this.q('[data-role=win]');
      const row = this.q('[data-nav="' + i + '"]');
      if (!win || !row) return null;
      const wr = win.getBoundingClientRect(), rr = row.getBoundingClientRect();
      const s = this._s || 1;
      // getBoundingClientRect is in scaled px; divide back to the window's local space
      return { x: (rr.left - wr.left) / s + 168, y: (rr.top - wr.top + rr.height / 2) / s };
    }

    async moveCursorTo(i) {
      const c = this.q('[data-role=cursor]'), pos = this.rowCenter(i);
      if (!c || !pos) return;
      c.style.transition = 'left 1s cubic-bezier(0.45,0.05,0.2,1), top 1s cubic-bezier(0.45,0.05,0.2,1)';
      c.style.left = pos.x + 'px';
      c.style.top = pos.y + 'px';
      await this.delay(1120);
    }

    async clickPulse() {
      const c = this.q('[data-role=cursor]'), rp = this.q('[data-role=ripple]');
      if (c) c.animate([{ transform: 'scale(1)' }, { transform: 'scale(0.78)' }, { transform: 'scale(1)' }], { duration: 380, easing: 'ease-out' });
      if (rp) rp.animate([{ transform: 'translate(-50%,-50%) scale(0.2)', opacity: 0.5 }, { transform: 'translate(-50%,-50%) scale(1.9)', opacity: 0 }], { duration: 560, easing: 'ease-out' });
      await this.delay(460);
    }

    async gotoEmail(i, initial) {
      if (!initial) {
        await this.moveCursorTo(i);
        await this.clickPulse();
      }
      this.selectEmail(i);
      await this.raf(); await this.raf();
      this.setScroll(0);
      await this.delay(initial ? 2400 : 1500);
      await this.autoScrollThrough();
      await this.delay(1200);
    }

    async runTour() {
      await this.delay(600);
      let initial = true;
      while (this.alive) {
        for (let i = 0; i < 3 && this.alive; i++) {
          await this.gotoEmail(i, initial && i === 0);
          initial = false;
        }
      }
    }

    render() {
      return React.createElement(
        'div',
        { ref: this.wrapRef, style: { position: 'relative', width: '100%', overflow: 'hidden', borderRadius: 16 } },
        React.createElement('div', {
          ref: this.stageRef,
          style: { width: NATIVE_W + 'px', height: NATIVE_H + 'px', transformOrigin: 'top left', willChange: 'transform' },
          dangerouslySetInnerHTML: { __html: window.__NFF_EMAIL_HTML || '' }
        })
      );
    }
  }

  window.NFFEmail = NFFEmail;
})();
