/* rathmind — The Path (mindfulness) + embedded Still Room
 * Nature as abstraction. Ambient. 10 stations; 4 carry long reflections.
 */

const ThePath = {};

const STATIONS = [
  { n: '01', y: 2007, t: 'The Seed', s: 'Sat in silence for the first time at a weekend workshop. Ten minutes felt like an hour.', long: "I remember the room was cold. Twenty strangers sitting cross-legged on cushions. I thought I would last five minutes. But somewhere between the third and fourth breath, the noise stopped. Not outside — inside." },
  { n: '02', y: 2009, t: 'The Struggle', s: 'Two years of inconsistent practice. Starting, stopping, doubting. The mind resists what it needs most.' },
  { n: '03', y: 2012, t: 'The Teacher', s: 'Found a guide at Agathiyar Ashram. Discipline isn’t rigidity — it’s devotion to showing up.', long: "My teacher said something that changed everything: 'You don't meditate to become good at meditating. You meditate to become good at living.' I stopped chasing perfect sessions after that." },
  { n: '04', y: 2015, t: 'The Bridge', s: 'First time applying mindfulness in a boardroom. A tense negotiation. Chose breath over reaction. It worked.' },
  { n: '05', y: 2017, t: 'The Deepening', s: 'Extended silent retreat. Seven days without words. Silence isn’t empty — it’s full of answers.', long: "Seven days of silence. No phone, no laptop, no conversation. By day three, I wanted to leave. By day five, I never wanted to leave. The silence became louder than any noise I had ever known." },
  { n: '06', y: 2019, t: 'The Calling', s: 'Began teaching formally. First corporate workshop — 20 skeptical engineers. By week four they were asking for more.' },
  { n: '07', y: 2020, t: 'The Storm', s: 'The pandemic tested every practice. Held space for hundreds virtually. Presence transcends distance.' },
  { n: '08', y: 2021, t: 'The Certification', s: 'Certified through buddhaceo.org. Not for the credential — for the commitment to rigor.', long: "People ask why I got certified when I was already teaching. Certification wasn't about permission — it was about precision. The same reason a surgeon keeps studying. The stakes are real." },
  { n: '09', y: 2023, t: 'The Integration', s: '500+ students guided. The line between “data consultant” and “mindfulness teacher” dissolved.' },
  { n: '10', y: 2024, t: 'The Present', s: 'Every session is the first session. Every breath is the first breath. The path has no destination — only depth.' },
];

ThePath.View = function({ tweaks, onBack, onCross, onNav }) {
  const ref = React.useRef(null);
  const canvasRef = React.useRef(null);
  const [open, setOpen] = React.useState(null);

  React.useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(es => {
      es.forEach(e => e.isIntersecting && (e.target.classList.add('in'), io.unobserve(e.target)));
    }, { threshold: 0.12, root: ref.current });
    ref.current.querySelectorAll('.rv').forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);

  React.useEffect(() => {
    if (!canvasRef.current) return;
    const f = new PointField(canvasRef.current, {
      mode: 'cloud', tone: 'light',
      variant: tweaks.throughline || 'A',
      motion: tweaks.motion / 100,
      heavy: tweaks.webgl / 100,
    });
    return () => f.destroy();
  }, [tweaks.throughline]);

  const { Nav, Cross, Footer } = window.__rathChrome;

  return (
    <div ref={ref} className="is-mind" style={{
      width: '100%', height: '100%', overflow: 'auto',
      background: 'var(--paper)', color: 'var(--ink)',
      fontFamily: 'var(--sans)',
    }}>
      <Nav side="mind" onBack={onBack} onCross={onCross} onNav={onNav}/>

      {/* Hero */}
      <section style={{ position: 'relative', padding: '120px 48px 140px', overflow: 'hidden', borderBottom: '1px solid var(--rule-faint)' }}>
        <canvas ref={canvasRef} style={{ position: 'absolute', inset: 0, opacity: 0.6 }}/>
        <div style={{ position: 'relative', display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 24 }}>
          <div className="num rv" style={{ gridColumn: '1 / span 3' }}>
            02 <span className="dot"/> The Path <span className="dot"/> 2007 — present
          </div>
          <div style={{ gridColumn: '1 / span 11', marginTop: 48 }}>
            <h1 className="rv" data-d="1" style={{
              fontFamily: 'var(--serif)', fontSize: 'clamp(72px, 9.5vw, 176px)',
              lineHeight: 0.92, letterSpacing: '-0.035em', margin: 0, fontWeight: 400,
            }}>
              Seventeen years.<br/>
              <em style={{ fontStyle: 'italic', color: 'var(--ink-3)' }}>Ten stations.</em><br/>
              One practice.
            </h1>
          </div>
          <p className="rv" data-d="2" style={{
            gridColumn: '3 / span 7', marginTop: 56,
            fontFamily: 'var(--sans)', fontSize: 18, lineHeight: 1.55, color: 'var(--ink-2)',
          }}>
            From the first silent breath to boardrooms and beyond — the milestones that shaped
            a practice. Mindfulness isn’t about emptying the mind; it’s about meeting the world
            with full awareness. Below, ten stations, in the order they arrived.
          </p>
        </div>
      </section>

      {/* Still Room — embedded, do-it-now */}
      <StillRoom tweaks={tweaks}/>

      {/* The Path — vertical timeline */}
      <section style={{ padding: '140px 48px 80px' }}>
        <div className="num rv" style={{ marginBottom: 64 }}>
          The stations <span className="dot"/> click any for more
        </div>
        {STATIONS.map((st, i) => (
          <button
            key={st.n}
            onClick={() => st.long && setOpen(i)}
            className="rv" data-d={Math.min((i % 5) + 1, 5)}
            style={{
              width: '100%', textAlign: 'left', background: 'none', border: 'none',
              cursor: st.long ? 'pointer' : 'default',
              display: 'grid',
              gridTemplateColumns: '80px 120px 1fr 160px 60px',
              gap: 32, padding: '42px 0',
              borderTop: i === 0 ? '1px solid var(--ink)' : '1px solid var(--rule-faint)',
              alignItems: 'baseline',
              color: 'var(--ink)',
              transition: 'background 300ms',
            }}
            onMouseEnter={e => e.currentTarget.style.background = 'var(--paper-2)'}
            onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
          >
            <div className="num">{st.n}</div>
            <div style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--mind-accent)', letterSpacing: '0.08em' }}>{st.y}</div>
            <div>
              <div style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(32px, 3.6vw, 56px)', letterSpacing: '-0.02em', lineHeight: 1 }}>{st.t}</div>
              <div style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 20, color: 'var(--ink-3)', marginTop: 10, letterSpacing: '-0.005em' }}>{st.s}</div>
            </div>
            <div className="num" style={{ color: st.long ? 'var(--mind-accent)' : 'var(--ink-3)' }}>
              {st.long ? 'reflection' : 'station'}
            </div>
            <div className="num" style={{ textAlign: 'right', color: st.long ? 'var(--ink)' : 'var(--ink-3)' }}>
              {st.long ? '+ open' : '·'}
            </div>
          </button>
        ))}
      </section>

      {/* Integration quote */}
      <section style={{ padding: '180px 48px', textAlign: 'center', borderTop: '1px solid var(--rule-faint)', background: 'var(--paper-2)' }}>
        <div className="num rv">The thesis of the site, in one line</div>
        <blockquote className="rv" data-d="1" style={{
          margin: '48px auto 0', maxWidth: 1100,
          fontFamily: 'var(--serif)', fontSize: 'clamp(48px, 5.6vw, 84px)',
          lineHeight: 1.08, letterSpacing: '-0.025em', fontWeight: 400,
        }}>
          "The path is not about becoming someone new. It is <em style={{ color: 'var(--mind-accent)' }}>about returning</em> to who you have always been."
        </blockquote>
        <div className="num rv" data-d="2" style={{ marginTop: 36 }}>— Rathinavel D <span className="dot"/> 2024, on integration</div>
      </section>

      <Cross side="mind" onCross={onCross}/>
      <Footer side="mind"/>

      {/* Reflection overlay */}
      {open !== null && (
        <div onClick={() => setOpen(null)} style={{
          position: 'fixed', inset: 0, background: 'rgba(18,17,16,0.82)',
          backdropFilter: 'blur(10px)', zIndex: 100,
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 60,
        }}>
          <div onClick={e => e.stopPropagation()} style={{
            maxWidth: 720, background: 'var(--paper)', padding: '56px 56px 48px',
            borderTop: '3px solid var(--mind-accent)',
          }}>
            <div className="num" style={{ color: 'var(--ink-3)' }}>
              {STATIONS[open].n} <span className="dot"/> {STATIONS[open].y} <span className="dot"/> {STATIONS[open].t}
            </div>
            <p style={{
              fontFamily: 'var(--serif)', fontSize: 28, lineHeight: 1.4,
              letterSpacing: '-0.01em', margin: '24px 0 0', fontStyle: 'italic', color: 'var(--ink)',
            }}>"{STATIONS[open].long}"</p>
            <div className="num" style={{ marginTop: 40, color: 'var(--ink-3)' }}>
              click anywhere to close
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ─── Still Room — live breath practice ─────────────────────────
function StillRoom({ tweaks }) {
  const [running, setRunning] = React.useState(false);
  const [phase, setPhase] = React.useState('inhale');
  const [cycle, setCycle] = React.useState(0);
  const [audio, setAudio] = React.useState(false);
  const audioRef = React.useRef(null);

  React.useEffect(() => {
    if (!running) return;
    const seq = [['inhale', 4000], ['hold', 2000], ['exhale', 6000]];
    let i = 0;
    const step = () => {
      setPhase(seq[i][0]);
      const t = setTimeout(() => {
        i = (i + 1) % seq.length;
        if (i === 0) setCycle(c => c + 1);
        step();
      }, seq[i][1]);
      return t;
    };
    const t = step();
    return () => clearTimeout(t);
  }, [running]);

  // Web Audio ambient — a soft drone
  React.useEffect(() => {
    if (!audio) {
      if (audioRef.current) { audioRef.current.stop(); audioRef.current = null; }
      return;
    }
    const Ctx = window.AudioContext || window.webkitAudioContext;
    if (!Ctx) return;
    const ctx = new Ctx();
    const osc1 = ctx.createOscillator(), osc2 = ctx.createOscillator();
    const gain = ctx.createGain();
    osc1.frequency.value = 110; osc2.frequency.value = 110 * 1.5;
    osc1.type = 'sine'; osc2.type = 'sine';
    gain.gain.value = 0.04;
    osc1.connect(gain); osc2.connect(gain); gain.connect(ctx.destination);
    osc1.start(); osc2.start();
    audioRef.current = { stop: () => { try { osc1.stop(); osc2.stop(); ctx.close(); } catch(e){} } };
    return () => { if (audioRef.current) { audioRef.current.stop(); audioRef.current = null; } };
  }, [audio]);

  const scale = phase === 'inhale' ? 1 : phase === 'hold' ? 1 : 0.55;
  const phaseLbl = { inhale: 'inhale · four', hold: 'hold · two', exhale: 'exhale · six' }[phase];
  const phaseDur = { inhale: '4s', hold: '2s', exhale: '6s' }[phase];

  return (
    <section style={{
      padding: '140px 48px', borderBottom: '1px solid var(--rule-faint)',
      background: 'var(--paper-2)',
    }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 24, marginBottom: 80 }}>
        <div className="num rv" style={{ gridColumn: '1 / span 3' }}>
          Still Room <span className="dot"/> do it now
        </div>
        <h2 className="rv" data-d="1" style={{
          gridColumn: '3 / span 9', margin: 0,
          fontFamily: 'var(--serif)', fontWeight: 400,
          fontSize: 'clamp(44px, 5vw, 80px)', letterSpacing: '-0.025em', lineHeight: 1,
        }}>
          Before you read about the practice, <em style={{ color: 'var(--mind-accent)' }}>breathe with me for sixty seconds.</em>
        </h2>
      </div>
      <div className="rv" data-d="2" style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80, alignItems: 'center',
      }}>
        <div style={{
          aspectRatio: '1/1', position: 'relative',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          {/* The breath mark */}
          <div style={{
            position: 'absolute', inset: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            {[0.4, 0.6, 0.8, 1.0].map((o, i) => (
              <div key={i} style={{
                position: 'absolute',
                width: `${40 + i * 15}%`, height: `${40 + i * 15}%`,
                borderRadius: '50%',
                border: '1px solid var(--mind-accent)',
                opacity: o * 0.3,
                transform: `scale(${running ? scale : 0.8})`,
                transition: `transform ${phaseDur} cubic-bezier(.4,.0,.2,1)`,
              }}/>
            ))}
            <div style={{
              width: '35%', height: '35%', borderRadius: '50%',
              background: 'var(--mind-accent)',
              transform: `scale(${running ? scale : 0.78})`,
              transition: `transform ${phaseDur} cubic-bezier(.4,.0,.2,1)`,
              opacity: 0.9,
            }}/>
            <div style={{
              position: 'absolute',
              fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.18em',
              textTransform: 'uppercase', color: 'var(--paper)', zIndex: 2,
            }}>
              {running ? phaseLbl : 'begin'}
            </div>
          </div>
        </div>
        <div>
          <div className="num">Box breath <span className="dot"/> 4 · 2 · 6</div>
          <div style={{
            fontFamily: 'var(--serif)', fontSize: 36, lineHeight: 1.2,
            letterSpacing: '-0.015em', marginTop: 16, fontStyle: 'italic', color: 'var(--ink-2)',
          }}>
            The quieter you become, the more you can hear. Three breaths is enough to begin.
          </div>
          <div style={{ display: 'flex', gap: 14, marginTop: 36 }}>
            <button className="btn btn-solid" onClick={() => setRunning(r => !r)}>
              {running ? '❙❙ pause' : '▸ begin'}
            </button>
            <button className="btn" onClick={() => setAudio(a => !a)}>
              {audio ? '◼ silence' : '◐ ambient'}
            </button>
          </div>
          <div className="num" style={{ marginTop: 32 }}>
            {running ? <>cycle {String(cycle + 1).padStart(2, '0')} <span className="dot"/> {phaseLbl}</> : 'press begin to start'}
          </div>
          <div style={{ marginTop: 40, paddingTop: 20, borderTop: '1px solid var(--rule)', maxWidth: 400 }}>
            <div className="num">Today's micro-practice</div>
            <div style={{
              fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 20,
              color: 'var(--ink-2)', marginTop: 8, lineHeight: 1.4,
            }}>
              "Today, give your full presence to the next person you speak with."
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

window.ThePath = ThePath;
